| 1 | /* |
| 2 | * Copyright 2007 brunella ltd |
| 3 | * |
| 4 | * Licensed under the LGPL Version 3 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * |
| 7 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 8 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 9 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 10 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE |
| 11 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 12 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 13 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 14 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 15 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 16 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF |
| 17 | * THE POSSIBILITY OF SUCH DAMAGE. |
| 18 | */ |
| 19 | package sf.qof.util; |
| 20 | |
| 21 | /** |
| 22 | * Helper class with utility method to replace in-clause parameters. |
| 23 | */ |
| 24 | public class InClauseParameterReplacer { |
| 25 | |
| 26 | /** |
| 27 | * Returns a SQL statement that replaces the <code>index</code>-th |
| 28 | * parameter '?' with a number <code>numArgs</code> of '?'. |
| 29 | * |
| 30 | * @param sql the SQL statement |
| 31 | * @param index the index of the parameter to replace |
| 32 | * @param numArgs number of parameters required |
| 33 | * @return new SQL statement with additional parameters |
| 34 | */ |
| 35 | public static String replace(String sql, int index, int numArgs) { |
| 36 | StringBuilder sb = new StringBuilder(sql.length() + (numArgs - 1) * 2); |
| 37 | int currentIndex = 0; |
| 38 | boolean replaced = false; |
| 39 | int i = 0; |
| 40 | while (i < sql.length()) { |
| 41 | char c = sql.charAt(i); |
| 42 | sb.append(c); |
| 43 | if (!replaced) { |
| 44 | if (c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') { |
| 45 | // skip until end of comment |
| 46 | i += 2; |
| 47 | sb.append('*'); |
| 48 | while (i < sql.length()) { |
| 49 | c = sql.charAt(i); |
| 50 | sb.append(c); |
| 51 | if (c == '*' && i + 1 < sql.length() && sql.charAt(i + 1) == '/') { |
| 52 | sb.append('/'); |
| 53 | i++; |
| 54 | break; |
| 55 | } |
| 56 | i++; |
| 57 | } |
| 58 | } |
| 59 | if (c == '?') { |
| 60 | currentIndex++; |
| 61 | if (index == currentIndex) { |
| 62 | for (int j = 0; j < numArgs - 1; j++) { |
| 63 | sb.append(',').append('?'); |
| 64 | } |
| 65 | replaced = true; |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | i++; |
| 70 | } |
| 71 | return sb.toString(); |
| 72 | } |
| 73 | |
| 74 | } |