Parses a string into duration type safe spec format if possible.

@param path           property path
@param durationString duration string using "10 seconds", "10 days", etc. format from type safe.
@return Duration parsed from typesafe config format.
555126
private Duration parseDurationUsingTypeSafeSpec(final String path, final String durationString) {

        /* Check to see if any of the postfixes are at the end of the durationString. */
        final Optional<Map.Entry<TimeUnit, List<String>>> entry = timeUnitMap.entrySet().stream()
                .filter(timeUnitListEntry ->
                        /* Go through values in map and see if there are any matches. */
                        timeUnitListEntry.getValue()
                                .stream()
                                .anyMatch(durationString::endsWith))
                .findFirst();

        /* if we did not match any postFixes then exit early with an exception. */
        if (!entry.isPresent()) {
            throw new IllegalArgumentException("Path " + path + " does not resolve to a duration " + durationString);
        }

        /*  Convert the value to a Duration.
         */
        Optional<Duration> optional = entry.map(timeUnitListEntry -> {

            /* Find the prefix that matches the best. Prefixes are ordered by length.
            * Biggest prefixes are matched first.
            */
            final Optional<String> postFix = timeUnitListEntry
                    .getValue()
                    .stream()
                    .filter(durationString::endsWith)
                    .findFirst();

            if (postFix.isPresent()) {
            /* Remove the prefix from the string so only the unit remains. */
                final String unitString = durationString.replace(postFix.get(), "").trim();

            /* Try to parse the units, if the units do not parse than they gave us a bad prefix. */
                try {
                    long unit = Long.parseLong(unitString);
                    return Duration.ofNanos(timeUnitListEntry.getKey().toNanos(unit));
                } catch (NumberFormatException nfe) {
                    throw new IllegalArgumentException("Path does not resolve to a duration " + durationString);
                }
            } else {
                throw new IllegalArgumentException("Path does not resolve to a duration " + durationString);
            }
        });
        if (optional.isPresent()) {
            return optional.get();
        } else {
            throw new IllegalArgumentException("Path does not resolve to a duration " + durationString);
        }
    }
1001351
@SuppressWarnings("unchecked")
    public <A extends Comparable<?>> DateTimePath<A> get(DateTimePath<A> path) {
        DateTimePath<A> newPath = getDateTime(toString(path), (Class<A>) path.getType());
        return addMetadataOf(newPath, path);
    }
30685
public static final int parse(String durationString) {

        durationString = durationString.toLowerCase();
        Matcher matcher = durationPattern.matcher(durationString);

        int currentUnitIndex = -1;
        int seconds = 0;
        Boolean validDuration = null;

        while (matcher.find() && validDuration != Boolean.FALSE) {
            
            validDuration = true;

            int numGroups = matcher.groupCount();
            if (numGroups == 3) {

                String unit = matcher.group(3);
                int nextUnitIndex = getUnitIndex(unit);
                if (nextUnitIndex > currentUnitIndex) {

                    currentUnitIndex = nextUnitIndex;
                    try {
                        seconds += Long.parseLong(matcher.group(2)) * TIME_UNIT_MULTIPLIERS[nextUnitIndex];
                    } catch (NumberFormatException nfe) {
                        validDuration = false;
                    }
                } else {
                    validDuration = false;
                }

            } else {
                validDuration = false;
            }
        }

        if (validDuration != Boolean.TRUE) {
            throw new IllegalArgumentException(String.format("'%s' is not a valid duration", durationString));
        }

        return (seconds);
    }
717894
private Duration convertFormat(long totalTime, TimeUnit format)
   {
      double duration = totalTime;

      switch (format)
      {
         case MINUTES:
         case ELAPSED_MINUTES:
         {
            duration /= (60 * 1000);
            break;
         }

         case HOURS:
         case ELAPSED_HOURS:
         {
            duration /= (60 * 60 * 1000);
            break;
         }

         case DAYS:
         {
            double minutesPerDay = getMinutesPerDay();
            if (minutesPerDay != 0)
            {
               duration /= (minutesPerDay * 60 * 1000);
            }
            else
            {
               duration = 0;
            }
            break;
         }

         case WEEKS:
         {
            double minutesPerWeek = getMinutesPerWeek();
            if (minutesPerWeek != 0)
            {
               duration /= (minutesPerWeek * 60 * 1000);
            }
            else
            {
               duration = 0;
            }
            break;
         }

         case MONTHS:
         {
            double daysPerMonth = getParentFile().getProjectProperties().getDaysPerMonth().doubleValue();
            double minutesPerDay = getMinutesPerDay();
            if (daysPerMonth != 0 && minutesPerDay != 0)
            {
               duration /= (daysPerMonth * minutesPerDay * 60 * 1000);
            }
            else
            {
               duration = 0;
            }
            break;
         }

         case ELAPSED_DAYS:
         {
            duration /= (24 * 60 * 60 * 1000);
            break;
         }

         case ELAPSED_WEEKS:
         {
            duration /= (7 * 24 * 60 * 60 * 1000);
            break;
         }

         case ELAPSED_MONTHS:
         {
            duration /= (30 * 24 * 60 * 60 * 1000);
            break;
         }

         default:
         {
            throw new IllegalArgumentException("TimeUnit " + format + " not supported");
         }
      }

      return (Duration.getInstance(duration, format));
   }
