001package com.pi4j.util;
002
003/*
004 * #%L
005 * **********************************************************************
006 * ORGANIZATION  :  Pi4J
007 * PROJECT       :  Pi4J :: Java Library (Core)
008 * FILENAME      :  ExecUtil.java  
009 * 
010 * This file is part of the Pi4J project. More information about 
011 * this project can be found here:  http://www.pi4j.com/
012 * **********************************************************************
013 * %%
014 * Copyright (C) 2012 - 2013 Pi4J
015 * %%
016 * Licensed under the Apache License, Version 2.0 (the "License");
017 * you may not use this file except in compliance with the License.
018 * You may obtain a copy of the License at
019 * 
020 *      http://www.apache.org/licenses/LICENSE-2.0
021 * 
022 * Unless required by applicable law or agreed to in writing, software
023 * distributed under the License is distributed on an "AS IS" BASIS,
024 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
025 * See the License for the specific language governing permissions and
026 * limitations under the License.
027 * #L%
028 */
029
030
031import java.io.BufferedReader;
032import java.io.IOException;
033import java.io.InputStreamReader;
034import java.util.ArrayList;
035import java.util.List;
036
037public class ExecUtil
038{
039    public static String[] execute(String command) throws IOException, InterruptedException {
040        return execute(command, null);
041    }
042    
043    public static String[] execute(String command, String split) throws IOException, InterruptedException {
044        List<String> result = new ArrayList<String>();
045        Process p = Runtime.getRuntime().exec(command);
046        p.waitFor();
047                
048        if(p.exitValue() != 0)
049            return null;
050        
051        InputStreamReader isr = new InputStreamReader(p.getInputStream());
052        BufferedReader reader = new BufferedReader(isr);
053        String line = reader.readLine();
054        while (line != null) {
055            if (!line.isEmpty()) {
056                if (split == null || split.isEmpty()) {
057                    result.add(line.trim());
058                } else {
059                    String[] parts = line.trim().split(split);
060                    for(String part : parts) {
061                        if (part != null && !part.isEmpty()) {
062                            result.add(part.trim());
063                        }
064                    }
065                }
066            }
067            line = reader.readLine();
068        }
069        
070        // close readers and stream
071        reader.close();
072        isr.close();
073        p.getInputStream().close();
074
075        if (result.size() > 0) {
076            return (String[])result.toArray(new String[0]);
077        } else {
078            return new String[0];
079        }
080    }
081}