Cambridge SMT System
Util.java
Go to the documentation of this file.
1 /*******************************************************************************
2  * Licensed under the Apache License, Version 2.0 (the "License");
3  * you may not use these files except in compliance with the License.
4  * You may obtain a copy of the License at
5  *
6  * http://www.apache.org/licenses/LICENSE-2.0
7  *
8  * Unless required by applicable law or agreed to in writing, software
9  * distributed under the License is distributed on an "AS IS" BASIS,
10  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  * See the License for the specific language governing permissions and
12  * limitations under the License.
13  *
14  * Copyright 2014 - Juan Pino, Aurelien Waite, William Byrne
15  *******************************************************************************/
20 package uk.ac.cam.eng.extraction.hadoop.util;
21 
22 import java.lang.reflect.Field;
23 
24 import org.apache.hadoop.conf.Configuration;
25 
26 import com.beust.jcommander.JCommander;
27 import com.beust.jcommander.Parameter;
28 import com.beust.jcommander.ParameterException;
29 import com.beust.jcommander.ParametersDelegate;
30 
38 public final class Util {
39 
40  private Util() {
41 
42  }
43 
53  private static void setProps(Object params, Configuration conf)
54  throws IllegalArgumentException, IllegalAccessException {
55  for (Field field : params.getClass().getDeclaredFields()) {
56  Parameter paramAnnotation = field.getAnnotation(Parameter.class);
57  if (paramAnnotation != null) {
58  // Use the first name only in annotation
59  String name = paramAnnotation.names()[0];
60  Object val = field.get(params);
61  if(val == null){
62  throw new RuntimeException("Null value for " + name);
63  }
64  Class<?> clazz = val.getClass();
65  if (Integer.class == clazz) {
66  conf.setInt(name, (Integer) val);
67  }else if (Double.class == clazz) {
68  conf.set(name, val.toString());
69  }else if (Boolean.class == clazz) {
70  conf.setBoolean(name, (Boolean) val);
71  } else if (String.class == clazz) {
72  conf.set(name, (String) val);
73  }
74  } else if (field.getAnnotation(ParametersDelegate.class) != null) {
75  setProps(field.get(params), conf);
76  }
77  }
78  }
79 
80  public static void ApplyConf(Object params, Configuration conf)
81  throws IllegalArgumentException, IllegalAccessException {
82  setProps(params, conf);
83  }
84 
85  public static JCommander parseCommandLine(String[] args, Object params) {
86  JCommander cmd = new JCommander();
87  cmd.setAcceptUnknownOptions(true);
88  cmd.addObject(params);
89  try {
90  cmd.parse(args);
91  } catch (ParameterException e) {
92  System.err.println(e.getMessage());
93  cmd.usage();
94  throw e;
95  }
96  return cmd;
97  }
98 
99 }
static void ApplyConf(Object params, Configuration conf)
Definition: Util.java:80
static JCommander parseCommandLine(String[] args, Object params)
Definition: Util.java:85