305895
public static final Duration parseDuration(String value)
   {
      return value == null ? null : Duration.getInstance(Double.parseDouble(value), TimeUnit.DAYS);
   }
800944
@Restricted(NoExternalUse.class)
    public static String normalize(@Nonnull String path) {
        StringBuilder buf = new StringBuilder();
        // Check for prefix designating absolute path
        Matcher m = ABSOLUTE_PREFIX_PATTERN.matcher(path);
        if (m.find()) {
            buf.append(m.group(1));
            path = path.substring(m.end());
        }
        boolean isAbsolute = buf.length() > 0;
        // Split remaining path into tokens, trimming any duplicate or trailing separators
        List<String> tokens = new ArrayList<>();
        int s = 0, end = path.length();
        for (int i = 0; i < end; i++) {
            char c = path.charAt(i);
            if (c == '/' || c == '\\') {
                tokens.add(path.substring(s, i));
                s = i;
                // Skip any extra separator chars
                while (++i < end && ((c = path.charAt(i)) == '/' || c == '\\')) { }
                // Add token for separator unless we reached the end
                if (i < end) tokens.add(path.substring(s, s+1));
                s = i;
            }
        }
        if (s < end) tokens.add(path.substring(s));
        // Look through tokens for "." or ".."
        for (int i = 0; i < tokens.size();) {
            String token = tokens.get(i);
            if (token.equals(".")) {
                tokens.remove(i);
                if (tokens.size() > 0)
                    tokens.remove(i > 0 ? i - 1 : i);
            } else if (token.equals("..")) {
                if (i == 0) {
                    // If absolute path, just remove: /../something
                    // If relative path, not collapsible so leave as-is
                    tokens.remove(0);
                    if (tokens.size() > 0) token += tokens.remove(0);
                    if (!isAbsolute) buf.append(token);
                } else {
                    // Normalize: remove something/.. plus separator before/after
                    i -= 2;
                    for (int j = 0; j < 3; j++) tokens.remove(i);
                    if (i > 0) tokens.remove(i-1);
                    else if (tokens.size() > 0) tokens.remove(0);
                }
            } else
                i += 2;
        }
        // Recombine tokens
        for (String token : tokens) buf.append(token);
        if (buf.length() == 0) buf.append('.');
        return buf.toString();
    }
1285163
public static String readTxt(String path)
    {
        if (path == null) return null;
        try
        {
            InputStream in = IOAdapter == null ? new FileInputStream(path) :
                    IOAdapter.open(path);
            byte[] fileContent = new byte[in.available()];
            int read = readBytesFromOtherInputStream(in, fileContent);
            in.close();
            // 处理 UTF-8 BOM
            if (read >= 3 && fileContent[0] == -17 && fileContent[1] == -69 && fileContent[2] == -65)
                return new String(fileContent, 3, fileContent.length - 3, Charset.forName("UTF-8"));
            return new String(fileContent, Charset.forName("UTF-8"));
        }
        catch (FileNotFoundException e)
        {
            logger.warning("找不到" + path + e);
            return null;
        }
        catch (IOException e)
        {
            logger.warning("读取" + path + "发生IO异常" + e);
            return null;
        }
    }
1343461
public static DateTime fromStringWithMinutes( String dateTimeString ) {
        DateTime dt = withMinutesformatter.parseDateTime(dateTimeString);
        return dt;
    }
