The Unified and Autonomous Development Platform
midwork
robin shine36f1b5737f3c
diff --git a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/CodeAssist.java b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/CodeAssist.javaindex ee87d37978..7e9fe39882 100644--- a/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/CodeAssist.java+++ b/commons.antlr/src/main/java/com/pmease/commons/antlr/codeassist/CodeAssist.java@@ -1,597 +1,597 @@-package com.pmease.commons.antlr.codeassist;--import java.io.Serializable;-import java.util.ArrayList;-import java.util.Collections;-import java.util.Comparator;-import java.util.HashSet;-import java.util.Iterator;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Map;-import java.util.Set;--import javax.annotation.Nullable;--import org.antlr.v4.runtime.Lexer;-import org.antlr.v4.runtime.Token;--import com.google.common.base.Preconditions;-import com.google.common.collect.Sets;-import com.pmease.commons.antlr.grammar.AlternativeSpec;-import com.pmease.commons.antlr.grammar.ElementSpec;-import com.pmease.commons.antlr.grammar.Grammar;-import com.pmease.commons.antlr.grammar.RuleRefElementSpec;-import com.pmease.commons.antlr.grammar.RuleSpec;-import com.pmease.commons.antlr.grammar.TokenElementSpec;-import com.pmease.commons.antlr.parser.EarleyParser;-import com.pmease.commons.antlr.parser.Element;-import com.pmease.commons.antlr.parser.State;-import com.pmease.commons.antlr.parser.Chart;-import com.pmease.commons.util.StringUtils;--public abstract class CodeAssist implements Serializable {-- private static final long serialVersionUID = 1L;-- private final Grammar grammar;-- public CodeAssist(Grammar grammar) {- this.grammar = grammar;- }-- /**- * Code assist constructor- * @param lexerClass- * lexer class to be used to lex code. Other required information such as- * grammar files and token file will be derived from the lexer class- */- public CodeAssist(Class<? extends Lexer> lexerClass) {- this(new Grammar(lexerClass));- }-- /**- * Code assist constructor.- *- * @param lexerClass- * lexer class to be used to lex code- * @param grammarFiles- * grammar files in class path, relative to class path root- * @param tokenFile- * generated tokens file in class path, relative to class path root- */- public CodeAssist(Class<? extends Lexer> lexerClass, String grammarFiles[], String tokenFile) {- this(new Grammar(lexerClass, grammarFiles, tokenFile));- }-- public List<String> getHints(InputStatus inputStatus, String ruleName) {- RuleSpec rule = Preconditions.checkNotNull(grammar.getRule(ruleName));- List<Token> tokens = grammar.lex(inputStatus.getContentBeforeCaret());- EarleyParser parser = new EarleyParser(rule, tokens);-- List<String> hints = new ArrayList<>();- for (Chart chart: getTerminatingCharts(parser)) {- String matchWith = getMatchWith(chart, inputStatus);- for (List<ParentedElement> expectChain: getExpectChains(chart)) {- for (ParentedElement element: expectChain)- hints.addAll(getHints(element, matchWith));- }- }- return hints;- }-- public List<InputCompletion> suggest(InputStatus inputStatus, String ruleName, int count) {- RuleSpec rule = Preconditions.checkNotNull(grammar.getRule(ruleName));-- String inputContent = inputStatus.getContent();- List<InputCompletion> inputCompletions = new ArrayList<>();-- /*- * Mandatory literals may come after a suggestion (for instance if a method name is suggested,- * the character '(' can be a mandatory literal), so for every suggestion, we need to- * append mandatory literals to make user typing less, however if a suggested text has two or- * more different mandatories (this is possible if the suggested text comes from different- * element specs, and each spec calculates a different set of mandatories after the text), we- * should display the suggested text as a single entry in the final suggestion list without- * appending mandatories they are no longer mandatories from aspect of whole rule. Below code- * mainly handles this logic.- */- Map<String, List<ElementCompletion>> grouped = new LinkedHashMap<>();- for (ElementCompletion elementCompletion: suggest(rule, inputStatus, count)) {- /*- * key will be the new input (without considering mandatories of course), and we use- * this to group suggestions to facilitate mandatories calculation and exclusion- * logic- */- String key = inputContent.substring(0, elementCompletion.getReplaceBegin())- + elementCompletion.getReplaceContent() + inputContent.substring(elementCompletion.getReplaceEnd());- List<ElementCompletion> value = grouped.get(key);- if (value == null) {- value = new ArrayList<>();- grouped.put(key, value);- }- value.add(elementCompletion);- }-- for (Map.Entry<String, List<ElementCompletion>> entry: grouped.entrySet()) {- List<ElementCompletion> value = entry.getValue();- ElementCompletion completion = value.get(0);- String description = completion.getDescription();- String content = entry.getKey();-- /*- * only append mandatory literals if suggested content is complete and it does not- * replace any part of current input. We do not append mandatories in the latter case- * as most probably they already exist in the current input- */- if (completion.isComplete() && completion.getReplaceEnd() == inputStatus.getCaret()) {- List<String> contents = new ArrayList<>();- for (ElementCompletion each: value) {- content = inputContent.substring(0, each.getReplaceBegin()) + each.getReplaceContent();- ParentedElement parentElement = each.getExpectedElement().getParent();- ElementSpec elementSpec = each.getExpectedElement().getSpec();- for (String mandatory: getMandatoriesAfter(parentElement, elementSpec)) {- String prevContent = content;- content += mandatory;-- if (grammar.getTokenTypeByLiteral(mandatory) != null) {- /*- * if mandatory can be appended without space, the last token- * position should remain unchanged in concatenated content- */- List<Token> tokens = grammar.lex(content);- if (!tokens.isEmpty()) {- Token lastToken = tokens.get(tokens.size()-1);- if (lastToken.getStartIndex() != content.length() - mandatory.length()- || lastToken.getStopIndex() != content.length()-1) {- content = prevContent + " " + mandatory;- }- } else {- content = prevContent + " " + mandatory;- }- }- }- content += inputContent.substring(each.getReplaceEnd());-- if (contents.isEmpty()) {- contents.add(content);- } else if (!contents.get(contents.size()-1).equals(content)) {- content = entry.getKey();- break;- }- }- }-- /*- * Adjust caret to move it to next place expecting user input if suggestion is- * complete, that is, we move it after all mandatory tokens after the replacement,- * unless user puts caret explicitly in the middle of replacement via suggestion,- * indicating the replacement has some place holders expecting user input.- */- int caret = completion.getCaret();- if (completion.isComplete() && caret == -1) {- // caret is not at the middle of replacement, so we need to move it to- // be after mandatory tokens if provided suggestion is complete- caret = content.length() - inputContent.length() + completion.getReplaceEnd();- if (content.equals(entry.getKey())) {- // in case mandatory tokens are not added after replacement,- // we skip existing mandatory tokens in current input- String contentAfterCaret = content.substring(caret);- ParentedElement parentElement = completion.getExpectedElement().getParent();- ElementSpec elementSpec = completion.getExpectedElement().getSpec();- caret += skipMandatories(contentAfterCaret, getMandatoriesAfter(parentElement, elementSpec));- }- } else {- if (caret == -1)- caret = completion.getReplaceContent().length();- caret += completion.getReplaceBegin();- }-- String replaceContent = content.substring(completion.getReplaceBegin(),- content.length()-inputContent.length()+completion.getReplaceEnd());- inputCompletions.add(new InputCompletion(completion.getReplaceBegin(),- completion.getReplaceEnd(), replaceContent, caret, description,- completion.getMatchRange()));- }-- /*- * remove duplicate suggestions and suggestions the same as current input- */- Set<String> suggestedContents = Sets.newHashSet(inputStatus.getContent());- for (Iterator<InputCompletion> it = inputCompletions.iterator(); it.hasNext();) {- String content = it.next().complete(inputStatus).getContent();- if (suggestedContents.contains(content))- it.remove();- else- suggestedContents.add(content);- }- return inputCompletions;- }-- private ParentedElement getElementExpectingTerminal(ParentedElement parent, Element element) {- parent = new ParentedElement(parent, element);- State state = element.getState();- if (state != null) {- // the last element is always the element assumed completed- element = state.getElements().get(state.getElements().size()-1);- return getElementExpectingTerminal(parent, element);- } else {- return parent;- }- }-- private void assumeCompleted(EarleyParser parser, State state, int position, Set<State> statesAssumeCompleted) {- Chart startChart = parser.getCharts().get(state.getOriginPosition());- for (State startState: startChart.getStates()) {- if (!startState.isCompleted()) {- ElementSpec nextElement = startState.getExpectedElementSpec();- if (nextElement instanceof RuleRefElementSpec) {- RuleRefElementSpec ruleRefElement = (RuleRefElementSpec) nextElement;- if (ruleRefElement.getRuleName().equals(state.getRuleSpec().getName())) {- List<Element> elements = new ArrayList<>(startState.getElements());- elements.add(new Element(parser, ruleRefElement, position, state));- State parentState = new State(startState.getOriginPosition(),- startState.getRuleSpec(), startState.getAlternativeSpecIndex(),- startState.getExpectedElementSpecIndex(),- startState.isExpectedElementSpecMatchedOnce(),- elements);- if (statesAssumeCompleted.add(parentState))- assumeCompleted(parser, parentState, position, statesAssumeCompleted);- }- }- }- }- }-- private List<List<ParentedElement>> getExpectChains(Chart chart) {- int position = chart.getPosition();- EarleyParser parser = chart.getParser();- List<List<ParentedElement>> expectChains = new ArrayList<>();- for (State stateExpectingTerminal: chart.getStatesExpectingTerminal()) {- List<Element> elements = new ArrayList<>(stateExpectingTerminal.getElements());- elements.add(new Element(parser, stateExpectingTerminal.getExpectedElementSpec(), 0, null));- stateExpectingTerminal = new State(stateExpectingTerminal.getOriginPosition(), stateExpectingTerminal.getRuleSpec(),- stateExpectingTerminal.getAlternativeSpecIndex(), stateExpectingTerminal.getExpectedElementSpecIndex(),- stateExpectingTerminal.isExpectedElementSpecMatchedOnce(), elements);-- /*- * Calculate all states assuming completed, this way we can get to the root state to- * construct a partial parse tree to provide suggestion contexts- */- Set<State> statesAssumeCompleted = new HashSet<>();- if (statesAssumeCompleted.add(stateExpectingTerminal))- assumeCompleted(parser, stateExpectingTerminal, position, statesAssumeCompleted);-- for (State stateAssumeCompleted: statesAssumeCompleted) {- if (stateAssumeCompleted.getRuleSpec().getName().equals(parser.getRule().getName())- && stateAssumeCompleted.getOriginPosition() == 0) {- Element rootElement = new Element(parser, null, position, stateAssumeCompleted);- List<ParentedElement> expectChain = new ArrayList<>();-- ParentedElement elementExpectingTerminal = getElementExpectingTerminal(null, rootElement);- expectChain.add(elementExpectingTerminal);-- /*- * Find out all parent elements not containing any matched tokens, and we will- * ask if there are suggestions for these parent elements later. For instance,- * if we input "Math.", we can provide suggestion for whole method element like- * "max(a, b)"; otherwise, we can only provide suggestion for method name "max".- */- ParentedElement expectedElement = elementExpectingTerminal.getParent();- while (expectedElement != null) {- if (expectedElement.getState().getElements().size() == 1) {- expectChain.add(expectedElement);- expectedElement = expectedElement.getParent();- } else {- break;- }- }-- expectChains.add(expectChain);- }- }- }- return expectChains;- }-- private String getMatchWith(Chart chart, InputStatus inputStatus) {- String matchWith;- Token token = chart.getOriginatingToken();- if (token != null) {- int endCharIndex = token.getStopIndex()+1;- matchWith = inputStatus.getContent().substring(endCharIndex, inputStatus.getCaret());- } else {- matchWith = inputStatus.getContentBeforeCaret();- }- return StringUtils.trimStart(matchWith);- }-- private List<ElementSuggestion> suggest(Chart chart, InputStatus inputStatus, int count) {- List<ElementSuggestion> suggestions = new ArrayList<>();- String matchWith = getMatchWith(chart, inputStatus);-- for (List<ParentedElement> expectChain: getExpectChains(chart)) {- // goes through the expect chain to check if there are suggestions for expected element- List<InputSuggestion> inputSuggestions = null;- for (ParentedElement element: expectChain) {- inputSuggestions = suggest(element, matchWith, count);- if (inputSuggestions != null) {- for (Iterator<InputSuggestion> it = inputSuggestions.iterator(); it.hasNext();) {- InputSuggestion suggestion = it.next();- if (suggestion.getContent().length() != 0 && suggestion.getContent().equals(matchWith))- it.remove();- }- if (!inputSuggestions.isEmpty())- suggestions.add(new ElementSuggestion(element, matchWith, inputSuggestions));- break;- }- }-- ParentedElement elementExpectingTerminal = expectChain.get(0);- // no suggestions, let's see if we can provide some default suggestions- if (inputSuggestions == null && elementExpectingTerminal.getSpec() instanceof TokenElementSpec) {- inputSuggestions = new ArrayList<>();- TokenElementSpec spec = (TokenElementSpec) elementExpectingTerminal.getSpec();- for (String leadingLiteral: spec.getPossiblePrefixes()) {- if (leadingLiteral.startsWith(matchWith) && leadingLiteral.length()>matchWith.length()) {- List<Token> tokens = grammar.lex(leadingLiteral);- boolean complete = tokens.size() == 1 && tokens.get(0).getType() == spec.getTokenType();- InputSuggestion suggestion = wrapAsSuggestion(elementExpectingTerminal, leadingLiteral, complete);- if (suggestion != null)- inputSuggestions.add(suggestion);- }- }- if (!inputSuggestions.isEmpty())- suggestions.add(new ElementSuggestion(elementExpectingTerminal, matchWith, inputSuggestions));- }- }-- // sort suggestions to make it the same order as appearing in grammar definition- Collections.sort(suggestions, new Comparator<ElementSuggestion>() {-- @Override- public int compare(ElementSuggestion suggestion1, ElementSuggestion suggestion2) {- ParentedElement root1 = suggestion1.getExpectedElement().getRoot();- ParentedElement root2 = suggestion2.getExpectedElement().getRoot();- return compare(root1, root2);- }-- private int compare(Element element1, Element element2) {- Preconditions.checkState(element1.getState() != null && element2.getState() != null);- int alternativeSpecIndex1 = element1.getState().getAlternativeSpecIndex();- int alternativeSpecIndex2 = element2.getState().getAlternativeSpecIndex();- if (alternativeSpecIndex1 != alternativeSpecIndex2)- return alternativeSpecIndex1 - alternativeSpecIndex2;- int expectedElementSpecIndex1 = element1.getState().getExpectedElementSpecIndex();- int expectedElementSpecIndex2 = element2.getState().getExpectedElementSpecIndex();- if (expectedElementSpecIndex1 != expectedElementSpecIndex2)- return expectedElementSpecIndex1 - expectedElementSpecIndex2;- element1 = element1.getState().getElements().get(element1.getState().getElements().size()-1);- element2 = element2.getState().getElements().get(element2.getState().getElements().size()-1);- if (element1.getState() == null || element2.getState() == null)- return 0;- else- return compare(element1, element2);- }-- });- return suggestions;- }-- private List<Chart> getTerminatingCharts(EarleyParser parser) {- List<Chart> terminatingCharts = new ArrayList<>();-- if (parser.getCharts().size() >= 1)- terminatingCharts.add(parser.getCharts().get(parser.getCharts().size()-1));-- /*- * do another match by not considering the last matched token. This is useful- * for below cases:- * 1. when the last token matches either a keyword or part of an identifier.- * For instance, the last token can be keyword 'for', but can also match- * identifier 'forme' if the spec allows.- * 2. assume we have a query rule containing multiple criterias, with each- * criteria composed of key/value pair key:value. value needs to be quoted- * if it contains spaces. In this case, we want to achieve the effect that- * if user input value containing spaces without surrounding quotes, we- * suggest the user to quote the value.- */- if (parser.getCharts().size() >= 2)- terminatingCharts.add(parser.getCharts().get(parser.getCharts().size()-2));-- return terminatingCharts;- }-- private List<ElementCompletion> suggest(RuleSpec spec, InputStatus inputStatus, int count) {- List<ElementCompletion> completions = new ArrayList<>();-- List<ElementSuggestion> suggestions = new ArrayList<>();-- List<Token> tokens = grammar.lex(inputStatus.getContentBeforeCaret());- EarleyParser parser = new EarleyParser(spec, tokens);-- for (Chart chart: getTerminatingCharts(parser))- suggestions.addAll(suggest(chart, inputStatus, count));-- String inputContent = inputStatus.getContent();- for (ElementSuggestion suggestion: suggestions) {- int replaceBegin = inputStatus.getCaret() - suggestion.getMatchWith().length();- int replaceEnd = inputStatus.getCaret();-- /*- * if input around the caret matches spec of the suggestion, we then replace- * the matched text with suggestion, instead of simply inserting the- * suggested content- */- ElementSpec elementSpec = suggestion.getExpectedElement().getSpec();- String contentAfterReplaceBegin = inputContent.substring(replaceBegin);-- int endOfMatch = getEndOfMatch(elementSpec, contentAfterReplaceBegin) + replaceBegin;- tokens = grammar.lex(contentAfterReplaceBegin);- if (endOfMatch > replaceEnd)- replaceEnd = endOfMatch;-- String before = inputContent.substring(0, replaceBegin);-- for (InputSuggestion inputSuggestion: suggestion.getInputSuggestions()) {- int position = suggestion.getExpectedElement().getRoot().getPosition();- if (position != 0) {- int lastMatchedTokenIndex = position-1;- Token lastMatchedToken = parser.getTokens().get(lastMatchedTokenIndex);- tokens = grammar.lex(before + inputSuggestion.getContent());-- /*- * ignore the suggestion if we can not append the suggested content directly.- * This normally indicates that a space is required before the suggestion,- * and we will show the suggestion when user presses the space to make the- * suggestion list less confusing- */- if (tokens.size() > lastMatchedTokenIndex) {- Token newToken = tokens.get(lastMatchedTokenIndex);- if (lastMatchedToken.getStartIndex() != newToken.getStartIndex()- || lastMatchedToken.getStopIndex() != newToken.getStopIndex()) {- continue;- }- } else {- continue;- }- }-- completions.add(new ElementCompletion(suggestion.getExpectedElement(), replaceBegin,- // replace only if provided suggestion is a complete representation of the element- inputSuggestion.isComplete()?replaceEnd:inputStatus.getCaret(),- inputSuggestion.getContent(), inputSuggestion.getCaret(),- inputSuggestion.isComplete(), inputSuggestion.getDescription(),- inputSuggestion.getMatchRange()));- }- }- return completions;- }-- private int skipMandatories(String content, List<String> mandatories) {- String mandatory = StringUtils.join(mandatories, "");- mandatory = StringUtils.deleteWhitespace(mandatory);- if (mandatory.length() != 0 && content.length() != 0) {- int mandatoryIndex = 0;- int contentIndex = 0;- while (true) {- char contentChar = content.charAt(contentIndex);- /*- * space may exist between mandatories in user input, but should- * not exist in ANTLR grammar- */- if (!Character.isWhitespace(contentChar)) {- if (contentChar != mandatory.charAt(mandatoryIndex))- break;- mandatoryIndex++;- }- contentIndex++;- if (mandatoryIndex == mandatory.length() || contentIndex == content.length())- break;- }- if (mandatoryIndex == mandatory.length())- return contentIndex;- else- return 0;- } else {- return 0;- }- }-- /*- * Get mandatory literals after specified element. For instance a method may have- * below rule:- * methodName '(' argList ')'- * The mandatories after element methodName will be '('. When a method name is- * suggested, we should add '(' and moves caret after '(' to avoid unnecessary- * key strokes- */- private List<String> getMandatoriesAfter(ParentedElement parentElement, ElementSpec elementSpec) {- List<String> literals = new ArrayList<>();- if (parentElement != null && elementSpec != null && !elementSpec.isMultiple()) {- AlternativeSpec alternativeSpec = parentElement.getState().getAlternativeSpec();- int specIndex = alternativeSpec.getElements().indexOf(elementSpec);- if (specIndex == alternativeSpec.getElements().size()-1) {- elementSpec = parentElement.getSpec();- parentElement = parentElement.getParent();- return getMandatoriesAfter(parentElement, elementSpec);- } else {- elementSpec = alternativeSpec.getElements().get(specIndex+1);- if (!elementSpec.isOptional()) {- MandatoryScan scan = elementSpec.scanMandatories();- literals = scan.getMandatories();- if (!scan.isStop())- literals.addAll(getMandatoriesAfter(parentElement, elementSpec));- }- }- }- return literals;- }-- public Grammar getGrammar() {- return grammar;- }-- /**- * Provide suggestions for expected element matching specified string- *- * @param expectedElement- * the element to expect.- * @param matchWith- * the string the suggestion has to match with- * @param count- * maximum number of suggestions to return- * @return- * a list of suggestions. If you do not have any suggestions and want code assist to- * drill down the element to provide default suggestions, return a <tt>null</tt> value- * instead of an empty list- */- @Nullable- protected abstract List<InputSuggestion> suggest(ParentedElement expectedElement, String matchWith, int count);-- protected List<String> getHints(ParentedElement expectedElement, String matchWith) {- return new ArrayList<>();- }-- /**- * Get index of next character after the match.- *- * @param spec- * spec to be matched- * @param content- * content to match against- * @return- * index of next character after the match, or 0 if the rule- * does not match any part of the string- */- protected int getEndOfMatch(ElementSpec spec, String content) {- int endOfMatch = 0;- List<Token> tokens = grammar.lex(content);- if (!tokens.isEmpty() && tokens.get(0).getStartIndex() == 0) {- endOfMatch = spec.getEndOfMatch(tokens);- if (endOfMatch > 0) // there exist an element match- endOfMatch = tokens.get(endOfMatch-1).getStopIndex()+1; // convert to char index- }- return endOfMatch;- }-- /**- * Wrap specified literal of specified terminal element as suggestion.- *- * @param expectedElement- * terminal element expecting to be matched next- * @param suggestedLiteral- * a proposed literal of above terminal element defined in grammar- * @param complete- * whether or not above literal is a complete representation of the- * expected terminal element- * @return- * suggestion of the literal, or <tt>null</tt> to suppress this suggestion- */- @Nullable- protected InputSuggestion wrapAsSuggestion(ParentedElement expectedElement,- String suggestedLiteral, boolean complete) {- return new InputSuggestion(suggestedLiteral, -1, complete, null, null);- }--}+package com.pmease.commons.antlr.codeassist;++import java.io.Serializable;+import java.util.ArrayList;+import java.util.Collections;+import java.util.Comparator;+import java.util.HashSet;+import java.util.Iterator;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;++import javax.annotation.Nullable;++import org.antlr.v4.runtime.Lexer;+import org.antlr.v4.runtime.Token;++import com.google.common.base.Preconditions;+import com.google.common.collect.Sets;+import com.pmease.commons.antlr.grammar.AlternativeSpec;+import com.pmease.commons.antlr.grammar.ElementSpec;+import com.pmease.commons.antlr.grammar.Grammar;+import com.pmease.commons.antlr.grammar.RuleRefElementSpec;+import com.pmease.commons.antlr.grammar.RuleSpec;+import com.pmease.commons.antlr.grammar.TokenElementSpec;+import com.pmease.commons.antlr.parser.EarleyParser;+import com.pmease.commons.antlr.parser.Element;+import com.pmease.commons.antlr.parser.State;+import com.pmease.commons.antlr.parser.Chart;+import com.pmease.commons.util.StringUtils;++public abstract class CodeAssist implements Serializable {++ private static final long serialVersionUID = 1L;++ private final Grammar grammar;++ public CodeAssist(Grammar grammar) {+ this.grammar = grammar;+ }++ /**+ * Code assist constructor+ * @param lexerClass+ * lexer class to be used to lex code. Other required information such as+ * grammar files and token file will be derived from the lexer class+ */+ public CodeAssist(Class<? extends Lexer> lexerClass) {+ this(new Grammar(lexerClass));+ }++ /**+ * Code assist constructor.+ *+ * @param lexerClass+ * lexer class to be used to lex code+ * @param grammarFiles+ * grammar files in class path, relative to class path root+ * @param tokenFile+ * generated tokens file in class path, relative to class path root+ */+ public CodeAssist(Class<? extends Lexer> lexerClass, String grammarFiles[], String tokenFile) {+ this(new Grammar(lexerClass, grammarFiles, tokenFile));+ }++ public List<String> getHints(InputStatus inputStatus, String ruleName) {+ RuleSpec rule = Preconditions.checkNotNull(grammar.getRule(ruleName));+ List<Token> tokens = grammar.lex(inputStatus.getContentBeforeCaret());+ EarleyParser parser = new EarleyParser(rule, tokens);++ List<String> hints = new ArrayList<>();+ for (Chart chart: getTerminatingCharts(parser)) {+ String matchWith = getMatchWith(chart, inputStatus);+ for (List<ParentedElement> expectChain: getExpectChains(chart)) {+ for (ParentedElement element: expectChain)+ hints.addAll(getHints(element, matchWith));+ }+ }+ return hints;+ }++ public List<InputCompletion> suggest(InputStatus inputStatus, String ruleName, int count) {+ RuleSpec rule = Preconditions.checkNotNull(grammar.getRule(ruleName));++ String inputContent = inputStatus.getContent();+ List<InputCompletion> inputCompletions = new ArrayList<>();++ /*+ * Mandatory literals may come after a suggestion (for instance if a method name is suggested,+ * the character '(' can be a mandatory literal), so for every suggestion, we need to+ * append mandatory literals to make user typing less, however if a suggested text has two or+ * more different mandatories (this is possible if the suggested text comes from different+ * element specs, and each spec calculates a different set of mandatories after the text), we+ * should display the suggested text as a single entry in the final suggestion list without+ * appending mandatories they are no longer mandatories from aspect of whole rule. Below code+ * mainly handles this logic.+ */+ Map<String, List<ElementCompletion>> grouped = new LinkedHashMap<>();+ for (ElementCompletion elementCompletion: suggest(rule, inputStatus, count)) {+ /*+ * key will be the new input (without considering mandatories of course), and we use+ * this to group suggestions to facilitate mandatories calculation and exclusion+ * logic+ */+ String key = inputContent.substring(0, elementCompletion.getReplaceBegin())+ + elementCompletion.getReplaceContent() + inputContent.substring(elementCompletion.getReplaceEnd());+ List<ElementCompletion> value = grouped.get(key);+ if (value == null) {+ value = new ArrayList<>();+ grouped.put(key, value);+ }+ value.add(elementCompletion);+ }++ for (Map.Entry<String, List<ElementCompletion>> entry: grouped.entrySet()) {+ List<ElementCompletion> value = entry.getValue();+ ElementCompletion completion = value.get(0);+ String description = completion.getDescription();+ String content = entry.getKey();++ /*+ * only append mandatory literals if suggested content is complete and it does not+ * replace any part of current input. We do not append mandatories in the latter case+ * as most probably they already exist in the current input+ */+ if (completion.isComplete() && completion.getReplaceEnd() == inputStatus.getCaret()) {+ List<String> contents = new ArrayList<>();+ for (ElementCompletion each: value) {+ content = inputContent.substring(0, each.getReplaceBegin()) + each.getReplaceContent();+ ParentedElement parentElement = each.getExpectedElement().getParent();+ ElementSpec elementSpec = each.getExpectedElement().getSpec();+ for (String mandatory: getMandatoriesAfter(parentElement, elementSpec)) {+ String prevContent = content;+ content += mandatory;++ if (grammar.getTokenTypeByLiteral(mandatory) != null) {+ /*+ * if mandatory can be appended without space, the last token+ * position should remain unchanged in concatenated content+ */+ List<Token> tokens = grammar.lex(content);+ if (!tokens.isEmpty()) {+ Token lastToken = tokens.get(tokens.size()-1);+ if (lastToken.getStartIndex() != content.length() - mandatory.length()+ || lastToken.getStopIndex() != content.length()-1) {+ content = prevContent + " " + mandatory;+ }+ } else {+ content = prevContent + " " + mandatory;+ }+ }+ }+ content += inputContent.substring(each.getReplaceEnd());++ if (contents.isEmpty()) {+ contents.add(content);+ } else if (!contents.get(contents.size()-1).equals(content)) {+ content = entry.getKey();+ break;+ }+ }+ }++ /*+ * Adjust caret to move it to next place expecting user input if suggestion is+ * complete, that is, we move it after all mandatory tokens after the replacement,+ * unless user puts caret explicitly in the middle of replacement via suggestion,+ * indicating the replacement has some place holders expecting user input.+ */+ int caret = completion.getCaret();+ if (completion.isComplete() && caret == -1) {+ // caret is not at the middle of replacement, so we need to move it to+ // be after mandatory tokens if provided suggestion is complete+ caret = content.length() - inputContent.length() + completion.getReplaceEnd();+ if (content.equals(entry.getKey())) {+ // in case mandatory tokens are not added after replacement,+ // we skip existing mandatory tokens in current input+ String contentAfterCaret = content.substring(caret);+ ParentedElement parentElement = completion.getExpectedElement().getParent();+ ElementSpec elementSpec = completion.getExpectedElement().getSpec();+ caret += skipMandatories(contentAfterCaret, getMandatoriesAfter(parentElement, elementSpec));+ }+ } else {+ if (caret == -1)+ caret = completion.getReplaceContent().length();+ caret += completion.getReplaceBegin();+ }++ String replaceContent = content.substring(completion.getReplaceBegin(),+ content.length()-inputContent.length()+completion.getReplaceEnd());+ inputCompletions.add(new InputCompletion(completion.getReplaceBegin(),+ completion.getReplaceEnd(), replaceContent, caret, description,+ completion.getMatchRange()));+ }++ /*+ * remove duplicate suggestions and suggestions the same as current input+ */+ Set<String> suggestedContents = Sets.newHashSet(inputStatus.getContent());+ for (Iterator<InputCompletion> it = inputCompletions.iterator(); it.hasNext();) {+ String content = it.next().complete(inputStatus).getContent();+ if (suggestedContents.contains(content))+ it.remove();+ else+ suggestedContents.add(content);+ }+ return inputCompletions;+ }++ private ParentedElement getElementExpectingTerminal(ParentedElement parent, Element element) {+ parent = new ParentedElement(parent, element);+ State state = element.getState();+ if (state != null) {+ // the last element is always the element assumed completed+ element = state.getElements().get(state.getElements().size()-1);+ return getElementExpectingTerminal(parent, element);+ } else {+ return parent;+ }+ }++ private void assumeCompleted(EarleyParser parser, State state, int position, Set<State> statesAssumeCompleted) {+ Chart startChart = parser.getCharts().get(state.getOriginPosition());+ for (State startState: startChart.getStates()) {+ if (!startState.isCompleted()) {+ ElementSpec nextElement = startState.getExpectedElementSpec();+ if (nextElement instanceof RuleRefElementSpec) {+ RuleRefElementSpec ruleRefElement = (RuleRefElementSpec) nextElement;+ if (ruleRefElement.getRuleName().equals(state.getRuleSpec().getName())) {+ List<Element> elements = new ArrayList<>(startState.getElements());+ elements.add(new Element(parser, ruleRefElement, position, state));+ State parentState = new State(startState.getOriginPosition(),+ startState.getRuleSpec(), startState.getAlternativeSpecIndex(),+ startState.getExpectedElementSpecIndex(),+ startState.isExpectedElementSpecMatchedOnce(),+ elements);+ if (statesAssumeCompleted.add(parentState))+ assumeCompleted(parser, parentState, position, statesAssumeCompleted);+ }+ }+ }+ }+ }++ private List<List<ParentedElement>> getExpectChains(Chart chart) {+ int position = chart.getPosition();+ EarleyParser parser = chart.getParser();+ List<List<ParentedElement>> expectChains = new ArrayList<>();+ for (State stateExpectingTerminal: chart.getStatesExpectingTerminal()) {+ List<Element> elements = new ArrayList<>(stateExpectingTerminal.getElements());+ elements.add(new Element(parser, stateExpectingTerminal.getExpectedElementSpec(), 0, null));+ stateExpectingTerminal = new State(stateExpectingTerminal.getOriginPosition(), stateExpectingTerminal.getRuleSpec(),+ stateExpectingTerminal.getAlternativeSpecIndex(), stateExpectingTerminal.getExpectedElementSpecIndex(),+ stateExpectingTerminal.isExpectedElementSpecMatchedOnce(), elements);++ /*+ * Calculate all states assuming completed, this way we can get to the root state to+ * construct a partial parse tree to provide suggestion contexts+ */+ Set<State> statesAssumeCompleted = new HashSet<>();+ if (statesAssumeCompleted.add(stateExpectingTerminal))+ assumeCompleted(parser, stateExpectingTerminal, position, statesAssumeCompleted);++ for (State stateAssumeCompleted: statesAssumeCompleted) {+ if (stateAssumeCompleted.getRuleSpec().getName().equals(parser.getRule().getName())+ && stateAssumeCompleted.getOriginPosition() == 0) {+ Element rootElement = new Element(parser, null, position, stateAssumeCompleted);+ List<ParentedElement> expectChain = new ArrayList<>();++ ParentedElement elementExpectingTerminal = getElementExpectingTerminal(null, rootElement);+ expectChain.add(elementExpectingTerminal);++ /*+ * Find out all parent elements not containing any matched tokens, and we will+ * ask if there are suggestions for these parent elements later. For instance,+ * if we input "Math.", we can provide suggestion for whole method element like+ * "max(a, b)"; otherwise, we can only provide suggestion for method name "max".+ */+ ParentedElement expectedElement = elementExpectingTerminal.getParent();+ while (expectedElement != null) {+ if (expectedElement.getState().getElements().size() == 1) {+ expectChain.add(expectedElement);+ expectedElement = expectedElement.getParent();+ } else {+ break;+ }+ }++ expectChains.add(expectChain);+ }+ }+ }+ return expectChains;+ }++ private String getMatchWith(Chart chart, InputStatus inputStatus) {+ String matchWith;+ Token token = chart.getOriginatingToken();+ if (token != null) {+ int endCharIndex = token.getStopIndex()+1;+ matchWith = inputStatus.getContent().substring(endCharIndex, inputStatus.getCaret());+ } else {+ matchWith = inputStatus.getContentBeforeCaret();+ }+ return StringUtils.trimStart(matchWith);+ }++ private List<ElementSuggestion> suggest(Chart chart, InputStatus inputStatus, int count) {+ List<ElementSuggestion> suggestions = new ArrayList<>();+ String matchWith = getMatchWith(chart, inputStatus);++ for (List<ParentedElement> expectChain: getExpectChains(chart)) {+ // goes through the expect chain to check if there are suggestions for expected element+ List<InputSuggestion> inputSuggestions = null;+ for (ParentedElement element: expectChain) {+ inputSuggestions = suggest(element, matchWith, count);+ if (inputSuggestions != null) {+ for (Iterator<InputSuggestion> it = inputSuggestions.iterator(); it.hasNext();) {+ InputSuggestion suggestion = it.next();+ if (suggestion.getContent().length() != 0 && suggestion.getContent().equals(matchWith))+ it.remove();+ }+ if (!inputSuggestions.isEmpty())+ suggestions.add(new ElementSuggestion(element, matchWith, inputSuggestions));+ break;+ }+ }++ ParentedElement elementExpectingTerminal = expectChain.get(0);+ // no suggestions, let's see if we can provide some default suggestions+ if (inputSuggestions == null && elementExpectingTerminal.getSpec() instanceof TokenElementSpec) {+ inputSuggestions = new ArrayList<>();+ TokenElementSpec spec = (TokenElementSpec) elementExpectingTerminal.getSpec();+ for (String leadingLiteral: spec.getPossiblePrefixes()) {+ if (leadingLiteral.startsWith(matchWith) && leadingLiteral.length()>matchWith.length()) {+ List<Token> tokens = grammar.lex(leadingLiteral);+ boolean complete = tokens.size() == 1 && tokens.get(0).getType() == spec.getTokenType();+ InputSuggestion suggestion = wrapAsSuggestion(elementExpectingTerminal, leadingLiteral, complete);+ if (suggestion != null)+ inputSuggestions.add(suggestion);+ }+ }+ if (!inputSuggestions.isEmpty())+ suggestions.add(new ElementSuggestion(elementExpectingTerminal, matchWith, inputSuggestions));+ }+ }++ // sort suggestions to make it the same order as appearing in grammar definition+ Collections.sort(suggestions, new Comparator<ElementSuggestion>() {++ @Override+ public int compare(ElementSuggestion suggestion1, ElementSuggestion suggestion2) {+ ParentedElement root1 = suggestion1.getExpectedElement().getRoot();+ ParentedElement root2 = suggestion2.getExpectedElement().getRoot();+ return compare(root1, root2);+ }++ private int compare(Element element1, Element element2) {+ Preconditions.checkState(element1.getState() != null && element2.getState() != null);+ int alternativeSpecIndex1 = element1.getState().getAlternativeSpecIndex();+ int alternativeSpecIndex2 = element2.getState().getAlternativeSpecIndex();+ if (alternativeSpecIndex1 != alternativeSpecIndex2)+ return alternativeSpecIndex1 - alternativeSpecIndex2;+ int expectedElementSpecIndex1 = element1.getState().getExpectedElementSpecIndex();+ int expectedElementSpecIndex2 = element2.getState().getExpectedElementSpecIndex();+ if (expectedElementSpecIndex1 != expectedElementSpecIndex2)+ return expectedElementSpecIndex1 - expectedElementSpecIndex2;+ element1 = element1.getState().getElements().get(element1.getState().getElements().size()-1);+ element2 = element2.getState().getElements().get(element2.getState().getElements().size()-1);+ if (element1.getState() == null || element2.getState() == null)+ return 0;+ else+ return compare(element1, element2);+ }++ });+ return suggestions;+ }++ private List<Chart> getTerminatingCharts(EarleyParser parser) {+ List<Chart> terminatingCharts = new ArrayList<>();++ if (parser.getCharts().size() >= 1)+ terminatingCharts.add(parser.getCharts().get(parser.getCharts().size()-1));++ /*+ * do another match by not considering the last matched token. This is useful+ * for below cases:+ * 1. when the last token matches either a keyword or part of an identifier.+ * For instance, the last token can be keyword 'for', but can also match+ * identifier 'forme' if the spec allows.+ * 2. assume we have a query rule containing multiple criterias, with each+ * criteria composed of key/value pair key:value. value needs to be quoted+ * if it contains spaces. In this case, we want to achieve the effect that+ * if user input value containing spaces without surrounding quotes, we+ * suggest the user to quote the value.+ */+ if (parser.getCharts().size() >= 2)+ terminatingCharts.add(parser.getCharts().get(parser.getCharts().size()-2));++ return terminatingCharts;+ }++ private List<ElementCompletion> suggest(RuleSpec spec, InputStatus inputStatus, int count) {+ List<ElementCompletion> completions = new ArrayList<>();++ List<ElementSuggestion> suggestions = new ArrayList<>();++ List<Token> tokens = grammar.lex(inputStatus.getContentBeforeCaret());+ EarleyParser parser = new EarleyParser(spec, tokens);++ for (Chart chart: getTerminatingCharts(parser))+ suggestions.addAll(suggest(chart, inputStatus, count));++ String inputContent = inputStatus.getContent();+ for (ElementSuggestion suggestion: suggestions) {+ int replaceBegin = inputStatus.getCaret() - suggestion.getMatchWith().length();+ int replaceEnd = inputStatus.getCaret();++ /*+ * if input around the caret matches spec of the suggestion, we then replace+ * the matched text with suggestion, instead of simply inserting the+ * suggested content+ */+ ElementSpec elementSpec = suggestion.getExpectedElement().getSpec();+ String contentAfterReplaceBegin = inputContent.substring(replaceBegin);++ int endOfMatch = getEndOfMatch(elementSpec, contentAfterReplaceBegin) + replaceBegin;+ tokens = grammar.lex(contentAfterReplaceBegin);+ if (endOfMatch > replaceEnd)+ replaceEnd = endOfMatch;++ String before = inputContent.substring(0, replaceBegin);++ for (InputSuggestion inputSuggestion: suggestion.getInputSuggestions()) {+ int position = suggestion.getExpectedElement().getRoot().getPosition();+ if (position != 0) {+ int lastMatchedTokenIndex = position-1;+ Token lastMatchedToken = parser.getTokens().get(lastMatchedTokenIndex);+ tokens = grammar.lex(before + inputSuggestion.getContent());++ /*+ * ignore the suggestion if we can not append the suggested content directly.+ * This normally indicates that a space is required before the suggestion,+ * and we will show the suggestion when user presses the space to make the+ * suggestion list less confusing+ */+ if (tokens.size() > lastMatchedTokenIndex) {+ Token newToken = tokens.get(lastMatchedTokenIndex);+ if (lastMatchedToken.getStartIndex() != newToken.getStartIndex()+ || lastMatchedToken.getStopIndex() != newToken.getStopIndex()) {+ continue;+ }+ } else {+ continue;+ }+ }++ completions.add(new ElementCompletion(suggestion.getExpectedElement(), replaceBegin,+ // replace only if provided suggestion is a complete representation of the element+ inputSuggestion.isComplete()?replaceEnd:inputStatus.getCaret(),+ inputSuggestion.getContent(), inputSuggestion.getCaret(),+ inputSuggestion.isComplete(), inputSuggestion.getDescription(),+ inputSuggestion.getMatchRange()));+ }+ }+ return completions;+ }++ private int skipMandatories(String content, List<String> mandatories) {+ String mandatory = StringUtils.join(mandatories, "");+ mandatory = StringUtils.deleteWhitespace(mandatory);+ if (mandatory.length() != 0 && content.length() != 0) {+ int mandatoryIndex = 0;+ int contentIndex = 0;+ while (true) {+ char contentChar = content.charAt(contentIndex);+ /*+ * space may exist between mandatories in user input, but should+ * not exist in ANTLR grammar+ */+ if (!Character.isWhitespace(contentChar)) {+ if (contentChar != mandatory.charAt(mandatoryIndex))+ break;+ mandatoryIndex++;+ }+ contentIndex++;+ if (mandatoryIndex == mandatory.length() || contentIndex == content.length())+ break;+ }+ if (mandatoryIndex == mandatory.length())+ return contentIndex;+ else+ return 0;+ } else {+ return 0;+ }+ }++ /*+ * Get mandatory literals after specified element. For instance a method may have+ * below rule:+ * methodName '(' argList ')'+ * The mandatories after element methodName will be '('. When a method name is+ * suggested, we should add '(' and moves caret after '(' to avoid unnecessary+ * key strokes+ */+ private List<String> getMandatoriesAfter(ParentedElement parentElement, ElementSpec elementSpec) {+ List<String> literals = new ArrayList<>();+ if (parentElement != null && elementSpec != null && !elementSpec.isMultiple()) {+ AlternativeSpec alternativeSpec = parentElement.getState().getAlternativeSpec();+ int specIndex = alternativeSpec.getElements().indexOf(elementSpec);+ if (specIndex == alternativeSpec.getElements().size()-1) {+ elementSpec = parentElement.getSpec();+ parentElement = parentElement.getParent();+ return getMandatoriesAfter(parentElement, elementSpec);+ } else {+ elementSpec = alternativeSpec.getElements().get(specIndex+1);+ if (!elementSpec.isOptional()) {+ MandatoryScan scan = elementSpec.scanMandatories();+ literals = scan.getMandatories();+ if (!scan.isStop())+ literals.addAll(getMandatoriesAfter(parentElement, elementSpec));+ }+ }+ }+ return literals;+ }++ public Grammar getGrammar() {+ return grammar;+ }++ /**+ * Provide suggestions for expected element matching specified string+ *+ * @param expectedElement+ * the element to expect.+ * @param matchWith+ * the string the suggestion has to match with+ * @param count+ * maximum number of suggestions to return+ * @return+ * a list of suggestions. If you do not have any suggestions and want code assist to+ * drill down the element to provide default suggestions, return a <tt>null</tt> value+ * instead of an empty list+ */+ @Nullable+ protected abstract List<InputSuggestion> suggest(ParentedElement expectedElement, String matchWith, int count);++ protected List<String> getHints(ParentedElement expectedElement, String matchWith) {+ return new ArrayList<>();+ }++ /**+ * Get index of next character after the match.+ *+ * @param spec+ * spec to be matched+ * @param content+ * content to match against+ * @return+ * index of next character after the match, or 0 if the rule+ * does not match any part of the string+ */+ protected int getEndOfMatch(ElementSpec spec, String content) {+ int endOfMatch = 0;+ List<Token> tokens = grammar.lex(content);+ if (!tokens.isEmpty() && tokens.get(0).getStartIndex() == 0) {+ endOfMatch = spec.getEndOfMatch(tokens);+ if (endOfMatch > 0) // there exist an element match+ endOfMatch = tokens.get(endOfMatch-1).getStopIndex()+1; // convert to char index+ }+ return endOfMatch;+ }++ /**+ * Wrap specified literal of specified terminal element as suggestion.+ *+ * @param expectedElement+ * terminal element expecting to be matched next+ * @param suggestedLiteral+ * a proposed literal of above terminal element defined in grammar+ * @param complete+ * whether or not above literal is a complete representation of the+ * expected terminal element+ * @return+ * suggestion of the literal, or <tt>null</tt> to suppress this suggestion+ */+ @Nullable+ protected InputSuggestion wrapAsSuggestion(ParentedElement expectedElement,+ String suggestedLiteral, boolean complete) {+ return new InputSuggestion(suggestedLiteral, -1, complete, null, null);+ }++}diff --git a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest2.java b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest2.javaindex 94e3078916..e7c4929ebf 100644--- a/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest2.java+++ b/commons.antlr/src/test/java/com/pmease/commons/antlr/codeassist/test/CodeAssistTest2.java@@ -1,129 +1,132 @@-package com.pmease.commons.antlr.codeassist.test;--import static org.junit.Assert.assertEquals;--import java.util.ArrayList;-import java.util.List;--import org.junit.Test;--import com.pmease.commons.antlr.codeassist.CodeAssist;-import com.pmease.commons.antlr.codeassist.InputCompletion;-import com.pmease.commons.antlr.codeassist.InputStatus;-import com.pmease.commons.antlr.codeassist.InputSuggestion;-import com.pmease.commons.antlr.codeassist.ParentedElement;-import com.pmease.commons.antlr.codeassist.FenceAware;-import com.pmease.commons.antlr.grammar.LexerRuleRefElementSpec;--public class CodeAssistTest2 {-- private static final String[] BRANCHS = new String[]{"master", "dev", "feature1", "feature2"};-- private CodeAssist codeAssist = new CodeAssist(CodeAssistTest2Lexer.class) {-- private static final long serialVersionUID = 1L;-- @Override- protected List<InputSuggestion> suggest(final ParentedElement element, String matchWith, int count) {- if (element.getSpec() instanceof LexerRuleRefElementSpec) {- LexerRuleRefElementSpec spec = (LexerRuleRefElementSpec) element.getSpec();- if (spec.getRuleName().equals("Value")) {- return new FenceAware(codeAssist.getGrammar(), "(", ")") {-- @Override- protected List<InputSuggestion> match(String matchWith) {- if (element.getRoot().getLastMatchedToken().getType() == CodeAssistTest2Lexer.BRANCH) {- List<InputSuggestion> suggestions = new ArrayList<>();- for (String value: BRANCHS) {- if (value.toLowerCase().contains(matchWith.toLowerCase()))- suggestions.add(new InputSuggestion(value));- }- return suggestions;- } else {- return null;- }- }-- }.suggest(element.getSpec(), matchWith);- }- }- return null;- }-- };-- private List<InputStatus> suggest(InputStatus inputStatus, String ruleName) {- List<InputStatus> suggestions = new ArrayList<>();- for (InputCompletion completion: codeAssist.suggest(inputStatus, ruleName, Integer.MAX_VALUE))- suggestions.add(completion.complete(inputStatus));- return suggestions;- }-- @Test- public void test() {- List<InputStatus> suggestions;-- suggestions = suggest(new InputStatus("message"), "query");- assertEquals(1, suggestions.size());- assertEquals("message(:8", suggestions.get(0).toString());-- suggestions = suggest(new InputStatus("branch"), "query");- assertEquals(4, suggestions.size());- assertEquals("branch(master):14", suggestions.get(0).toString());- assertEquals("branch(dev):11", suggestions.get(1).toString());- assertEquals("branch(feature1):16", suggestions.get(2).toString());- assertEquals("branch(feature2):16", suggestions.get(3).toString());-- suggestions = suggest(new InputStatus("branch(feature)"), "query");- assertEquals(12, suggestions.size());- assertEquals("branch(feature)^:16", suggestions.get(0).toString());- assertEquals("branch(feature)branch(:22", suggestions.get(1).toString());- assertEquals("branch(feature)tag(:19", suggestions.get(2).toString());- assertEquals("branch(feature)id(:18", suggestions.get(3).toString());- assertEquals("branch(feature)..:17", suggestions.get(4).toString());- assertEquals("branch(feature)...:18", suggestions.get(5).toString());- assertEquals("branch(feature)before(:22", suggestions.get(6).toString());- assertEquals("branch(feature)after(:21", suggestions.get(7).toString());- assertEquals("branch(feature)committer(:25", suggestions.get(8).toString());- assertEquals("branch(feature)author(:22", suggestions.get(9).toString());- assertEquals("branch(feature)path(:20", suggestions.get(10).toString());- assertEquals("branch(feature)message(:23", suggestions.get(11).toString());-- suggestions = suggest(new InputStatus(""), "revisionCriteria");- assertEquals(4, suggestions.size());- assertEquals("branch(:7", suggestions.get(0).toString());- assertEquals("tag(:4", suggestions.get(1).toString());- assertEquals("id(:3", suggestions.get(2).toString());- assertEquals("^:1", suggestions.get(3).toString());-- suggestions = suggest(new InputStatus("branch(master)"), "revisionCriteria");- assertEquals(2, suggestions.size());- assertEquals("branch(master)..:16", suggestions.get(0).toString());- assertEquals("branch(master)...:17", suggestions.get(1).toString());-- suggestions = suggest(new InputStatus("br"), "query");- assertEquals(1, suggestions.size());- assertEquals("branch(:7", suggestions.get(0).toString());-- suggestions = suggest(new InputStatus("branch("), "query");- assertEquals(4, suggestions.size());- assertEquals("branch(master):14", suggestions.get(0).toString());- assertEquals("branch(dev):11", suggestions.get(1).toString());- assertEquals("branch(feature1):16", suggestions.get(2).toString());- assertEquals("branch(feature2):16", suggestions.get(3).toString());-- suggestions = suggest(new InputStatus("branch( fea"), "query");- assertEquals(2, suggestions.size());- assertEquals("branch(feature1):16", suggestions.get(0).toString());- assertEquals("branch(feature2):16", suggestions.get(1).toString());-- suggestions = suggest(new InputStatus("tag"), "query");- assertEquals(1, suggestions.size());- assertEquals("tag(:4", suggestions.get(0).toString());-- suggestions = suggest(new InputStatus("branch(master)t"), "query");- assertEquals(1, suggestions.size());- assertEquals("branch(master)tag(:18", suggestions.get(0).toString());- }--}+package com.pmease.commons.antlr.codeassist.test;++import static org.junit.Assert.assertEquals;++import java.util.ArrayList;+import java.util.List;++import org.junit.Test;++import com.pmease.commons.antlr.codeassist.CodeAssist;+import com.pmease.commons.antlr.codeassist.InputCompletion;+import com.pmease.commons.antlr.codeassist.InputStatus;+import com.pmease.commons.antlr.codeassist.InputSuggestion;+import com.pmease.commons.antlr.codeassist.ParentedElement;+import com.pmease.commons.antlr.codeassist.FenceAware;+import com.pmease.commons.antlr.grammar.LexerRuleRefElementSpec;++public class CodeAssistTest2 {++ private static final String[] BRANCHS = new String[]{"master", "dev", "feature1", "feature2"};++ private CodeAssist codeAssist = new CodeAssist(CodeAssistTest2Lexer.class) {++ private static final long serialVersionUID = 1L;++ @Override+ protected List<InputSuggestion> suggest(final ParentedElement element, String matchWith, int count) {+ if (element.getSpec() instanceof LexerRuleRefElementSpec) {+ LexerRuleRefElementSpec spec = (LexerRuleRefElementSpec) element.getSpec();+ if (spec.getRuleName().equals("Value")) {+ return new FenceAware(codeAssist.getGrammar(), "(", ")") {++ @Override+ protected List<InputSuggestion> match(String matchWith) {+ if (element.getRoot().getLastMatchedToken().getType() == CodeAssistTest2Lexer.BRANCH) {+ List<InputSuggestion> suggestions = new ArrayList<>();+ for (String value: BRANCHS) {+ if (value.toLowerCase().contains(matchWith.toLowerCase()))+ suggestions.add(new InputSuggestion(value));+ }+ return suggestions;+ } else {+ return null;+ }+ }++ }.suggest(element.getSpec(), matchWith);+ }+ }+ return null;+ }++ };++ private List<InputStatus> suggest(InputStatus inputStatus, String ruleName) {+ List<InputStatus> suggestions = new ArrayList<>();+ for (InputCompletion completion: codeAssist.suggest(inputStatus, ruleName, Integer.MAX_VALUE))+ suggestions.add(completion.complete(inputStatus));+ return suggestions;+ }++ @Test+ public void test() {+ List<InputStatus> suggestions;++ suggestions = suggest(new InputStatus(""), "query");+ System.out.println(suggestions);++ suggestions = suggest(new InputStatus("message"), "query");+ assertEquals(1, suggestions.size());+ assertEquals("message(:8", suggestions.get(0).toString());++ suggestions = suggest(new InputStatus("branch"), "query");+ assertEquals(4, suggestions.size());+ assertEquals("branch(master):14", suggestions.get(0).toString());+ assertEquals("branch(dev):11", suggestions.get(1).toString());+ assertEquals("branch(feature1):16", suggestions.get(2).toString());+ assertEquals("branch(feature2):16", suggestions.get(3).toString());++ suggestions = suggest(new InputStatus("branch(feature)"), "query");+ assertEquals(12, suggestions.size());+ assertEquals("branch(feature)branch(:22", suggestions.get(0).toString());+ assertEquals("branch(feature)tag(:19", suggestions.get(1).toString());+ assertEquals("branch(feature)id(:18", suggestions.get(2).toString());+ assertEquals("branch(feature)^:16", suggestions.get(3).toString());+ assertEquals("branch(feature)..:17", suggestions.get(4).toString());+ assertEquals("branch(feature)...:18", suggestions.get(5).toString());+ assertEquals("branch(feature)before(:22", suggestions.get(6).toString());+ assertEquals("branch(feature)after(:21", suggestions.get(7).toString());+ assertEquals("branch(feature)committer(:25", suggestions.get(8).toString());+ assertEquals("branch(feature)author(:22", suggestions.get(9).toString());+ assertEquals("branch(feature)path(:20", suggestions.get(10).toString());+ assertEquals("branch(feature)message(:23", suggestions.get(11).toString());++ suggestions = suggest(new InputStatus(""), "revisionCriteria");+ assertEquals(4, suggestions.size());+ assertEquals("branch(:7", suggestions.get(0).toString());+ assertEquals("tag(:4", suggestions.get(1).toString());+ assertEquals("id(:3", suggestions.get(2).toString());+ assertEquals("^:1", suggestions.get(3).toString());++ suggestions = suggest(new InputStatus("branch(master)"), "revisionCriteria");+ assertEquals(2, suggestions.size());+ assertEquals("branch(master)..:16", suggestions.get(0).toString());+ assertEquals("branch(master)...:17", suggestions.get(1).toString());++ suggestions = suggest(new InputStatus("br"), "query");+ assertEquals(1, suggestions.size());+ assertEquals("branch(:7", suggestions.get(0).toString());++ suggestions = suggest(new InputStatus("branch("), "query");+ assertEquals(4, suggestions.size());+ assertEquals("branch(master):14", suggestions.get(0).toString());+ assertEquals("branch(dev):11", suggestions.get(1).toString());+ assertEquals("branch(feature1):16", suggestions.get(2).toString());+ assertEquals("branch(feature2):16", suggestions.get(3).toString());++ suggestions = suggest(new InputStatus("branch( fea"), "query");+ assertEquals(2, suggestions.size());+ assertEquals("branch(feature1):16", suggestions.get(0).toString());+ assertEquals("branch(feature2):16", suggestions.get(1).toString());++ suggestions = suggest(new InputStatus("tag"), "query");+ assertEquals(1, suggestions.size());+ assertEquals("tag(:4", suggestions.get(0).toString());++ suggestions = suggest(new InputStatus("branch(master)t"), "query");+ assertEquals(1, suggestions.size());+ assertEquals("branch(master)tag(:18", suggestions.get(0).toString());+ }++}diff --git a/commons.util/src/main/java/com/pmease/commons/util/pattern/ExclusiveAwarePattern.java b/commons.util/src/main/java/com/pmease/commons/util/match/ExclusiveAwarePattern.javasimilarity index 90%rename from commons.util/src/main/java/com/pmease/commons/util/pattern/ExclusiveAwarePattern.javarename to commons.util/src/main/java/com/pmease/commons/util/match/ExclusiveAwarePattern.javaindex 00385acd24..7b85ffe5ea 100644--- a/commons.util/src/main/java/com/pmease/commons/util/pattern/ExclusiveAwarePattern.java+++ b/commons.util/src/main/java/com/pmease/commons/util/match/ExclusiveAwarePattern.java@@ -1,44 +1,44 @@-package com.pmease.commons.util.pattern;--public class ExclusiveAwarePattern {-- private final String pattern;-- private final boolean exclusive;-- public ExclusiveAwarePattern(String pattern, boolean exclusive) {- this.pattern = pattern;- this.exclusive = exclusive;- }-- public String getPattern() {- return pattern;- }-- public boolean isExclusive() {- return exclusive;- }-- @Override- public String toString() {- if (exclusive)- return "-" + pattern;- else- return pattern;- }-- public static ExclusiveAwarePattern fromString(String str) {- str = str.trim();-- boolean exclusive = false;- if (str.startsWith("+"))- str = str.substring(1).trim();- if (str.startsWith("-")) {- str = str.substring(1).trim();- exclusive = true;- }-- return new ExclusiveAwarePattern(str, exclusive);- }-+package com.pmease.commons.util.match;++public class ExclusiveAwarePattern {++ private final String pattern;++ private final boolean exclusive;++ public ExclusiveAwarePattern(String pattern, boolean exclusive) {+ this.pattern = pattern;+ this.exclusive = exclusive;+ }++ public String getPattern() {+ return pattern;+ }++ public boolean isExclusive() {+ return exclusive;+ }++ @Override+ public String toString() {+ if (exclusive)+ return "-" + pattern;+ else+ return pattern;+ }++ public static ExclusiveAwarePattern fromString(String str) {+ str = str.trim();++ boolean exclusive = false;+ if (str.startsWith("+"))+ str = str.substring(1).trim();+ if (str.startsWith("-")) {+ str = str.substring(1).trim();+ exclusive = true;+ }++ return new ExclusiveAwarePattern(str, exclusive);+ }+}\ No newline at end of filediff --git a/commons.util/src/main/java/com/pmease/commons/util/match/IncludeExclude.java b/commons.util/src/main/java/com/pmease/commons/util/match/IncludeExclude.javanew file mode 100644index 0000000000..67cabd7c8a--- /dev/null+++ b/commons.util/src/main/java/com/pmease/commons/util/match/IncludeExclude.java@@ -0,0 +1,32 @@+package com.pmease.commons.util.match;++import java.util.List;++public class IncludeExclude<T, V> {++ private final List<T> includes;++ private final List<T> excludes;++ public IncludeExclude(List<T> includes, List<T> excludes) {+ this.includes = includes;+ this.excludes = excludes;+ }++ public boolean matches(RuleMatcher<T, V> matcher, V value) {+ for (T exclude: excludes) {+ if (matcher.matches(exclude, value))+ return false;+ }+ if (includes.isEmpty()) {+ return true;+ } else {+ for (T include: includes) {+ if (matcher.matches(include, value))+ return true;+ }+ return false;+ }+ }++}diff --git a/commons.util/src/main/java/com/pmease/commons/util/match/PatternMatcher.java b/commons.util/src/main/java/com/pmease/commons/util/match/PatternMatcher.javanew file mode 100644index 0000000000..fd24831bd6--- /dev/null+++ b/commons.util/src/main/java/com/pmease/commons/util/match/PatternMatcher.java@@ -0,0 +1,4 @@+package com.pmease.commons.util.match;++public interface PatternMatcher extends RuleMatcher<String, String> {+}diff --git a/commons.util/src/main/java/com/pmease/commons/util/pattern/PatternSet.java b/commons.util/src/main/java/com/pmease/commons/util/match/PatternSet.javasimilarity index 92%rename from commons.util/src/main/java/com/pmease/commons/util/pattern/PatternSet.javarename to commons.util/src/main/java/com/pmease/commons/util/match/PatternSet.javaindex 470aca92ab..2a0b61d649 100644--- a/commons.util/src/main/java/com/pmease/commons/util/pattern/PatternSet.java+++ b/commons.util/src/main/java/com/pmease/commons/util/match/PatternSet.java@@ -1,36 +1,36 @@-package com.pmease.commons.util.pattern;--import java.util.ArrayList;-import java.util.List;--import com.pmease.commons.util.StringUtils;--public class PatternSet {-- private final List<ExclusiveAwarePattern> patterns;-- public PatternSet(List<ExclusiveAwarePattern> patterns) {- this.patterns = patterns;- }-- public List<ExclusiveAwarePattern> getPatterns() {- return patterns;- }-- @Override- public String toString() {- List<String> list = new ArrayList<String>();- for (ExclusiveAwarePattern each: getPatterns())- list.add(each.toString());- return StringUtils.join(list, ", ").trim();- }-- public static PatternSet fromString(String str) {- List<ExclusiveAwarePattern> patterns = new ArrayList<ExclusiveAwarePattern>();- for (String pattern: StringUtils.splitAndTrim(str)) {- patterns.add(ExclusiveAwarePattern.fromString(pattern));- }- return new PatternSet(patterns);- }--}+package com.pmease.commons.util.match;++import java.util.ArrayList;+import java.util.List;++import com.pmease.commons.util.StringUtils;++public class PatternSet {++ private final List<ExclusiveAwarePattern> patterns;++ public PatternSet(List<ExclusiveAwarePattern> patterns) {+ this.patterns = patterns;+ }++ public List<ExclusiveAwarePattern> getPatterns() {+ return patterns;+ }++ @Override+ public String toString() {+ List<String> list = new ArrayList<String>();+ for (ExclusiveAwarePattern each: getPatterns())+ list.add(each.toString());+ return StringUtils.join(list, ", ").trim();+ }++ public static PatternSet fromString(String str) {+ List<ExclusiveAwarePattern> patterns = new ArrayList<ExclusiveAwarePattern>();+ for (String pattern: StringUtils.splitAndTrim(str)) {+ patterns.add(ExclusiveAwarePattern.fromString(pattern));+ }+ return new PatternSet(patterns);+ }++}diff --git a/commons.util/src/main/java/com/pmease/commons/util/pattern/PatternSetMatcher.java b/commons.util/src/main/java/com/pmease/commons/util/match/PatternSetMatcher.javasimilarity index 58%rename from commons.util/src/main/java/com/pmease/commons/util/pattern/PatternSetMatcher.javarename to commons.util/src/main/java/com/pmease/commons/util/match/PatternSetMatcher.javaindex e4feb6e2cd..3b29333e51 100644--- a/commons.util/src/main/java/com/pmease/commons/util/pattern/PatternSetMatcher.java+++ b/commons.util/src/main/java/com/pmease/commons/util/match/PatternSetMatcher.java@@ -1,6 +1,4 @@-package com.pmease.commons.util.pattern;--import java.util.List;+package com.pmease.commons.util.match;public class PatternSetMatcher implements PatternMatcher {@@ -27,20 +25,4 @@ public class PatternSetMatcher implements PatternMatcher {return lastExclusive;}- public boolean matches(List<String> includes, List<String> excludes, String input) {- for (String exclude: excludes) {- if (patternMatcher.matches(exclude, input))- return false;- }- if (includes.isEmpty()) {- return true;- } else {- for (String include: includes) {- if (patternMatcher.matches(include, input))- return true;- }- return false;- }- }-}diff --git a/commons.util/src/main/java/com/pmease/commons/util/match/RuleMatcher.java b/commons.util/src/main/java/com/pmease/commons/util/match/RuleMatcher.javanew file mode 100644index 0000000000..556d506d46--- /dev/null+++ b/commons.util/src/main/java/com/pmease/commons/util/match/RuleMatcher.java@@ -0,0 +1,5 @@+package com.pmease.commons.util.match;++public interface RuleMatcher<T, V> {+ boolean matches(T rule, V value);+}diff --git a/commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardApplied.java b/commons.util/src/main/java/com/pmease/commons/util/match/WildcardApplied.javasimilarity index 88%rename from commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardApplied.javarename to commons.util/src/main/java/com/pmease/commons/util/match/WildcardApplied.javaindex aedf86a977..9570c4c0d8 100644--- a/commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardApplied.java+++ b/commons.util/src/main/java/com/pmease/commons/util/match/WildcardApplied.java@@ -1,32 +1,32 @@-package com.pmease.commons.util.pattern;--import java.io.Serializable;--import com.pmease.commons.util.Range;--public class WildcardApplied implements Serializable {-- private static final long serialVersionUID = 1L;-- private final String text;-- private final Range matchRange;-- public WildcardApplied(String text, Range matchRange) {- this.text = text;- this.matchRange = matchRange;- }-- public String getText() {- return text;- }-- public Range getMatchRange() {- return matchRange;- }-- @Override- public String toString() {- return text + ":" + matchRange;- }-}+package com.pmease.commons.util.match;++import java.io.Serializable;++import com.pmease.commons.util.Range;++public class WildcardApplied implements Serializable {++ private static final long serialVersionUID = 1L;++ private final String text;++ private final Range matchRange;++ public WildcardApplied(String text, Range matchRange) {+ this.text = text;+ this.matchRange = matchRange;+ }++ public String getText() {+ return text;+ }++ public Range getMatchRange() {+ return matchRange;+ }++ @Override+ public String toString() {+ return text + ":" + matchRange;+ }+}diff --git a/commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardPathMatcher.java b/commons.util/src/main/java/com/pmease/commons/util/match/WildcardPathMatcher.javasimilarity index 97%rename from commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardPathMatcher.javarename to commons.util/src/main/java/com/pmease/commons/util/match/WildcardPathMatcher.javaindex 4a9e95a700..8e4681601a 100644--- a/commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardPathMatcher.java+++ b/commons.util/src/main/java/com/pmease/commons/util/match/WildcardPathMatcher.java@@ -1,427 +1,427 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package com.pmease.commons.util.pattern;--import com.pmease.commons.util.StringUtils;--/**- * <p>PathMatcher implementation for Ant-style path patterns.- * Examples are provided below.</p>- *- * <p>Part of this mapping code has been kindly borrowed from- * <a href="http://ant.apache.org">Apache Ant</a>.- *- * <p>The mapping matches URLs using the following rules:<br>- * <ul>- * <li>? matches one character</li>- * <li>* matches zero or more characters</li>- * <li>** matches zero or more 'directories' in a path</li>- * </ul>- *- * <p>Some examples:<br>- * <ul>- * <li><code>com/t?st.jsp</code> - matches <code>com/test.jsp</code> but also- * <code>com/tast.jsp</code> or <code>com/txst.jsp</code></li>- * <li><code>com/*.jsp</code> - matches all <code>.jsp</code> files in the- * <code>com</code> directory</li>- * <li><code>com/**/test.jsp</code> - matches all <code>test.jsp</code>- * files underneath the <code>com</code> path</li>- * <li><code>org/apache/shiro/**/*.jsp</code> - matches all <code>.jsp</code>- * files underneath the <code>org/apache/shiro</code> path</li>- * <li><code>org/**/servlet/bla.jsp</code> - matches- * <code>org/apache/shiro/servlet/bla.jsp</code> but also- * <code>org/apache/shiro/testing/servlet/bla.jsp</code> and- * <code>org/servlet/bla.jsp</code></li>- * </ul>- *- * <p><b>N.B.</b>: This class was borrowed (with much appreciation) from the- * <a href="http://www.springframework.org">Spring Framework</a> with modifications. We didn't want to reinvent the- * wheel of great work they've done, but also didn't want to force every Shiro user to depend on Spring</p>- *- * <p>As per the Apache 2.0 license, the original copyright notice and all author and copyright information have- * remained in tact.</p>- *- * @since 16.07.2003- */-public class WildcardPathMatcher implements PatternMatcher {-- //TODO - complete JavaDoc-- /**- * Default path separator: "/"- */- public static final String DEFAULT_PATH_SEPARATOR = "/";-- private String pathSeparator = DEFAULT_PATH_SEPARATOR;--- /**- * Set the path separator to use for pattern parsing.- * Default is "/", as in Ant.- */- public void setPathSeparator(String pathSeparator) {- this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR);- }--- public boolean isPattern(String path) {- return (path.indexOf('*') != -1 || path.indexOf('?') != -1);- }-- public boolean matches(String pattern, String input) {- return match(pattern, input);- }-- public boolean match(String pattern, String path) {- return doMatch(pattern, path, true);- }-- public boolean matchStart(String pattern, String path) {- return doMatch(pattern, path, false);- }--- /**- * Actually match the given <code>path</code> against the given <code>pattern</code>.- *- * @param pattern the pattern to match against- * @param path the path String to test- * @param fullMatch whether a full pattern match is required- * (else a pattern match as far as the given base path goes is sufficient)- * @return <code>true</code> if the supplied <code>path</code> matched,- * <code>false</code> if it didn't- */- protected boolean doMatch(String pattern, String path, boolean fullMatch) {- if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) {- return false;- }-- String[] pattDirs = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);- String[] pathDirs = StringUtils.tokenizeToStringArray(path, this.pathSeparator);-- int pattIdxStart = 0;- int pattIdxEnd = pattDirs.length - 1;- int pathIdxStart = 0;- int pathIdxEnd = pathDirs.length - 1;-- // Match all elements up to the first **- while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {- String patDir = pattDirs[pattIdxStart];- if ("**".equals(patDir)) {- break;- }- if (!matchStrings(patDir, pathDirs[pathIdxStart])) {- return false;- }- pattIdxStart++;- pathIdxStart++;- }-- if (pathIdxStart > pathIdxEnd) {- // Path is exhausted, only match if rest of pattern is * or **'s- if (pattIdxStart > pattIdxEnd) {- return (pattern.endsWith(this.pathSeparator) ?- path.endsWith(this.pathSeparator) : !path.endsWith(this.pathSeparator));- }- if (!fullMatch) {- return true;- }- if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") &&- path.endsWith(this.pathSeparator)) {- return true;- }- for (int i = pattIdxStart; i <= pattIdxEnd; i++) {- if (!pattDirs[i].equals("**")) {- return false;- }- }- return true;- } else if (pattIdxStart > pattIdxEnd) {- // String not exhausted, but pattern is. Failure.- return false;- } else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {- // Path start definitely matches due to "**" part in pattern.- return true;- }-- // up to last '**'- while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {- String patDir = pattDirs[pattIdxEnd];- if (patDir.equals("**")) {- break;- }- if (!matchStrings(patDir, pathDirs[pathIdxEnd])) {- return false;- }- pattIdxEnd--;- pathIdxEnd--;- }- if (pathIdxStart > pathIdxEnd) {- // String is exhausted- for (int i = pattIdxStart; i <= pattIdxEnd; i++) {- if (!pattDirs[i].equals("**")) {- return false;- }- }- return true;- }-- while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) {- int patIdxTmp = -1;- for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) {- if (pattDirs[i].equals("**")) {- patIdxTmp = i;- break;- }- }- if (patIdxTmp == pattIdxStart + 1) {- // '**/**' situation, so skip one- pattIdxStart++;- continue;- }- // Find the pattern between padIdxStart & padIdxTmp in str between- // strIdxStart & strIdxEnd- int patLength = (patIdxTmp - pattIdxStart - 1);- int strLength = (pathIdxEnd - pathIdxStart + 1);- int foundIdx = -1;-- strLoop:- for (int i = 0; i <= strLength - patLength; i++) {- for (int j = 0; j < patLength; j++) {- String subPat = (String) pattDirs[pattIdxStart + j + 1];- String subStr = (String) pathDirs[pathIdxStart + i + j];- if (!matchStrings(subPat, subStr)) {- continue strLoop;- }- }- foundIdx = pathIdxStart + i;- break;- }-- if (foundIdx == -1) {- return false;- }-- pattIdxStart = patIdxTmp;- pathIdxStart = foundIdx + patLength;- }-- for (int i = pattIdxStart; i <= pattIdxEnd; i++) {- if (!pattDirs[i].equals("**")) {- return false;- }- }-- return true;- }-- /**- * Tests whether or not a string matches against a pattern.- * The pattern may contain two special characters:<br>- * '*' means zero or more characters<br>- * '?' means one and only one character- *- * @param pattern pattern to match against.- * Must not be <code>null</code>.- * @param str string which must be matched against the pattern.- * Must not be <code>null</code>.- * @return <code>true</code> if the string matches against the- * pattern, or <code>false</code> otherwise.- */- private boolean matchStrings(String pattern, String str) {- char[] patArr = pattern.toCharArray();- char[] strArr = str.toCharArray();- int patIdxStart = 0;- int patIdxEnd = patArr.length - 1;- int strIdxStart = 0;- int strIdxEnd = strArr.length - 1;- char ch;-- boolean containsStar = false;- for (char aPatArr : patArr) {- if (aPatArr == '*') {- containsStar = true;- break;- }- }-- if (!containsStar) {- // No '*'s, so we make a shortcut- if (patIdxEnd != strIdxEnd) {- return false; // Pattern and string do not have the same size- }- for (int i = 0; i <= patIdxEnd; i++) {- ch = patArr[i];- if (ch != '?') {- if (ch != strArr[i]) {- return false;// Character mismatch- }- }- }- return true; // String matches against pattern- }--- if (patIdxEnd == 0) {- return true; // Pattern contains only '*', which matches anything- }-- // Process characters before first star- while ((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) {- if (ch != '?') {- if (ch != strArr[strIdxStart]) {- return false;// Character mismatch- }- }- patIdxStart++;- strIdxStart++;- }- if (strIdxStart > strIdxEnd) {- // All characters in the string are used. Check if only '*'s are- // left in the pattern. If so, we succeeded. Otherwise failure.- for (int i = patIdxStart; i <= patIdxEnd; i++) {- if (patArr[i] != '*') {- return false;- }- }- return true;- }-- // Process characters after last star- while ((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) {- if (ch != '?') {- if (ch != strArr[strIdxEnd]) {- return false;// Character mismatch- }- }- patIdxEnd--;- strIdxEnd--;- }- if (strIdxStart > strIdxEnd) {- // All characters in the string are used. Check if only '*'s are- // left in the pattern. If so, we succeeded. Otherwise failure.- for (int i = patIdxStart; i <= patIdxEnd; i++) {- if (patArr[i] != '*') {- return false;- }- }- return true;- }-- // process pattern between stars. padIdxStart and patIdxEnd point- // always to a '*'.- while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {- int patIdxTmp = -1;- for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {- if (patArr[i] == '*') {- patIdxTmp = i;- break;- }- }- if (patIdxTmp == patIdxStart + 1) {- // Two stars next to each other, skip the first one.- patIdxStart++;- continue;- }- // Find the pattern between padIdxStart & padIdxTmp in str between- // strIdxStart & strIdxEnd- int patLength = (patIdxTmp - patIdxStart - 1);- int strLength = (strIdxEnd - strIdxStart + 1);- int foundIdx = -1;- strLoop:- for (int i = 0; i <= strLength - patLength; i++) {- for (int j = 0; j < patLength; j++) {- ch = patArr[patIdxStart + j + 1];- if (ch != '?') {- if (ch != strArr[strIdxStart + i + j]) {- continue strLoop;- }- }- }-- foundIdx = strIdxStart + i;- break;- }-- if (foundIdx == -1) {- return false;- }-- patIdxStart = patIdxTmp;- strIdxStart = foundIdx + patLength;- }-- // All characters in the string are used. Check if only '*'s are left- // in the pattern. If so, we succeeded. Otherwise failure.- for (int i = patIdxStart; i <= patIdxEnd; i++) {- if (patArr[i] != '*') {- return false;- }- }-- return true;- }-- /**- * Given a pattern and a full path, determine the pattern-mapped part.- * <p>For example:- * <ul>- * <li>'<code>/docs/cvs/commit.html</code>' and '<code>/docs/cvs/commit.html</code> -> ''</li>- * <li>'<code>/docs/*</code>' and '<code>/docs/cvs/commit</code> -> '<code>cvs/commit</code>'</li>- * <li>'<code>/docs/cvs/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>commit.html</code>'</li>- * <li>'<code>/docs/**</code>' and '<code>/docs/cvs/commit</code> -> '<code>cvs/commit</code>'</li>- * <li>'<code>/docs/**\/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>cvs/commit.html</code>'</li>- * <li>'<code>/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>docs/cvs/commit.html</code>'</li>- * <li>'<code>*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>/docs/cvs/commit.html</code>'</li>- * <li>'<code>*</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>/docs/cvs/commit.html</code>'</li>- * </ul>- * <p>Assumes that {@link #match} returns <code>true</code> for '<code>pattern</code>'- * and '<code>path</code>', but does <strong>not</strong> enforce this.- */- public String extractPathWithinPattern(String pattern, String path) {- String[] patternParts = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);- String[] pathParts = StringUtils.tokenizeToStringArray(path, this.pathSeparator);-- StringBuilder buffer = new StringBuilder();-- // Add any path parts that have a wildcarded pattern part.- int puts = 0;- for (int i = 0; i < patternParts.length; i++) {- String patternPart = patternParts[i];- if ((patternPart.indexOf('*') > -1 || patternPart.indexOf('?') > -1) && pathParts.length >= i + 1) {- if (puts > 0 || (i == 0 && !pattern.startsWith(this.pathSeparator))) {- buffer.append(this.pathSeparator);- }- buffer.append(pathParts[i]);- puts++;- }- }-- // Append any trailing path parts.- for (int i = patternParts.length; i < pathParts.length; i++) {- if (puts > 0 || i > 0) {- buffer.append(this.pathSeparator);- }- buffer.append(pathParts[i]);- }-- return buffer.toString();- }--}+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package com.pmease.commons.util.match;++import com.pmease.commons.util.StringUtils;++/**+ * <p>PathMatcher implementation for Ant-style path patterns.+ * Examples are provided below.</p>+ *+ * <p>Part of this mapping code has been kindly borrowed from+ * <a href="http://ant.apache.org">Apache Ant</a>.+ *+ * <p>The mapping matches URLs using the following rules:<br>+ * <ul>+ * <li>? matches one character</li>+ * <li>* matches zero or more characters</li>+ * <li>** matches zero or more 'directories' in a path</li>+ * </ul>+ *+ * <p>Some examples:<br>+ * <ul>+ * <li><code>com/t?st.jsp</code> - matches <code>com/test.jsp</code> but also+ * <code>com/tast.jsp</code> or <code>com/txst.jsp</code></li>+ * <li><code>com/*.jsp</code> - matches all <code>.jsp</code> files in the+ * <code>com</code> directory</li>+ * <li><code>com/**/test.jsp</code> - matches all <code>test.jsp</code>+ * files underneath the <code>com</code> path</li>+ * <li><code>org/apache/shiro/**/*.jsp</code> - matches all <code>.jsp</code>+ * files underneath the <code>org/apache/shiro</code> path</li>+ * <li><code>org/**/servlet/bla.jsp</code> - matches+ * <code>org/apache/shiro/servlet/bla.jsp</code> but also+ * <code>org/apache/shiro/testing/servlet/bla.jsp</code> and+ * <code>org/servlet/bla.jsp</code></li>+ * </ul>+ *+ * <p><b>N.B.</b>: This class was borrowed (with much appreciation) from the+ * <a href="http://www.springframework.org">Spring Framework</a> with modifications. We didn't want to reinvent the+ * wheel of great work they've done, but also didn't want to force every Shiro user to depend on Spring</p>+ *+ * <p>As per the Apache 2.0 license, the original copyright notice and all author and copyright information have+ * remained in tact.</p>+ *+ * @since 16.07.2003+ */+public class WildcardPathMatcher implements PatternMatcher {++ //TODO - complete JavaDoc++ /**+ * Default path separator: "/"+ */+ public static final String DEFAULT_PATH_SEPARATOR = "/";++ private String pathSeparator = DEFAULT_PATH_SEPARATOR;+++ /**+ * Set the path separator to use for pattern parsing.+ * Default is "/", as in Ant.+ */+ public void setPathSeparator(String pathSeparator) {+ this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR);+ }+++ public boolean isPattern(String path) {+ return (path.indexOf('*') != -1 || path.indexOf('?') != -1);+ }++ public boolean matches(String pattern, String input) {+ return match(pattern, input);+ }++ public boolean match(String pattern, String path) {+ return doMatch(pattern, path, true);+ }++ public boolean matchStart(String pattern, String path) {+ return doMatch(pattern, path, false);+ }+++ /**+ * Actually match the given <code>path</code> against the given <code>pattern</code>.+ *+ * @param pattern the pattern to match against+ * @param path the path String to test+ * @param fullMatch whether a full pattern match is required+ * (else a pattern match as far as the given base path goes is sufficient)+ * @return <code>true</code> if the supplied <code>path</code> matched,+ * <code>false</code> if it didn't+ */+ protected boolean doMatch(String pattern, String path, boolean fullMatch) {+ if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) {+ return false;+ }++ String[] pattDirs = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);+ String[] pathDirs = StringUtils.tokenizeToStringArray(path, this.pathSeparator);++ int pattIdxStart = 0;+ int pattIdxEnd = pattDirs.length - 1;+ int pathIdxStart = 0;+ int pathIdxEnd = pathDirs.length - 1;++ // Match all elements up to the first **+ while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {+ String patDir = pattDirs[pattIdxStart];+ if ("**".equals(patDir)) {+ break;+ }+ if (!matchStrings(patDir, pathDirs[pathIdxStart])) {+ return false;+ }+ pattIdxStart++;+ pathIdxStart++;+ }++ if (pathIdxStart > pathIdxEnd) {+ // Path is exhausted, only match if rest of pattern is * or **'s+ if (pattIdxStart > pattIdxEnd) {+ return (pattern.endsWith(this.pathSeparator) ?+ path.endsWith(this.pathSeparator) : !path.endsWith(this.pathSeparator));+ }+ if (!fullMatch) {+ return true;+ }+ if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") &&+ path.endsWith(this.pathSeparator)) {+ return true;+ }+ for (int i = pattIdxStart; i <= pattIdxEnd; i++) {+ if (!pattDirs[i].equals("**")) {+ return false;+ }+ }+ return true;+ } else if (pattIdxStart > pattIdxEnd) {+ // String not exhausted, but pattern is. Failure.+ return false;+ } else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {+ // Path start definitely matches due to "**" part in pattern.+ return true;+ }++ // up to last '**'+ while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {+ String patDir = pattDirs[pattIdxEnd];+ if (patDir.equals("**")) {+ break;+ }+ if (!matchStrings(patDir, pathDirs[pathIdxEnd])) {+ return false;+ }+ pattIdxEnd--;+ pathIdxEnd--;+ }+ if (pathIdxStart > pathIdxEnd) {+ // String is exhausted+ for (int i = pattIdxStart; i <= pattIdxEnd; i++) {+ if (!pattDirs[i].equals("**")) {+ return false;+ }+ }+ return true;+ }++ while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) {+ int patIdxTmp = -1;+ for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) {+ if (pattDirs[i].equals("**")) {+ patIdxTmp = i;+ break;+ }+ }+ if (patIdxTmp == pattIdxStart + 1) {+ // '**/**' situation, so skip one+ pattIdxStart++;+ continue;+ }+ // Find the pattern between padIdxStart & padIdxTmp in str between+ // strIdxStart & strIdxEnd+ int patLength = (patIdxTmp - pattIdxStart - 1);+ int strLength = (pathIdxEnd - pathIdxStart + 1);+ int foundIdx = -1;++ strLoop:+ for (int i = 0; i <= strLength - patLength; i++) {+ for (int j = 0; j < patLength; j++) {+ String subPat = (String) pattDirs[pattIdxStart + j + 1];+ String subStr = (String) pathDirs[pathIdxStart + i + j];+ if (!matchStrings(subPat, subStr)) {+ continue strLoop;+ }+ }+ foundIdx = pathIdxStart + i;+ break;+ }++ if (foundIdx == -1) {+ return false;+ }++ pattIdxStart = patIdxTmp;+ pathIdxStart = foundIdx + patLength;+ }++ for (int i = pattIdxStart; i <= pattIdxEnd; i++) {+ if (!pattDirs[i].equals("**")) {+ return false;+ }+ }++ return true;+ }++ /**+ * Tests whether or not a string matches against a pattern.+ * The pattern may contain two special characters:<br>+ * '*' means zero or more characters<br>+ * '?' means one and only one character+ *+ * @param pattern pattern to match against.+ * Must not be <code>null</code>.+ * @param str string which must be matched against the pattern.+ * Must not be <code>null</code>.+ * @return <code>true</code> if the string matches against the+ * pattern, or <code>false</code> otherwise.+ */+ private boolean matchStrings(String pattern, String str) {+ char[] patArr = pattern.toCharArray();+ char[] strArr = str.toCharArray();+ int patIdxStart = 0;+ int patIdxEnd = patArr.length - 1;+ int strIdxStart = 0;+ int strIdxEnd = strArr.length - 1;+ char ch;++ boolean containsStar = false;+ for (char aPatArr : patArr) {+ if (aPatArr == '*') {+ containsStar = true;+ break;+ }+ }++ if (!containsStar) {+ // No '*'s, so we make a shortcut+ if (patIdxEnd != strIdxEnd) {+ return false; // Pattern and string do not have the same size+ }+ for (int i = 0; i <= patIdxEnd; i++) {+ ch = patArr[i];+ if (ch != '?') {+ if (ch != strArr[i]) {+ return false;// Character mismatch+ }+ }+ }+ return true; // String matches against pattern+ }+++ if (patIdxEnd == 0) {+ return true; // Pattern contains only '*', which matches anything+ }++ // Process characters before first star+ while ((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) {+ if (ch != '?') {+ if (ch != strArr[strIdxStart]) {+ return false;// Character mismatch+ }+ }+ patIdxStart++;+ strIdxStart++;+ }+ if (strIdxStart > strIdxEnd) {+ // All characters in the string are used. Check if only '*'s are+ // left in the pattern. If so, we succeeded. Otherwise failure.+ for (int i = patIdxStart; i <= patIdxEnd; i++) {+ if (patArr[i] != '*') {+ return false;+ }+ }+ return true;+ }++ // Process characters after last star+ while ((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) {+ if (ch != '?') {+ if (ch != strArr[strIdxEnd]) {+ return false;// Character mismatch+ }+ }+ patIdxEnd--;+ strIdxEnd--;+ }+ if (strIdxStart > strIdxEnd) {+ // All characters in the string are used. Check if only '*'s are+ // left in the pattern. If so, we succeeded. Otherwise failure.+ for (int i = patIdxStart; i <= patIdxEnd; i++) {+ if (patArr[i] != '*') {+ return false;+ }+ }+ return true;+ }++ // process pattern between stars. padIdxStart and patIdxEnd point+ // always to a '*'.+ while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {+ int patIdxTmp = -1;+ for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {+ if (patArr[i] == '*') {+ patIdxTmp = i;+ break;+ }+ }+ if (patIdxTmp == patIdxStart + 1) {+ // Two stars next to each other, skip the first one.+ patIdxStart++;+ continue;+ }+ // Find the pattern between padIdxStart & padIdxTmp in str between+ // strIdxStart & strIdxEnd+ int patLength = (patIdxTmp - patIdxStart - 1);+ int strLength = (strIdxEnd - strIdxStart + 1);+ int foundIdx = -1;+ strLoop:+ for (int i = 0; i <= strLength - patLength; i++) {+ for (int j = 0; j < patLength; j++) {+ ch = patArr[patIdxStart + j + 1];+ if (ch != '?') {+ if (ch != strArr[strIdxStart + i + j]) {+ continue strLoop;+ }+ }+ }++ foundIdx = strIdxStart + i;+ break;+ }++ if (foundIdx == -1) {+ return false;+ }++ patIdxStart = patIdxTmp;+ strIdxStart = foundIdx + patLength;+ }++ // All characters in the string are used. Check if only '*'s are left+ // in the pattern. If so, we succeeded. Otherwise failure.+ for (int i = patIdxStart; i <= patIdxEnd; i++) {+ if (patArr[i] != '*') {+ return false;+ }+ }++ return true;+ }++ /**+ * Given a pattern and a full path, determine the pattern-mapped part.+ * <p>For example:+ * <ul>+ * <li>'<code>/docs/cvs/commit.html</code>' and '<code>/docs/cvs/commit.html</code> -> ''</li>+ * <li>'<code>/docs/*</code>' and '<code>/docs/cvs/commit</code> -> '<code>cvs/commit</code>'</li>+ * <li>'<code>/docs/cvs/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>commit.html</code>'</li>+ * <li>'<code>/docs/**</code>' and '<code>/docs/cvs/commit</code> -> '<code>cvs/commit</code>'</li>+ * <li>'<code>/docs/**\/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>cvs/commit.html</code>'</li>+ * <li>'<code>/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>docs/cvs/commit.html</code>'</li>+ * <li>'<code>*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>/docs/cvs/commit.html</code>'</li>+ * <li>'<code>*</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>/docs/cvs/commit.html</code>'</li>+ * </ul>+ * <p>Assumes that {@link #match} returns <code>true</code> for '<code>pattern</code>'+ * and '<code>path</code>', but does <strong>not</strong> enforce this.+ */+ public String extractPathWithinPattern(String pattern, String path) {+ String[] patternParts = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);+ String[] pathParts = StringUtils.tokenizeToStringArray(path, this.pathSeparator);++ StringBuilder buffer = new StringBuilder();++ // Add any path parts that have a wildcarded pattern part.+ int puts = 0;+ for (int i = 0; i < patternParts.length; i++) {+ String patternPart = patternParts[i];+ if ((patternPart.indexOf('*') > -1 || patternPart.indexOf('?') > -1) && pathParts.length >= i + 1) {+ if (puts > 0 || (i == 0 && !pattern.startsWith(this.pathSeparator))) {+ buffer.append(this.pathSeparator);+ }+ buffer.append(pathParts[i]);+ puts++;+ }+ }++ // Append any trailing path parts.+ for (int i = patternParts.length; i < pathParts.length; i++) {+ if (puts > 0 || i > 0) {+ buffer.append(this.pathSeparator);+ }+ buffer.append(pathParts[i]);+ }++ return buffer.toString();+ }++}diff --git a/commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardStringMatcher.java b/commons.util/src/main/java/com/pmease/commons/util/match/WildcardStringMatcher.javasimilarity index 82%rename from commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardStringMatcher.javarename to commons.util/src/main/java/com/pmease/commons/util/match/WildcardStringMatcher.javaindex 789b467ce9..d830772ace 100644--- a/commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardStringMatcher.java+++ b/commons.util/src/main/java/com/pmease/commons/util/match/WildcardStringMatcher.java@@ -1,12 +1,12 @@-package com.pmease.commons.util.pattern;--import org.apache.tools.ant.types.selectors.SelectorUtils;--public class WildcardStringMatcher implements PatternMatcher {-- @Override- public boolean matches(String pattern, String input) {- return SelectorUtils.match(pattern, input);- }--}+package com.pmease.commons.util.match;++import org.apache.tools.ant.types.selectors.SelectorUtils;++public class WildcardStringMatcher implements PatternMatcher {++ @Override+ public boolean matches(String pattern, String input) {+ return SelectorUtils.match(pattern, input);+ }++}diff --git a/commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardUtils.java b/commons.util/src/main/java/com/pmease/commons/util/match/WildcardUtils.javasimilarity index 91%rename from commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardUtils.javarename to commons.util/src/main/java/com/pmease/commons/util/match/WildcardUtils.javaindex b468dae2d6..ce744d71bc 100644--- a/commons.util/src/main/java/com/pmease/commons/util/pattern/WildcardUtils.java+++ b/commons.util/src/main/java/com/pmease/commons/util/match/WildcardUtils.java@@ -1,4 +1,4 @@-package com.pmease.commons.util.pattern;+package com.pmease.commons.util.match;import java.util.ArrayList;import java.util.List;@@ -49,10 +49,6 @@ public class WildcardUtils {return pathPatternSetMatcher.matches(patterns, path);}- public static boolean matchPath(List<String> includes, List<String> excludes, String path) {- return pathPatternSetMatcher.matches(includes, excludes, path);- }-/*** Tests whether or not a string matches against specified patterns.* <p>@@ -89,10 +85,6 @@ public class WildcardUtils {return stringPatternSetMatcher.matches(patterns, str);}- public static boolean matchString(List<String> includes, List<String> excludes, String str) {- return stringPatternSetMatcher.matches(includes, excludes, str);- }-public static boolean hasWildcards(String input) {return (input.indexOf('*') != -1 || input.indexOf('?') != -1);}diff --git a/commons.util/src/main/java/com/pmease/commons/util/pattern/PatternMatcher.java b/commons.util/src/main/java/com/pmease/commons/util/pattern/PatternMatcher.javadeleted file mode 100644index a74d5dff5f..0000000000--- a/commons.util/src/main/java/com/pmease/commons/util/pattern/PatternMatcher.java+++ /dev/null@@ -1,5 +0,0 @@-package com.pmease.commons.util.pattern;--public interface PatternMatcher {- boolean matches(String pattern, String input);-}diff --git a/commons.util/src/test/java/com/pmease/commons/util/pattern/WildcardUtilsTest.java b/commons.util/src/test/java/com/pmease/commons/util/pattern/WildcardUtilsTest.javaindex 1738dedecd..71570b898b 100644--- a/commons.util/src/test/java/com/pmease/commons/util/pattern/WildcardUtilsTest.java+++ b/commons.util/src/test/java/com/pmease/commons/util/pattern/WildcardUtilsTest.java@@ -1,62 +1,62 @@-package com.pmease.commons.util.pattern;--import static org.junit.Assert.*;-import static com.pmease.commons.util.pattern.WildcardUtils.*;--import org.junit.Test;--public class WildcardUtilsTest {-- @Test- public void shouldMatchPath() {- assertTrue(matchPath("-*.java", "file.c"));- assertTrue(matchPath("**//*.java", "com/example/Test.java"));- assertFalse(matchPath("**/*.java", "com/example/test.c"));- assertFalse(matchPath("com/*.java", "com/example/Test.java"));- assertTrue(matchPath("com/**//*.java", "com/example/Test.java"));- assertTrue(matchPath("com/*.java", "com/Test.java"));- assertTrue(matchPath("src///**/*.java", "src/com/example/Test.java"));- assertFalse(matchPath("/src/**/*.java", "src/com/example/Test.java"));- assertFalse(matchPath("src/**////*.java", "resource/com/example/Test.java"));-- assertTrue(matchPath("-**/*.java, **", "test/hello.c"));- assertFalse(matchPath("-**/*.java, **", "test/hello.java"));- assertFalse(matchPath("-**/*.java, **/*.java, **/*.c", "test/hello.txt"));- assertFalse(matchPath("-**/*.java, **/*.java, **/*.c", "test/hello.java"));- assertTrue(matchPath("+**/*.java, -**/*.java, **/*.c", "test/hello.java"));- assertTrue(matchPath("-**/generated/**, **/*.xml", "test/test.xml"));- assertFalse(matchPath("-**/generated/**, **/*.xml", "generated/test.xml"));- }-- @Test- public void shouldMatchString() {- assertTrue(matchString("hello?world", "hello world"));- assertFalse(matchString("hello?world", "hello world"));- assertTrue(matchString("hello*world", "hello world"));- assertTrue(matchString("**/*.java", "com/example/Test.java"));- assertFalse(matchString("**/*.java", "com/example/test.c"));- assertTrue(matchString("com/*.java", "com/example/Test.java"));- assertTrue(matchString("com/**/*.java", "com/example/Test.java"));- assertTrue(matchString("com/*.java", "com/Test.java"));- assertTrue(matchString("src/**/*.java", "src/com/example/Test.java"));- assertFalse(matchString("src/**/*.java", "resource/com/example/Test.java"));-- assertTrue(matchString("-*.java", "hello.c"));- assertFalse(matchString("-*.java", "hello.java"));- assertTrue(matchString("-*.java, *", "hello.c"));- assertFalse(matchString("-*.java, *", "hello.java"));- assertFalse(matchString("-*.java, *.java, *.c", "hello.txt"));- assertFalse(matchString("-*.java, *.java, *.c", "hello.java"));- assertTrue(matchString("+*.java, -*.java, *.c", "hello.java"));- }-- @Test- public void shouldApplyWildcard() {- assertEquals("he*llo:1-4", applyWildcard("hello", "e*l", false).toString());- assertEquals(null, applyWildcard("hello world", "*he ld", false));- assertEquals("*he*ld 2:0-6", applyWildcard("hello world 2", "*he*ld", false).toString());- assertEquals("hello:0-0", applyWildcard("hello", "", false).toString());- assertEquals("*:0-1", applyWildcard("hello", "*", false).toString());- assertEquals("**:0-2", applyWildcard("hello", "**", false).toString());- }-}+package com.pmease.commons.util.pattern;++import static com.pmease.commons.util.match.WildcardUtils.*;+import static org.junit.Assert.*;++import org.junit.Test;++public class WildcardUtilsTest {++ @Test+ public void shouldMatchPath() {+ assertTrue(matchPath("-*.java", "file.c"));+ assertTrue(matchPath("**//*.java", "com/example/Test.java"));+ assertFalse(matchPath("**/*.java", "com/example/test.c"));+ assertFalse(matchPath("com/*.java", "com/example/Test.java"));+ assertTrue(matchPath("com/**//*.java", "com/example/Test.java"));+ assertTrue(matchPath("com/*.java", "com/Test.java"));+ assertTrue(matchPath("src///**/*.java", "src/com/example/Test.java"));+ assertFalse(matchPath("/src/**/*.java", "src/com/example/Test.java"));+ assertFalse(matchPath("src/**////*.java", "resource/com/example/Test.java"));++ assertTrue(matchPath("-**/*.java, **", "test/hello.c"));+ assertFalse(matchPath("-**/*.java, **", "test/hello.java"));+ assertFalse(matchPath("-**/*.java, **/*.java, **/*.c", "test/hello.txt"));+ assertFalse(matchPath("-**/*.java, **/*.java, **/*.c", "test/hello.java"));+ assertTrue(matchPath("+**/*.java, -**/*.java, **/*.c", "test/hello.java"));+ assertTrue(matchPath("-**/generated/**, **/*.xml", "test/test.xml"));+ assertFalse(matchPath("-**/generated/**, **/*.xml", "generated/test.xml"));+ }++ @Test+ public void shouldMatchString() {+ assertTrue(matchString("hello?world", "hello world"));+ assertFalse(matchString("hello?world", "hello world"));+ assertTrue(matchString("hello*world", "hello world"));+ assertTrue(matchString("**/*.java", "com/example/Test.java"));+ assertFalse(matchString("**/*.java", "com/example/test.c"));+ assertTrue(matchString("com/*.java", "com/example/Test.java"));+ assertTrue(matchString("com/**/*.java", "com/example/Test.java"));+ assertTrue(matchString("com/*.java", "com/Test.java"));+ assertTrue(matchString("src/**/*.java", "src/com/example/Test.java"));+ assertFalse(matchString("src/**/*.java", "resource/com/example/Test.java"));++ assertTrue(matchString("-*.java", "hello.c"));+ assertFalse(matchString("-*.java", "hello.java"));+ assertTrue(matchString("-*.java, *", "hello.c"));+ assertFalse(matchString("-*.java, *", "hello.java"));+ assertFalse(matchString("-*.java, *.java, *.c", "hello.txt"));+ assertFalse(matchString("-*.java, *.java, *.c", "hello.java"));+ assertTrue(matchString("+*.java, -*.java, *.c", "hello.java"));+ }++ @Test+ public void shouldApplyWildcard() {+ assertEquals("he*llo:1-4", applyWildcard("hello", "e*l", false).toString());+ assertEquals(null, applyWildcard("hello world", "*he ld", false));+ assertEquals("*he*ld 2:0-6", applyWildcard("hello world 2", "*he*ld", false).toString());+ assertEquals("hello:0-0", applyWildcard("hello", "", false).toString());+ assertEquals("*:0-1", applyWildcard("hello", "*", false).toString());+ assertEquals("**:0-2", applyWildcard("hello", "**", false).toString());+ }+}diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.js b/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.jsindex 3a359c16e3..a26d2c1dfe 100644--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.js+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.js@@ -1,566 +1,570 @@-/**************************************************************- * Define common javascript functions and setups here.- *- **************************************************************/--var pmease = {};--pmease.commons = {- setupCollapse: function(triggerId, targetId) {- var trigger = $("#" + triggerId);- var target = $("#" + targetId);-- // This script can still be called if CollapseBehavior is added to a- // a component enclosed in an invisible wicket:enclosure. So we- // should check if relevant element exists.- if (!trigger[0] || !target[0])- return;-- target[0].trigger = trigger[0];-- target.on("shown.bs.collapse hidden.bs.collapse", function() {- var $floating = target.closest(".floating");- if ($floating.length != 0) {- var borderTop = $(window).scrollTop();- var borderBottom = borderTop + $(window).height();- var borderLeft = $(window).scrollLeft();- var borderRight = borderLeft + $(window).width();-- var left = $floating.position().left;- var top = $floating.position().top;- var width = $floating.outerWidth();- var height = $floating.outerHeight();-- if (left < borderLeft || left + width > borderRight- || top < borderTop || top + height > borderBottom) {- if ($floating.data("alignment"))- $floating.align($floating.data("alignment"));- }- }-- });- trigger.click(function() {- if (target[0].collapsibleIds == undefined) {- if (!target.hasClass("in")) {- target.collapse("show");- $(target[0].trigger).removeClass("collapsed");- } else {- target.collapse("hide");- $(target[0].trigger).addClass("collapsed");- }- } else if (!target.hasClass("in")) {- for (var i in target[0].collapsibleIds) {- var collapsible = $("#" + target[0].collapsibleIds[i]);- if (collapsible.hasClass("in")) {- collapsible.collapse("hide");- $(collapsible[0].trigger).addClass("collapsed");- }- }- target.collapse("show");- $(target[0].trigger).removeClass("collapsed");- }- });- },-- setupAccordion: function(accordionId) {- var accordion = $("#" + accordionId);- var collapsibleIds = new Array();- accordion.find(".collapse:not(#" + accordionId + " .collapse .collapse, #" + accordionId + " .accordion .collapse)").each(function() {- collapsibleIds.push(this.id);- });- if (collapsibleIds[0]) {- var collapsible = $("#" + collapsibleIds[0]);- collapsible.removeClass("collapse");- collapsible.addClass("in");- }- for (var i in collapsibleIds) {- var collapsible = $("#" + collapsibleIds[i]);- if (i == 0) {- $(collapsible[0].trigger).removeClass("collapsed");- collapsible.removeClass("collapse");- collapsible.addClass("in");- } else {- $(collapsible[0].trigger).addClass("collapsed");- }- collapsible[0].collapsibleIds = collapsibleIds;- }- },-- editable: {- adjustReflectionEditor: function(editorId) {- var editor = $("#" + editorId);- var input = editor.find(".value>input[type=checkbox]");- input.parent().prev("label.name").addClass("pull-left");- input.after("<div style='clear:both;'/>")-- input = editor.find(".value>div>input[type=checkbox]");- input.parent().parent().prev("label.name").addClass("pull-left");- input.after("<div style='clear:both;'/>")- }- },-- form: {- /*- * This function can be called to mark enclosing form of specified element dirty. It should be- * called if underlying data has been changed but no form fields are updated, for instance- * when sorting the elements inside a form.- */- markDirty: function($forms) {- $forms.addClass("dirty").find(".dirty-aware").removeAttr("disabled");- },- markClean: function($forms) {- $forms.removeClass("dirty").find(".dirty-aware").attr("disabled", "disabled");- },- removeDirty: function(triggerId, $forms) {- $(function() {- var $trigger = $("#" + triggerId);-- var previousClick;-- var handlers = $._data($trigger[0], 'events').click;-- $.each(handlers, function(i,f) {- previousClick = f.handler;- return false;- });-- $trigger.unbind('click');-- $trigger.click(function(event){- pmease.commons.form.markClean($forms);- previousClick(event);- });- });- },- trackDirty: function(form) {- var $form = $(form);- var $dirtyAware = $form.find(".dirty-aware");-- if ($dirtyAware.length != 0) {- $form.addClass("ays-inited");- $dirtyAware.attr("disabled", "disabled");-- $form.areYouSure({- "silent": !$form.hasClass("leave-confirm"),- "addRemoveFieldsMarksDirty": true,- change: function() {- if ($(this).hasClass("dirty")) {- $(this).find(".dirty-aware").removeAttr("disabled");- } else {- $(this).find(".dirty-aware").attr("disabled", "disabled")- }- }- });- } else if ($form.hasClass("leave-confirm")) {- $form.areYouSure({"addRemoveFieldsMarksDirty": true});- }- },- setupDirtyCheck: function() {- $("form").each(function() {- pmease.commons.form.trackDirty(this);- });-- $(document).on("elementReplaced", function(event, componentId) {- var $component = $("#" + componentId);- var $forms = $component.find("form");- if ($component.is("form"))- $forms = $forms.add($component);- $forms.each(function() {- pmease.commons.form.trackDirty(this);- });-- $component.closest("form.ays-inited").not($component).trigger("checkform.areYouSure");- });-- if (Wicket && Wicket.Ajax) {- var processAjaxResponse = Wicket.Ajax.Call.prototype.processAjaxResponse;- Wicket.Ajax.Call.prototype.processAjaxResponse = function (data, textStatus, jqXHR, context) {- if (jqXHR.readyState === 4) {- var redirectUrl;- try {- redirectUrl = jqXHR.getResponseHeader('Ajax-Location');- } catch (ignore) { // might happen in older mozilla- }-- if (typeof(redirectUrl) !== "undefined" && redirectUrl !== null && redirectUrl !== "") {- $("form.leave-confirm").removeClass("dirty");- }- }- processAjaxResponse.call(this, data, textStatus, jqXHR, context);- }- }- },- confirmLeave: function(containerId) {- var $container;- if (containerId)- $container = $("#" + containerId);- else- $container = $(document);- var dirty = "form.leave-confirm.dirty";- if ($container.is(dirty) || $container.find(dirty).length != 0)- return confirm("There are unsaved changes, do you want to discard and continue?");- else- return true;- }- },- setupAutoSize: function() {- autosize($("textarea"));- $(document).on("elementReplaced", function(event, componentId) {- var $component = $("#" + componentId);- var $textarea = $component.find("textarea");- if ($component.is("textarea"))- $textarea = $textarea.add($component);- autosize($textarea);- });- },- setupAjaxLoadingIndicator: function() {- $("#ajax-loading-overlay").click(function(e) {- e.stopPropagation();- });-- Wicket.Event.subscribe('/ajax/call/beforeSend', function() {- var $ajaxLoadingIndicator = $("#ajax-loading-indicator");- if ($ajaxLoadingIndicator[0].timer)- clearTimeout($ajaxLoadingIndicator[0].timer);- $ajaxLoadingIndicator[0].timer = setTimeout(function() {- if (!$ajaxLoadingIndicator.is(":visible"))- $ajaxLoadingIndicator.show();- }, 2000);- });-- Wicket.Event.subscribe('/ajax/call/complete', function() {- var $ajaxLoadingIndicator = $("#ajax-loading-indicator");- if ($ajaxLoadingIndicator[0].timer) {- clearTimeout($ajaxLoadingIndicator[0].timer);- $ajaxLoadingIndicator[0].timer = null;- }- $ajaxLoadingIndicator.hide();- });- },-- stick: function(sticky, parent) {- var $sticky = $(sticky);- var offset = 0;- var $parent;- if (parent != undefined)- $parent = $(parent);- else- $parent = $sticky.parent();- $parent.parents().each(function() {- var $this = $(this);- var maxHeight = 0;- $this.children(".sticky").each(function() {- var height = $(this).outerHeight();- if (height > maxHeight)- maxHeight = height;- });- offset += maxHeight;- });- if (parent != undefined)- $sticky.stick_in_parent({"offset_top": offset, "parent": parent, "inner_scrolling": false});- else- $sticky.stick_in_parent({"offset_top": offset, "inner_scrolling": false});- },-- scroll: {- setupScrollStop: function() {- var $window = $(window);- $window.scroll(function() {- if ($window.data('scrollTimeout')) {- clearTimeout($window.data('scrollTimeout'));- }- $window.data('scrollTimeout', setTimeout("$(window).trigger('scrollStopped');",250));- });- },-- getTopOffset: function(selector) {- var offset = 0;- $(selector).first().parents().each(function() {- var $this = $(this);- var maxHeight = 0;- $this.children(".sticky").each(function() {- var height = $(this).outerHeight();- if (height > maxHeight)- maxHeight = height;- });- offset += maxHeight;- });- return offset;- },-- next: function(selector, margin) {- var next = pmease.commons.scroll.getNext(selector, margin);- if (next != null) {- var topOffset = margin + pmease.commons.scroll.getTopOffset(selector);- $('html, body').animate({scrollTop: $(next).offset().top - topOffset}, 500);- }- },-- prev: function(selector, margin) {- var prev = pmease.commons.scroll.getPrev(selector, margin);- if (prev != null) {- var topOffset = margin + pmease.commons.scroll.getTopOffset(selector);- $('html, body').animate({scrollTop: $(prev).offset().top - topOffset}, 500);- }- },-- getNext: function(selector, margin) {- var next = null;- $(selector).each(function() {- var bottom = $(window).scrollTop() + $(window).height() - margin;-- var thisTop = $(this).offset().top;- if (bottom < thisTop && $(document).height() - thisTop > margin) {- next = this;- return false;- }- });- return next;- },-- getPrev: function(selector, margin) {- var topOffset = margin + pmease.commons.scroll.getTopOffset(selector);- var prev = null;- $($(selector).get().reverse()).each(function() {- var top = $(window).scrollTop() + topOffset;-- var thisTop = $(this).offset().top;- if (top > thisTop && thisTop > topOffset) {- prev = this;- return false;- }- });- return prev;- }-- },-- focus: {- $components: null,-- focusOn: function(componentId) {- if (componentId)- pmease.commons.focus.doFocus($("#" + componentId));- pmease.commons.focus.$components = null;- },-- doFocus: function($containers) {- $containers.find(".focusable:visible").each(function() {- var $this = $(this);- if ($this.parents(".nofocus").length == 0) {- $this.focus();- return false;- }- });- $containers.find(".has-error:first .focusable").focus();- },-- setupAutoFocus: function() {- if (typeof(Wicket) != "undefined" && typeof(Wicket.Focus) != "undefined") {- var wicketSetFocusOnId = Wicket.Focus.setFocusOnId;- Wicket.Focus.setFocusOnId = function(componentId) {- pmease.commons.focus.focusOn(componentId);- wicketSetFocusOnId(componentId);- }- }-- Wicket.Event.subscribe('/ajax/call/beforeSend', function() {- pmease.commons.focus.$components = $();- });- Wicket.Event.subscribe('/ajax/call/complete', function() {- if (pmease.commons.focus.$components != null)- pmease.commons.focus.doFocus(pmease.commons.focus.$components);- });-- pmease.commons.focus.doFocus($(document));-- $(document).on("elementReplaced", function(event, componentId) {- if (pmease.commons.focus.$components != null)- pmease.commons.focus.$components = pmease.commons.focus.$components.add("#" + componentId);- });- },-- },-- // Disable specified button if value of specified input is blank- disableIfBlank: function(inputId, buttonId) {- var $input = $("#" + inputId);- $input.bind("input propertychange keyup", function() {- var value = $(this).val();- var $button = $("#" + buttonId);- if (value.trim().length != 0)- $button.removeAttr("disabled");- else- $button.attr("disabled", "disabled");- });- $input.trigger("input");- },-- autoHeight: function(targetSelector, bottomOffset) {- var adjustHeight = function() {- $(targetSelector).css("max-height", $(document).scrollTop() + $(window).height()- - $(targetSelector).offset().top - bottomOffset + "px");- };- adjustHeight();- $(window).resize(adjustHeight);- $(window).scroll(adjustHeight);- },-- showSessionFeedback: function() {- if ($("#session-feedback li").length != 0) {- var feedback = $("#session-feedback");- var x = ($(window).width() - feedback.outerWidth()) / 2;- feedback.css("left", x+$(window).scrollLeft());- feedback.css("top", $(window).scrollTop());- feedback.slideDown("slow");-- var body = $("body");- if (body[0].hideCatchAllFeedbackTimer) {- clearTimeout(body[0].hideCatchAllFeedbackTimer);- }- body[0].hideCatchAllFeedbackTimer = setTimeout(function() {- $("#session-feedback").slideUp();- }, 5000);- }- },-- backToTop: function(backToTop) {- var $backToTop = $(backToTop);- $backToTop.hide();- $(window).scroll(function(){- if ($(window).scrollTop()>500)- $backToTop.fadeIn(1000);- else- $backToTop.fadeOut(1000);- });- $backToTop.click(function(){- $("body, html").animate({scrollTop:0}, 700);- return false;- });- },-- choiceFormatter: {- id: {- formatSelection: function(choice) {- return choice.id;- },-- formatResult: function(choice) {- return choice.id;- },-- escapeMarkup: function(m) {- return m;- }- }- },-- websocket: {- setupCallback: function() {- Wicket.Event.subscribe("/websocket/message", function(jqEvent, message) {- var json = JSON.parse(message);- if (json.type == "RenderCallback")- Wicket.WebSocket.send(message);- else if (json.type == "ErrorMessage")- $("#websocket-error").show();- });- },- },-- history: {- init: function(callback) {- pmease.commons.history.urlWithoutHash = location.pathname+(location.search?location.search:"");-- // Use a timeout here solve the problem that Safari (and previous versions of Chrome)- // fires event "onpopstate" on initial page load and this causes the page to reload- // infinitely- setTimeout(function() {- window.onpopstate = function(event) {- var currentUrlWithoutHash = location.pathname+(location.search?location.search:"");- if (currentUrlWithoutHash != pmease.commons.history.urlWithoutHash) { // ignore hash changes- if (pmease.commons.form.confirmLeave()) {- if (!event.state || !event.state.data)- location.reload();- else- callback(event.state.data);- pmease.commons.history.current = {- state: event.state,- url: window.location.href- };- } else {- history.pushState(pmease.commons.history.current.state, '' ,- pmease.commons.history.current.url);- }- }- pmease.commons.history.urlWithoutHash = currentUrlWithoutHash;- };- }, 100);-- pmease.commons.history.current = {- url: window.location.href- };- },- pushState: function(data, url) {- var state = {data: data};- pmease.commons.history.current = {state: state, url: url};- history.pushState(state, '', url);- pmease.commons.history.urlWithoutHash = location.pathname+(location.search?location.search:'');- },- replaceState: function(data, url) {- var state = {data: data};- pmease.commons.history.current = {state: state, url: url};- history.replaceState(state, '', url);- pmease.commons.history.urlWithoutHash = location.pathname+(location.search?location.search:'');- },- setScroll: function(scroll) {- var state = history.state;- if (!state)- state = {};- var newState = {scroll: scroll, cursor: state.cursor, data: state.data};- history.replaceState(newState, '', window.location.href );- pmease.commons.history.current = {- state: newState,- url: window.location.href- };- },- setCursor: function(cursor) {- var state = history.state;- if (!state)- state = {};- var newState = {cursor: cursor, scroll: state.scroll, data: state.data};- history.replaceState(newState, '', window.location.href );- pmease.commons.history.current = {- state: newState,- url: window.location.href- };- },- getScroll: function() {- if (history.state && history.state.scroll)- return history.state.scroll;- else- return undefined;- },- getCursor: function() {- if (history.state && history.state.cursor)- return history.state.cursor;- else- return undefined;- }- },- isDevice: function() {- var ua = navigator.userAgent.toLowerCase();- return ua.indexOf("android") != -1- || ua.indexOf("iphone") != -1- || ua.indexOf("ipad") != -1- || ua.indexOf("windows phone") != -1;- }-};--$(function() {- pmease.commons.setupAutoSize();- pmease.commons.setupAjaxLoadingIndicator();- pmease.commons.form.setupDirtyCheck();- pmease.commons.focus.setupAutoFocus();- pmease.commons.scroll.setupScrollStop();- pmease.commons.websocket.setupCallback();-});+/**************************************************************+ * Define common javascript functions and setups here.+ *+ **************************************************************/++var pmease = {};++pmease.commons = {+ setupCollapse: function(triggerId, targetId) {+ var trigger = $("#" + triggerId);+ var target = $("#" + targetId);++ // This script can still be called if CollapseBehavior is added to a+ // a component enclosed in an invisible wicket:enclosure. So we+ // should check if relevant element exists.+ if (!trigger[0] || !target[0])+ return;++ target[0].trigger = trigger[0];++ target.on("shown.bs.collapse hidden.bs.collapse", function() {+ var $floating = target.closest(".floating");+ if ($floating.length != 0) {+ var borderTop = $(window).scrollTop();+ var borderBottom = borderTop + $(window).height();+ var borderLeft = $(window).scrollLeft();+ var borderRight = borderLeft + $(window).width();++ var left = $floating.position().left;+ var top = $floating.position().top;+ var width = $floating.outerWidth();+ var height = $floating.outerHeight();++ if (left < borderLeft || left + width > borderRight+ || top < borderTop || top + height > borderBottom) {+ if ($floating.data("alignment"))+ $floating.align($floating.data("alignment"));+ }+ }++ });+ trigger.click(function() {+ if (target[0].collapsibleIds == undefined) {+ if (!target.hasClass("in")) {+ target.collapse("show");+ $(target[0].trigger).removeClass("collapsed");+ } else {+ target.collapse("hide");+ $(target[0].trigger).addClass("collapsed");+ }+ } else if (!target.hasClass("in")) {+ for (var i in target[0].collapsibleIds) {+ var collapsible = $("#" + target[0].collapsibleIds[i]);+ if (collapsible.hasClass("in")) {+ collapsible.collapse("hide");+ $(collapsible[0].trigger).addClass("collapsed");+ }+ }+ target.collapse("show");+ $(target[0].trigger).removeClass("collapsed");+ }+ });+ },++ setupAccordion: function(accordionId) {+ var accordion = $("#" + accordionId);+ var collapsibleIds = new Array();+ accordion.find(".collapse:not(#" + accordionId + " .collapse .collapse, #" + accordionId + " .accordion .collapse)").each(function() {+ collapsibleIds.push(this.id);+ });+ if (collapsibleIds[0]) {+ var collapsible = $("#" + collapsibleIds[0]);+ collapsible.removeClass("collapse");+ collapsible.addClass("in");+ }+ for (var i in collapsibleIds) {+ var collapsible = $("#" + collapsibleIds[i]);+ if (i == 0) {+ $(collapsible[0].trigger).removeClass("collapsed");+ collapsible.removeClass("collapse");+ collapsible.addClass("in");+ } else {+ $(collapsible[0].trigger).addClass("collapsed");+ }+ collapsible[0].collapsibleIds = collapsibleIds;+ }+ },++ editable: {+ adjustReflectionEditor: function(editorId) {+ var editor = $("#" + editorId);+ var input = editor.find(".value>input[type=checkbox]");+ input.parent().prev("label.name").addClass("pull-left");+ input.after("<div style='clear:both;'/>")++ input = editor.find(".value>div>input[type=checkbox]");+ input.parent().parent().prev("label.name").addClass("pull-left");+ input.after("<div style='clear:both;'/>")+ }+ },++ form: {+ /*+ * This function can be called to mark enclosing form of specified element dirty. It should be+ * called if underlying data has been changed but no form fields are updated, for instance+ * when sorting the elements inside a form.+ */+ markDirty: function($forms) {+ $forms.addClass("dirty").find(".dirty-aware").removeAttr("disabled");+ },+ markClean: function($forms) {+ $forms.removeClass("dirty").find(".dirty-aware").attr("disabled", "disabled");+ },+ removeDirty: function(triggerId, $forms) {+ $(function() {+ var $trigger = $("#" + triggerId);++ var previousClick;++ var handlers = $._data($trigger[0], 'events').click;++ $.each(handlers, function(i,f) {+ previousClick = f.handler;+ return false;+ });++ $trigger.unbind('click');++ $trigger.click(function(event){+ pmease.commons.form.markClean($forms);+ previousClick(event);+ });+ });+ },+ trackDirty: function(form) {+ var $form = $(form);+ var $dirtyAware = $form.find(".dirty-aware");++ if ($dirtyAware.length != 0) {+ $form.addClass("ays-inited");+ $dirtyAware.attr("disabled", "disabled");++ $form.areYouSure({+ "silent": !$form.hasClass("leave-confirm"),+ "addRemoveFieldsMarksDirty": true,+ change: function() {+ if ($(this).hasClass("dirty")) {+ $(this).find(".dirty-aware").removeAttr("disabled");+ } else {+ $(this).find(".dirty-aware").attr("disabled", "disabled")+ }+ }+ });+ } else if ($form.hasClass("leave-confirm")) {+ $form.areYouSure({"addRemoveFieldsMarksDirty": true});+ }+ },+ setupDirtyCheck: function() {+ $("form").each(function() {+ pmease.commons.form.trackDirty(this);+ });++ $(document).on("elementReplaced", function(event, componentId) {+ var $component = $("#" + componentId);+ var $forms = $component.find("form");+ if ($component.is("form"))+ $forms = $forms.add($component);+ $forms.each(function() {+ pmease.commons.form.trackDirty(this);+ });++ $component.closest("form.ays-inited").not($component).trigger("checkform.areYouSure");+ });++ if (Wicket && Wicket.Ajax) {+ var processAjaxResponse = Wicket.Ajax.Call.prototype.processAjaxResponse;+ Wicket.Ajax.Call.prototype.processAjaxResponse = function (data, textStatus, jqXHR, context) {+ if (jqXHR.readyState === 4) {+ var redirectUrl;+ try {+ redirectUrl = jqXHR.getResponseHeader('Ajax-Location');+ } catch (ignore) { // might happen in older mozilla+ }++ if (typeof(redirectUrl) !== "undefined" && redirectUrl !== null && redirectUrl !== "") {+ $("form.leave-confirm").removeClass("dirty");+ }+ }+ processAjaxResponse.call(this, data, textStatus, jqXHR, context);+ }+ }+ },+ confirmLeave: function(containerId) {+ var $container;+ if (containerId)+ $container = $("#" + containerId);+ else+ $container = $(document);+ var dirty = "form.leave-confirm.dirty";+ if ($container.is(dirty) || $container.find(dirty).length != 0)+ return confirm("There are unsaved changes, do you want to discard and continue?");+ else+ return true;+ }+ },+ setupAutoSize: function() {+ autosize($("textarea"));+ $(document).on("elementReplaced", function(event, componentId) {+ var $component = $("#" + componentId);+ var $textarea = $component.find("textarea");+ if ($component.is("textarea"))+ $textarea = $textarea.add($component);+ autosize($textarea);+ });+ },+ setupAjaxLoadingIndicator: function() {+ $("#ajax-loading-overlay").click(function(e) {+ e.stopPropagation();+ });++ Wicket.Event.subscribe('/ajax/call/beforeSend', function() {+ var $ajaxLoadingIndicator = $("#ajax-loading-indicator");+ if ($ajaxLoadingIndicator[0].timer)+ clearTimeout($ajaxLoadingIndicator[0].timer);+ $ajaxLoadingIndicator[0].timer = setTimeout(function() {+ if (!$ajaxLoadingIndicator.is(":visible"))+ $ajaxLoadingIndicator.show();+ }, 2000);+ });++ Wicket.Event.subscribe('/ajax/call/complete', function() {+ var $ajaxLoadingIndicator = $("#ajax-loading-indicator");+ if ($ajaxLoadingIndicator[0].timer) {+ clearTimeout($ajaxLoadingIndicator[0].timer);+ $ajaxLoadingIndicator[0].timer = null;+ }+ $ajaxLoadingIndicator.hide();+ });+ },++ stick: function(sticky, parent) {+ var $sticky = $(sticky);+ var offset = 0;+ var $parent;+ if (parent != undefined)+ $parent = $(parent);+ else+ $parent = $sticky.parent();+ $parent.parents().each(function() {+ var $this = $(this);+ var maxHeight = 0;+ $this.children(".sticky").each(function() {+ var height = $(this).outerHeight();+ if (height > maxHeight)+ maxHeight = height;+ });+ offset += maxHeight;+ });+ if (parent != undefined)+ $sticky.stick_in_parent({"offset_top": offset, "parent": parent, "inner_scrolling": false});+ else+ $sticky.stick_in_parent({"offset_top": offset, "inner_scrolling": false});+ },++ scroll: {+ setupScrollStop: function() {+ var $window = $(window);+ $window.scroll(function() {+ if ($window.data('scrollTimeout')) {+ clearTimeout($window.data('scrollTimeout'));+ }+ $window.data('scrollTimeout', setTimeout("$(window).trigger('scrollStopped');",250));+ });+ },++ getTopOffset: function(selector) {+ var offset = 0;+ $(selector).first().parents().each(function() {+ var $this = $(this);+ var maxHeight = 0;+ $this.children(".sticky").each(function() {+ var height = $(this).outerHeight();+ if (height > maxHeight)+ maxHeight = height;+ });+ offset += maxHeight;+ });+ return offset;+ },++ next: function(selector, margin) {+ var next = pmease.commons.scroll.getNext(selector, margin);+ if (next != null) {+ var topOffset = margin + pmease.commons.scroll.getTopOffset(selector);+ $('html, body').animate({scrollTop: $(next).offset().top - topOffset}, 500);+ }+ },++ prev: function(selector, margin) {+ var prev = pmease.commons.scroll.getPrev(selector, margin);+ if (prev != null) {+ var topOffset = margin + pmease.commons.scroll.getTopOffset(selector);+ $('html, body').animate({scrollTop: $(prev).offset().top - topOffset}, 500);+ }+ },++ getNext: function(selector, margin) {+ var next = null;+ $(selector).each(function() {+ var bottom = $(window).scrollTop() + $(window).height() - margin;++ var thisTop = $(this).offset().top;+ if (bottom < thisTop && $(document).height() - thisTop > margin) {+ next = this;+ return false;+ }+ });+ return next;+ },++ getPrev: function(selector, margin) {+ var topOffset = margin + pmease.commons.scroll.getTopOffset(selector);+ var prev = null;+ $($(selector).get().reverse()).each(function() {+ var top = $(window).scrollTop() + topOffset;++ var thisTop = $(this).offset().top;+ if (top > thisTop && thisTop > topOffset) {+ prev = this;+ return false;+ }+ });+ return prev;+ }++ },++ focus: {+ $components: null,++ focusOn: function(componentId) {+ if (componentId)+ pmease.commons.focus.doFocus($("#" + componentId));+ pmease.commons.focus.$components = null;+ },++ doFocus: function($containers) {+ var $inError = $containers.find(".has-error:first .focusable");+ if ($inError.length != 0) {+ $inError.focus();+ } else {+ $containers.find(".focusable:visible").each(function() {+ var $this = $(this);+ if ($this.parents(".nofocus").length == 0) {+ $this.focus();+ return false;+ }+ });+ }+ },++ setupAutoFocus: function() {+ if (typeof(Wicket) != "undefined" && typeof(Wicket.Focus) != "undefined") {+ var wicketSetFocusOnId = Wicket.Focus.setFocusOnId;+ Wicket.Focus.setFocusOnId = function(componentId) {+ pmease.commons.focus.focusOn(componentId);+ wicketSetFocusOnId(componentId);+ }+ }++ Wicket.Event.subscribe('/ajax/call/beforeSend', function() {+ pmease.commons.focus.$components = $();+ });+ Wicket.Event.subscribe('/ajax/call/complete', function() {+ if (pmease.commons.focus.$components != null)+ pmease.commons.focus.doFocus(pmease.commons.focus.$components);+ });++ pmease.commons.focus.doFocus($(document));++ $(document).on("elementReplaced", function(event, componentId) {+ if (pmease.commons.focus.$components != null)+ pmease.commons.focus.$components = pmease.commons.focus.$components.add("#" + componentId);+ });+ },++ },++ // Disable specified button if value of specified input is blank+ disableIfBlank: function(inputId, buttonId) {+ var $input = $("#" + inputId);+ $input.bind("input propertychange keyup", function() {+ var value = $(this).val();+ var $button = $("#" + buttonId);+ if (value.trim().length != 0)+ $button.removeAttr("disabled");+ else+ $button.attr("disabled", "disabled");+ });+ $input.trigger("input");+ },++ autoHeight: function(targetSelector, bottomOffset) {+ var adjustHeight = function() {+ $(targetSelector).css("max-height", $(document).scrollTop() + $(window).height()+ - $(targetSelector).offset().top - bottomOffset + "px");+ };+ adjustHeight();+ $(window).resize(adjustHeight);+ $(window).scroll(adjustHeight);+ },++ showSessionFeedback: function() {+ if ($("#session-feedback li").length != 0) {+ var feedback = $("#session-feedback");+ var x = ($(window).width() - feedback.outerWidth()) / 2;+ feedback.css("left", x+$(window).scrollLeft());+ feedback.css("top", $(window).scrollTop());+ feedback.slideDown("slow");++ var body = $("body");+ if (body[0].hideCatchAllFeedbackTimer) {+ clearTimeout(body[0].hideCatchAllFeedbackTimer);+ }+ body[0].hideCatchAllFeedbackTimer = setTimeout(function() {+ $("#session-feedback").slideUp();+ }, 5000);+ }+ },++ backToTop: function(backToTop) {+ var $backToTop = $(backToTop);+ $backToTop.hide();+ $(window).scroll(function(){+ if ($(window).scrollTop()>500)+ $backToTop.fadeIn(1000);+ else+ $backToTop.fadeOut(1000);+ });+ $backToTop.click(function(){+ $("body, html").animate({scrollTop:0}, 700);+ return false;+ });+ },++ choiceFormatter: {+ id: {+ formatSelection: function(choice) {+ return choice.id;+ },++ formatResult: function(choice) {+ return choice.id;+ },++ escapeMarkup: function(m) {+ return m;+ }+ }+ },++ websocket: {+ setupCallback: function() {+ Wicket.Event.subscribe("/websocket/message", function(jqEvent, message) {+ var json = JSON.parse(message);+ if (json.type == "RenderCallback")+ Wicket.WebSocket.send(message);+ else if (json.type == "ErrorMessage")+ $("#websocket-error").show();+ });+ },+ },++ history: {+ init: function(callback) {+ pmease.commons.history.urlWithoutHash = location.pathname+(location.search?location.search:"");++ // Use a timeout here solve the problem that Safari (and previous versions of Chrome)+ // fires event "onpopstate" on initial page load and this causes the page to reload+ // infinitely+ setTimeout(function() {+ window.onpopstate = function(event) {+ var currentUrlWithoutHash = location.pathname+(location.search?location.search:"");+ if (currentUrlWithoutHash != pmease.commons.history.urlWithoutHash) { // ignore hash changes+ if (pmease.commons.form.confirmLeave()) {+ if (!event.state || !event.state.data)+ location.reload();+ else+ callback(event.state.data);+ pmease.commons.history.current = {+ state: event.state,+ url: window.location.href+ };+ } else {+ history.pushState(pmease.commons.history.current.state, '' ,+ pmease.commons.history.current.url);+ }+ }+ pmease.commons.history.urlWithoutHash = currentUrlWithoutHash;+ };+ }, 100);++ pmease.commons.history.current = {+ url: window.location.href+ };+ },+ pushState: function(data, url) {+ var state = {data: data};+ pmease.commons.history.current = {state: state, url: url};+ history.pushState(state, '', url);+ pmease.commons.history.urlWithoutHash = location.pathname+(location.search?location.search:'');+ },+ replaceState: function(data, url) {+ var state = {data: data};+ pmease.commons.history.current = {state: state, url: url};+ history.replaceState(state, '', url);+ pmease.commons.history.urlWithoutHash = location.pathname+(location.search?location.search:'');+ },+ setScroll: function(scroll) {+ var state = history.state;+ if (!state)+ state = {};+ var newState = {scroll: scroll, cursor: state.cursor, data: state.data};+ history.replaceState(newState, '', window.location.href );+ pmease.commons.history.current = {+ state: newState,+ url: window.location.href+ };+ },+ setCursor: function(cursor) {+ var state = history.state;+ if (!state)+ state = {};+ var newState = {cursor: cursor, scroll: state.scroll, data: state.data};+ history.replaceState(newState, '', window.location.href );+ pmease.commons.history.current = {+ state: newState,+ url: window.location.href+ };+ },+ getScroll: function() {+ if (history.state && history.state.scroll)+ return history.state.scroll;+ else+ return undefined;+ },+ getCursor: function() {+ if (history.state && history.state.cursor)+ return history.state.cursor;+ else+ return undefined;+ }+ },+ isDevice: function() {+ var ua = navigator.userAgent.toLowerCase();+ return ua.indexOf("android") != -1+ || ua.indexOf("iphone") != -1+ || ua.indexOf("ipad") != -1+ || ua.indexOf("windows phone") != -1;+ }+};++$(function() {+ pmease.commons.setupAutoSize();+ pmease.commons.setupAjaxLoadingIndicator();+ pmease.commons.form.setupDirtyCheck();+ pmease.commons.focus.setupAutoFocus();+ pmease.commons.scroll.setupScrollStop();+ pmease.commons.websocket.setupCallback();+});diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/ANTLRAssistBehavior.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/ANTLRAssistBehavior.javaindex 9ce2e5ccb9..2a7e26367e 100644--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/ANTLRAssistBehavior.java+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/ANTLRAssistBehavior.java@@ -1,233 +1,233 @@-package com.pmease.commons.wicket.behavior.inputassist;--import java.lang.reflect.Constructor;-import java.lang.reflect.InvocationTargetException;-import java.lang.reflect.Method;-import java.util.ArrayList;-import java.util.List;--import javax.annotation.Nullable;--import org.antlr.v4.runtime.ANTLRInputStream;-import org.antlr.v4.runtime.BaseErrorListener;-import org.antlr.v4.runtime.CharStream;-import org.antlr.v4.runtime.CommonToken;-import org.antlr.v4.runtime.CommonTokenStream;-import org.antlr.v4.runtime.Lexer;-import org.antlr.v4.runtime.Parser;-import org.antlr.v4.runtime.RecognitionException;-import org.antlr.v4.runtime.Recognizer;-import org.antlr.v4.runtime.Token;-import org.antlr.v4.runtime.TokenStream;--import com.pmease.commons.antlr.AntlrUtils;-import com.pmease.commons.antlr.codeassist.CodeAssist;-import com.pmease.commons.antlr.codeassist.InputCompletion;-import com.pmease.commons.antlr.codeassist.InputStatus;-import com.pmease.commons.antlr.codeassist.InputSuggestion;-import com.pmease.commons.antlr.codeassist.ParentedElement;-import com.pmease.commons.antlr.grammar.ElementSpec;-import com.pmease.commons.util.Range;-import com.pmease.commons.util.StringUtils;--@SuppressWarnings("serial")-public abstract class ANTLRAssistBehavior extends InputAssistBehavior {-- protected final Class<? extends Lexer> lexerClass;-- protected final Class<? extends Parser> parserClass;-- private transient Constructor<? extends Lexer> lexerCtor;-- private transient Constructor<? extends Parser> parserCtor;-- private transient Method ruleMethod;-- protected final CodeAssist codeAssist;-- protected final String ruleName;-- public ANTLRAssistBehavior(Class<? extends Parser> parserClass, String ruleName) {- this(parserClass, AntlrUtils.getLexerClass(parserClass), ruleName);- }-- public ANTLRAssistBehavior(Class<? extends Parser> parserClass,- Class<? extends Lexer> lexerClass, String ruleName) {- this(parserClass, lexerClass,- new String[]{AntlrUtils.getDefaultGrammarFile(lexerClass)},- AntlrUtils.getDefaultTokenFile(lexerClass), ruleName);- }-- public ANTLRAssistBehavior(Class<? extends Parser> parserClass, Class<? extends Lexer> lexerClass,- String grammarFiles[], String tokenFile, String ruleName) {- this.lexerClass = lexerClass;- this.parserClass = parserClass;-- codeAssist = new CodeAssist(lexerClass, grammarFiles, tokenFile) {-- @Override- protected List<InputSuggestion> suggest(ParentedElement element, String matchWith, int count) {- return ANTLRAssistBehavior.this.suggest(element, matchWith, count);- }-- @Override- protected List<String> getHints(ParentedElement expectedElement, String matchWith) {- return ANTLRAssistBehavior.this.getHints(expectedElement, matchWith);- }-- @Override- protected InputSuggestion wrapAsSuggestion(ParentedElement expectedElement, String suggestedLiteral,- boolean complete) {- return ANTLRAssistBehavior.this.wrapAsSuggestion(expectedElement, suggestedLiteral, complete);- }-- @Override- protected int getEndOfMatch(ElementSpec spec, String content) {- return ANTLRAssistBehavior.this.getEndOfMatch(spec, content);- }-- };- this.ruleName = ruleName;- }-- @Override- protected List<InputCompletion> getSuggestions(InputStatus inputStatus, int count) {- return codeAssist.suggest(inputStatus, ruleName, count);- }-- protected int getEndOfMatch(ElementSpec spec, String content) {- int endOfMatch = 0;- List<Token> tokens = codeAssist.getGrammar().lex(content);- if (!tokens.isEmpty() && tokens.get(0).getStartIndex() == 0) {- endOfMatch = spec.getEndOfMatch(tokens);- if (endOfMatch > 0) // there exist an element match- endOfMatch = tokens.get(endOfMatch-1).getStopIndex()+1; // convert to char index- }- return endOfMatch;- }-- private Constructor<? extends Lexer> getLexerCtor() {- if (lexerCtor == null) {- try {- lexerCtor = lexerClass.getConstructor(CharStream.class);- } catch (NoSuchMethodException | SecurityException e) {- throw new RuntimeException(e);- }-- }- return lexerCtor;- }-- private Constructor<? extends Parser> getParserCtor() {- if (parserCtor == null) {- try {- parserCtor = parserClass.getConstructor(TokenStream.class);- } catch (NoSuchMethodException | SecurityException e) {- throw new RuntimeException(e);- }-- }- return parserCtor;- }-- private Method getRuleMethod() {- if (ruleMethod == null) {- try {- ruleMethod = parserClass.getDeclaredMethod(ruleName);- } catch (NoSuchMethodException | SecurityException e) {- throw new RuntimeException(e);- }- }- return ruleMethod;- }-- @Override- protected List<Range> getErrors(final String inputContent) {- final List<Range> errors = new ArrayList<>();-- Lexer lexer;- try {- lexer = getLexerCtor().newInstance(new ANTLRInputStream(inputContent));- } catch (InstantiationException | IllegalAccessException | IllegalArgumentException- | InvocationTargetException e) {- throw new RuntimeException(e);- }-- lexer.removeErrorListeners();- lexer.addErrorListener(new BaseErrorListener() {-- @Override- public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,- int charPositionInLine, String msg, RecognitionException e) {- int charIndex = getCharIndex(inputContent, line-1, charPositionInLine);- errors.add(new Range(charIndex, recognizer.getInputStream().index()));- }-- });-- Parser parser;- try {- parser = getParserCtor().newInstance(new CommonTokenStream(lexer));- } catch (InstantiationException | IllegalAccessException | IllegalArgumentException- | InvocationTargetException e) {- throw new RuntimeException(e);- }- parser.removeErrorListeners();- parser.addErrorListener(new BaseErrorListener() {-- @Override- public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,- int charPositionInLine, String msg, RecognitionException e) {- int fromIndex = getCharIndex(inputContent, line-1, charPositionInLine);- CommonToken token = (CommonToken) offendingSymbol;- int toIndex;- if (token != null && token.getType() != Token.EOF)- toIndex = fromIndex + token.getText().length() - 1;- else- toIndex = fromIndex;- errors.add(new Range(fromIndex, toIndex));- }-- });- try {- getRuleMethod().invoke(parser);- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {- throw new RuntimeException(e);- }- return errors;- }-- @Override- protected int getAnchor(String content) {- List<Token> tokens = codeAssist.getGrammar().lex(content);- if (tokens.isEmpty()) {- return 0;- } else {- Token lastToken = tokens.get(tokens.size()-1);- String contentAfterLastToken = content.substring(lastToken.getStopIndex()+1);- if (contentAfterLastToken.length() > 0) {- contentAfterLastToken = StringUtils.trimStart(contentAfterLastToken);- return content.length() - contentAfterLastToken.length();- } else {- return lastToken.getStartIndex();- }- }- }-- protected abstract List<InputSuggestion> suggest(ParentedElement element, String matchWith, int count);-- @Override- protected final List<String> getHints(InputStatus inputStatus) {- return codeAssist.getHints(inputStatus, ruleName);- }-- protected List<String> getHints(ParentedElement expectedElement, String matchWith) {- return new ArrayList<>();- }-- @Nullable- protected InputSuggestion wrapAsSuggestion(ParentedElement expectedElement,- String suggestedLiteral, boolean complete) {- return new InputSuggestion(suggestedLiteral, suggestedLiteral.length(), complete, null, null);- }-}+package com.pmease.commons.wicket.behavior.inputassist;++import java.lang.reflect.Constructor;+import java.lang.reflect.InvocationTargetException;+import java.lang.reflect.Method;+import java.util.ArrayList;+import java.util.List;++import javax.annotation.Nullable;++import org.antlr.v4.runtime.ANTLRInputStream;+import org.antlr.v4.runtime.BaseErrorListener;+import org.antlr.v4.runtime.CharStream;+import org.antlr.v4.runtime.CommonToken;+import org.antlr.v4.runtime.CommonTokenStream;+import org.antlr.v4.runtime.Lexer;+import org.antlr.v4.runtime.Parser;+import org.antlr.v4.runtime.RecognitionException;+import org.antlr.v4.runtime.Recognizer;+import org.antlr.v4.runtime.Token;+import org.antlr.v4.runtime.TokenStream;++import com.pmease.commons.antlr.AntlrUtils;+import com.pmease.commons.antlr.codeassist.CodeAssist;+import com.pmease.commons.antlr.codeassist.InputCompletion;+import com.pmease.commons.antlr.codeassist.InputStatus;+import com.pmease.commons.antlr.codeassist.InputSuggestion;+import com.pmease.commons.antlr.codeassist.ParentedElement;+import com.pmease.commons.antlr.grammar.ElementSpec;+import com.pmease.commons.util.Range;+import com.pmease.commons.util.StringUtils;++@SuppressWarnings("serial")+public abstract class ANTLRAssistBehavior extends InputAssistBehavior {++ protected final Class<? extends Lexer> lexerClass;++ protected final Class<? extends Parser> parserClass;++ private transient Constructor<? extends Lexer> lexerCtor;++ private transient Constructor<? extends Parser> parserCtor;++ private transient Method ruleMethod;++ protected final CodeAssist codeAssist;++ protected final String ruleName;++ public ANTLRAssistBehavior(Class<? extends Parser> parserClass, String ruleName) {+ this(parserClass, AntlrUtils.getLexerClass(parserClass), ruleName);+ }++ public ANTLRAssistBehavior(Class<? extends Parser> parserClass,+ Class<? extends Lexer> lexerClass, String ruleName) {+ this(parserClass, lexerClass,+ new String[]{AntlrUtils.getDefaultGrammarFile(lexerClass)},+ AntlrUtils.getDefaultTokenFile(lexerClass), ruleName);+ }++ public ANTLRAssistBehavior(Class<? extends Parser> parserClass, Class<? extends Lexer> lexerClass,+ String grammarFiles[], String tokenFile, String ruleName) {+ this.lexerClass = lexerClass;+ this.parserClass = parserClass;++ codeAssist = new CodeAssist(lexerClass, grammarFiles, tokenFile) {++ @Override+ protected List<InputSuggestion> suggest(ParentedElement element, String matchWith, int count) {+ return ANTLRAssistBehavior.this.suggest(element, matchWith, count);+ }++ @Override+ protected List<String> getHints(ParentedElement expectedElement, String matchWith) {+ return ANTLRAssistBehavior.this.getHints(expectedElement, matchWith);+ }++ @Override+ protected InputSuggestion wrapAsSuggestion(ParentedElement expectedElement, String suggestedLiteral,+ boolean complete) {+ return ANTLRAssistBehavior.this.wrapAsSuggestion(expectedElement, suggestedLiteral, complete);+ }++ @Override+ protected int getEndOfMatch(ElementSpec spec, String content) {+ return ANTLRAssistBehavior.this.getEndOfMatch(spec, content);+ }++ };+ this.ruleName = ruleName;+ }++ @Override+ protected List<InputCompletion> getSuggestions(InputStatus inputStatus, int count) {+ return codeAssist.suggest(inputStatus, ruleName, count);+ }++ protected int getEndOfMatch(ElementSpec spec, String content) {+ int endOfMatch = 0;+ List<Token> tokens = codeAssist.getGrammar().lex(content);+ if (!tokens.isEmpty() && tokens.get(0).getStartIndex() == 0) {+ endOfMatch = spec.getEndOfMatch(tokens);+ if (endOfMatch > 0) // there exist an element match+ endOfMatch = tokens.get(endOfMatch-1).getStopIndex()+1; // convert to char index+ }+ return endOfMatch;+ }++ private Constructor<? extends Lexer> getLexerCtor() {+ if (lexerCtor == null) {+ try {+ lexerCtor = lexerClass.getConstructor(CharStream.class);+ } catch (NoSuchMethodException | SecurityException e) {+ throw new RuntimeException(e);+ }++ }+ return lexerCtor;+ }++ private Constructor<? extends Parser> getParserCtor() {+ if (parserCtor == null) {+ try {+ parserCtor = parserClass.getConstructor(TokenStream.class);+ } catch (NoSuchMethodException | SecurityException e) {+ throw new RuntimeException(e);+ }++ }+ return parserCtor;+ }++ private Method getRuleMethod() {+ if (ruleMethod == null) {+ try {+ ruleMethod = parserClass.getDeclaredMethod(ruleName);+ } catch (NoSuchMethodException | SecurityException e) {+ throw new RuntimeException(e);+ }+ }+ return ruleMethod;+ }++ @Override+ protected List<Range> getErrors(final String inputContent) {+ final List<Range> errors = new ArrayList<>();++ Lexer lexer;+ try {+ lexer = getLexerCtor().newInstance(new ANTLRInputStream(inputContent));+ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException+ | InvocationTargetException e) {+ throw new RuntimeException(e);+ }++ lexer.removeErrorListeners();+ lexer.addErrorListener(new BaseErrorListener() {++ @Override+ public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,+ int charPositionInLine, String msg, RecognitionException e) {+ int charIndex = getCharIndex(inputContent, line-1, charPositionInLine);+ errors.add(new Range(charIndex, recognizer.getInputStream().index()));+ }++ });++ Parser parser;+ try {+ parser = getParserCtor().newInstance(new CommonTokenStream(lexer));+ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException+ | InvocationTargetException e) {+ throw new RuntimeException(e);+ }+ parser.removeErrorListeners();+ parser.addErrorListener(new BaseErrorListener() {++ @Override+ public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,+ int charPositionInLine, String msg, RecognitionException e) {+ int fromIndex = getCharIndex(inputContent, line-1, charPositionInLine);+ CommonToken token = (CommonToken) offendingSymbol;+ int toIndex;+ if (token != null && token.getType() != Token.EOF)+ toIndex = fromIndex + token.getText().length() - 1;+ else+ toIndex = fromIndex;+ errors.add(new Range(fromIndex, toIndex));+ }++ });+ try {+ getRuleMethod().invoke(parser);+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {+ throw new RuntimeException(e);+ }+ return errors;+ }++ @Override+ protected int getAnchor(String content) {+ List<Token> tokens = codeAssist.getGrammar().lex(content);+ if (tokens.isEmpty()) {+ return 0;+ } else {+ Token lastToken = tokens.get(tokens.size()-1);+ String contentAfterLastToken = content.substring(lastToken.getStopIndex()+1);+ if (contentAfterLastToken.length() > 0) {+ contentAfterLastToken = StringUtils.trimStart(contentAfterLastToken);+ return content.length() - contentAfterLastToken.length();+ } else {+ return lastToken.getStartIndex();+ }+ }+ }++ protected abstract List<InputSuggestion> suggest(ParentedElement element, String matchWith, int count);++ @Override+ protected final List<String> getHints(InputStatus inputStatus) {+ return codeAssist.getHints(inputStatus, ruleName);+ }++ protected List<String> getHints(ParentedElement expectedElement, String matchWith) {+ return new ArrayList<>();+ }++ @Nullable+ protected InputSuggestion wrapAsSuggestion(ParentedElement expectedElement,+ String suggestedLiteral, boolean complete) {+ return new InputSuggestion(suggestedLiteral, suggestedLiteral.length(), complete, null, null);+ }+}diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/AssistPanel.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/AssistPanel.javaindex 781d1f3ef1..2aa21b41ab 100644--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/AssistPanel.java+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/AssistPanel.java@@ -1,118 +1,118 @@-package com.pmease.commons.wicket.behavior.inputassist;--import java.util.List;--import org.apache.commons.lang3.StringEscapeUtils;-import org.apache.wicket.Component;-import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;-import org.apache.wicket.ajax.AjaxRequestTarget;-import org.apache.wicket.behavior.AttributeAppender;-import org.apache.wicket.markup.head.IHeaderResponse;-import org.apache.wicket.markup.head.OnDomReadyHeaderItem;-import org.apache.wicket.markup.html.WebMarkupContainer;-import org.apache.wicket.markup.html.basic.Label;-import org.apache.wicket.markup.html.panel.Panel;-import org.apache.wicket.markup.repeater.RepeatingView;--import com.pmease.commons.antlr.codeassist.InputCompletion;-import com.pmease.commons.antlr.codeassist.InputStatus;-import com.pmease.commons.util.Range;--@SuppressWarnings("serial")-class AssistPanel extends Panel {-- private final InputAssistBehavior assistBehavior;-- private final InputStatus inputStatus;-- private List<InputCompletion> suggestions;-- private List<String> hints;-- private RepeatingView suggestionsView;-- private int page = 1;-- public AssistPanel(String id, InputAssistBehavior assistBehavior, InputStatus inputStatus,- List<InputCompletion> suggestions, List<String> hints) {- super(id);- this.assistBehavior = assistBehavior;- this.inputStatus = inputStatus;- this.suggestions = suggestions;- this.hints = hints;- }-- @Override- protected void onInitialize() {- super.onInitialize();-- suggestionsView = new RepeatingView("suggestions");- add(suggestionsView);- for (InputCompletion suggestion: suggestions)- suggestionsView.add(newSuggestionItem(suggestionsView.newChildId(), suggestion));-- RepeatingView hintsView = new RepeatingView("hints");- add(hintsView);- for (String hint: hints)- hintsView.add(new Label(hintsView.newChildId(), hint).setEscapeModelStrings(false));-- add(new AbstractDefaultAjaxBehavior() {-- @Override- protected void respond(AjaxRequestTarget target) {- List<InputCompletion> suggestions = assistBehavior.getSuggestions(inputStatus, (++page)*InputAssistBehavior.PAGE_SIZE);- if (suggestions.size() > AssistPanel.this.suggestions.size()) {- List<InputCompletion> additionalSuggestions =- suggestions.subList(AssistPanel.this.suggestions.size(), suggestions.size());- for (InputCompletion suggestion: additionalSuggestions) {- Component suggestionItem = newSuggestionItem(suggestionsView.newChildId(), suggestion);- suggestionsView.add(suggestionItem);- String script = String.format("$('#%s .suggestions>table>tbody').append('<tr id=\"%s\"></tr>');",- AssistPanel.this.getMarkupId(), suggestionItem.getMarkupId());- target.prependJavaScript(script);- target.add(suggestionItem);- script = String.format("$('#%s').click(function() {$('#%s').data('update')($(this));});",- suggestionItem.getMarkupId(), assistBehavior.getInputField().getMarkupId());- target.appendJavaScript(script);- }- AssistPanel.this.suggestions = suggestions;- }- }-- @Override- public void renderHead(Component component, IHeaderResponse response) {- super.renderHead(component, response);- String script = String.format("pmease.commons.inputassist.initInfiniteScroll('%s', %s);",- getMarkupId(true), getCallbackFunction());- response.render(OnDomReadyHeaderItem.forScript(script));- }-- });- setOutputMarkupId(true);- }-- private Component newSuggestionItem(String itemId, InputCompletion suggestion) {- WebMarkupContainer item = new WebMarkupContainer(itemId);- WebMarkupContainer link = new WebMarkupContainer("link");- Range matchRange = suggestion.getMatchRange();- if (matchRange != null) {- String content = suggestion.getReplaceContent();- String prefix = StringEscapeUtils.escapeHtml4(content.substring(0, matchRange.getFrom()));- String suffix = StringEscapeUtils.escapeHtml4(content.substring(matchRange.getTo()));- String matched = StringEscapeUtils.escapeHtml4(content.substring(matchRange.getFrom(), matchRange.getTo()));- link.add(new Label("label", prefix + "<b>" + matched + "</b>" + suffix).setEscapeModelStrings(false));- } else {- link.add(new Label("label", suggestion.getReplaceContent()));- }- item.add(link);- if (suggestion.getDescription() != null)- item.add(new Label("description", suggestion.getDescription()));- else- item.add(new Label("description").setVisible(false));- item.add(AttributeAppender.append("data-content", suggestion.complete(inputStatus).getContent()));- item.add(AttributeAppender.append("data-caret", suggestion.getCaret()));- item.setOutputMarkupId(true);- return item;- }--}+package com.pmease.commons.wicket.behavior.inputassist;++import java.util.List;++import org.apache.commons.lang3.StringEscapeUtils;+import org.apache.wicket.Component;+import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;+import org.apache.wicket.ajax.AjaxRequestTarget;+import org.apache.wicket.behavior.AttributeAppender;+import org.apache.wicket.markup.head.IHeaderResponse;+import org.apache.wicket.markup.head.OnDomReadyHeaderItem;+import org.apache.wicket.markup.html.WebMarkupContainer;+import org.apache.wicket.markup.html.basic.Label;+import org.apache.wicket.markup.html.panel.Panel;+import org.apache.wicket.markup.repeater.RepeatingView;++import com.pmease.commons.antlr.codeassist.InputCompletion;+import com.pmease.commons.antlr.codeassist.InputStatus;+import com.pmease.commons.util.Range;++@SuppressWarnings("serial")+class AssistPanel extends Panel {++ private final InputAssistBehavior assistBehavior;++ private final InputStatus inputStatus;++ private List<InputCompletion> suggestions;++ private List<String> hints;++ private RepeatingView suggestionsView;++ private int page = 1;++ public AssistPanel(String id, InputAssistBehavior assistBehavior, InputStatus inputStatus,+ List<InputCompletion> suggestions, List<String> hints) {+ super(id);+ this.assistBehavior = assistBehavior;+ this.inputStatus = inputStatus;+ this.suggestions = suggestions;+ this.hints = hints;+ }++ @Override+ protected void onInitialize() {+ super.onInitialize();++ suggestionsView = new RepeatingView("suggestions");+ add(suggestionsView);+ for (InputCompletion suggestion: suggestions)+ suggestionsView.add(newSuggestionItem(suggestionsView.newChildId(), suggestion));++ RepeatingView hintsView = new RepeatingView("hints");+ add(hintsView);+ for (String hint: hints)+ hintsView.add(new Label(hintsView.newChildId(), hint).setEscapeModelStrings(false));++ add(new AbstractDefaultAjaxBehavior() {++ @Override+ protected void respond(AjaxRequestTarget target) {+ List<InputCompletion> suggestions = assistBehavior.getSuggestions(inputStatus, (++page)*InputAssistBehavior.PAGE_SIZE);+ if (suggestions.size() > AssistPanel.this.suggestions.size()) {+ List<InputCompletion> additionalSuggestions =+ suggestions.subList(AssistPanel.this.suggestions.size(), suggestions.size());+ for (InputCompletion suggestion: additionalSuggestions) {+ Component suggestionItem = newSuggestionItem(suggestionsView.newChildId(), suggestion);+ suggestionsView.add(suggestionItem);+ String script = String.format("$('#%s .suggestions>table>tbody').append('<tr id=\"%s\"></tr>');",+ AssistPanel.this.getMarkupId(), suggestionItem.getMarkupId());+ target.prependJavaScript(script);+ target.add(suggestionItem);+ script = String.format("$('#%s').click(function() {$('#%s').data('update')($(this));});",+ suggestionItem.getMarkupId(), assistBehavior.getInputField().getMarkupId());+ target.appendJavaScript(script);+ }+ AssistPanel.this.suggestions = suggestions;+ }+ }++ @Override+ public void renderHead(Component component, IHeaderResponse response) {+ super.renderHead(component, response);+ String script = String.format("pmease.commons.inputassist.initInfiniteScroll('%s', %s);",+ getMarkupId(true), getCallbackFunction());+ response.render(OnDomReadyHeaderItem.forScript(script));+ }++ });+ setOutputMarkupId(true);+ }++ private Component newSuggestionItem(String itemId, InputCompletion suggestion) {+ WebMarkupContainer item = new WebMarkupContainer(itemId);+ WebMarkupContainer link = new WebMarkupContainer("link");+ Range matchRange = suggestion.getMatchRange();+ if (matchRange != null) {+ String content = suggestion.getReplaceContent();+ String prefix = StringEscapeUtils.escapeHtml4(content.substring(0, matchRange.getFrom()));+ String suffix = StringEscapeUtils.escapeHtml4(content.substring(matchRange.getTo()));+ String matched = StringEscapeUtils.escapeHtml4(content.substring(matchRange.getFrom(), matchRange.getTo()));+ link.add(new Label("label", prefix + "<b>" + matched + "</b>" + suffix).setEscapeModelStrings(false));+ } else {+ link.add(new Label("label", suggestion.getReplaceContent()));+ }+ item.add(link);+ if (suggestion.getDescription() != null)+ item.add(new Label("description", suggestion.getDescription()));+ else+ item.add(new Label("description").setVisible(false));+ item.add(AttributeAppender.append("data-content", suggestion.complete(inputStatus).getContent()));+ item.add(AttributeAppender.append("data-caret", suggestion.getCaret()));+ item.setOutputMarkupId(true);+ return item;+ }++}diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/InputAssistBehavior.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/InputAssistBehavior.javaindex 4d218849ad..2f592db55c 100644--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/InputAssistBehavior.java+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/InputAssistBehavior.java@@ -1,216 +1,216 @@-package com.pmease.commons.wicket.behavior.inputassist;--import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;--import java.util.ArrayList;-import java.util.List;--import org.apache.wicket.Component;-import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;-import org.apache.wicket.ajax.AjaxChannel;-import org.apache.wicket.ajax.AjaxRequestTarget;-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;-import org.apache.wicket.markup.head.CssHeaderItem;-import org.apache.wicket.markup.head.IHeaderResponse;-import org.apache.wicket.markup.head.JavaScriptHeaderItem;-import org.apache.wicket.markup.head.OnDomReadyHeaderItem;-import org.apache.wicket.request.IRequestParameters;-import org.apache.wicket.request.cycle.RequestCycle;-import org.apache.wicket.request.resource.CssResourceReference;-import org.apache.wicket.request.resource.JavaScriptResourceReference;--import com.fasterxml.jackson.core.JsonProcessingException;-import com.fasterxml.jackson.databind.ObjectMapper;-import com.google.common.base.Preconditions;-import com.google.common.base.Splitter;-import com.pmease.commons.antlr.codeassist.InputCompletion;-import com.pmease.commons.antlr.codeassist.InputStatus;-import com.pmease.commons.loader.AppLoader;-import com.pmease.commons.util.JoinedRanges;-import com.pmease.commons.util.Range;-import com.pmease.commons.wicket.assets.caret.CaretResourceReference;-import com.pmease.commons.wicket.assets.hotkeys.HotkeysResourceReference;-import com.pmease.commons.wicket.assets.scrollintoview.ScrollIntoViewResourceReference;-import com.pmease.commons.wicket.assets.textareacaretposition.TextareaCaretPositionResourceReference;-import com.pmease.commons.wicket.component.floating.AlignPlacement;-import com.pmease.commons.wicket.component.floating.AlignTarget;-import com.pmease.commons.wicket.component.floating.ComponentTarget;-import com.pmease.commons.wicket.component.floating.FloatingPanel;--@SuppressWarnings("serial")-public abstract class InputAssistBehavior extends AbstractDefaultAjaxBehavior {-- static final int PAGE_SIZE = 25;-- private FloatingPanel dropdown;-- @Override- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {- super.updateAjaxAttributes(attributes);-- attributes.setChannel(new AjaxChannel(AjaxChannel.DEFAULT_NAME, AjaxChannel.Type.DROP));- }-- @Override- protected void onBind() {- super.onBind();-- Component inputField = getComponent();- inputField.setOutputMarkupId(true);- }-- private int getLine(String content, int charIndex) {- int line = 0;- if (charIndex >= content.length())- charIndex = content.length()-1;- for (int i=0; i<=charIndex; i++) {- if (content.charAt(i) == '\n')- line++;- }- return line;- }-- private List<Range> normalizeErrors(String inputContent, List<Range> errors) {- List<Range> normalizedErrors = new ArrayList<>();-- List<String> lines = Splitter.on('\n').splitToList(inputContent);- for (Range error: new JoinedRanges(errors)) {- int fromLine = getLine(inputContent, error.getFrom());- int toLine = getLine(inputContent, error.getTo());- if (fromLine != toLine) {- int index = getCharIndex(inputContent, fromLine, lines.get(fromLine).length()-1);- if (index >= error.getFrom())- normalizedErrors.add(new Range(error.getFrom(), index));- index = getCharIndex(inputContent, toLine, 0);- if (index <= error.getTo())- normalizedErrors.add(new Range(index, error.getTo()));- for (int i=fromLine+1; i<toLine; i++) {- String line = lines.get(i);- if (line.length() != 0) {- int from = getCharIndex(inputContent, i, 0);- normalizedErrors.add(new Range(from, from+line.length()-1));- }- }- } else {- normalizedErrors.add(error);- }- }-- return normalizedErrors;- }-- protected int getCharIndex(String content, int line, int charIndexInLine) {- List<String> lines = Splitter.on('\n').splitToList(content);- int index = 0;- for (int i=0; i<line; i++)- index += lines.get(i).length()+1;- return index + charIndexInLine;- }-- @Override- protected void respond(AjaxRequestTarget target) {- IRequestParameters params = RequestCycle.get().getRequest().getQueryParameters();- String inputContent = params.getParameterValue("input").toString();- Integer inputCaret = params.getParameterValue("caret").toOptionalInteger();-- Preconditions.checkArgument(inputContent.indexOf('\r') == -1);-- List<Range> errors = normalizeErrors(inputContent, getErrors(inputContent));- String json;- try {- json = AppLoader.getInstance(ObjectMapper.class).writeValueAsString(errors);- } catch (JsonProcessingException e) {- throw new RuntimeException(e);- }- String script = String.format("pmease.commons.inputassist.markErrors('%s', %s);",- getComponent().getMarkupId(), json);- target.appendJavaScript(script);-- if (inputCaret != null) {- final InputStatus inputStatus = new InputStatus(inputContent, inputCaret);- final List<InputCompletion> suggestions = getSuggestions(new InputStatus(inputContent, inputCaret), PAGE_SIZE);- if (!suggestions.isEmpty()) {- int anchor = getAnchor(inputContent.substring(0, inputCaret));- if (dropdown == null) {- dropdown = new FloatingPanel(target, new ComponentTarget(getComponent(), anchor), AlignPlacement.bottom(0)) {-- @Override- protected Component newContent(String id) {- return new AssistPanel(id, InputAssistBehavior.this, inputStatus,- suggestions, getHints(inputStatus));- }-- @Override- protected void onClosed(AjaxRequestTarget target) {- super.onClosed(target);- dropdown = null;- }-- };- script = String.format("pmease.commons.inputassist.assistOpened('%s', '%s');",- getComponent().getMarkupId(), dropdown.getMarkupId());- target.appendJavaScript(script);- } else {- Component content = dropdown.getContent();- Component newContent = new AssistPanel(content.getId(), InputAssistBehavior.this,- inputStatus, suggestions, getHints(inputStatus));- content.replaceWith(newContent);- target.add(newContent);-- AlignTarget alignTarget = new ComponentTarget(getComponent(), anchor);- script = String.format("$('#%s').data('alignment').target=%s;", dropdown.getMarkupId(), alignTarget);- target.prependJavaScript(script);-- script = String.format("pmease.commons.inputassist.assistUpdated('%s', '%s');",- getComponent().getMarkupId(), dropdown.getMarkupId());- target.appendJavaScript(script);- }- } else if (dropdown != null) {- dropdown.close(target);- }- } else if (dropdown != null) {- dropdown.close(target);- }- }-- public void close(AjaxRequestTarget target) {- if (dropdown != null)- dropdown.close(target);- }-- Component getInputField() {- return super.getComponent();- }-- @Override- public void renderHead(Component component, IHeaderResponse response) {- super.renderHead(component, response);-- response.render(JavaScriptHeaderItem.forReference(ScrollIntoViewResourceReference.INSTANCE));- response.render(JavaScriptHeaderItem.forReference(CaretResourceReference.INSTANCE));- response.render(JavaScriptHeaderItem.forReference(HotkeysResourceReference.INSTANCE));- response.render(JavaScriptHeaderItem.forReference(TextareaCaretPositionResourceReference.INSTANCE));- response.render(CssHeaderItem.forReference(- new CssResourceReference(AssistPanel.class, "input-assist.css")));-- response.render(JavaScriptHeaderItem.forReference(- new JavaScriptResourceReference(InputAssistBehavior.class, "input-assist.js")));-- String script = String.format("pmease.commons.inputassist.init('%s', %s);",- getComponent().getMarkupId(true),- getCallbackFunction(explicit("input"), explicit("caret")));-- response.render(OnDomReadyHeaderItem.forScript(script));- }-- protected abstract List<InputCompletion> getSuggestions(InputStatus inputStatus, int count);-- protected List<String> getHints(InputStatus inputStatus) {- return new ArrayList<>();- }-- protected abstract List<Range> getErrors(String inputContent);-- protected abstract int getAnchor(String content);-+package com.pmease.commons.wicket.behavior.inputassist;++import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;++import java.util.ArrayList;+import java.util.List;++import org.apache.wicket.Component;+import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;+import org.apache.wicket.ajax.AjaxChannel;+import org.apache.wicket.ajax.AjaxRequestTarget;+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;+import org.apache.wicket.markup.head.CssHeaderItem;+import org.apache.wicket.markup.head.IHeaderResponse;+import org.apache.wicket.markup.head.JavaScriptHeaderItem;+import org.apache.wicket.markup.head.OnDomReadyHeaderItem;+import org.apache.wicket.request.IRequestParameters;+import org.apache.wicket.request.cycle.RequestCycle;+import org.apache.wicket.request.resource.CssResourceReference;+import org.apache.wicket.request.resource.JavaScriptResourceReference;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.google.common.base.Preconditions;+import com.google.common.base.Splitter;+import com.pmease.commons.antlr.codeassist.InputCompletion;+import com.pmease.commons.antlr.codeassist.InputStatus;+import com.pmease.commons.loader.AppLoader;+import com.pmease.commons.util.JoinedRanges;+import com.pmease.commons.util.Range;+import com.pmease.commons.wicket.assets.caret.CaretResourceReference;+import com.pmease.commons.wicket.assets.hotkeys.HotkeysResourceReference;+import com.pmease.commons.wicket.assets.scrollintoview.ScrollIntoViewResourceReference;+import com.pmease.commons.wicket.assets.textareacaretposition.TextareaCaretPositionResourceReference;+import com.pmease.commons.wicket.component.floating.AlignPlacement;+import com.pmease.commons.wicket.component.floating.AlignTarget;+import com.pmease.commons.wicket.component.floating.ComponentTarget;+import com.pmease.commons.wicket.component.floating.FloatingPanel;++@SuppressWarnings("serial")+public abstract class InputAssistBehavior extends AbstractDefaultAjaxBehavior {++ static final int PAGE_SIZE = 25;++ private FloatingPanel dropdown;++ @Override+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {+ super.updateAjaxAttributes(attributes);++ attributes.setChannel(new AjaxChannel(AjaxChannel.DEFAULT_NAME, AjaxChannel.Type.DROP));+ }++ @Override+ protected void onBind() {+ super.onBind();++ Component inputField = getComponent();+ inputField.setOutputMarkupId(true);+ }++ private int getLine(String content, int charIndex) {+ int line = 0;+ if (charIndex >= content.length())+ charIndex = content.length()-1;+ for (int i=0; i<=charIndex; i++) {+ if (content.charAt(i) == '\n')+ line++;+ }+ return line;+ }++ private List<Range> normalizeErrors(String inputContent, List<Range> errors) {+ List<Range> normalizedErrors = new ArrayList<>();++ List<String> lines = Splitter.on('\n').splitToList(inputContent);+ for (Range error: new JoinedRanges(errors)) {+ int fromLine = getLine(inputContent, error.getFrom());+ int toLine = getLine(inputContent, error.getTo());+ if (fromLine != toLine) {+ int index = getCharIndex(inputContent, fromLine, lines.get(fromLine).length()-1);+ if (index >= error.getFrom())+ normalizedErrors.add(new Range(error.getFrom(), index));+ index = getCharIndex(inputContent, toLine, 0);+ if (index <= error.getTo())+ normalizedErrors.add(new Range(index, error.getTo()));+ for (int i=fromLine+1; i<toLine; i++) {+ String line = lines.get(i);+ if (line.length() != 0) {+ int from = getCharIndex(inputContent, i, 0);+ normalizedErrors.add(new Range(from, from+line.length()-1));+ }+ }+ } else {+ normalizedErrors.add(error);+ }+ }++ return normalizedErrors;+ }++ protected int getCharIndex(String content, int line, int charIndexInLine) {+ List<String> lines = Splitter.on('\n').splitToList(content);+ int index = 0;+ for (int i=0; i<line; i++)+ index += lines.get(i).length()+1;+ return index + charIndexInLine;+ }++ @Override+ protected void respond(AjaxRequestTarget target) {+ IRequestParameters params = RequestCycle.get().getRequest().getQueryParameters();+ String inputContent = params.getParameterValue("input").toString();+ Integer inputCaret = params.getParameterValue("caret").toOptionalInteger();++ Preconditions.checkArgument(inputContent.indexOf('\r') == -1);++ List<Range> errors = normalizeErrors(inputContent, getErrors(inputContent));+ String json;+ try {+ json = AppLoader.getInstance(ObjectMapper.class).writeValueAsString(errors);+ } catch (JsonProcessingException e) {+ throw new RuntimeException(e);+ }+ String script = String.format("pmease.commons.inputassist.markErrors('%s', %s);",+ getComponent().getMarkupId(), json);+ target.appendJavaScript(script);++ if (inputCaret != null) {+ final InputStatus inputStatus = new InputStatus(inputContent, inputCaret);+ final List<InputCompletion> suggestions = getSuggestions(new InputStatus(inputContent, inputCaret), PAGE_SIZE);+ if (!suggestions.isEmpty()) {+ int anchor = getAnchor(inputContent.substring(0, inputCaret));+ if (dropdown == null) {+ dropdown = new FloatingPanel(target, new ComponentTarget(getComponent(), anchor), AlignPlacement.bottom(0)) {++ @Override+ protected Component newContent(String id) {+ return new AssistPanel(id, InputAssistBehavior.this, inputStatus,+ suggestions, getHints(inputStatus));+ }++ @Override+ protected void onClosed(AjaxRequestTarget target) {+ super.onClosed(target);+ dropdown = null;+ }++ };+ script = String.format("pmease.commons.inputassist.assistOpened('%s', '%s');",+ getComponent().getMarkupId(), dropdown.getMarkupId());+ target.appendJavaScript(script);+ } else {+ Component content = dropdown.getContent();+ Component newContent = new AssistPanel(content.getId(), InputAssistBehavior.this,+ inputStatus, suggestions, getHints(inputStatus));+ content.replaceWith(newContent);+ target.add(newContent);++ AlignTarget alignTarget = new ComponentTarget(getComponent(), anchor);+ script = String.format("$('#%s').data('alignment').target=%s;", dropdown.getMarkupId(), alignTarget);+ target.prependJavaScript(script);++ script = String.format("pmease.commons.inputassist.assistUpdated('%s', '%s');",+ getComponent().getMarkupId(), dropdown.getMarkupId());+ target.appendJavaScript(script);+ }+ } else if (dropdown != null) {+ dropdown.close(target);+ }+ } else if (dropdown != null) {+ dropdown.close(target);+ }+ }++ public void close(AjaxRequestTarget target) {+ if (dropdown != null)+ dropdown.close(target);+ }++ Component getInputField() {+ return super.getComponent();+ }++ @Override+ public void renderHead(Component component, IHeaderResponse response) {+ super.renderHead(component, response);++ response.render(JavaScriptHeaderItem.forReference(ScrollIntoViewResourceReference.INSTANCE));+ response.render(JavaScriptHeaderItem.forReference(CaretResourceReference.INSTANCE));+ response.render(JavaScriptHeaderItem.forReference(HotkeysResourceReference.INSTANCE));+ response.render(JavaScriptHeaderItem.forReference(TextareaCaretPositionResourceReference.INSTANCE));+ response.render(CssHeaderItem.forReference(+ new CssResourceReference(AssistPanel.class, "input-assist.css")));++ response.render(JavaScriptHeaderItem.forReference(+ new JavaScriptResourceReference(InputAssistBehavior.class, "input-assist.js")));++ String script = String.format("pmease.commons.inputassist.init('%s', %s);",+ getComponent().getMarkupId(true),+ getCallbackFunction(explicit("input"), explicit("caret")));++ response.render(OnDomReadyHeaderItem.forScript(script));+ }++ protected abstract List<InputCompletion> getSuggestions(InputStatus inputStatus, int count);++ protected List<String> getHints(InputStatus inputStatus) {+ return new ArrayList<>();+ }++ protected abstract List<Range> getErrors(String inputContent);++ protected abstract int getAnchor(String content);+}\ No newline at end of filediff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/input-assist.js b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/input-assist.jsindex b2dfe38ba3..c60e636982 100644--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/input-assist.js+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/inputassist/input-assist.js@@ -1,174 +1,186 @@-pmease.commons.inputassist = {- init: function(inputId, callback) {- var $input = $("#" + inputId);-- $input.data("prevValue", $input.val());- $input.data("prevCaret", -1);- $input.on("input click keyup", function(e) {- var value = $input.val();- var caret;- if ($input.is(":focus"))- caret = $input.caret();- else- caret = -1;- if (value != $input.data("prevValue") || caret != $input.data("prevCaret")) {- $input.data("prevValue", value);- $input.data("prevCaret", caret);- if ($input.is(":focus") && e.keyCode != 27 && e.keyCode != 13) // ignore esc, enter- callback(value, caret, 1);- }- if (value.trim().length == 0)- pmease.commons.inputassist.markErrors(inputId, []);- });- $input.on("blur", function(e) {- $input.data("prevCaret", -1);- });-- $input.data("update", function($item) {- var value = $item.data("content");- $input.val(value);- var caret = $item.data("caret");- if (caret != undefined)- $input.caret(caret);- $input.focus();- $input.trigger("input");- });-- $input.bind("keydown", "up", function() {- var $dropdown = $input.data("dropdown");- if ($dropdown) {- var $active = $dropdown.find("tr.active");- if ($active.length != 0) {- var $prev = $active.prev();- if ($prev.length != 0) {- $prev.addClass("active");- $active.removeClass("active");- }- } else {- $dropdown.find("tr").last().addClass("active");- }- $dropdown.find(".suggestions").scrollIntoView("tr.active");- pmease.commons.inputassist.updateHelp($dropdown);- $dropdown.align($dropdown.data("alignment"));- return false;- }- });-- $input.bind("keydown", "down", function() {- var $dropdown = $input.data("dropdown");- if ($dropdown) {- var $active = $dropdown.find("tr.active");- if ($active.length != 0) {- var $next = $active.next();- if ($next.length != 0) {- $next.addClass("active");- $active.removeClass("active");- }- } else {- $dropdown.find("tr").first().addClass("active");- }- $dropdown.find(".suggestions").scrollIntoView("tr.active");- pmease.commons.inputassist.updateHelp($dropdown);- $dropdown.align($dropdown.data("alignment"));- return false;- }- });-- $input.bind("keydown", "return", function() {- var $dropdown = $input.data("dropdown");- if ($dropdown) {- var $active = $dropdown.find("tr.active");- if ($active.length != 0) {- $input.data("update")($active);- return false;- } else {- pmease.commons.floating.close($dropdown, true);- }- }- });-- $input.bind("keydown", "tab", function() {- var $dropdown = $input.data("dropdown");- if ($dropdown) {- var $active = $dropdown.find("tr.active");- if ($active.length != 0)- $input.data("update")($active);- else- $input.data("update")($dropdown.find("tr").first());- return false;- }- });-- callback($input.val());- },-- markErrors: function(inputId, errors) {- var $input = $("#" + inputId);- $input.data("errors", errors);- var $parent = $input.closest("form");- $parent.css("position", "relative");- $parent.find(">.input-error-mark").remove();- if ($input.val().length != 0) {- for (var i in errors) {- var error = errors[i];- var fromCoord = getCaretCoordinates($input[0], error.from);- var toCoord = getCaretCoordinates($input[0], error.to+1);- var $error = $("<div class='input-error-mark'></div>");- $error.appendTo($parent);- var inputCoord = $input.offset();- var parentCoord = $parent.offset();- var textHeight = 16;- var errorHeight = 5;- var errorOffset = 9;- var minWidth = 5;- var left = fromCoord.left + inputCoord.left - parentCoord.left;- var top = fromCoord.top + inputCoord.top - parentCoord.top + textHeight;- $error.css({left: left, top: top});- $error.outerWidth(Math.max(toCoord.left-fromCoord.left, minWidth));- $error.outerHeight(errorHeight);- }- }- },-- assistOpened: function(inputId, dropdownId) {- var $input = $("#" + inputId);- var $dropdown = $("#" + dropdownId);- $dropdown.data("trigger", $input);- $input.data("dropdown", $dropdown);- $dropdown.on("close", function() {- $input.data("dropdown", null);- });- pmease.commons.inputassist.assistUpdated(inputId, dropdownId);- },-- assistUpdated: function(inputId, dropdownId) {- var $input = $("#" + inputId);- var $dropdown = $("#" + dropdownId);- $dropdown.click(function() {- $input.focus();- });- var $item = $dropdown.find("tr");- $item.click(function() {- var $this = $(this);- $input.data("update")($this);- });- pmease.commons.inputassist.updateHelp($dropdown);- },-- initInfiniteScroll: function(assistId, callback) {- $("#" + assistId + " .suggestions").scroll(function() {- if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight)- callback();- });- },-- updateHelp: function($dropdown) {- if ($dropdown.find(".help>li").length > 1)- $dropdown.find(".help").addClass("multiple");- if ($dropdown.find("tr.active").length != 0) {- $dropdown.find(".help>.completion").empty().append("Press 'enter' to complete selected item");- } else {- $dropdown.find(".help>.completion").empty().append("Press 'tab' to complete first item");- }- }+pmease.commons.inputassist = {+ init: function(inputId, callback) {+ var $input = $("#" + inputId);++ $input.data("prevValue", $input.val());+ $input.data("prevCaret", -1);+ $input.on("input click keyup", function(e) {+ var value = $input.val();+ var caret;+ if ($input.is(":focus"))+ caret = $input.caret();+ else+ caret = -1;+ if (value != $input.data("prevValue") || caret != $input.data("prevCaret")) {+ $input.data("prevValue", value);+ $input.data("prevCaret", caret);+ if ($input.is(":focus") && e.keyCode != 27 && e.keyCode != 13) // ignore esc, enter+ callback(value, caret, 1);+ }+ if (value.trim().length == 0)+ pmease.commons.inputassist.markErrors(inputId, []);+ });+ function onFocus() {+ var value = $input.val();+ if (value.length == 0 && $input.closest(".has-error").length == 0) {+ var caret = $input.caret();+ $input.data("prevValue", value);+ $input.data("prevCaret", caret);+ callback(value, caret, 1);+ }+ $input.off("focus", onFocus);+ }+ $input.on("focus", onFocus);++ $input.on("blur", function(e) {+ $input.data("prevCaret", -1);+ });++ $input.data("update", function($item) {+ var value = $item.data("content");+ $input.val(value);+ var caret = $item.data("caret");+ if (caret != undefined)+ $input.caret(caret);+ $input.focus();+ $input.trigger("input");+ });++ $input.bind("keydown", "up", function() {+ var $dropdown = $input.data("dropdown");+ if ($dropdown) {+ var $active = $dropdown.find("tr.active");+ if ($active.length != 0) {+ var $prev = $active.prev();+ if ($prev.length != 0) {+ $prev.addClass("active");+ $active.removeClass("active");+ }+ } else {+ $dropdown.find("tr").last().addClass("active");+ }+ $dropdown.find(".suggestions").scrollIntoView("tr.active");+ pmease.commons.inputassist.updateHelp($dropdown);+ $dropdown.align($dropdown.data("alignment"));+ return false;+ }+ });++ $input.bind("keydown", "down", function() {+ var $dropdown = $input.data("dropdown");+ if ($dropdown) {+ var $active = $dropdown.find("tr.active");+ if ($active.length != 0) {+ var $next = $active.next();+ if ($next.length != 0) {+ $next.addClass("active");+ $active.removeClass("active");+ }+ } else {+ $dropdown.find("tr").first().addClass("active");+ }+ $dropdown.find(".suggestions").scrollIntoView("tr.active");+ pmease.commons.inputassist.updateHelp($dropdown);+ $dropdown.align($dropdown.data("alignment"));+ return false;+ }+ });++ $input.bind("keydown", "return", function() {+ var $dropdown = $input.data("dropdown");+ if ($dropdown) {+ var $active = $dropdown.find("tr.active");+ if ($active.length != 0) {+ $input.data("update")($active);+ return false;+ } else {+ pmease.commons.floating.close($dropdown, true);+ }+ }+ });++ $input.bind("keydown", "tab", function() {+ var $dropdown = $input.data("dropdown");+ if ($dropdown) {+ var $active = $dropdown.find("tr.active");+ if ($active.length != 0)+ $input.data("update")($active);+ else+ $input.data("update")($dropdown.find("tr").first());+ return false;+ }+ });++ callback($input.val());+ },++ markErrors: function(inputId, errors) {+ var $input = $("#" + inputId);+ $input.data("errors", errors);+ var $parent = $input.closest("form");+ $parent.css("position", "relative");+ $parent.find(">.input-error-mark").remove();+ if ($input.val().length != 0) {+ for (var i in errors) {+ var error = errors[i];+ var fromCoord = getCaretCoordinates($input[0], error.from);+ var toCoord = getCaretCoordinates($input[0], error.to+1);+ var $error = $("<div class='input-error-mark'></div>");+ $error.appendTo($parent);+ var inputCoord = $input.offset();+ var parentCoord = $parent.offset();+ var textHeight = 16;+ var errorHeight = 5;+ var errorOffset = 9;+ var minWidth = 5;+ var left = fromCoord.left + inputCoord.left - parentCoord.left;+ var top = fromCoord.top + inputCoord.top - parentCoord.top + textHeight;+ $error.css({left: left, top: top});+ $error.outerWidth(Math.max(toCoord.left-fromCoord.left, minWidth));+ $error.outerHeight(errorHeight);+ }+ }+ },++ assistOpened: function(inputId, dropdownId) {+ var $input = $("#" + inputId);+ var $dropdown = $("#" + dropdownId);+ $dropdown.data("trigger", $input);+ $input.data("dropdown", $dropdown);+ $dropdown.on("close", function() {+ $input.data("dropdown", null);+ });+ pmease.commons.inputassist.assistUpdated(inputId, dropdownId);+ },++ assistUpdated: function(inputId, dropdownId) {+ var $input = $("#" + inputId);+ var $dropdown = $("#" + dropdownId);+ $dropdown.click(function() {+ $input.focus();+ });+ var $item = $dropdown.find("tr");+ $item.click(function() {+ var $this = $(this);+ $input.data("update")($this);+ });+ pmease.commons.inputassist.updateHelp($dropdown);+ },++ initInfiniteScroll: function(assistId, callback) {+ $("#" + assistId + " .suggestions").scroll(function() {+ if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight)+ callback();+ });+ },++ updateHelp: function($dropdown) {+ if ($dropdown.find(".help>li").length > 1)+ $dropdown.find(".help").addClass("multiple");+ if ($dropdown.find("tr.active").length != 0) {+ $dropdown.find(".help>.completion").empty().append("Press 'enter' to complete selected item");+ } else {+ $dropdown.find(".help>.completion").empty().append("Press 'tab' to complete first item");+ }+ }}\ No newline at end of filediff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfChangeSpecifiedRefs.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfChangeSpecifiedRefs.javaindex 35f5a31052..0564070727 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfChangeSpecifiedRefs.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfChangeSpecifiedRefs.java@@ -20,7 +20,7 @@ public class IfChangeSpecifiedRefs extends AbstractGateKeeper {private String refMatch;- @Editable(name="Refs to Match", order=100, description="Specify refs to match")+ @Editable(name="Refs to Match", order=100)@RefMatch@NotEmptypublic String getRefMatch() {diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.javaindex ceb1bdfe35..0d72659eb3 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java@@ -20,7 +20,7 @@ public class IfTouchSpecifiedFiles extends AbstractGateKeeper {private String pathMatch;- @Editable(name="Files to Match", description="Specify files to match.")+ @Editable(name="Files to Match")@PathMatch@NotEmptypublic String getPathMatch() {diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.javaindex 6315f2fe5e..6b4108056d 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java@@ -73,6 +73,7 @@ import com.pmease.gitplex.core.model.DepotAndBranch;import com.pmease.gitplex.core.model.Depot;import com.pmease.gitplex.core.model.ReviewInvitation;import com.pmease.gitplex.core.model.User;+import com.pmease.gitplex.core.util.fullbranchmatch.FullBranchMatchUtils;import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeUtils;@Singleton@@ -369,7 +370,7 @@ public class DefaultPullRequestManager implements PullRequestManager, DepotListeList<IntegrationStrategy> strategies = null;for (IntegrationPolicy policy: request.getTargetDepot().getIntegrationPolicies()) {if (IncludeExcludeUtils.matches(policy.getTargetBranchMatch(), request.getTargetBranch())- && policy.getSourceBranches().matches(request.getSourceDepot(), request.getSourceBranch())) {+ && FullBranchMatchUtils.matches(policy.getSourceBranchMatch(), request.getTargetDepot(), request.getSource())) {strategies = policy.getIntegrationStrategies();break;}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Depot.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Depot.javaindex bec342dee5..dec399e369 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Depot.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/Depot.java@@ -186,7 +186,7 @@ public class Depot extends AbstractEntity implements UserBelonging {this.name = name;}- @Editable(order=200, description="Specify description of the repository.")+ @Editable(order=200)@Markdownpublic String getDescription() {return description;diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPolicy.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPolicy.javaindex 86bee92a5a..ae205932ea 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPolicy.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/model/IntegrationPolicy.java@@ -4,8 +4,6 @@ import java.io.Serializable;import java.util.ArrayList;import java.util.List;-import javax.validation.Valid;-import javax.validation.constraints.NotNull;import javax.validation.constraints.Size;import org.hibernate.validator.constraints.NotEmpty;@@ -13,8 +11,8 @@ import org.hibernate.validator.constraints.NotEmpty;import com.pmease.commons.wicket.editable.annotation.Editable;import com.pmease.commons.wicket.editable.annotation.Horizontal;import com.pmease.gitplex.core.model.PullRequest.IntegrationStrategy;-import com.pmease.gitplex.core.util.branchmatcher.AffinalBranchMatcher;import com.pmease.gitplex.core.util.editable.BranchMatch;+import com.pmease.gitplex.core.util.editable.FullBranchMatch;@SuppressWarnings("serial")@Editable@@ -23,7 +21,7 @@ public class IntegrationPolicy implements Serializable {private String targetBranchMatch;- private AffinalBranchMatcher sourceBranches;+ private String sourceBranchMatch;private List<IntegrationStrategy> integrationStrategies = new ArrayList<>();@@ -41,14 +39,14 @@ public class IntegrationPolicy implements Serializable {@Editable(name="Source Branches", order=200, description="Specify source branches of pull requests to which "+ "this policy applies to.")- @NotNull- @Valid- public AffinalBranchMatcher getSourceBranches() {- return sourceBranches;+ @FullBranchMatch+ @NotEmpty+ public String getSourceBranchMatch() {+ return sourceBranchMatch;}- public void setSourceBranches(AffinalBranchMatcher sourceBranches) {- this.sourceBranches = sourceBranches;+ public void setSourceBranchMatch(String sourceBranchMatch) {+ this.sourceBranchMatch = sourceBranchMatch;}@Editable(order=300, descriptionProvider="getIntegrationStrategyHelp")diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchAffinalBranchesByPatterns.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchAffinalBranchesByPatterns.javaindex b5b3e26164..06ab99e528 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchAffinalBranchesByPatterns.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchAffinalBranchesByPatterns.java@@ -2,7 +2,7 @@ package com.pmease.gitplex.core.util.branchmatcher;import org.hibernate.validator.constraints.NotEmpty;-import com.pmease.commons.util.pattern.WildcardUtils;+import com.pmease.commons.util.match.WildcardUtils;import com.pmease.commons.wicket.editable.annotation.Editable;import com.pmease.commons.wicket.editable.annotation.OmitName;import com.pmease.gitplex.core.model.Depot;diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchGlobalBranchesByPatterns.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchGlobalBranchesByPatterns.javaindex 071248939d..7f9677c875 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchGlobalBranchesByPatterns.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchGlobalBranchesByPatterns.java@@ -2,7 +2,7 @@ package com.pmease.gitplex.core.util.branchmatcher;import org.hibernate.validator.constraints.NotEmpty;-import com.pmease.commons.util.pattern.WildcardUtils;+import com.pmease.commons.util.match.WildcardUtils;import com.pmease.commons.wicket.editable.annotation.Editable;import com.pmease.commons.wicket.editable.annotation.OmitName;import com.pmease.gitplex.core.model.Depot;diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchLocalBranchesByPatterns.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchLocalBranchesByPatterns.javaindex 13cefd2fea..1a813af2ca 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchLocalBranchesByPatterns.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/branchmatcher/MatchLocalBranchesByPatterns.java@@ -2,7 +2,7 @@ package com.pmease.gitplex.core.util.branchmatcher;import org.hibernate.validator.constraints.NotEmpty;-import com.pmease.commons.util.pattern.WildcardUtils;+import com.pmease.commons.util.match.WildcardUtils;import com.pmease.commons.wicket.editable.annotation.Editable;import com.pmease.commons.wicket.editable.annotation.OmitName;diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/editable/FullBranchMatch.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/editable/FullBranchMatch.javanew file mode 100644index 0000000000..1a9f0333ef--- /dev/null+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/editable/FullBranchMatch.java@@ -0,0 +1,12 @@+package com.pmease.gitplex.core.util.editable;++import java.lang.annotation.ElementType;+import java.lang.annotation.Retention;+import java.lang.annotation.RetentionPolicy;+import java.lang.annotation.Target;++@Target(ElementType.METHOD)+@Retention(RetentionPolicy.RUNTIME)+public @interface FullBranchMatch {++}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/fullbranchmatch/FullBranchMatch.g4 b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/fullbranchmatch/FullBranchMatch.g4new file mode 100644index 0000000000..5720bf1a88--- /dev/null+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/fullbranchmatch/FullBranchMatch.g4@@ -0,0 +1,27 @@+grammar FullBranchMatch;++match: criteria+ EOF;++criteria: includeMatch | excludeMatch;++includeMatch: INCLUDE '(' fullBranchMatch ')';+excludeMatch: EXCLUDE '(' fullBranchMatch ')';++fullBranchMatch: accountMatch ':' depotMatch ':' branchMatch | depotMatch ':' branchMatch | branchMatch;++accountMatch: ACCOUNT Value;+depotMatch: REPOSITORY Value;+branchMatch: BRANCH Value;++INCLUDE: 'include';+EXCLUDE: 'exclude';+ACCOUNT: 'account';+REPOSITORY: 'repository';+BRANCH: 'branch';++Value: '(' (ESCAPE|~[()\\])+? ')';++fragment+ESCAPE: '\\'[()\\];++WS: [ \t\r\n]+ -> skip;\ No newline at end of filediff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/fullbranchmatch/FullBranchMatchUtils.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/fullbranchmatch/FullBranchMatchUtils.javanew file mode 100644index 0000000000..fd822405d1--- /dev/null+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/fullbranchmatch/FullBranchMatchUtils.java@@ -0,0 +1,78 @@+package com.pmease.gitplex.core.util.fullbranchmatch;++import java.util.ArrayList;+import java.util.List;++import org.antlr.v4.runtime.ANTLRInputStream;+import org.antlr.v4.runtime.BailErrorStrategy;+import org.antlr.v4.runtime.CommonTokenStream;+import org.antlr.v4.runtime.tree.TerminalNode;++import com.pmease.commons.util.match.IncludeExclude;+import com.pmease.commons.util.match.RuleMatcher;+import com.pmease.commons.util.match.WildcardUtils;+import com.pmease.gitplex.core.model.Depot;+import com.pmease.gitplex.core.model.DepotAndBranch;+import com.pmease.gitplex.core.util.fullbranchmatch.FullBranchMatchParser.CriteriaContext;+import com.pmease.gitplex.core.util.fullbranchmatch.FullBranchMatchParser.FullBranchMatchContext;+import com.pmease.gitplex.core.util.fullbranchmatch.FullBranchMatchParser.MatchContext;++public class FullBranchMatchUtils {++ public static MatchContext parse(String match) {+ ANTLRInputStream is = new ANTLRInputStream(match);+ FullBranchMatchLexer lexer = new FullBranchMatchLexer(is);+ lexer.removeErrorListeners();+ CommonTokenStream tokens = new CommonTokenStream(lexer);+ FullBranchMatchParser parser = new FullBranchMatchParser(tokens);+ parser.removeErrorListeners();+ parser.setErrorHandler(new BailErrorStrategy());+ return parser.match();+ }++ private static String getValue(TerminalNode terminal) {+ String value = terminal.getText().substring(1);+ return value.substring(0, value.length()-1).trim();+ }++ public static boolean matches(String match, final Depot currentDepot, DepotAndBranch depotAndBranch) {+ MatchContext matchContext = parse(match);+ List<FullBranchMatchContext> includes = new ArrayList<>();+ List<FullBranchMatchContext> excludes = new ArrayList<>();+ for (CriteriaContext criteriaContext: matchContext.criteria()) {+ if (criteriaContext.includeMatch() != null) {+ includes.add(criteriaContext.includeMatch().fullBranchMatch());+ } else if (criteriaContext.excludeMatch() != null) {+ excludes.add(criteriaContext.excludeMatch().fullBranchMatch());+ }+ }++ RuleMatcher<FullBranchMatchContext, DepotAndBranch> matcher = new RuleMatcher<FullBranchMatchContext, DepotAndBranch>() {++ @Override+ public boolean matches(FullBranchMatchContext rule, DepotAndBranch value) {+ if (rule.accountMatch() != null) {+ String accountPattern = getValue(rule.accountMatch().Value());+ String depotPattern = getValue(rule.depotMatch().Value());+ String branchPattern = getValue(rule.branchMatch().Value());+ return WildcardUtils.matchString(accountPattern, value.getDepot().getUser().getName())+ && WildcardUtils.matchString(depotPattern, value.getDepot().getName())+ && WildcardUtils.matchString(branchPattern, value.getBranch());+ } else if (rule.depotMatch() != null) {+ String depotPattern = getValue(rule.depotMatch().Value());+ String branchPattern = getValue(rule.branchMatch().Value());+ return value.getDepot().getUser().equals(currentDepot.getUser())+ && WildcardUtils.matchString(depotPattern, value.getDepot().getName())+ && WildcardUtils.matchString(branchPattern, value.getBranch());+ } else {+ String branchPattern = getValue(rule.branchMatch().Value());+ return value.getDepot().equals(currentDepot)+ && WildcardUtils.matchString(branchPattern, value.getBranch());+ }+ }++ };+ return new IncludeExclude<FullBranchMatchContext, DepotAndBranch>(includes, excludes).matches(matcher, depotAndBranch);+ }++}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/includeexclude/IncludeExcludeUtils.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/includeexclude/IncludeExcludeUtils.javaindex f557dfa37a..c160c4fb0e 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/util/includeexclude/IncludeExcludeUtils.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/util/includeexclude/IncludeExcludeUtils.java@@ -8,7 +8,8 @@ import org.antlr.v4.runtime.BailErrorStrategy;import org.antlr.v4.runtime.CommonTokenStream;import org.antlr.v4.runtime.tree.TerminalNode;-import com.pmease.commons.util.pattern.WildcardUtils;+import com.pmease.commons.util.match.IncludeExclude;+import com.pmease.commons.util.match.WildcardStringMatcher;import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeParser.CriteriaContext;import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeParser.MatchContext;@@ -46,7 +47,7 @@ public class IncludeExcludeUtils {}}- return WildcardUtils.matchString(includes, excludes, value);+ return new IncludeExclude<String, String>(includes, excludes).matches(new WildcardStringMatcher(), value);}}diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/query/FileQuery.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/query/FileQuery.javaindex b4c449b189..853edc24fa 100644--- a/gitplex.search/src/main/java/com/pmease/gitplex/search/query/FileQuery.java+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/query/FileQuery.java@@ -1,89 +1,89 @@-package com.pmease.gitplex.search.query;--import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;--import java.util.List;--import javax.annotation.Nullable;--import org.apache.lucene.index.Term;-import org.apache.lucene.search.BooleanClause.Occur;-import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.WildcardQuery;-import org.eclipse.jgit.treewalk.TreeWalk;--import com.google.common.base.Splitter;-import com.pmease.commons.util.StringUtils;-import com.pmease.commons.util.pattern.WildcardUtils;-import com.pmease.gitplex.search.hit.FileHit;-import com.pmease.gitplex.search.hit.QueryHit;--public class FileQuery extends BlobQuery {-- private final String fileNames;-- private final boolean caseSensitive;-- private final String directory;-- public FileQuery(String fileNames, boolean caseSensitive, @Nullable String directory, int count) {- super(count);-- this.fileNames = fileNames;- this.caseSensitive = caseSensitive;- this.directory = directory;- }-- @Override- public void collect(TreeWalk treeWalk, List<QueryHit> hits) {- String blobPath = treeWalk.getPathString();- if (caseSensitive) {- String blobName;- int index = blobPath.indexOf('/');- if (index != -1)- blobName = StringUtils.substringAfterLast(blobPath, "/");- else- blobName = blobPath;-- for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames)) {- if (WildcardUtils.matchString(pattern, blobName)) {- hits.add(new FileHit(blobPath));- break;- }- }- } else {- hits.add(new FileHit(blobPath));- }- }-- @Override- public Query asLuceneQuery() throws TooGeneralQueryException {- BooleanQuery query = new BooleanQuery(true);-- if (directory != null)- applyDirectory(query, directory);-- boolean tooGeneral = true;- for (char ch: fileNames.toCharArray()) {- if (ch != '?' && ch != '*' && ch != ',' && ch != '.') {- tooGeneral = false;- break;- }- }- if (tooGeneral)- throw new TooGeneralQueryException();-- BooleanQuery subQuery = new BooleanQuery(true);- for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase()))- subQuery.add(new WildcardQuery(new Term(BLOB_NAME.name(), pattern)), Occur.SHOULD);-- if (subQuery.getClauses().length != 0)- query.add(subQuery, Occur.MUST);- else- throw new TooGeneralQueryException();-- return query;- }--}+package com.pmease.gitplex.search.query;++import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;++import java.util.List;++import javax.annotation.Nullable;++import org.apache.lucene.index.Term;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.WildcardQuery;+import org.eclipse.jgit.treewalk.TreeWalk;++import com.google.common.base.Splitter;+import com.pmease.commons.util.StringUtils;+import com.pmease.commons.util.match.WildcardUtils;+import com.pmease.gitplex.search.hit.FileHit;+import com.pmease.gitplex.search.hit.QueryHit;++public class FileQuery extends BlobQuery {++ private final String fileNames;++ private final boolean caseSensitive;++ private final String directory;++ public FileQuery(String fileNames, boolean caseSensitive, @Nullable String directory, int count) {+ super(count);++ this.fileNames = fileNames;+ this.caseSensitive = caseSensitive;+ this.directory = directory;+ }++ @Override+ public void collect(TreeWalk treeWalk, List<QueryHit> hits) {+ String blobPath = treeWalk.getPathString();+ if (caseSensitive) {+ String blobName;+ int index = blobPath.indexOf('/');+ if (index != -1)+ blobName = StringUtils.substringAfterLast(blobPath, "/");+ else+ blobName = blobPath;++ for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames)) {+ if (WildcardUtils.matchString(pattern, blobName)) {+ hits.add(new FileHit(blobPath));+ break;+ }+ }+ } else {+ hits.add(new FileHit(blobPath));+ }+ }++ @Override+ public Query asLuceneQuery() throws TooGeneralQueryException {+ BooleanQuery query = new BooleanQuery(true);++ if (directory != null)+ applyDirectory(query, directory);++ boolean tooGeneral = true;+ for (char ch: fileNames.toCharArray()) {+ if (ch != '?' && ch != '*' && ch != ',' && ch != '.') {+ tooGeneral = false;+ break;+ }+ }+ if (tooGeneral)+ throw new TooGeneralQueryException();++ BooleanQuery subQuery = new BooleanQuery(true);+ for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase()))+ subQuery.add(new WildcardQuery(new Term(BLOB_NAME.name(), pattern)), Occur.SHOULD);++ if (subQuery.getClauses().length != 0)+ query.add(subQuery, Occur.MUST);+ else+ throw new TooGeneralQueryException();++ return query;+ }++}diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/query/SymbolQuery.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/query/SymbolQuery.javaindex ef22548ca3..a95014441c 100644--- a/gitplex.search/src/main/java/com/pmease/gitplex/search/query/SymbolQuery.java+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/query/SymbolQuery.java@@ -1,143 +1,143 @@-package com.pmease.gitplex.search.query;--import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;-import static com.pmease.gitplex.search.FieldConstants.BLOB_PRIMARY_SYMBOLS;-import static com.pmease.gitplex.search.FieldConstants.BLOB_SECONDARY_SYMBOLS;-import static com.pmease.gitplex.search.IndexConstants.MAX_INDEXABLE_SIZE;--import java.io.IOException;-import java.util.List;--import javax.annotation.Nullable;--import org.apache.lucene.index.Term;-import org.apache.lucene.search.BooleanClause.Occur;-import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.WildcardQuery;-import org.eclipse.jgit.lib.ObjectLoader;-import org.eclipse.jgit.treewalk.TreeWalk;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import com.google.common.base.Splitter;-import com.pmease.commons.lang.extractors.ExtractException;-import com.pmease.commons.lang.extractors.Extractor;-import com.pmease.commons.lang.extractors.Extractors;-import com.pmease.commons.lang.extractors.Symbol;-import com.pmease.commons.util.ContentDetector;-import com.pmease.commons.util.pattern.WildcardUtils;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.search.hit.QueryHit;-import com.pmease.gitplex.search.hit.SymbolHit;--public class SymbolQuery extends BlobQuery {-- private static final Logger logger = LoggerFactory.getLogger(SymbolQuery.class);-- private final String term;-- private final boolean primary;-- private final boolean caseSensitive;-- private final String directory;-- private final String fileNames;-- public SymbolQuery(String term, boolean primary, boolean caseSensitive,- @Nullable String directory, @Nullable String fileNames, int count) {- super(count);-- this.term = term;- this.primary = primary;- this.caseSensitive = caseSensitive;- this.directory = directory;- this.fileNames = fileNames;- }-- @Override- public void collect(TreeWalk treeWalk, List<QueryHit> hits) {- String blobPath = treeWalk.getPathString();-- Extractor extractor = GitPlex.getInstance(Extractors.class).getExtractor(blobPath);- if (extractor != null) {- ObjectLoader objectLoader;- try {- objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));- if (objectLoader.getSize() <= MAX_INDEXABLE_SIZE) {- byte[] bytes = objectLoader.getCachedBytes();- String content = ContentDetector.convertToText(bytes, blobPath);- if (content != null) {- try {- for (Symbol symbol: extractor.extract(content)) {- if (hits.size() < getCount()) {- if (primary == symbol.isPrimary() && symbol.getName() != null) {- String normalizedTerm;- if (!caseSensitive)- normalizedTerm = term.toLowerCase();- else- normalizedTerm = term;-- String normalizedSymbolName;- if (!caseSensitive)- normalizedSymbolName = symbol.getName().toLowerCase();- else- normalizedSymbolName = symbol.getName();-- if (WildcardUtils.matchString(normalizedTerm, normalizedSymbolName))- hits.add(new SymbolHit(blobPath, symbol));- }- } else {- break;- }- }- } catch (ExtractException e) {- logger.debug("Error extracting symbols from blob (hash:"- + treeWalk.getObjectId(0).getName() + ", path:" + blobPath + ")", e);- }- }- }- } catch (IOException e) {- throw new RuntimeException(e);- }- }- }-- @Override- public Query asLuceneQuery() throws TooGeneralQueryException {- BooleanQuery query = new BooleanQuery(true);-- if (directory != null)- applyDirectory(query, directory);-- if (fileNames != null) {- BooleanQuery subQuery = new BooleanQuery(true);- for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase()))- subQuery.add(new WildcardQuery(new Term(BLOB_NAME.name(), pattern)), Occur.SHOULD);- if (subQuery.getClauses().length != 0)- query.add(subQuery, Occur.MUST);- }-- boolean tooGeneral = true;- for (char ch: term.toCharArray()) {- if (ch != '?' && ch != '*') {- tooGeneral = false;- break;- }- }- if (tooGeneral)- throw new TooGeneralQueryException();-- String fieldName;- if (primary)- fieldName = BLOB_PRIMARY_SYMBOLS.name();- else- fieldName = BLOB_SECONDARY_SYMBOLS.name();-- query.add(new WildcardQuery(new Term(fieldName, term.toLowerCase())), Occur.MUST);-- return query;- }--}+package com.pmease.gitplex.search.query;++import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;+import static com.pmease.gitplex.search.FieldConstants.BLOB_PRIMARY_SYMBOLS;+import static com.pmease.gitplex.search.FieldConstants.BLOB_SECONDARY_SYMBOLS;+import static com.pmease.gitplex.search.IndexConstants.MAX_INDEXABLE_SIZE;++import java.io.IOException;+import java.util.List;++import javax.annotation.Nullable;++import org.apache.lucene.index.Term;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.WildcardQuery;+import org.eclipse.jgit.lib.ObjectLoader;+import org.eclipse.jgit.treewalk.TreeWalk;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import com.google.common.base.Splitter;+import com.pmease.commons.lang.extractors.ExtractException;+import com.pmease.commons.lang.extractors.Extractor;+import com.pmease.commons.lang.extractors.Extractors;+import com.pmease.commons.lang.extractors.Symbol;+import com.pmease.commons.util.ContentDetector;+import com.pmease.commons.util.match.WildcardUtils;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.search.hit.QueryHit;+import com.pmease.gitplex.search.hit.SymbolHit;++public class SymbolQuery extends BlobQuery {++ private static final Logger logger = LoggerFactory.getLogger(SymbolQuery.class);++ private final String term;++ private final boolean primary;++ private final boolean caseSensitive;++ private final String directory;++ private final String fileNames;++ public SymbolQuery(String term, boolean primary, boolean caseSensitive,+ @Nullable String directory, @Nullable String fileNames, int count) {+ super(count);++ this.term = term;+ this.primary = primary;+ this.caseSensitive = caseSensitive;+ this.directory = directory;+ this.fileNames = fileNames;+ }++ @Override+ public void collect(TreeWalk treeWalk, List<QueryHit> hits) {+ String blobPath = treeWalk.getPathString();++ Extractor extractor = GitPlex.getInstance(Extractors.class).getExtractor(blobPath);+ if (extractor != null) {+ ObjectLoader objectLoader;+ try {+ objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));+ if (objectLoader.getSize() <= MAX_INDEXABLE_SIZE) {+ byte[] bytes = objectLoader.getCachedBytes();+ String content = ContentDetector.convertToText(bytes, blobPath);+ if (content != null) {+ try {+ for (Symbol symbol: extractor.extract(content)) {+ if (hits.size() < getCount()) {+ if (primary == symbol.isPrimary() && symbol.getName() != null) {+ String normalizedTerm;+ if (!caseSensitive)+ normalizedTerm = term.toLowerCase();+ else+ normalizedTerm = term;++ String normalizedSymbolName;+ if (!caseSensitive)+ normalizedSymbolName = symbol.getName().toLowerCase();+ else+ normalizedSymbolName = symbol.getName();++ if (WildcardUtils.matchString(normalizedTerm, normalizedSymbolName))+ hits.add(new SymbolHit(blobPath, symbol));+ }+ } else {+ break;+ }+ }+ } catch (ExtractException e) {+ logger.debug("Error extracting symbols from blob (hash:"+ + treeWalk.getObjectId(0).getName() + ", path:" + blobPath + ")", e);+ }+ }+ }+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ }++ @Override+ public Query asLuceneQuery() throws TooGeneralQueryException {+ BooleanQuery query = new BooleanQuery(true);++ if (directory != null)+ applyDirectory(query, directory);++ if (fileNames != null) {+ BooleanQuery subQuery = new BooleanQuery(true);+ for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase()))+ subQuery.add(new WildcardQuery(new Term(BLOB_NAME.name(), pattern)), Occur.SHOULD);+ if (subQuery.getClauses().length != 0)+ query.add(subQuery, Occur.MUST);+ }++ boolean tooGeneral = true;+ for (char ch: term.toCharArray()) {+ if (ch != '?' && ch != '*') {+ tooGeneral = false;+ break;+ }+ }+ if (tooGeneral)+ throw new TooGeneralQueryException();++ String fieldName;+ if (primary)+ fieldName = BLOB_PRIMARY_SYMBOLS.name();+ else+ fieldName = BLOB_SECONDARY_SYMBOLS.name();++ query.add(new WildcardQuery(new Term(fieldName, term.toLowerCase())), Occur.MUST);++ return query;+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/branchmatch/BranchMatchBehavior.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/branchmatch/BranchMatchBehavior.javaindex 3c56f493d8..c26802d15e 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/branchmatch/BranchMatchBehavior.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/branchmatch/BranchMatchBehavior.java@@ -79,10 +79,4 @@ public class BranchMatchBehavior extends ANTLRAssistBehavior {return super.getEndOfMatch(spec, content);}- @Override- protected InputSuggestion wrapAsSuggestion(ParentedElement expectedElement,- String suggestedLiteral, boolean complete) {- return new InputSuggestion(suggestedLiteral);- }-}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/branchmatch/BranchMatchInput.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/branchmatch/BranchMatchInput.javaindex 9e1770442a..ca29163483 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/branchmatch/BranchMatchInput.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/branchmatch/BranchMatchInput.java@@ -21,8 +21,8 @@ public class BranchMatchInput extends TextField<String> {private final IModel<Depot> depotModel;- public BranchMatchInput(String id, IModel<Depot> depotModel, IModel<String> refMatchModel) {- super(id, refMatchModel);+ public BranchMatchInput(String id, IModel<Depot> depotModel, IModel<String> branchMatchModel) {+ super(id, branchMatchModel);this.depotModel = depotModel;}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/fullbranchmatch/FullBranchMatchBehavior.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/fullbranchmatch/FullBranchMatchBehavior.javanew file mode 100644index 0000000000..d2917ece74--- /dev/null+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/fullbranchmatch/FullBranchMatchBehavior.java@@ -0,0 +1,82 @@+package com.pmease.gitplex.web.component.fullbranchmatch;++import java.util.ArrayList;+import java.util.List;++import org.apache.wicket.Component;+import org.apache.wicket.model.IModel;++import com.pmease.commons.antlr.codeassist.FenceAware;+import com.pmease.commons.antlr.codeassist.InputSuggestion;+import com.pmease.commons.antlr.codeassist.ParentedElement;+import com.pmease.commons.antlr.grammar.ElementSpec;+import com.pmease.commons.antlr.grammar.LexerRuleRefElementSpec;+import com.pmease.commons.wicket.behavior.inputassist.ANTLRAssistBehavior;+import com.pmease.gitplex.core.model.Depot;+import com.pmease.gitplex.core.util.fullbranchmatch.FullBranchMatchParser;+import com.pmease.gitplex.web.util.SuggestionUtils;++@SuppressWarnings("serial")+public class FullBranchMatchBehavior extends ANTLRAssistBehavior {++ private final IModel<Depot> depotModel;++ private static final String VALUE_OPEN = "(";++ private static final String VALUE_CLOSE = ")";++ public FullBranchMatchBehavior(IModel<Depot> depotModel) {+ super(FullBranchMatchParser.class, "match");+ this.depotModel = depotModel;+ }++ @Override+ public void detach(Component component) {+ super.detach(component);+ depotModel.detach();+ }++ @Override+ protected List<InputSuggestion> suggest(final ParentedElement expectedElement, String matchWith, final int count) {+ if (expectedElement.getSpec() instanceof LexerRuleRefElementSpec) {+ LexerRuleRefElementSpec spec = (LexerRuleRefElementSpec) expectedElement.getSpec();+ if (spec.getRuleName().equals("Value")) {+ return new FenceAware(codeAssist.getGrammar(), VALUE_OPEN, VALUE_CLOSE) {++ @Override+ protected List<InputSuggestion> match(String unfencedMatchWith) {+ return SuggestionUtils.suggestBranch(depotModel.getObject(), unfencedMatchWith, count);+ }++ @Override+ protected String getFencingDescription() {+ return "value needs to be enclosed in brackets";+ }++ }.suggest(expectedElement.getSpec(), matchWith);+ }+ }+ return null;+ }++ @Override+ protected List<String> getHints(ParentedElement expectedElement, String matchWith) {+ List<String> hints = new ArrayList<>();+ if (expectedElement.getSpec() instanceof LexerRuleRefElementSpec) {+ LexerRuleRefElementSpec spec = (LexerRuleRefElementSpec) expectedElement.getSpec();+ if (spec.getRuleName().equals("Value") && !matchWith.contains(VALUE_CLOSE)) {+ hints.add("Use * to do wildcard match");+ }+ }+ return hints;+ }++ @Override+ protected int getEndOfMatch(ElementSpec spec, String content) {+ if (content.startsWith(VALUE_OPEN+VALUE_CLOSE))+ return 2;+ else+ return super.getEndOfMatch(spec, content);+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/fullbranchmatch/FullBranchMatchInput.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/fullbranchmatch/FullBranchMatchInput.javanew file mode 100644index 0000000000..13f44d9d20--- /dev/null+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/fullbranchmatch/FullBranchMatchInput.java@@ -0,0 +1,74 @@+package com.pmease.gitplex.web.component.fullbranchmatch;++import java.io.Serializable;++import org.apache.wicket.markup.html.form.TextField;+import org.apache.wicket.model.IModel;+import org.apache.wicket.validation.IErrorMessageSource;+import org.apache.wicket.validation.IValidatable;+import org.apache.wicket.validation.IValidationError;+import org.apache.wicket.validation.IValidator;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import com.pmease.gitplex.core.model.Depot;+import com.pmease.gitplex.core.util.fullbranchmatch.FullBranchMatchUtils;++@SuppressWarnings("serial")+public class FullBranchMatchInput extends TextField<String> {++ private static final Logger logger = LoggerFactory.getLogger(FullBranchMatchInput.class);++ private final IModel<Depot> depotModel;++ public FullBranchMatchInput(String id, IModel<Depot> depotModel, IModel<String> fullBranchMatchModel) {+ super(id, fullBranchMatchModel);++ this.depotModel = depotModel;+ }++ @Override+ protected void onInitialize() {+ super.onInitialize();++ add(new FullBranchMatchBehavior(depotModel));+ add(new IValidator<String>() {++ @Override+ public void validate(IValidatable<String> validatable) {+ try {+ FullBranchMatchUtils.parse(validatable.getValue());+ } catch (final Exception e) {+ logger.error("Error parsing branch match string: " + validatable.getValue(), e);+ if (e.getCause().getMessage() != null) {+ validatable.error(new IValidationError() {++ @Override+ public Serializable getErrorMessage(IErrorMessageSource messageSource) {+ return "Syntax error: " + e.getCause().getMessage();+ }++ });+ } else {+ validatable.error(new IValidationError() {++ @Override+ public Serializable getErrorMessage(IErrorMessageSource messageSource) {+ return "Syntax error: " + e.getCause().getClass().getSimpleName();+ }++ });+ }+ }+ }++ });+ }++ @Override+ protected void onDetach() {+ depotModel.detach();+ super.onDetach();+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pathmatch/PathMatchBehavior.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pathmatch/PathMatchBehavior.javaindex 08dc5e4386..db784bad69 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pathmatch/PathMatchBehavior.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pathmatch/PathMatchBehavior.java@@ -80,10 +80,4 @@ public class PathMatchBehavior extends ANTLRAssistBehavior {return super.getEndOfMatch(spec, content);}- @Override- protected InputSuggestion wrapAsSuggestion(ParentedElement expectedElement,- String suggestedLiteral, boolean complete) {- return new InputSuggestion(suggestedLiteral);- }-}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pathmatch/PathMatchInput.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pathmatch/PathMatchInput.javaindex e4e878c142..cd687775a7 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pathmatch/PathMatchInput.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pathmatch/PathMatchInput.java@@ -21,8 +21,8 @@ public class PathMatchInput extends TextField<String> {private final IModel<Depot> depotModel;- public PathMatchInput(String id, IModel<Depot> depotModel, IModel<String> refMatchModel) {- super(id, refMatchModel);+ public PathMatchInput(String id, IModel<Depot> depotModel, IModel<String> pathMatchModel) {+ super(id, pathMatchModel);this.depotModel = depotModel;}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/refmatch/RefMatchBehavior.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/refmatch/RefMatchBehavior.javaindex ea8acbec59..b7d360ee89 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/refmatch/RefMatchBehavior.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/refmatch/RefMatchBehavior.java@@ -119,10 +119,4 @@ public class RefMatchBehavior extends ANTLRAssistBehavior {return super.getEndOfMatch(spec, content);}- @Override- protected InputSuggestion wrapAsSuggestion(ParentedElement expectedElement,- String suggestedLiteral, boolean complete) {- return new InputSuggestion(suggestedLiteral);- }-}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/branchmatch/BranchMatchEditor.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/branchmatch/BranchMatchEditor.htmlindex 9383fc76b9..09838564b4 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/branchmatch/BranchMatchEditor.html+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/branchmatch/BranchMatchEditor.html@@ -1,3 +1,3 @@<wicket:panel>- <input wicket:id="input" spellcheck="false" autocomplete="off" class="form-control"></input>+ <input wicket:id="input" spellcheck="false" autocomplete="off" class="form-control focusable"></input></wicket:panel>\ No newline at end of filediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/branchmatch/BranchMatchEditor.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/branchmatch/BranchMatchEditor.javaindex 5907e148ec..62c63524e3 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/branchmatch/BranchMatchEditor.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/branchmatch/BranchMatchEditor.java@@ -1,7 +1,9 @@package com.pmease.gitplex.web.editable.branchmatch;+import org.apache.wicket.behavior.AttributeAppender;import org.apache.wicket.model.AbstractReadOnlyModel;import org.apache.wicket.model.IModel;+import org.apache.wicket.model.LoadableDetachableModel;import org.apache.wicket.util.convert.ConversionException;import com.pmease.commons.wicket.editable.ErrorContext;@@ -35,6 +37,19 @@ public class BranchMatchEditor extends PropertyEditor<String> {}, getModel());add(input);++ add(new AttributeAppender("class", new LoadableDetachableModel<String>() {++ @Override+ protected String load() {+ if (hasError(true))+ return " has-error";+ else+ return "";+ }++ }));+}@Overridediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/fullbranchmatch/FullBranchMatchEditSupport.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/fullbranchmatch/FullBranchMatchEditSupport.javanew file mode 100644index 0000000000..84285f44f8--- /dev/null+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/fullbranchmatch/FullBranchMatchEditSupport.java@@ -0,0 +1,66 @@+package com.pmease.gitplex.web.editable.fullbranchmatch;++import java.lang.reflect.Method;++import org.apache.wicket.Component;+import org.apache.wicket.markup.html.basic.Label;+import org.apache.wicket.model.IModel;++import com.pmease.commons.wicket.editable.BeanContext;+import com.pmease.commons.wicket.editable.DefaultPropertyDescriptor;+import com.pmease.commons.wicket.editable.EditSupport;+import com.pmease.commons.wicket.editable.NotDefinedLabel;+import com.pmease.commons.wicket.editable.PropertyContext;+import com.pmease.commons.wicket.editable.PropertyDescriptor;+import com.pmease.commons.wicket.editable.PropertyEditor;+import com.pmease.commons.wicket.editable.PropertyViewer;+import com.pmease.gitplex.core.util.editable.FullBranchMatch;++@SuppressWarnings("serial")+public class FullBranchMatchEditSupport implements EditSupport {++ @Override+ public BeanContext<?> getBeanEditContext(Class<?> beanClass) {+ return null;+ }++ @Override+ public PropertyContext<?> getPropertyEditContext(Class<?> beanClass, String propertyName) {+ PropertyDescriptor propertyDescriptor = new DefaultPropertyDescriptor(beanClass, propertyName);+ Method propertyGetter = propertyDescriptor.getPropertyGetter();+ if (propertyGetter.getAnnotation(FullBranchMatch.class) != null) {+ if (propertyGetter.getReturnType() != String.class) {+ throw new RuntimeException("Annotation 'FullBranchMatch' should be applied to property "+ + "with type 'String'.");+ }+ return new PropertyContext<String>(propertyDescriptor) {++ @Override+ public PropertyViewer renderForView(String componentId, final IModel<String> model) {+ return new PropertyViewer(componentId, this) {++ @Override+ protected Component newContent(String id, PropertyDescriptor propertyDescriptor) {+ String refMatch = model.getObject();+ if (refMatch != null) {+ return new Label(id, refMatch);+ } else {+ return new NotDefinedLabel(id);+ }+ }++ };+ }++ @Override+ public PropertyEditor<String> renderForEdit(String componentId, IModel<String> model) {+ return new FullBranchMatchEditor(componentId, this, model);+ }++ };+ } else {+ return null;+ }+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/fullbranchmatch/FullBranchMatchEditor.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/fullbranchmatch/FullBranchMatchEditor.htmlnew file mode 100644index 0000000000..09838564b4--- /dev/null+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/fullbranchmatch/FullBranchMatchEditor.html@@ -0,0 +1,3 @@+<wicket:panel>+ <input wicket:id="input" spellcheck="false" autocomplete="off" class="form-control focusable"></input>+</wicket:panel>\ No newline at end of filediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/fullbranchmatch/FullBranchMatchEditor.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/fullbranchmatch/FullBranchMatchEditor.javanew file mode 100644index 0000000000..ec61259d18--- /dev/null+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/fullbranchmatch/FullBranchMatchEditor.java@@ -0,0 +1,65 @@+package com.pmease.gitplex.web.editable.fullbranchmatch;++import org.apache.wicket.behavior.AttributeAppender;+import org.apache.wicket.model.AbstractReadOnlyModel;+import org.apache.wicket.model.IModel;+import org.apache.wicket.model.LoadableDetachableModel;+import org.apache.wicket.util.convert.ConversionException;++import com.pmease.commons.wicket.editable.ErrorContext;+import com.pmease.commons.wicket.editable.PathSegment;+import com.pmease.commons.wicket.editable.PropertyDescriptor;+import com.pmease.commons.wicket.editable.PropertyEditor;+import com.pmease.gitplex.core.model.Depot;+import com.pmease.gitplex.web.component.fullbranchmatch.FullBranchMatchInput;+import com.pmease.gitplex.web.page.depot.DepotPage;++@SuppressWarnings("serial")+public class FullBranchMatchEditor extends PropertyEditor<String> {++ private FullBranchMatchInput input;++ public FullBranchMatchEditor(String id, PropertyDescriptor propertyDescriptor, IModel<String> propertyModel) {+ super(id, propertyDescriptor, propertyModel);+ }++ @Override+ protected void onInitialize() {+ super.onInitialize();++ input = new FullBranchMatchInput("input", new AbstractReadOnlyModel<Depot>() {++ @Override+ public Depot getObject() {+ return ((DepotPage) getPage()).getDepot();+ }++ }, getModel());++ add(input);++ add(new AttributeAppender("class", new LoadableDetachableModel<String>() {++ @Override+ protected String load() {+ if (hasError(true))+ return " has-error";+ else+ return "";+ }++ }));++ }++ @Override+ public ErrorContext getErrorContext(PathSegment pathSegment) {+ return null;+ }++ @Override+ protected String convertInputToValue() throws ConversionException {+ return input.getConvertedInput();+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/pathmatch/PathMatchEditor.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/pathmatch/PathMatchEditor.htmlindex 9383fc76b9..09838564b4 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/pathmatch/PathMatchEditor.html+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/pathmatch/PathMatchEditor.html@@ -1,3 +1,3 @@<wicket:panel>- <input wicket:id="input" spellcheck="false" autocomplete="off" class="form-control"></input>+ <input wicket:id="input" spellcheck="false" autocomplete="off" class="form-control focusable"></input></wicket:panel>\ No newline at end of filediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/pathmatch/PathMatchEditor.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/pathmatch/PathMatchEditor.javaindex 75699d877e..085e1d4d27 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/pathmatch/PathMatchEditor.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/pathmatch/PathMatchEditor.java@@ -1,7 +1,9 @@package com.pmease.gitplex.web.editable.pathmatch;+import org.apache.wicket.behavior.AttributeAppender;import org.apache.wicket.model.AbstractReadOnlyModel;import org.apache.wicket.model.IModel;+import org.apache.wicket.model.LoadableDetachableModel;import org.apache.wicket.util.convert.ConversionException;import com.pmease.commons.wicket.editable.ErrorContext;@@ -35,6 +37,19 @@ public class PathMatchEditor extends PropertyEditor<String> {}, getModel());add(input);++ add(new AttributeAppender("class", new LoadableDetachableModel<String>() {++ @Override+ protected String load() {+ if (hasError(true))+ return " has-error";+ else+ return "";+ }++ }));+}@Overridediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/refmatch/RefMatchEditor.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/refmatch/RefMatchEditor.htmlindex 9383fc76b9..09838564b4 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/refmatch/RefMatchEditor.html+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/refmatch/RefMatchEditor.html@@ -1,3 +1,3 @@<wicket:panel>- <input wicket:id="input" spellcheck="false" autocomplete="off" class="form-control"></input>+ <input wicket:id="input" spellcheck="false" autocomplete="off" class="form-control focusable"></input></wicket:panel>\ No newline at end of filediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/refmatch/RefMatchEditor.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/refmatch/RefMatchEditor.javaindex 12253f7119..edc86fe934 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/refmatch/RefMatchEditor.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/editable/refmatch/RefMatchEditor.java@@ -1,7 +1,9 @@package com.pmease.gitplex.web.editable.refmatch;+import org.apache.wicket.behavior.AttributeAppender;import org.apache.wicket.model.AbstractReadOnlyModel;import org.apache.wicket.model.IModel;+import org.apache.wicket.model.LoadableDetachableModel;import org.apache.wicket.util.convert.ConversionException;import com.pmease.commons.wicket.editable.ErrorContext;@@ -35,6 +37,19 @@ public class RefMatchEditor extends PropertyEditor<String> {}, getModel());add(input);++ add(new AttributeAppender("class", new LoadableDetachableModel<String>() {++ @Override+ protected String load() {+ if (hasError(true))+ return " has-error";+ else+ return "";+ }++ }));+}@Overridediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/commit/QueryAssistBehavior.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/commit/QueryAssistBehavior.javaindex 0317bef80b..4b7bfa530b 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/commit/QueryAssistBehavior.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/commit/QueryAssistBehavior.java@@ -16,8 +16,8 @@ import com.pmease.commons.antlr.grammar.LexerRuleRefElementSpec;import com.pmease.commons.git.NameAndEmail;import com.pmease.commons.util.Range;import com.pmease.commons.util.StringUtils;-import com.pmease.commons.util.pattern.WildcardApplied;-import com.pmease.commons.util.pattern.WildcardUtils;+import com.pmease.commons.util.match.WildcardApplied;+import com.pmease.commons.util.match.WildcardUtils;import com.pmease.commons.wicket.behavior.inputassist.ANTLRAssistBehavior;import com.pmease.gitplex.core.GitPlex;import com.pmease.gitplex.core.manager.AuxiliaryManager;diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.htmlindex d733c65cfa..f0c2cd624e 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html@@ -1,7 +1,7 @@<wicket:extend><form wicket:id="form"><div wicket:id="feedback"></div>- <input wicket:id="input"></input>+ <input wicket:id="input" spellcheck="false" autocomplete="off"></input><input type="submit" value="submit"></input></form></wicket:extend>\ No newline at end of filediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.javaindex b0479ea87e..42838ad88f 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java@@ -1,13 +1,15 @@package com.pmease.gitplex.web.page.test;+import java.util.List;+import org.apache.wicket.markup.html.form.Form;-import org.apache.wicket.model.AbstractReadOnlyModel;-import org.apache.wicket.model.PropertyModel;+import org.apache.wicket.markup.html.form.TextField;+import org.apache.wicket.model.Model;-import com.pmease.commons.hibernate.dao.Dao;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.model.Depot;-import com.pmease.gitplex.web.component.refmatch.RefMatchInput;+import com.pmease.commons.antlr.codeassist.InputSuggestion;+import com.pmease.commons.antlr.codeassist.ParentedElement;+import com.pmease.commons.antlr.codeassist.test.CodeAssistTest2Parser;+import com.pmease.commons.wicket.behavior.inputassist.ANTLRAssistBehavior;import com.pmease.gitplex.web.page.base.BasePage;import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;@@ -15,31 +17,21 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel@SuppressWarnings("serial")public class TestPage extends BasePage {- private String refMatch;-@Overrideprotected void onInitialize() {super.onInitialize();- Form<?> form = new Form<Void>("form") {-- @Override- protected void onSubmit() {- super.onSubmit();- System.out.println(refMatch);- }-- };+ Form<?> form = new Form<Void>("form");form.add(new NotificationPanel("feedback", form));- form.add(new RefMatchInput("input", new AbstractReadOnlyModel<Depot>() {+ form.add(new TextField<String>("input", Model.of("")).add(new ANTLRAssistBehavior(CodeAssistTest2Parser.class, "query") {@Override- public Depot getObject() {- return GitPlex.getInstance(Dao.class).load(Depot.class, 1L);+ protected List<InputSuggestion> suggest(ParentedElement element, String matchWith, final int count) {+ return null;}- }, new PropertyModel<String>(this, "refMatch")));+ }));add(form);}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/util/SuggestionUtils.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/util/SuggestionUtils.javaindex d6a0d1fc9c..2a783d03d4 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/util/SuggestionUtils.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/util/SuggestionUtils.java@@ -12,8 +12,8 @@ import org.eclipse.jgit.lib.Ref;import com.pmease.commons.antlr.codeassist.InputSuggestion;import com.pmease.commons.git.GitUtils;import com.pmease.commons.util.Range;-import com.pmease.commons.util.pattern.WildcardApplied;-import com.pmease.commons.util.pattern.WildcardUtils;+import com.pmease.commons.util.match.WildcardApplied;+import com.pmease.commons.util.match.WildcardUtils;import com.pmease.gitplex.core.GitPlex;import com.pmease.gitplex.core.manager.AuxiliaryManager;import com.pmease.gitplex.core.model.Depot;