001     
002    /*****************************************************************************
003    
004        jBudget.
005        Copyright (C) 2006  Dmitri Petrov
006    
007        This program is free software: you can redistribute it and/or modify
008        it under the terms of the GNU General Public License as published by
009        the Free Software Foundation, either version 3 of the License, or
010        (at your option) any later version.
011    
012        This program is distributed in the hope that it will be useful,
013        but WITHOUT ANY WARRANTY; without even the implied warranty of
014        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015        GNU General Public License for more details.
016    
017        You should have received a copy of the GNU General Public License
018        along with this program.  If not, see <http://www.gnu.org/licenses/>.
019     
020    /*****************************************************************************
021    
022    /*
023     * ExpressionParser.java
024     *
025     * Created on December 4, 2006, 8:22 AM
026     */
027    
028    package org.jbudget.util;
029    
030    import java.math.BigDecimal;
031    import java.text.DecimalFormat;
032    import java.text.DecimalFormatSymbols;
033    import java.text.ParseException;
034    import java.util.Currency;
035    import java.util.Locale;
036    import java.util.regex.Matcher;
037    import java.util.regex.Pattern;
038    
039    /**
040     * A class that is used to parse simple expressions containing arithmetic
041     * operations on money.
042     *
043     * @author petrov
044     */
045    public class ExpressionParser
046    {
047      private static final DecimalFormatSymbols symbols = 
048                        (new DecimalFormat()).getDecimalFormatSymbols();
049      
050      /** Currency symbol */
051      private final String currencySymbol = symbols.getCurrencySymbol();
052      
053      /** Decimal separator (dot in the US locale) */
054      private final char decimalSeparator = symbols.getMonetaryDecimalSeparator();
055      
056      private final String decimalSeparatorPattern;
057      
058      /** Grouping separator (comma in the US locale) */
059      private final char groupingSeparator = symbols.getGroupingSeparator();
060      
061      /** number of fraction digits used by the currency */
062      private final int nDigits = Currency.getInstance(
063                                  Locale.getDefault()).getDefaultFractionDigits();
064      
065      //==================== Patterns ===========================================//
066      
067      private final String valueStr;
068      private final Pattern valuePattern;
069      private final Pattern bracketsPattern;
070      private final Pattern plusPattern;
071      private final Pattern minusPattern;
072      private final Pattern multPattern;
073      private final Pattern divPattern;
074      private final Pattern illegalCharsPattern;
075      private final Pattern illegalSpacesPattern;
076      
077      
078      /** Creates a new instance of ExpressionParser */
079      public ExpressionParser()
080      {
081        if (decimalSeparator == '.')
082          decimalSeparatorPattern = "\\.";
083        else
084        {
085          StringBuffer buffer = new StringBuffer();
086          buffer.append(decimalSeparator);
087          decimalSeparatorPattern = buffer.toString();
088        }
089        
090        valueStr = "(\\-?+\\d+" + decimalSeparatorPattern + "?+\\d*)";
091        valuePattern    = Pattern.compile(valueStr);
092        bracketsPattern = Pattern.compile("\\(([\\d\\+\\-\\*\\/"+
093                                          decimalSeparatorPattern + "]+)\\)");
094        plusPattern  = Pattern.compile(valueStr + "\\+" + valueStr);
095        minusPattern = Pattern.compile(valueStr + "\\-" + valueStr);
096        multPattern  = Pattern.compile(valueStr + "\\*" + valueStr);
097        divPattern   = Pattern.compile(valueStr + "\\/" + valueStr);
098        
099        illegalCharsPattern = Pattern.compile(
100                      "[^0-9\\+\\-\\*\\/\\s\\(\\)" + decimalSeparatorPattern + "]");
101        illegalSpacesPattern = Pattern.compile("\\d\\s+\\d");
102      }
103      
104      
105      /** Performs arithmetic operations on a given string. */
106      private String convert(String input) 
107      {
108        
109        if (valuePattern.matcher(input).matches())
110          return input;
111        
112        
113        // First we need to deal with the brackets.
114        Matcher matcher = bracketsPattern.matcher(input);
115        while (matcher.find())
116        {
117          int start = matcher.start();
118          int end = matcher.end();
119          String s = convert(matcher.group(1));
120          StringBuffer buffer = new StringBuffer();
121          buffer.append(input.substring(0,start));
122          buffer.append(s);
123          buffer.append(input.substring(end, input.length()));
124          input = buffer.toString();
125          matcher = bracketsPattern.matcher(input);
126        }
127        
128        
129        // Now deal with multiplication
130        matcher = multPattern.matcher(input);
131        while (matcher.find())
132        {
133          int start = matcher.start();
134          int end = matcher.end();
135          String s1 = convert(matcher.group(1));
136          String s2 = convert(matcher.group(2));
137          BigDecimal d1 = new BigDecimal(s1);
138          BigDecimal d2 = new BigDecimal(s2);
139          d1 = d1.multiply(d2);
140          StringBuffer buffer = new StringBuffer();
141          buffer.append(input.substring(0,start));
142          buffer.append(d1.toPlainString());
143          buffer.append(input.substring(end, input.length()));
144          input = buffer.toString();
145          matcher = multPattern.matcher(input);
146        }
147    
148        // Now division
149        matcher = divPattern.matcher(input);
150        while (matcher.find())
151        {
152          int start = matcher.start();
153          int end = matcher.end();
154          String s1 = convert(matcher.group(1));
155          String s2 = convert(matcher.group(2));
156          BigDecimal d1 = new BigDecimal(s1);
157          BigDecimal d2 = new BigDecimal(s2);
158          d1 = d1.divide(d2);
159          StringBuffer buffer = new StringBuffer();
160          buffer.append(input.substring(0,start));
161          buffer.append(d1.toPlainString());
162          buffer.append(input.substring(end, input.length()));
163          input = buffer.toString();
164          matcher = divPattern.matcher(input);
165        }
166        
167        // addition
168        matcher = plusPattern.matcher(input);
169        while (matcher.find())
170        {
171          int start = matcher.start();
172          int end = matcher.end();
173          String s1 = convert(matcher.group(1));
174          String s2 = convert(matcher.group(2));
175          BigDecimal d1 = new BigDecimal(s1);
176          BigDecimal d2 = new BigDecimal(s2);
177          d1 = d1.add(d2);
178          StringBuffer buffer = new StringBuffer();
179          buffer.append(input.substring(0,start));
180          buffer.append(d1.toPlainString());
181          buffer.append(input.substring(end, input.length()));
182          input = buffer.toString();
183          matcher = plusPattern.matcher(input);
184        }
185    
186        // subtraction
187        matcher = minusPattern.matcher(input);
188        while (matcher.find())
189        {
190          int start = matcher.start();
191          int end = matcher.end();
192          String s1 = convert(matcher.group(1));
193          String s2 = convert(matcher.group(2));
194          BigDecimal d1 = new BigDecimal(s1);
195          BigDecimal d2 = new BigDecimal(s2);
196          d1 = d1.subtract(d2);
197          StringBuffer buffer = new StringBuffer();
198          buffer.append(input.substring(0,start));
199          buffer.append(d1.toPlainString());
200          buffer.append(input.substring(end, input.length()));
201          input = buffer.toString();
202          matcher = minusPattern.matcher(input);
203        }
204           
205        return input;
206      }
207      
208      public long parse (String input) throws ParseException
209      {
210        StringBuffer buffer = new StringBuffer();
211        buffer.append(input);
212        
213        //Eliminating currency symbols.
214        int ind = buffer.lastIndexOf(currencySymbol);
215        while(ind != -1)
216        {
217          buffer.delete(ind, ind+currencySymbol.length());
218          ind = buffer.lastIndexOf(currencySymbol);
219        }
220        
221        StringBuffer separatorBuffer = new StringBuffer();
222        separatorBuffer.append(groupingSeparator);
223        String separator = separatorBuffer.toString();
224        
225        //Eliminating comma symbols.
226        ind = buffer.lastIndexOf(separator);
227        while(ind != -1)
228        {
229          buffer.delete(ind, ind+1);
230          ind = buffer.lastIndexOf(separator);
231        }
232        
233        // Make sure that there are not illegal chars
234        Matcher matcher = illegalCharsPattern.matcher(buffer.toString());
235        if (matcher.find())
236          throw new ParseException("Bad format", matcher.start());
237        
238        matcher = illegalSpacesPattern.matcher(buffer.toString());
239        if (matcher.find())
240          throw new ParseException("Bad format", matcher.start());
241        
242        //Eliminating spaces
243        ind = buffer.lastIndexOf(" ");
244        while(ind != -1)
245        {
246          buffer.delete(ind, ind+1);
247          ind = buffer.lastIndexOf(" ");
248        }
249        
250        try
251        {
252        
253          String processed = convert(buffer.toString());
254          matcher = valuePattern.matcher(processed);
255          if (!matcher.matches())
256            throw new ParseException("Bad format", 0);
257    
258          BigDecimal d1 = new BigDecimal(processed);
259          d1 = d1.multiply(new BigDecimal(100.0));
260          return d1.longValue();
261          
262        }
263        catch (NumberFormatException ex){
264          throw new ParseException("Bad format", 0);
265        }
266        
267      }
268      
269    }