001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.marshall;
018
019import java.time.*;
020
021/**
022 * Supported wire formats for {@link Period} values.
023 */
024public enum PeriodFormat {
025
026   NOT_SET,
027   ISO_8601,
028   DAYS;
029
030   /**
031    * Formats the specified period using this format.
032    *
033    * @param value The value to format.  Can be <jk>null</jk> (returns <jk>null</jk>).
034    * @return The formatted value, or <jk>null</jk> if {@code value} is <jk>null</jk>.
035    */
036   public String format(Period value) {
037      if (value == null)
038         return null;
039      return switch (this) {
040         case NOT_SET, ISO_8601 -> value.toString();
041         case DAYS -> Integer.toString(value.getYears() * 365 + value.getMonths() * 30 + value.getDays());
042      };
043   }
044
045   /**
046    * Parses the specified wire value using this format.
047    *
048    * @param value The value to parse.  Can be <jk>null</jk> or blank (returns <jk>null</jk>).
049    * @return The parsed period, or <jk>null</jk> if {@code value} is <jk>null</jk> or blank.
050    */
051   public Period parse(String value) {
052      if (value == null)
053         return null;
054      String s = value.trim();
055      if (s.isEmpty())
056         return null;
057      return switch (this) {
058         case NOT_SET, ISO_8601 -> Period.parse(s);
059         case DAYS -> Period.ofDays(Integer.parseInt(s));
060      };
061   }
062}