2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.logreader.internal.searchengine;
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.regex.Matcher;
18 import java.util.regex.Pattern;
19 import java.util.regex.PatternSyntaxException;
21 import org.eclipse.jdt.annotation.Nullable;
24 * This class implements logic for regular expression based searching.
26 * @author Pauli Anttila - Initial contribution
28 public class SearchEngine {
30 private List<Pattern> matchers;
31 private List<Pattern> blacklistingMatchers;
33 private long matchCount;
36 * Initialize search patterns.
38 * @param patterns search patterns.
39 * @param blacklistingPatterns search patterns to bypass results which have found by the initial search patterns.
42 public SearchEngine(String patterns, String blacklistingPatterns) throws PatternSyntaxException {
43 matchers = compilePatterns(patterns);
44 blacklistingMatchers = compilePatterns(blacklistingPatterns);
48 * Check if data is matching to one of the provided search patterns.
50 * @param data data against search will be done.
51 * @return true if one of the search patterns found.
53 public boolean isMatching(String data) {
54 if (isMatching(matchers, data)) {
55 if (notBlacklisted(data)) {
63 public long getMatchCount() {
67 public void setMatchCount(long matchCount) {
68 this.matchCount = matchCount;
71 public void clearMatchCount() {
76 * Split pattern string and precompile search patterns.
78 * @param patterns patterns which will handled.
79 * @return list of precompiled patterns. If pattern parameter is null, empty list is returned.
81 private List<Pattern> compilePatterns(@Nullable String patterns) throws PatternSyntaxException {
82 List<Pattern> patternsList = new ArrayList<>();
84 if (patterns != null && !patterns.isEmpty()) {
85 String list[] = patterns.split("\\|");
86 if (list.length > 0) {
87 for (String patternStr : list) {
88 patternsList.add(Pattern.compile(patternStr));
95 private boolean notBlacklisted(String data) {
96 return !isMatching(blacklistingMatchers, data);
99 private boolean isMatching(@Nullable List<Pattern> patterns, String data) {
100 if (patterns != null) {
101 for (Pattern pattern : patterns) {
102 Matcher matcher = pattern.matcher(data);
103 if (matcher.find()) {