1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
  28  *
  29  * All rights reserved.
  30  *
  31  * Redistribution and use in source and binary forms, with or without
  32  * modification, are permitted provided that the following conditions are met:
  33  *
  34  *  * Redistributions of source code must retain the above copyright notice,
  35  *    this list of conditions and the following disclaimer.
  36  *
  37  *  * Redistributions in binary form must reproduce the above copyright notice,
  38  *    this list of conditions and the following disclaimer in the documentation
  39  *    and/or other materials provided with the distribution.
  40  *
  41  *  * Neither the name of JSR-310 nor the names of its contributors
  42  *    may be used to endorse or promote products derived from this software
  43  *    without specific prior written permission.
  44  *
  45  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  46  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  47  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  48  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  49  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  50  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  51  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  52  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  53  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  54  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  55  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  56  */
  57 package tck.java.time.calendar;
  58 
  59 import static org.testng.Assert.assertEquals;
  60 import static org.testng.Assert.assertTrue;
  61 
  62 import java.io.ByteArrayInputStream;
  63 import java.io.ByteArrayOutputStream;
  64 import java.io.ObjectInputStream;
  65 import java.io.ObjectOutputStream;
  66 import java.util.ArrayList;
  67 import java.util.List;
  68 
  69 import java.time.Duration;
  70 import java.time.LocalDate;
  71 import java.time.LocalDateTime;
  72 import java.time.LocalTime;
  73 import java.time.calendar.HijrahChrono;
  74 import java.time.calendar.JapaneseChrono;
  75 import java.time.calendar.MinguoChrono;
  76 import java.time.calendar.ThaiBuddhistChrono;
  77 import java.time.temporal.Chrono;
  78 import java.time.temporal.ChronoLocalDateTime;
  79 import java.time.temporal.ChronoUnit;
  80 import java.time.temporal.SimplePeriod;
  81 import java.time.temporal.Temporal;
  82 import java.time.temporal.TemporalAccessor;
  83 import java.time.format.DateTimeBuilder;
  84 import java.time.temporal.TemporalAdder;
  85 import java.time.temporal.TemporalAdjuster;
  86 import java.time.temporal.TemporalField;
  87 import java.time.temporal.TemporalSubtractor;
  88 import java.time.temporal.ValueRange;
  89 import java.time.temporal.ISOChrono;
  90 import java.time.temporal.TemporalUnit;
  91 
  92 import org.testng.Assert;
  93 import org.testng.annotations.DataProvider;
  94 import org.testng.annotations.Test;
  95 
  96 /**
  97  * Test assertions that must be true for all built-in chronologies.
  98  */
  99 @Test
 100 public class TestChronoLocalDateTime {
 101     //-----------------------------------------------------------------------
 102     // regular data factory for names and descriptions of available calendars
 103     //-----------------------------------------------------------------------
 104     @DataProvider(name = "calendars")
 105     Chrono[][] data_of_calendars() {
 106         return new Chrono[][]{
 107                     {HijrahChrono.INSTANCE},
 108                     {ISOChrono.INSTANCE},
 109                     {JapaneseChrono.INSTANCE},
 110                     {MinguoChrono.INSTANCE},
 111                     {ThaiBuddhistChrono.INSTANCE}};
 112     }
 113 
 114     @Test(groups={"tck"}, dataProvider="calendars")
 115     public void test_badWithAdjusterChrono(Chrono chrono) {
 116         LocalDate refDate = LocalDate.of(1900, 1, 1);
 117         ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON);
 118         for (Chrono[] clist : data_of_calendars()) {
 119             Chrono chrono2 = clist[0];
 120             ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON);
 121             TemporalAdjuster adjuster = new FixedAdjuster(cdt2);
 122             if (chrono != chrono2) {
 123                 try {
 124                     ChronoLocalDateTime<?> notreached = cdt.with(adjuster);
 125                     Assert.fail("WithAdjuster should have thrown a ClassCastException, "
 126                             + "required: " + cdt + ", supplied: " + cdt2);
 127                 } catch (ClassCastException cce) {
 128                     // Expected exception; not an error
 129                 }
 130             } else {
 131                 // Same chronology,
 132                 ChronoLocalDateTime<?> result = cdt.with(adjuster);
 133                 assertEquals(result, cdt2, "WithAdjuster failed to replace date");
 134             }
 135         }
 136     }
 137 
 138     @Test(groups={"tck"}, dataProvider="calendars")
 139     public void test_badPlusAdjusterChrono(Chrono chrono) {
 140         LocalDate refDate = LocalDate.of(1900, 1, 1);
 141         ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON);
 142         for (Chrono[] clist : data_of_calendars()) {
 143             Chrono chrono2 = clist[0];
 144             ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON);
 145             TemporalAdder adjuster = new FixedAdjuster(cdt2);
 146             if (chrono != chrono2) {
 147                 try {
 148                     ChronoLocalDateTime<?> notreached = cdt.plus(adjuster);
 149                     Assert.fail("WithAdjuster should have thrown a ClassCastException, "
 150                             + "required: " + cdt + ", supplied: " + cdt2);
 151                 } catch (ClassCastException cce) {
 152                     // Expected exception; not an error
 153                 }
 154             } else {
 155                 // Same chronology,
 156                 ChronoLocalDateTime<?> result = cdt.plus(adjuster);
 157                 assertEquals(result, cdt2, "WithAdjuster failed to replace date time");
 158             }
 159         }
 160     }
 161 
 162     @Test(groups={"tck"}, dataProvider="calendars")
 163     public void test_badMinusAdjusterChrono(Chrono chrono) {
 164         LocalDate refDate = LocalDate.of(1900, 1, 1);
 165         ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON);
 166         for (Chrono[] clist : data_of_calendars()) {
 167             Chrono chrono2 = clist[0];
 168             ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON);
 169             TemporalSubtractor adjuster = new FixedAdjuster(cdt2);
 170             if (chrono != chrono2) {
 171                 try {
 172                     ChronoLocalDateTime<?> notreached = cdt.minus(adjuster);
 173                     Assert.fail("WithAdjuster should have thrown a ClassCastException, "
 174                             + "required: " + cdt + ", supplied: " + cdt2);
 175                 } catch (ClassCastException cce) {
 176                     // Expected exception; not an error
 177                 }
 178             } else {
 179                 // Same chronology,
 180                 ChronoLocalDateTime<?> result = cdt.minus(adjuster);
 181                 assertEquals(result, cdt2, "WithAdjuster failed to replace date");
 182             }
 183         }
 184     }
 185 
 186     @Test(groups={"tck"}, dataProvider="calendars")
 187     public void test_badPlusTemporalUnitChrono(Chrono chrono) {
 188         LocalDate refDate = LocalDate.of(1900, 1, 1);
 189         ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON);
 190         for (Chrono[] clist : data_of_calendars()) {
 191             Chrono chrono2 = clist[0];
 192             ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON);
 193             TemporalUnit adjuster = new FixedTemporalUnit(cdt2);
 194             if (chrono != chrono2) {
 195                 try {
 196                     ChronoLocalDateTime<?> notreached = cdt.plus(1, adjuster);
 197                     Assert.fail("TemporalUnit.doAdd plus should have thrown a ClassCastException" + cdt
 198                             + ", can not be cast to " + cdt2);
 199                 } catch (ClassCastException cce) {
 200                     // Expected exception; not an error
 201                 }
 202             } else {
 203                 // Same chronology,
 204                 ChronoLocalDateTime<?> result = cdt.plus(1, adjuster);
 205                 assertEquals(result, cdt2, "WithAdjuster failed to replace date");
 206             }
 207         }
 208     }
 209 
 210     @Test(groups={"tck"}, dataProvider="calendars")
 211     public void test_badMinusTemporalUnitChrono(Chrono chrono) {
 212         LocalDate refDate = LocalDate.of(1900, 1, 1);
 213         ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON);
 214         for (Chrono[] clist : data_of_calendars()) {
 215             Chrono chrono2 = clist[0];
 216             ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON);
 217             TemporalUnit adjuster = new FixedTemporalUnit(cdt2);
 218             if (chrono != chrono2) {
 219                 try {
 220                     ChronoLocalDateTime<?> notreached = cdt.minus(1, adjuster);
 221                     Assert.fail("TemporalUnit.doAdd minus should have thrown a ClassCastException" + cdt.getClass()
 222                             + ", can not be cast to " + cdt2.getClass());
 223                 } catch (ClassCastException cce) {
 224                     // Expected exception; not an error
 225                 }
 226             } else {
 227                 // Same chronology,
 228                 ChronoLocalDateTime<?> result = cdt.minus(1, adjuster);
 229                 assertEquals(result, cdt2, "WithAdjuster failed to replace date");
 230             }
 231         }
 232     }
 233 
 234     @Test(groups={"tck"}, dataProvider="calendars")
 235     public void test_badTemporalFieldChrono(Chrono chrono) {
 236         LocalDate refDate = LocalDate.of(1900, 1, 1);
 237         ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON);
 238         for (Chrono[] clist : data_of_calendars()) {
 239             Chrono chrono2 = clist[0];
 240             ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON);
 241             TemporalField adjuster = new FixedTemporalField(cdt2);
 242             if (chrono != chrono2) {
 243                 try {
 244                     ChronoLocalDateTime<?> notreached = cdt.with(adjuster, 1);
 245                     Assert.fail("TemporalField doSet should have thrown a ClassCastException" + cdt.getClass()
 246                             + ", can not be cast to " + cdt2.getClass());
 247                 } catch (ClassCastException cce) {
 248                     // Expected exception; not an error
 249                 }
 250             } else {
 251                 // Same chronology,
 252                 ChronoLocalDateTime<?> result = cdt.with(adjuster, 1);
 253                 assertEquals(result, cdt2, "TemporalField doSet failed to replace date");
 254             }
 255         }
 256     }
 257 
 258     //-----------------------------------------------------------------------
 259     // isBefore, isAfter, isEqual
 260     //-----------------------------------------------------------------------
 261     @Test(groups={"tck"}, dataProvider="calendars")
 262     public void test_datetime_comparisons(Chrono chrono) {
 263         List<ChronoLocalDateTime<?>> dates = new ArrayList<>();
 264 
 265         ChronoLocalDateTime<?> date = chrono.date(LocalDate.of(1900, 1, 1)).atTime(LocalTime.MIN);
 266 
 267         // Insert dates in order, no duplicates
 268         dates.add(date.minus(100, ChronoUnit.YEARS));
 269         dates.add(date.minus(1, ChronoUnit.YEARS));
 270         dates.add(date.minus(1, ChronoUnit.MONTHS));
 271         dates.add(date.minus(1, ChronoUnit.WEEKS));
 272         dates.add(date.minus(1, ChronoUnit.DAYS));
 273         dates.add(date.minus(1, ChronoUnit.HOURS));
 274         dates.add(date.minus(1, ChronoUnit.MINUTES));
 275         dates.add(date.minus(1, ChronoUnit.SECONDS));
 276         dates.add(date.minus(1, ChronoUnit.NANOS));
 277         dates.add(date);
 278         dates.add(date.plus(1, ChronoUnit.NANOS));
 279         dates.add(date.plus(1, ChronoUnit.SECONDS));
 280         dates.add(date.plus(1, ChronoUnit.MINUTES));
 281         dates.add(date.plus(1, ChronoUnit.HOURS));
 282         dates.add(date.plus(1, ChronoUnit.DAYS));
 283         dates.add(date.plus(1, ChronoUnit.WEEKS));
 284         dates.add(date.plus(1, ChronoUnit.MONTHS));
 285         dates.add(date.plus(1, ChronoUnit.YEARS));
 286         dates.add(date.plus(100, ChronoUnit.YEARS));
 287 
 288         // Check these dates against the corresponding dates for every calendar
 289         for (Chrono[] clist : data_of_calendars()) {
 290             List<ChronoLocalDateTime<?>> otherDates = new ArrayList<>();
 291             Chrono chrono2 = clist[0];
 292             for (ChronoLocalDateTime<?> d : dates) {
 293                 otherDates.add(chrono2.date(d).atTime(d.getTime()));
 294             }
 295 
 296             // Now compare  the sequence of original dates with the sequence of converted dates
 297             for (int i = 0; i < dates.size(); i++) {
 298                 ChronoLocalDateTime<?> a = dates.get(i);
 299                 for (int j = 0; j < otherDates.size(); j++) {
 300                     ChronoLocalDateTime<?> b = otherDates.get(j);
 301                     int cmp = ChronoLocalDateTime.DATE_TIME_COMPARATOR.compare(a, b);
 302                     if (i < j) {
 303                         assertTrue(cmp < 0, a + " compare " + b);
 304                         assertEquals(a.isBefore(b), true, a + " isBefore " + b);
 305                         assertEquals(a.isAfter(b), false, a + " isAfter " + b);
 306                         assertEquals(a.isEqual(b), false, a + " isEqual " + b);
 307                     } else if (i > j) {
 308                         assertTrue(cmp > 0, a + " compare " + b);
 309                         assertEquals(a.isBefore(b), false, a + " isBefore " + b);
 310                         assertEquals(a.isAfter(b), true, a + " isAfter " + b);
 311                         assertEquals(a.isEqual(b), false, a + " isEqual " + b);
 312                     } else {
 313                         assertTrue(cmp == 0, a + " compare " + b);
 314                         assertEquals(a.isBefore(b), false, a + " isBefore " + b);
 315                         assertEquals(a.isAfter(b), false, a + " isAfter " + b);
 316                         assertEquals(a.isEqual(b), true, a + " isEqual " + b);
 317                     }
 318                 }
 319             }
 320         }
 321     }
 322 
 323     //-----------------------------------------------------------------------
 324     // Test Serialization of ISO via chrono API
 325     //-----------------------------------------------------------------------
 326     @Test( groups={"tck"}, dataProvider="calendars")
 327     public <C extends Chrono<C>> void test_ChronoLocalDateTimeSerialization(C chrono) throws Exception {
 328         LocalDateTime ref = LocalDate.of(2000, 1, 5).atTime(12, 1, 2, 3);
 329         ChronoLocalDateTime<C> orginal = chrono.date(ref).atTime(ref.getTime());
 330         ByteArrayOutputStream baos = new ByteArrayOutputStream();
 331         ObjectOutputStream out = new ObjectOutputStream(baos);
 332         out.writeObject(orginal);
 333         out.close();
 334         ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
 335         ObjectInputStream in = new ObjectInputStream(bais);
 336         ChronoLocalDateTime<C> ser = (ChronoLocalDateTime<C>) in.readObject();
 337         assertEquals(ser, orginal, "deserialized date is wrong");
 338     }
 339 
 340 
 341     /**
 342      * FixedAdjusted returns a fixed Temporal in all adjustments.
 343      * Construct an adjuster with the Temporal that should be returned from adjust.
 344      */
 345     static class FixedAdjuster implements TemporalAdjuster, TemporalAdder, TemporalSubtractor {
 346         private Temporal datetime;
 347 
 348         FixedAdjuster(Temporal datetime) {
 349             this.datetime = datetime;
 350         }
 351 
 352         @Override
 353         public Temporal adjustInto(Temporal ignore) {
 354             return datetime;
 355         }
 356 
 357         @Override
 358         public Temporal addTo(Temporal ignore) {
 359             return datetime;
 360         }
 361 
 362         @Override
 363         public Temporal subtractFrom(Temporal ignore) {
 364             return datetime;
 365         }
 366 
 367     }
 368 
 369     /**
 370      * FixedTemporalUnit returns a fixed Temporal in all adjustments.
 371      * Construct an FixedTemporalUnit with the Temporal that should be returned from doAdd.
 372      */
 373     static class FixedTemporalUnit implements TemporalUnit {
 374         private Temporal temporal;
 375 
 376         FixedTemporalUnit(Temporal temporal) {
 377             this.temporal = temporal;
 378         }
 379 
 380         @Override
 381         public String getName() {
 382             return "FixedTemporalUnit";
 383         }
 384 
 385         @Override
 386         public Duration getDuration() {
 387             throw new UnsupportedOperationException("Not supported yet.");
 388         }
 389 
 390         @Override
 391         public boolean isDurationEstimated() {
 392             throw new UnsupportedOperationException("Not supported yet.");
 393         }
 394 
 395         @Override
 396         public boolean isSupported(Temporal temporal) {
 397             throw new UnsupportedOperationException("Not supported yet.");
 398         }
 399 
 400         @SuppressWarnings("unchecked")
 401         @Override
 402         public <R extends Temporal> R doPlus(R dateTime, long periodToAdd) {
 403             return (R) this.temporal;
 404         }
 405 
 406         @Override
 407         public <R extends Temporal> SimplePeriod between(R dateTime1, R dateTime2) {
 408             throw new UnsupportedOperationException("Not supported yet.");
 409         }
 410     }
 411 
 412     /**
 413      * FixedTemporalField returns a fixed Temporal in all adjustments.
 414      * Construct an FixedTemporalField with the Temporal that should be returned from doSet.
 415      */
 416     static class FixedTemporalField implements TemporalField {
 417         private Temporal temporal;
 418         FixedTemporalField(Temporal temporal) {
 419             this.temporal = temporal;
 420         }
 421 
 422         @Override
 423         public String getName() {
 424             return "FixedTemporalField";
 425         }
 426 
 427         @Override
 428         public TemporalUnit getBaseUnit() {
 429             throw new UnsupportedOperationException("Not supported yet.");
 430         }
 431 
 432         @Override
 433         public TemporalUnit getRangeUnit() {
 434             throw new UnsupportedOperationException("Not supported yet.");
 435         }
 436 
 437         @Override
 438         public ValueRange range() {
 439             throw new UnsupportedOperationException("Not supported yet.");
 440         }
 441 
 442         @Override
 443         public boolean doIsSupported(TemporalAccessor temporal) {
 444             throw new UnsupportedOperationException("Not supported yet.");
 445         }
 446 
 447         @Override
 448         public ValueRange doRange(TemporalAccessor temporal) {
 449             throw new UnsupportedOperationException("Not supported yet.");
 450         }
 451 
 452         @Override
 453         public long doGet(TemporalAccessor temporal) {
 454             throw new UnsupportedOperationException("Not supported yet.");
 455         }
 456 
 457         @SuppressWarnings("unchecked")
 458         @Override
 459         public <R extends Temporal> R doWith(R temporal, long newValue) {
 460             return (R) this.temporal;
 461         }
 462 
 463         @Override
 464         public boolean resolve(DateTimeBuilder builder, long value) {
 465             throw new UnsupportedOperationException("Not supported yet.");
 466         }
 467 
 468     }
 469 }