'Properties'에 해당되는 글 1건

  1. 2012.02.17 Common CLI 와 Properties 사용 예제



java에서 jvm으로 넘어오면 파라미터를 체크하려면 좀 귀찮은 작업을 해야 하는데. Apache common cli를 쓰면 좀 편리하다.  properties 체크도 할 때 하려면 귀찮아서 추후를 위해서 만들어본다.


Test.java

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;


public class Test {
 public static final String DEFAULT_CONFIG = "a.prop";
 
 public static void main(String[] args) throws Exception {
  Map<String, String> propMap = readProperties();
  Map<String, String> argMap = readOption(args);
  if (argMap == null) {
   return;
  }
  
  //...
  System.out.println("property..");
  for (Map.Entry<String,String> entry : propMap.entrySet()) {
   System.out.println("key : " + entry.getKey() + ", value : " + entry.getValue());
  }
  
  System.out.println("argument..");
  for (Map.Entry<String,String> entry : argMap.entrySet()) {
   System.out.println("key : " + entry.getKey() + ", value : " + entry.getValue());
  }
 }

 private static Map<String, String> readOption(String[] args) throws ParseException {
  Options options = new Options();
  options.addOption("m", "mode", true, "mode data");
  options.addOption("n", "num", true, "number data");

  CommandLineParser parser = new PosixParser();
  CommandLine cmd = parser.parse(options, args);

  if (!cmd.hasOption('n') || !cmd.hasOption('m')) {
   HelpFormatter formatter = new HelpFormatter();
   formatter.printHelp("Help ....", options);
   return null;
  }
  
  Map<String, String> map = new HashMap<String, String>();
  String number = cmd.getOptionValue('n');
  String mode = cmd.getOptionValue('m');
  map.put("number", number);
  map.put("mode", mode);
  return map;
 }

 private static Map<String, String> readProperties() throws IOException {
  InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_CONFIG);
  if (in == null) {
   throw new IOException("Not found config file " + DEFAULT_CONFIG);
  }

  Properties properties = new Properties();
  properties.load(in);
  
  Map<String, String> map = new HashMap<String, String>();
  for (Map.Entry<Object,Object> entry : properties.entrySet()) {
   map.put((String) entry.getKey(), (String)entry.getValue());
  }
  return map;
 }
}




a.prop


a=1
b=2


그냥 실행시에는 에러가 발생


usage: Help ....
 -m,--mode <arg>   mode data
 -n,--num <arg>    number data


파라미터를 넘기면(-n 5 -m run) 다음과 같은 결과 나옴

property..
key : b, value : 2
key : a, value : 1
argument..
key : number, value : 5
key : mode, value : run




pom.xml의 추가할 depdendency 추가.



  <dependency>
   <groupId>commons-cli</groupId>
   <artifactId>commons-cli</artifactId>
   <version>1.1</version>
  </dependency>
Posted by '김용환'
,