View Javadoc

1   package com.lexicalscope.jewel.cli;
2   
3   import static com.lexicalscope.fluentreflection.ReflectionMatchers.annotatedWith;
4   
5   import java.util.Map;
6   
7   import com.lexicalscope.fluentreflection.FluentClass;
8   import com.lexicalscope.fluentreflection.FluentMethod;
9   import com.lexicalscope.jewel.cli.specification.OptionsSpecification;
10  
11  /*
12   * Copyright 2011 Tim Wood
13   *
14   * Licensed under the Apache License, Version 2.0 (the "License");
15   * you may not use this file except in compliance with the License.
16   * You may obtain a copy of the License at
17   *
18   * http://www.apache.org/licenses/LICENSE-2.0
19   *
20   * Unless required by applicable law or agreed to in writing, software
21   * distributed under the License is distributed on an "AS IS" BASIS,
22   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23   * See the License for the specific language governing permissions and
24   * limitations under the License.
25   */
26  
27  class InstanceArgumentPresentingStrategy<O> implements ArgumentPresentingStrategy<O> {
28      private final O options;
29      private final FluentClass<O> klass;
30      private final OptionsSpecification<O> specification;
31  
32      public InstanceArgumentPresentingStrategy(
33              final OptionsSpecification<O> specification,
34              final FluentClass<O> klass,
35              final O options) {
36          this.specification = specification;
37          this.klass = klass;
38          this.options = options;
39      }
40  
41      @Override public O presentArguments(final Map<String, Object> argumentMap) {
42          for (final FluentMethod reflectedMethod : klass.methods(annotatedWith(Option.class))) {
43              final boolean isBoolean = specification.getSpecification(reflectedMethod).isBoolean();
44              setValueOnOptions(argumentMap, reflectedMethod, isBoolean);
45          }
46          for (final FluentMethod reflectedMethod : klass.methods(annotatedWith(Unparsed.class))) {
47              setValueOnOptions(argumentMap, reflectedMethod, false);
48          }
49          return options;
50      }
51  
52      private void setValueOnOptions(
53              final Map<String, Object> argumentMap,
54              final FluentMethod reflectedMethod,
55              final boolean isBoolean) {
56          if (argumentMap.containsKey(reflectedMethod.property()))
57          {
58              if (isBoolean)
59              {
60                  reflectedMethod.call(options, argumentMap.containsKey(reflectedMethod.property()));
61              }
62              else if (argumentMap.get(reflectedMethod.property()) != null)
63              {
64                  reflectedMethod.call(options, argumentMap.get(reflectedMethod.property()));
65              }
66          }
67      }
68  }