summaryrefslogtreecommitdiffstats
path: root/node-maintainer/src/main/java/com/yahoo/vespa/hosted/node/verification/commons/parser/OutputParser.java
blob: 88e1d22cc0e3e0064d37ce5fdb1880f46c49eb48 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.verification.commons.parser;

import java.util.ArrayList;
import java.util.regex.Pattern;

/**
 * Created by sgrostad on 17/07/2017.
 * Parses terminal command output, and returns results based on ParseInstructions
 */
public class OutputParser {

    public static ArrayList<ParseResult> parseOutput(ParseInstructions parseInstructions, ArrayList<String> commandOutput) {
        ArrayList<ParseResult> results = new ArrayList<>();
        int searchElementIndex = parseInstructions.getSearchElementIndex();
        int valueElementIndex = parseInstructions.getValueElementIndex();
        ArrayList<String> searchWords = parseInstructions.getSearchWords();
        for (String line : commandOutput) {
            String[] lineSplit = line.trim().split(parseInstructions.getSplitRegex());
            if (lineSplit.length <= Math.max(searchElementIndex, valueElementIndex)) {
                continue;
            }
            String searchWordCandidate = lineSplit[searchElementIndex].trim();
            boolean searchWordCandidateMatch = matchingSearchWord(searchWords, searchWordCandidate);
            if (searchWordCandidateMatch) {
                String value = lineSplit[valueElementIndex];
                results.add(new ParseResult(searchWordCandidate, value.trim()));
            }
        }
        return results;
    }

    public static ParseResult parseSingleOutput(ParseInstructions parseInstructions, ArrayList<String> commandOutput) {
        ArrayList<ParseResult> parseResults = parseOutput(parseInstructions, commandOutput);
        if (parseResults.size() == 0) {
            return new ParseResult("invalid", "invalid");
        }
        return parseResults.get(0);
    }

    private static boolean matchingSearchWord(ArrayList<String> searchWords, String searchWordCandidate) {
        return searchWords.stream().anyMatch(w -> Pattern.compile(w).matcher(searchWordCandidate).matches());
    }

}