423210
public static Duration parse(String value) {
		/*
		 * Implementation note: Regular expressions are not used to improve
		 * performance.
		 */

		if (value.length() == 0) {
			throw parseError(value);
		}

		int index = 0;
		char first = value.charAt(index);
		boolean prior = (first == '-');
		if (first == '-' || first == '+') {
			index++;
		}

		if (value.charAt(index) != 'P') {
			throw parseError(value);
		}

		Builder builder = new Builder();
		builder.prior(prior);

		StringBuilder buffer = new StringBuilder();
		for (int i = index + 1; i < value.length(); i++) {
			char c = value.charAt(i);

			if (c == 'T') {
				/*
				 * A "T" character is supposed to immediately precede the time
				 * component value(s). It is required by the syntax, but not
				 * really necessary. Ignore it.
				 */
				continue;
			}

			if (c >= '0' && c <= '9') {
				buffer.append(c);
				continue;
			}

			if (buffer.length() == 0) {
				throw parseError(value);
			}

			Integer num = Integer.valueOf(buffer.toString());
			buffer.setLength(0);

			switch (c) {
			case 'W':
				builder.weeks(num);
				break;
			case 'D':
				builder.days(num);
				break;
			case 'H':
				builder.hours(num);
				break;
			case 'M':
				builder.minutes(num);
				break;
			case 'S':
				builder.seconds(num);
				break;
			default:
				throw parseError(value);
			}
		}

		return builder.build();
	}
1269603
@Override
   public String getTrimmedPath(String path)
   {
      if (path == null)
      {
         return "/";
      }
      if (!path.startsWith("/"))
      {
         try
         {
            path = new URL(path).getPath();
         }
         catch (MalformedURLException ex)
         {
            // ignore
            Logger.getLogger(JBossWSDestinationRegistryImpl.class).trace(ex);
         }
         if (!path.startsWith("/")) {
            path = "/" + path;
         }
      }
      return path;
   }
872962
public long getLength(String path)
  {
    try {
      ZipEntry entry = getZipEntry(path);

      long length = entry != null ? entry.getSize() : -1;
      
      return length;
    } catch (IOException e) {
      log.log(Level.FINE, e.toString(), e);
      
      return -1;
    }
  }
431208
@SuppressWarnings("unchecked")
    public <A extends Comparable<?>> TimePath<A> get(TimePath<A> path) {
        TimePath<A> newPath = getTime(toString(path), (Class<A>) path.getType());
        return addMetadataOf(newPath, path);
    }
232618
public static String readResource(String path) {
        final long start = System.nanoTime();
        try (InputStream is = UScale.class.getClassLoader().getResourceAsStream(path);) {
            int len = 0;
            byte[] buffer = new byte[2048];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((len = is.read(buffer)) >= 0) {
                baos.write(buffer, 0, len);
            }
            return new String(baos.toByteArray(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, e, () -> "IOException loading resource " + path);
            throw new IllegalStateException("Unable to read class loaded stream " + path, e);
        } catch (RuntimeException re) {
            LOGGER.log(Level.WARNING, re, () -> "Unexpected exception loading resource " + path);
            throw re;
        } finally {
            LOGGER.fine(() -> String.format("Loaded resource %s in %.3fms", path,
                    (System.nanoTime() - start) / 1000000.0));
        }
    }
284029
public static <T extends Comparable<?>> DateTimePath<T> dateTimePath(Class<? extends T> type, PathMetadata metadata) {
        return new DateTimePath<T>(type, metadata);
    }
758777
public static Optional<List<Duration>> getDurationListOptional(Config config, String path) {
        return Optional.ofNullable(getDurationList(config, path));
    }
662283
public static String durationToFormattedString(final Duration duration) {
        if (duration == null) {
            return null;
        }

        return LocalTime.ofNanoOfDay(duration.toNanos()).format(DateTimeFormatter.ofPattern(DURATION_FORMAT));
    }
371197
static Duration duration(String value) {
        Duration result;
        if (value != null) {
            value = value.trim();
            Matcher matcher = DURATION_PATTERN.matcher(value);
            if (matcher.matches()) {
                int hours = matcher.group(1) != null ? Integer.parseInt(matcher.group(1)) : 0;
                int minutes = matcher.group(2) != null ? Integer.parseInt(matcher.group(2)) : 0;
                int seconds = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0;
                int millis = matcher.group(4) != null ? Integer.parseInt(matcher.group(4)) : 0;
                result = new Duration(hours, minutes, seconds, millis);
            } else {
                throw new IllegalArgumentException("Unknown format for value: " + value);
            }
        } else {
            result = null;
        }
        return result;
    }