Line data Source code
1 : // Copyright (C) 2021 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.args4j; 16 : 17 : import com.google.inject.Inject; 18 : import com.google.inject.assistedinject.Assisted; 19 : import java.time.Instant; 20 : import java.time.ZoneId; 21 : import java.time.format.DateTimeFormatter; 22 : import java.time.format.DateTimeParseException; 23 : import org.kohsuke.args4j.CmdLineException; 24 : import org.kohsuke.args4j.CmdLineParser; 25 : import org.kohsuke.args4j.OptionDef; 26 : import org.kohsuke.args4j.spi.OptionHandler; 27 : import org.kohsuke.args4j.spi.Parameters; 28 : import org.kohsuke.args4j.spi.Setter; 29 : 30 : public class InstantHandler extends OptionHandler<Instant> { 31 : public static final String TIMESTAMP_FORMAT = "yyyyMMdd_HHmm"; 32 : 33 : @Inject 34 : public InstantHandler( 35 : @Assisted CmdLineParser parser, 36 : @Assisted OptionDef option, 37 : @Assisted Setter<Instant> setter) { 38 1 : super(parser, option, setter); 39 1 : } 40 : 41 : @Override 42 : public int parseArguments(Parameters params) throws CmdLineException { 43 0 : String timestamp = params.getParameter(0); 44 : try { 45 0 : setter.addValue( 46 0 : DateTimeFormatter.ofPattern(TIMESTAMP_FORMAT) 47 0 : .withZone(ZoneId.of("UTC")) 48 0 : .parse(timestamp, Instant::from)); 49 0 : return 1; 50 0 : } catch (DateTimeParseException e) { 51 0 : throw new CmdLineException( 52 : owner, 53 0 : String.format("Invalid timestamp: %s; expected format: %s", timestamp, TIMESTAMP_FORMAT), 54 : e); 55 : } 56 : } 57 : 58 : @Override 59 : public String getDefaultMetaVariable() { 60 0 : return "TIMESTAMP"; 61 : } 62 : }