001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.util;
018
019import java.util.ArrayList;
020import java.util.List;
021import java.util.regex.Matcher;
022import java.util.regex.Pattern;
023
024/**
025 * Helper for Camel OGNL (Object-Graph Navigation Language) expressions.
026 *
027 * @version 
028 */
029public final class OgnlHelper {
030
031    private static final Pattern INDEX_PATTERN = Pattern.compile("^(.*)\\[(.*)\\]$");
032
033    private OgnlHelper() {
034    }
035
036    /**
037     * Tests whether or not the given String is a Camel OGNL expression.
038     * <p/>
039     * An expression is considered an OGNL expression when it contains either one of the following chars: . or [
040     *
041     * @param expression  the String
042     * @return <tt>true</tt> if a Camel OGNL expression, otherwise <tt>false</tt>. 
043     */
044    public static boolean isValidOgnlExpression(String expression) {
045        if (ObjectHelper.isEmpty(expression)) {
046            return false;
047        }
048
049        // the brackets should come in a pair
050        int bracketBegin = StringHelper.countChar(expression, '[');
051        int bracketEnd = StringHelper.countChar(expression, ']');
052        if (bracketBegin > 0 && bracketEnd > 0) {
053            return bracketBegin == bracketEnd;
054        }
055
056        return expression.contains(".");
057    }
058
059    public static boolean isInvalidValidOgnlExpression(String expression) {
060        if (ObjectHelper.isEmpty(expression)) {
061            return false;
062        }
063
064        if (!expression.contains(".") && !expression.contains("[") && !expression.contains("]")) {
065            return false;
066        }
067
068        // the brackets should come in pair
069        int bracketBegin = StringHelper.countChar(expression, '[');
070        int bracketEnd = StringHelper.countChar(expression, ']');
071        if (bracketBegin > 0 || bracketEnd > 0) {
072            return bracketBegin != bracketEnd;
073        }
074        
075        // check for double dots
076        if (expression.contains("..")) {
077            return true;
078        }
079
080        return false;
081    }
082
083    /**
084     * Validates whether the method name is using valid java identifiers in the name
085     * Will throw {@link IllegalArgumentException} if the method name is invalid.
086     */
087    public static void validateMethodName(String method) {
088        if (ObjectHelper.isEmpty(method)) {
089            return;
090        }
091        for (int i = 0; i < method.length(); i++) {
092            char ch = method.charAt(i);
093            if (i == 0 && '.' == ch) {
094                // its a dot before a method name
095                continue;
096            }
097            if (ch == '(' || ch == '[' || ch == '.' || ch == '?') {
098                // break when method name ends and sub method or arguments begin
099                break;
100            }
101            if (i == 0 && !Character.isJavaIdentifierStart(ch)) {
102                throw new IllegalArgumentException("Method name must start with a valid java identifier at position: 0 in method: " + method);
103            } else if (!Character.isJavaIdentifierPart(ch)) {
104                throw new IllegalArgumentException("Method name must be valid java identifier at position: " + i + " in method: " + method);
105            }
106        }
107    }
108
109    /**
110     * Tests whether or not the given Camel OGNL expression is using the null safe operator or not.
111     *
112     * @param ognlExpression the Camel OGNL expression
113     * @return <tt>true</tt> if the null safe operator is used, otherwise <tt>false</tt>.
114     */
115    public static boolean isNullSafeOperator(String ognlExpression) {
116        if (ObjectHelper.isEmpty(ognlExpression)) {
117            return false;
118        }
119
120        return ognlExpression.startsWith("?");
121    }
122
123    /**
124     * Removes any leading operators from the Camel OGNL expression.
125     * <p/>
126     * Will remove any leading of the following chars: ? or .
127     *
128     * @param ognlExpression  the Camel OGNL expression
129     * @return the Camel OGNL expression without any leading operators.
130     */
131    public static String removeLeadingOperators(String ognlExpression) {
132        if (ObjectHelper.isEmpty(ognlExpression)) {
133            return ognlExpression;
134        }
135
136        if (ognlExpression.startsWith("?")) {
137            ognlExpression = ognlExpression.substring(1);
138        }
139        if (ognlExpression.startsWith(".")) {
140            ognlExpression = ognlExpression.substring(1);
141        }
142
143        return ognlExpression;
144    }
145
146    /**
147     * Removes any trailing operators from the Camel OGNL expression.
148     *
149     * @param ognlExpression  the Camel OGNL expression
150     * @return the Camel OGNL expression without any trailing operators.
151     */
152    public static String removeTrailingOperators(String ognlExpression) {
153        if (ObjectHelper.isEmpty(ognlExpression)) {
154            return ognlExpression;
155        }
156
157        if (ognlExpression.contains("[")) {
158            return ObjectHelper.before(ognlExpression, "[");
159        }
160        return ognlExpression;
161    }
162
163    public static String removeOperators(String ognlExpression) {
164        return removeLeadingOperators(removeTrailingOperators(ognlExpression));
165    }
166
167    public static KeyValueHolder<String, String> isOgnlIndex(String ognlExpression) {
168        Matcher matcher = INDEX_PATTERN.matcher(ognlExpression);
169        if (matcher.matches()) {
170
171            // to avoid empty strings as we want key/value to be null in such cases
172            String key = matcher.group(1);
173            if (ObjectHelper.isEmpty(key)) {
174                key = null;
175            }
176
177            // to avoid empty strings as we want key/value to be null in such cases
178            String value = matcher.group(2);
179            if (ObjectHelper.isEmpty(value)) {
180                value = null;
181            }
182
183            return new KeyValueHolder<>(key, value);
184        }
185
186        return null;
187    }
188
189    /**
190     * Regular expression with repeating groups is a pain to get right
191     * and then nobody understands the reg exp afterwards.
192     * So we use a bit ugly/low-level Java code to split the OGNL into methods.
193     *
194     * @param ognl the ognl expression
195     * @return a list of methods, will return an empty list, if ognl expression has no methods
196     * @throws IllegalArgumentException if the last method has a missing ending parenthesis
197     */
198    public static List<String> splitOgnl(String ognl) {
199        List<String> methods = new ArrayList<>();
200
201        // return an empty list if ognl is empty
202        if (ObjectHelper.isEmpty(ognl)) {
203            return methods;
204        }
205
206        StringBuilder sb = new StringBuilder();
207
208        int j = 0; // j is used as counter per method
209        boolean squareBracket = false; // special to keep track if we are inside a square bracket block, eg: [foo]
210        boolean parenthesisBracket = false; // special to keep track if we are inside a parenthesis block, eg: bar(${body}, ${header.foo})
211        for (int i = 0; i < ognl.length(); i++) {
212            char ch = ognl.charAt(i);
213            // special for starting a new method
214            if (j == 0 || (j == 1 && ognl.charAt(i - 1) == '?')
215                    || (ch != '.' && ch != '?' && ch != ']')) {
216                sb.append(ch);
217                // special if we are doing square bracket
218                if (ch == '[' && !parenthesisBracket) {
219                    squareBracket = true;
220                } else if (ch == '(') {
221                    parenthesisBracket = true;
222                } else if (ch == ')') {
223                    parenthesisBracket = false;
224                }
225                j++; // advance
226            } else {
227                if (ch == '.' && !squareBracket && !parenthesisBracket) {
228                    // only treat dot as a method separator if not inside a square bracket block
229                    // as dots can be used in key names when accessing maps
230
231                    // a dit denotes end of this method and a new method is to be invoked
232                    String s = sb.toString();
233
234                    // reset sb
235                    sb.setLength(0);
236
237                    // pass over ? to the new method
238                    if (s.endsWith("?")) {
239                        sb.append("?");
240                        s = s.substring(0, s.length() - 1);
241                    }
242
243                    // add the method
244                    methods.add(s);
245
246                    // reset j to begin a new method
247                    j = 0;
248                } else if (ch == ']' && !parenthesisBracket) {
249                    // append ending ] to method name
250                    sb.append(ch);
251                    String s = sb.toString();
252
253                    // reset sb
254                    sb.setLength(0);
255
256                    // add the method
257                    methods.add(s);
258
259                    // reset j to begin a new method
260                    j = 0;
261
262                    // no more square bracket
263                    squareBracket = false;
264                }
265
266                // and don't lose the char if its not an ] end marker (as we already added that)
267                if (ch != ']' || parenthesisBracket) {
268                    sb.append(ch);
269                }
270
271                // only advance if already begun on the new method
272                if (j > 0) {
273                    j++;
274                }
275            }
276        }
277
278        // add remainder in buffer when reached end of data
279        if (sb.length() > 0) {
280            methods.add(sb.toString());
281        }
282
283        String last = methods.isEmpty() ? null : methods.get(methods.size() - 1);
284        if (parenthesisBracket && last != null) {
285            // there is an unclosed parenthesis bracket on the last method, so it should end with a parenthesis
286            if (last.contains("(") && !last.endsWith(")")) {
287                throw new IllegalArgumentException("Method should end with parenthesis, was " + last);
288            }
289        }
290
291        return methods;
292    }
293
294}