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 */ 017 018package org.apache.logging.log4j.core.appender.rolling.action; 019 020import java.io.Serializable; 021import java.util.Objects; 022import java.util.regex.Matcher; 023import java.util.regex.Pattern; 024 025/** 026 * Simplified implementation of the <a href="https://en.wikipedia.org/wiki/ISO_8601#Durations">ISO-8601 Durations</a> 027 * standard. The supported format is {@code PnDTnHnMnS}, with 'P' and 'T' optional. Days are considered to be exactly 24 028 * hours. 029 * <p> 030 * Similarly to the {@code java.time.Duration} class, this class does not support year or month sections in the format. 031 * This implementation does not support fractions or negative values. 032 * 033 * @see #parse(CharSequence) 034 */ 035public class Duration implements Serializable, Comparable<Duration> { 036 private static final long serialVersionUID = -3756810052716342061L; 037 038 /** 039 * Constant for a duration of zero. 040 */ 041 public static final Duration ZERO = new Duration(0); 042 043 /** 044 * Hours per day. 045 */ 046 private static final int HOURS_PER_DAY = 24; 047 /** 048 * Minutes per hour. 049 */ 050 private static final int MINUTES_PER_HOUR = 60; 051 /** 052 * Seconds per minute. 053 */ 054 private static final int SECONDS_PER_MINUTE = 60; 055 /** 056 * Seconds per hour. 057 */ 058 private static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; 059 /** 060 * Seconds per day. 061 */ 062 private static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY; 063 064 /** 065 * The pattern for parsing. 066 */ 067 private static final Pattern PATTERN = Pattern.compile("P?(?:([0-9]+)D)?" 068 + "(T?(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)?S)?)?", Pattern.CASE_INSENSITIVE); 069 070 /** 071 * The number of seconds in the duration. 072 */ 073 private final long seconds; 074 075 /** 076 * Constructs an instance of {@code Duration} using seconds. 077 * 078 * @param seconds the length of the duration in seconds, positive or negative 079 */ 080 private Duration(final long seconds) { 081 this.seconds = seconds; 082 } 083 084 /** 085 * Obtains a {@code Duration} from a text string such as {@code PnDTnHnMnS}. 086 * <p> 087 * This will parse a textual representation of a duration, including the string produced by {@code toString()}. The 088 * formats accepted are based on the ISO-8601 duration format {@code PnDTnHnMnS} with days considered to be exactly 089 * 24 hours. 090 * <p> 091 * This implementation does not support negative numbers or fractions (so the smallest non-zero value a Duration can 092 * have is one second). 093 * <p> 094 * The string optionally starts with the ASCII letter "P" in upper or lower case. There are then four sections, each 095 * consisting of a number and a suffix. The sections have suffixes in ASCII of "D", "H", "M" and "S" for days, 096 * hours, minutes and seconds, accepted in upper or lower case. The suffixes must occur in order. The ASCII letter 097 * "T" may occur before the first occurrence, if any, of an hour, minute or second section. At least one of the four 098 * sections must be present, and if "T" is present there must be at least one section after the "T". The number part 099 * of each section must consist of one or more ASCII digits. The number may not be prefixed by the ASCII negative or 100 * positive symbol. The number of days, hours, minutes and seconds must parse to a {@code long}. 101 * <p> 102 * Examples: 103 * 104 * <pre> 105 * "PT20S" -- parses as "20 seconds" 106 * "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds) 107 * "PT10H" -- parses as "10 hours" (where an hour is 3600 seconds) 108 * "P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds) 109 * "P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes" 110 * </pre> 111 * 112 * @param text the text to parse, not null 113 * @return the parsed duration, not null 114 * @throws IllegalArgumentException if the text cannot be parsed to a duration 115 */ 116 public static Duration parse(final CharSequence text) { 117 Objects.requireNonNull(text, "text"); 118 final Matcher matcher = PATTERN.matcher(text); 119 if (matcher.matches()) { 120 // check for letter T but no time sections 121 if ("T".equals(matcher.group(2)) == false) { 122 final String dayMatch = matcher.group(1); 123 final String hourMatch = matcher.group(3); 124 final String minuteMatch = matcher.group(4); 125 final String secondMatch = matcher.group(5); 126 if (dayMatch != null || hourMatch != null || minuteMatch != null || secondMatch != null) { 127 final long daysAsSecs = parseNumber(text, dayMatch, SECONDS_PER_DAY, "days"); 128 final long hoursAsSecs = parseNumber(text, hourMatch, SECONDS_PER_HOUR, "hours"); 129 final long minsAsSecs = parseNumber(text, minuteMatch, SECONDS_PER_MINUTE, "minutes"); 130 final long seconds = parseNumber(text, secondMatch, 1, "seconds"); 131 try { 132 return create(daysAsSecs, hoursAsSecs, minsAsSecs, seconds); 133 } catch (final ArithmeticException ex) { 134 throw new IllegalArgumentException("Text cannot be parsed to a Duration (overflow) " + text, ex); 135 } 136 } 137 } 138 } 139 throw new IllegalArgumentException("Text cannot be parsed to a Duration: " + text); 140 } 141 142 private static long parseNumber(final CharSequence text, final String parsed, final int multiplier, 143 final String errorText) { 144 // regex limits to [0-9]+ 145 if (parsed == null) { 146 return 0; 147 } 148 try { 149 final long val = Long.parseLong(parsed); 150 return val * multiplier; 151 } catch (final Exception ex) { 152 throw new IllegalArgumentException("Text cannot be parsed to a Duration: " + errorText + " (in " + text 153 + ")", ex); 154 } 155 } 156 157 private static Duration create(final long daysAsSecs, final long hoursAsSecs, final long minsAsSecs, final long secs) { 158 return create(daysAsSecs + hoursAsSecs + minsAsSecs + secs); 159 } 160 161 /** 162 * Obtains an instance of {@code Duration} using seconds. 163 * 164 * @param seconds the length of the duration in seconds, positive only 165 */ 166 private static Duration create(final long seconds) { 167 if ((seconds) == 0) { 168 return ZERO; 169 } 170 return new Duration(seconds); 171 } 172 173 /** 174 * Converts this duration to the total length in milliseconds. 175 * 176 * @return the total length of the duration in milliseconds 177 */ 178 public long toMillis() { 179 return seconds * 1000L; 180 } 181 182 @Override 183 public boolean equals(final Object obj) { 184 if (obj == this) { 185 return true; 186 } 187 if (!(obj instanceof Duration)) { 188 return false; 189 } 190 final Duration other = (Duration) obj; 191 return other.seconds == this.seconds; 192 } 193 194 @Override 195 public int hashCode() { 196 return (int) (seconds ^ (seconds >>> 32)); 197 } 198 199 /** 200 * A string representation of this duration using ISO-8601 seconds based representation, such as {@code PT8H6M12S}. 201 * <p> 202 * The format of the returned string will be {@code PnDTnHnMnS}, where n is the relevant days, hours, minutes or 203 * seconds part of the duration. If a section has a zero value, it is omitted. The hours, minutes and seconds are 204 * all positive. 205 * <p> 206 * Examples: 207 * 208 * <pre> 209 * "20 seconds" -- "PT20S 210 * "15 minutes" (15 * 60 seconds) -- "PT15M" 211 * "10 hours" (10 * 3600 seconds) -- "PT10H" 212 * "2 days" (2 * 86400 seconds) -- "P2D" 213 * </pre> 214 * 215 * @return an ISO-8601 representation of this duration, not null 216 */ 217 @Override 218 public String toString() { 219 if (this == ZERO) { 220 return "PT0S"; 221 } 222 final long days = seconds / SECONDS_PER_DAY; 223 final long hours = (seconds % SECONDS_PER_DAY) / SECONDS_PER_HOUR; 224 final int minutes = (int) ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE); 225 final int secs = (int) (seconds % SECONDS_PER_MINUTE); 226 final StringBuilder buf = new StringBuilder(24); 227 buf.append("P"); 228 if (days != 0) { 229 buf.append(days).append('D'); 230 } 231 if ((hours | minutes | secs) != 0) { 232 buf.append('T'); 233 } 234 if (hours != 0) { 235 buf.append(hours).append('H'); 236 } 237 if (minutes != 0) { 238 buf.append(minutes).append('M'); 239 } 240 if (secs == 0 && buf.length() > 0) { 241 return buf.toString(); 242 } 243 buf.append(secs).append('S'); 244 return buf.toString(); 245 } 246 247 /* 248 * (non-Javadoc) 249 * 250 * @see java.lang.Comparable#compareTo(java.lang.Object) 251 */ 252 @Override 253 public int compareTo(final Duration other) { 254 return Long.signum(toMillis() - other.toMillis()); 255 } 256}