메뉴 건너뛰기

Bigdata, Semantic IoT, Hadoop, NoSQL

Bigdata, Hadoop ecosystem, Semantic IoT등의 프로젝트를 진행중에 습득한 내용을 정리하는 곳입니다.
필요한 분을 위해서 공개하고 있습니다. 문의사항은 gooper@gooper.com로 메일을 보내주세요.


Runtime.getRuntime().exe()로 문제가 발생 할만한 상황을 고려하여 만든소스임

String[] args = {"", "", ""};

  // conf값을 확인해서 재설정함
  args[0] = "/home/hadoop/bin/run.sh";
  args[1] = "default"; 
  args[2] = "a.txt";

  StringBuilder sb = new StringBuilder();

  for (String str : args) {
   sb.append(str);
   sb.append(" ");
  }

후에  String[] result = Utils.runShell(sb)을 호출한다. (result[0]은 stdMsg, result[1]은 errorMsg가 넘어온다)

---------------------------------------Utils.java-----------------------------------------------------

(args는 shell명령어및 인자를 넣어서 runShell()을 실행시켜줌)

 public static String[] runShell(StringBuilder args) throws Exception {
  Process process = null;
  boolean notTimeOver = true;
  String[] result = new String[] { "", "" };
  ProcessOutputThread stdMsgT=null;
  ProcessOutputThread errMsgT=null;

  // OS 종류 확인
  String osName = System.getProperty("os.name");

  try {
   String[] cmd = null;
   if (osName.toLowerCase().startsWith("window")) {
    cmd = new String[] { "cmd.exe", "/y", "/c", sb.toString() };
   } else {
    cmd = new String[] { "/bin/sh", "-c", args.toString() };
   }
   // 콘솔 명령 실행
   process = Runtime.getRuntime().exec(cmd);

   // 실행 결과 확인 (에러)
   StringBuffer stdMsg = new StringBuffer();
   // 스레드로 inputStream 버퍼 비우기
   stdMsgT = new ProcessOutputThread(process.getInputStream(), stdMsg);
   stdMsgT.start();

   StringBuffer errMsg = new StringBuffer();
   // 스레드로 errorStream 버퍼 비우기
   errMsgT = new ProcessOutputThread(process.getErrorStream(), errMsg);
   errMsgT.start();

   // 수행종료시까지 대기
   while(true) {
    if(! stdMsgT.isAlive() && ! errMsgT.isAlive()) {
     notTimeOver = process.waitFor(30L, TimeUnit.MINUTES);
     log.debug("Thread stdMsgT Status : "+stdMsgT.getState());
           log.debug("Thread errMsgT Status : "+errMsgT.getState());

     break;
    }
   }
   log.debug("notTimeOver ==========================>" + notTimeOver);

   // 실행결과
   result[0] = stdMsg.toString();
   result[1] = errMsg.toString();
  } catch (Exception e) {
   e.printStackTrace();
   throw e;
  } finally {
   if (process != null) {
    IOUtils.closeQuietly(process.getOutputStream());
    IOUtils.closeQuietly(process.getInputStream());
    IOUtils.closeQuietly(process.getErrorStream());
    
    process.destroy();
    log.debug("process destoryed ==========================>");
   }
  }

  args.delete(0, args.length());
  args.setLength(0);
  args = null;

  return result;
 }

 

--------------------------------ProcessOutputThread .java----------------------------------------------------------

//스레드로 inputStream 버퍼 비우기 위한 클래스 생성
public class ProcessOutputThread extends Thread {
 private InputStream is;
 private StringBuffer msg;

 public ProcessOutputThread(InputStream is, StringBuffer msg) {
  this.is = is;
  this.msg = msg;
 }

 public void run() {
  try {
   msg.append(getStreamString(is));
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (is != null) {
    try {
     is.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 private String getStreamString(InputStream is) {
  BufferedReader reader = null;
  try {
   reader = new BufferedReader(new InputStreamReader(is));
   StringBuffer out = new StringBuffer();
   String stdLine;
   while ((stdLine = reader.readLine()) != null) {
    out.append(stdLine);
   }
   return out.toString();
  } catch (Exception e) {
   e.printStackTrace();
   return "";
  } finally {
   if (reader != null) {
    try {
     reader.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

 

번호 제목 글쓴이 날짜 조회 수
261 servlet-api를 jar형태로 build할때 포함하지 말고 java 설치 위치의 jre/lib/ext에 복사하여 사용하는것이 좋다. 총관리자 2016.08.10 452
260 [Elephas] Jena Elephas를 이용하여 Spark에서 rdfTriples의 RDD를 만들고 RDD관련 작업하는 샘플소스 총관리자 2016.08.10 90
259 로컬의 라이브러리파일들을 dependency에 포함시키는 방법 총관리자 2016.08.09 49
258 gradle을 이용하여 jar파일 생성시 provided속성을 지정할 수 있게 설정하는 방법 총관리자 2016.08.09 75
257 [SBT] assembly시 "[error] deduplicate: different file contents found in the following:"오류 발생시 조치사항 총관리자 2016.08.04 579
256 [SBT] SBT 사용법 정리(링크) 총관리자 2016.08.04 839
255 [SBT] project.sbt에 libraryDependencies에 필요한 jar를 지정했으나 sbt compile할때 클래스를 못찾는 오류가 발생했을때 조치사항 총관리자 2016.08.03 74
254 build할때 unmappable character for encoding MS949 에러 발생시 조치사항 총관리자 2016.08.03 178
253 kafkaWordCount.scala의 producer와 consumer 클래스를 이용하여 kafka를 이용한 word count 테스트 하기 총관리자 2016.08.02 97
252 bin/start-hbase.sh실행시 org.apache.hadoop.hbase.util.FileSystemVersionException: HBase file layout needs to be upgraded오류가 발생하면 조치사항 총관리자 2016.08.01 205
251 start-all.sh로 spark데몬 기동시 "JAVA_HOME is not set"오류 발생시 조치사항 총관리자 2016.08.01 126
250 hadoop클러스터를 구성하던 서버중 HA를 담당하는 서버의 hostname등이 변경되어 문제가 발생했을때 조치사항 총관리자 2016.07.29 363
249 Journal Storage Directory /data/hadoop/journal/data/mycluster not formatted 오류시 조치사항 총관리자 2016.07.29 1518
248 슬라이딩 윈도우 예제 총관리자 2016.07.28 67
247 거침없이 배우는 Drools 책의 샘플소스 file 총관리자 2016.07.22 1232
246 drools를 이용한 로그,rule matching등의 테스트 java프로그램 file 총관리자 2016.07.21 181
245 ServerInfo객체파일 총관리자 2016.07.21 35
244 drools에서 drl관련 로그를 기록하기 위한 클래스 파일 총관리자 2016.07.21 74
243 워킹 메모리에 대한 정보를 처리하는 클래스 파일 총관리자 2016.07.21 49
242 커리 변경 이벤트를 처리하기 위한 구현클래스 총관리자 2016.07.21 41

A personal place to organize information learned during the development of such Hadoop, Hive, Hbase, Semantic IoT, etc.
We are open to the required minutes. Please send inquiries to gooper@gooper.com.

위로