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 static org.apache.juneau.commons.utils.Shorts.*; 020import static org.apache.juneau.commons.utils.StringUtils.*; 021 022import java.math.*; 023import java.time.*; 024import java.util.Locale; 025 026/** 027 * Supported wire formats for {@link Duration} values. 028 */ 029public enum DurationFormat { 030 031 NOT_SET, 032 ISO_8601, 033 ISO_8601_WITH_DAYS, 034 NANOS, 035 MILLIS, 036 SECONDS, 037 HOCON; 038 039 private static final BigDecimal NANOS_PER_SECOND = BigDecimal.valueOf(1_000_000_000L); 040 041 /** 042 * Formats the specified duration using this format. 043 * 044 * @param value The value to format. Can be <jk>null</jk> (returns <jk>null</jk>). 045 * @return The formatted value, or <jk>null</jk> if {@code value} is <jk>null</jk>. 046 */ 047 public String format(Duration value) { 048 if (value == null) 049 return null; 050 return switch (this) { 051 case NOT_SET, ISO_8601 -> value.toString(); 052 case ISO_8601_WITH_DAYS -> formatIso8601WithDays(value); 053 case NANOS -> Long.toString(value.toNanos()); 054 case MILLIS -> Long.toString(value.toMillis()); 055 case SECONDS -> { 056 long seconds = value.getSeconds(); 057 int nanos = value.getNano(); 058 yield seconds + "." + f("%09d", nanos); 059 } 060 case HOCON -> formatHocon(value); 061 }; 062 } 063 064 /** 065 * Parses the specified wire value using this format. 066 * 067 * @param value The value to parse. Can be <jk>null</jk> or blank (returns <jk>null</jk>). 068 * @return The parsed duration, or <jk>null</jk> if {@code value} is <jk>null</jk> or blank. 069 */ 070 public Duration parse(String value) { 071 if (value == null) 072 return null; 073 String s = value.trim(); 074 if (s.isEmpty()) 075 return null; 076 return switch (this) { 077 case NOT_SET, ISO_8601, ISO_8601_WITH_DAYS -> Duration.parse(normalizeIso(s)); 078 case NANOS -> Duration.ofNanos(Long.parseLong(s)); 079 case MILLIS -> Duration.ofMillis(Long.parseLong(s)); 080 case SECONDS -> parseSeconds(s); 081 case HOCON -> parseHocon(s); 082 }; 083 } 084 085 /** 086 * Returns <jk>true</jk> if this format is numeric on the wire. 087 * 088 * @return <jk>true</jk> if this format emits numeric wire values. 089 */ 090 public boolean isNumeric() { 091 return this == NANOS || this == MILLIS || this == SECONDS; 092 } 093 094 private static String normalizeIso(String s) { 095 String x = s; 096 if (x.startsWith("PT-")) 097 x = "-PT" + x.substring(3); 098 return x; 099 } 100 101 private static Duration parseSeconds(String s) { 102 var bd = parseBigDecimal(s); 103 long seconds = bd.longValue(); 104 BigDecimal frac = bd.subtract(BigDecimal.valueOf(seconds)); 105 int nanos = frac.multiply(NANOS_PER_SECOND).intValue(); 106 return Duration.ofSeconds(seconds, nanos); 107 } 108 109 @SuppressWarnings({ 110 "java:S3776" // Cognitive complexity acceptable for ISO-8601 duration formatting logic 111 }) 112 private static String formatIso8601WithDays(Duration value) { 113 boolean neg = value.isNegative(); 114 Duration d = neg ? value.abs() : value; 115 long totalSeconds = d.getSeconds(); 116 int nanos = d.getNano(); 117 long days = totalSeconds / 86400; 118 long rem = totalSeconds % 86400; 119 long hours = rem / 3600; 120 rem %= 3600; 121 long minutes = rem / 60; 122 long seconds = rem % 60; 123 124 var sb = new StringBuilder(); 125 if (neg) 126 sb.append('-'); 127 sb.append('P'); 128 if (days > 0) 129 sb.append(days).append('D'); 130 if (hours > 0 || minutes > 0 || seconds > 0 || nanos > 0 || days == 0) { 131 sb.append('T'); 132 if (hours > 0) 133 sb.append(hours).append('H'); 134 if (minutes > 0) 135 sb.append(minutes).append('M'); 136 if (seconds > 0 || nanos > 0 || (hours == 0 && minutes == 0)) 137 sb.append(seconds).append(nanos == 0 ? "" : "." + trimTrailingZeros(f("%09d", nanos))).append('S'); 138 } 139 return sb.toString(); 140 } 141 142 private static String formatHocon(Duration value) { 143 long nanos = value.toNanos(); 144 long abs = Math.abs(nanos); 145 if (abs == 0) 146 return "0s"; 147 long sign = nanos < 0 ? -1 : 1; 148 long[] divisors = {86_400_000_000_000L, 3_600_000_000_000L, 60_000_000_000L, 1_000_000_000L, 1_000_000L, 1_000L, 1L}; 149 String[] suffixes = {"d", "h", "m", "s", "ms", "us", "ns"}; 150 for (int i = 0; i < divisors.length; i++) { 151 long divisor = divisors[i]; 152 if (abs % divisor == 0) 153 return (sign * (abs / divisor)) + suffixes[i]; 154 } 155 return nanos + "ns"; 156 } 157 158 private static Duration parseHocon(String s) { 159 // Programmatic equivalent of full match ^([+-]?\d++(?:\.\d++)?)(ns|us|ms|s|m|h|d)$ (CASE_INSENSITIVE) to avoid per-parse matching. 160 // Group 1 = the numeric part, group 2 = the (case-insensitive) unit suffix. \d = ASCII [0-9]. 161 var len = s.length(); 162 var i = 0; 163 if (i < len && (s.charAt(i) == '+' || s.charAt(i) == '-')) 164 i++; 165 var digitsStart = i; 166 while (i < len && isAsciiDigit(s.charAt(i))) 167 i++; 168 var valid = i > digitsStart; 169 if (valid && i < len && s.charAt(i) == '.') { 170 i++; 171 var fracStart = i; 172 while (i < len && isAsciiDigit(s.charAt(i))) 173 i++; 174 valid = i > fracStart; 175 } 176 BigDecimal nanos = null; 177 if (valid) { 178 var value = parseBigDecimal(s.substring(0, i)); 179 nanos = switch (s.substring(i).toLowerCase(Locale.ROOT)) { 180 case "d" -> value.multiply(BigDecimal.valueOf(86_400_000_000_000L)); 181 case "h" -> value.multiply(BigDecimal.valueOf(3_600_000_000_000L)); 182 case "m" -> value.multiply(BigDecimal.valueOf(60_000_000_000L)); 183 case "s" -> value.multiply(BigDecimal.valueOf(1_000_000_000L)); 184 case "ms" -> value.multiply(BigDecimal.valueOf(1_000_000L)); 185 case "us" -> value.multiply(BigDecimal.valueOf(1_000L)); 186 case "ns" -> value; 187 default -> null; 188 }; 189 } 190 if (nanos == null) 191 throw iaex("Invalid HOCON duration: %s", s); 192 return Duration.ofNanos(nanos.longValue()); 193 } 194 195 private static boolean isAsciiDigit(char c) { 196 return c >= '0' && c <= '9'; 197 } 198 199 // Removes trailing '0' characters. Equivalent of replaceAll("0++$", ""); returns "" if the input is all zeros. 200 private static String trimTrailingZeros(String s) { 201 var end = s.length(); 202 while (end > 0 && s.charAt(end - 1) == '0') 203 end--; 204 return s.substring(0, end); 205 } 206}