001/*
002 * Syncany, www.syncany.org
003 * Copyright (C) 2011-2016 Philipp C. Heckel <philipp.heckel@gmail.com> 
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU General Public License as published by
007 * the Free Software Foundation, either version 3 of the License, or
008 * (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU General Public License for more details.
014 *
015 * You should have received a copy of the GNU General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018package org.syncany.cli.util;
019
020import java.util.regex.Matcher;
021import java.util.regex.Pattern;
022
023/**
024 * Various CLI-utilities.
025 * 
026 * @author Pim Otte
027 */
028public class CommandLineUtil {
029        /**
030         * Parses a string of type "1y2mo3w4d5h6m7s", where the units represent
031         * years, months, weeks, days, hours, minutes and second respectively.
032         * 
033         * returns: the duration of the period represented by the string in seconds.
034         */
035        public static long parseTimePeriod(String period) {
036                Pattern relativeDatePattern = Pattern.compile("(\\d+(?:[.,]\\d+)?)(mo|[smhdwy])");              
037                Matcher relativeDateMatcher = relativeDatePattern.matcher(period);              
038                
039                relativeDateMatcher.reset();
040                long periodSeconds = 0;
041                
042                while (relativeDateMatcher.find()) {
043                        double time = Double.parseDouble(relativeDateMatcher.group(1));
044                        String unitStr = relativeDateMatcher.group(2).toLowerCase();
045                        int unitMultiplier = 0;
046                        
047                        if (unitStr.startsWith("mo")) { unitMultiplier = 30*24*60*60; } // must be before "m"
048                        else if (unitStr.startsWith("s")) { unitMultiplier = 1; }
049                        else if (unitStr.startsWith("m")) { unitMultiplier = 60; }
050                        else if (unitStr.startsWith("h")) { unitMultiplier = 60*60; }
051                        else if (unitStr.startsWith("d")) { unitMultiplier = 24*60*60; }
052                        else if (unitStr.startsWith("w")) { unitMultiplier = 7*24*60*60; }
053                        else if (unitStr.startsWith("y")) { unitMultiplier = 365*24*60*60; }
054                        
055                        periodSeconds += (long) ((double)time*unitMultiplier);
056                }
057                
058                return periodSeconds;
059        }
060}