Debian Codegraph @

maven-packager-utils/src/main/java/org/debian/maven/packager/util/IOUtil.java

raw
1 /*
2 * Copyright 2012 Ludovic Claude.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.debian.maven.packager.util;
18
19 import java.io.BufferedReader;
20 import java.io.File;
21 import java.io.IOException;
22 import java.io.InputStreamReader;
23 import java.util.concurrent.ExecutorService;
24 import java.util.concurrent.Executors;
25 import java.util.concurrent.ThreadFactory;
26 import java.util.concurrent.TimeUnit;
27
28 public class IOUtil {
29
30 public static void executeProcess(final String[] cmd, final OutputHandler handler) {
31 try {
32 ProcessBuilder pb = new ProcessBuilder(cmd);
33 pb.redirectErrorStream(true);
34 System.out.print("> ");
35 for (String arg : cmd) {
36 System.out.print(arg + " ");
37 }
38 System.out.println();
39 final Process process = pb.start();
40 try {
41 ThreadFactory threadFactory = new ThreadFactory() {
42
43 public Thread newThread(Runnable r) {
44 Thread t = new Thread(r, "Run command " + cmd[0]);
45 t.setDaemon(true);
46 return t;
47 }
48 };
49
50 ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);
51 executor.execute(new Runnable() {
52
53 public void run() {
54 try {
55 BufferedReader in = new BufferedReader(new BufferedReader(new InputStreamReader(process.getInputStream())));
56 String line;
57 while ((line = in.readLine()) != null) {
58 handler.newLine(line);
59 }
60 in.close();
61 } catch (IOException ex) {
62 ex.printStackTrace();
63 }
64 }
65 });
66
67 process.waitFor();
68 executor.awaitTermination(5, TimeUnit.SECONDS);
69 if (process.exitValue() != 0) {
70 System.out.println(cmd[0] + " failed to execute successfully");
71 handler.failure();
72 }
73 process.destroy();
74 } catch (InterruptedException ex) {
75 ex.printStackTrace();
76 Thread.interrupted();
77 }
78 } catch (IOException ex) {
79 ex.printStackTrace();
80 handler.failure();
81 }
82 }
83
84 public static void mkDirIfNotExists(File file) {
85 if (!file.exists()) {
86 file.mkdirs();
87 }
88 }
89
90 public static String relativePath(File base, File inBase) {
91 return inBase.getAbsolutePath().substring(base.getAbsolutePath().length() + 1);
92 }
93 }