/*
* Copyright (C) 2007-2014 Christian Bockermann <chris@jwall.org>
*
* This file is part of the web-audit library.
*
* web-audit library is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The web-audit library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.jwall.log.io;
import java.util.LinkedHashMap;
import java.util.Map;
import org.jwall.web.audit.io.ParseException;
public class TimeParser extends MParser implements Parser<Long> {
public final static Long SECOND = 1000L;
public final static Long MINUTE = 60 * SECOND;
public final static Long HOUR = 60 * MINUTE;
public final static Long DAY = 24 * HOUR;
public final static Long WEEK = 7 * DAY;
public final static Long MONTH = 30 * DAY;
public final static Long YEAR = 12 * MONTH;
public final static Map<String,Long> units = new LinkedHashMap<String,Long>();
static {
units.put( "sec", SECOND );
units.put( "min", MINUTE );
units.put( "hour", HOUR );
units.put( "day", DAY );
units.put( "week", WEEK );
units.put( "month", MONTH );
units.put( "year", YEAR );
}
@Override
public Map<String, String> getDefaults() {
return null;
}
@Override
public void setDefaults(Map<String, String> defaults) {
}
public Long readTimeUnit( String str ) throws ParseException {
int start = this.pos;
skipBlanks( str );
String token = readNonNumeric( str );
Long unit = this.guessUnit( token );
if( unit > 0 )
return unit;
throw new ParseException( "No valid time-unit found at '" + str.substring( start ) + "'!");
}
public String readNonNumeric( String str ){
skipBlanks( str );
StringBuffer s = new StringBuffer();
while( pos < str.length() && ! Character.isWhitespace( str.charAt( pos ) ) && ! Character.isDigit( str.charAt( pos ) ) ){
s.append( str.charAt( pos ) );
pos++;
}
return s.toString();
}
public Long guessUnit( String name ){
for( String key : units.keySet() ){
if( key.startsWith( name ) || name.startsWith( key ) )
return units.get( key );
}
return 0L;
}
@Override
public Long parse(String str) throws ParseException {
Long value = 0L;
skipBlanks( str );
while( ! "".equals(str.substring( pos ).trim()) && ! isBlank( remainder( str ) ) ){
Integer i = readInteger( str );
skipBlanks( str );
Long unit = readTimeUnit( str );
value += i * unit;
}
return value;
}
}