aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/ant/apache-ant-1.9.6/src/tests/junit/org/apache/tools/ant/taskdefs/SQLExecTest.java
blob: fbce8a6d526109d2fcdc1edbb4b6820bbd20404f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/*
 *  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 org.apache.tools.ant.taskdefs;

import java.sql.Driver;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DriverPropertyInfo;
import java.util.Properties;
import java.io.File;
import java.net.URL;
import java.util.logging.Logger;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.BuildException;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import static org.apache.tools.ant.AntAssert.assertContains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * Simple testcase to test for driver caching.
 * To test for your own database, you may need to tweak getProperties(int)
 * and add a couple of keys. see testOracle and testMySQL for an example.
 *
 * It would be much better to extend this testcase by using HSQL
 * as the test db, so that a db is really used.
 *
 */
public class SQLExecTest {

    // some database keys, see #getProperties(int)
    public final static int NULL = 0;
    public final static int ORACLE = 1;
    public final static int MYSQL = 2;

    // keys used in properties.
    public final static String DRIVER = "driver";
    public final static String USER = "user";
    public final static String PASSWORD = "password";
    public final static String URL = "url";
    public final static String PATH = "path";
    public final static String SQL = "sql";

    @Before
    public void setUp() throws Exception {
        // make sure the cache is cleared.
        JDBCTask.getLoaderMap().clear();
    }

   // simple test to ensure that the caching does work...
    @Test
    public void testDriverCaching(){
        SQLExec sql = createTask(getProperties(NULL));
        assertTrue(!SQLExec.getLoaderMap().containsKey(NULL_DRIVER));
        try {
            sql.execute();
            fail("BuildException should have been thrown");
        } catch (BuildException e){
            assertContains("No suitable Driver", e.getMessage());
        }
        assertTrue(SQLExec.getLoaderMap().containsKey(NULL_DRIVER));
        assertSame(sql.getLoader(), JDBCTask.getLoaderMap().get(NULL_DRIVER));
        ClassLoader loader1 = sql.getLoader();

        // 2nd run..
        sql = createTask(getProperties(NULL));
        // the driver must still be cached.
        assertTrue(JDBCTask.getLoaderMap().containsKey(NULL_DRIVER));
        try {
            sql.execute();
        } catch (BuildException e){
            assertTrue(e.getCause().getMessage().indexOf("No suitable Driver") != -1);
        }
        assertTrue(JDBCTask.getLoaderMap().containsKey(NULL_DRIVER));
        assertSame(sql.getLoader(), JDBCTask.getLoaderMap().get(NULL_DRIVER));
        assertSame(loader1, sql.getLoader());
    }

    @Test
    public void testNull() throws Exception {
        doMultipleCalls(1000, NULL, true, true);
    }

    @Ignore
    @Test
    public void testOracle(){
        doMultipleCalls(1000, ORACLE, true, false);
    }

    @Ignore
    @Test
    public void testMySQL(){
        doMultipleCalls(1000, MYSQL, true, false);
    }


    /**
     * run a sql tasks multiple times.
     * @param calls number of times to execute the task
     * @param database the database to execute on.
     * @param caching should caching be enabled ?
     * @param catchexception true to catch exception for each call, false if not.
     */
    protected void doMultipleCalls(int calls, int database, boolean caching, boolean catchexception){
        Properties props = getProperties(database);
        for (int i = 0; i < calls; i++){
            SQLExec sql = createTask(props);
            sql.setCaching(caching);
            try  {
                sql.execute();
            } catch (BuildException e){
                if (!catchexception){
                    throw e;
                }
            }
        }
    }

    /**
     * Create a task from a set of properties
     * @see #getProperties(int)
     */
    protected SQLExec createTask(Properties props){
        SQLExec sql = new SQLExec();
        sql.setProject( new Project() );
        sql.setDriver( props.getProperty(DRIVER) );
        sql.setUserid( props.getProperty(USER) );
        sql.setPassword( props.getProperty(PASSWORD) );
        sql.setUrl( props.getProperty(URL) );
        sql.createClasspath().setLocation( new File(props.getProperty(PATH)) );
        sql.addText( props.getProperty(SQL) );
        return sql;
    }

    /**
     * try to find the path from a resource (jar file or directory name)
     * so that it can be used as a classpath to load the resource.
     */
    protected String findResourcePath(String resource){
        resource = resource.replace('.', '/') + ".class";
        URL url = getClass().getClassLoader().getResource(resource);
        if (url == null) {
            return null;
        }
        String u = url.toString();
        if (u.startsWith("jar:file:")) {
            int pling = u.indexOf("!");
            return u.substring("jar:file:".length(), pling);
        } else if (u.startsWith("file:")) {
            int tail = u.indexOf(resource);
            return u.substring("file:".length(), tail);
        }
        return null;
    }

    /**
     * returns a configuration associated to a specific database.
     * If you want to test on your specific base, you'd better
     * tweak this to make it run or add your own database.
     * The driver lib should be dropped into the system classloader.
     */
    protected Properties getProperties(int database){
        Properties props = null;
        switch (database){
            case ORACLE:
                props = getProperties("oracle.jdbc.driver.OracleDriver", "test", "test", "jdbc:oracle:thin:@127.0.0.1:1521:orcl");
                break;
            case MYSQL:
                props = getProperties("org.gjt.mm.mysql.Driver", "test", "test", "jdbc:mysql://127.0.0.1:3306/test");
                break;
            case NULL:
            default:
                props = getProperties(NULL_DRIVER, "test", "test", "jdbc:database://hostname:port/name");
        }
        // look for the driver path...
        String path = findResourcePath(props.getProperty(DRIVER));
        props.put(PATH, path);
        props.put(SQL, "create table OOME_TEST(X INTEGER NOT NULL);\ndrop table if exists OOME_TEST;");
        return props;
    }

    /** helper method to build properties */
    protected Properties getProperties(String driver, String user, String pwd, String url){
        Properties props = new Properties();
        props.put(DRIVER, driver);
        props.put(USER, user);
        props.put(PASSWORD, pwd);
        props.put(URL, url);
        return props;
    }


//--- NULL JDBC driver just for simple test since there are no db driver
// available as a default in Ant :)

    public final static String NULL_DRIVER = NullDriver.class.getName();

    public static class NullDriver implements Driver {
        public Connection connect(String url, Properties info)
                throws SQLException {
            return null;
        }

        public boolean acceptsURL(String url) throws SQLException {
            return false;
        }

        public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
                throws SQLException {
            return new DriverPropertyInfo[0];
        }

        public int getMajorVersion() {
            return 0;
        }

        public int getMinorVersion() {
            return 0;
        }

        public boolean jdbcCompliant() {
            return false;
        }

        public Logger getParentLogger() /*throws SQLFeatureNotSupportedException*/ {
            return Logger.getAnonymousLogger();
        }
    }

    @Test
    public void testLastDelimiterPositionNormalModeStrict() {
        SQLExec s = new SQLExec();
        assertEquals(-1,
                     s.lastDelimiterPosition(new StringBuffer(), null));
        assertEquals(-1,
                     s.lastDelimiterPosition(new StringBuffer("GO"), null));
        assertEquals(-1,
                     s.lastDelimiterPosition(new StringBuffer("; "), null));
        assertEquals(2,
                     s.lastDelimiterPosition(new StringBuffer("ab;"), null));
        s.setDelimiter("GO");
        assertEquals(-1,
                     s.lastDelimiterPosition(new StringBuffer("GO "), null));
        assertEquals(-1,
                     s.lastDelimiterPosition(new StringBuffer("go"), null));
        assertEquals(0,
                     s.lastDelimiterPosition(new StringBuffer("GO"), null));
    }

    @Test
    public void testLastDelimiterPositionNormalModeNonStrict() {
        SQLExec s = new SQLExec();
        s.setStrictDelimiterMatching(false);
        assertEquals(-1,
                     s.lastDelimiterPosition(new StringBuffer(), null));
        assertEquals(-1,
                     s.lastDelimiterPosition(new StringBuffer("GO"), null));
        assertEquals(0,
                     s.lastDelimiterPosition(new StringBuffer("; "), null));
        assertEquals(2,
                     s.lastDelimiterPosition(new StringBuffer("ab;"), null));
        s.setDelimiter("GO");
        assertEquals(0,
                     s.lastDelimiterPosition(new StringBuffer("GO "), null));
        assertEquals(0,
                     s.lastDelimiterPosition(new StringBuffer("go"), null));
        assertEquals(0,
                     s.lastDelimiterPosition(new StringBuffer("GO"), null));
    }

    @Test
    public void testLastDelimiterPositionRowModeStrict() {
        SQLExec s = new SQLExec();
        SQLExec.DelimiterType t = new SQLExec.DelimiterType();
        t.setValue("row");
        s.setDelimiterType(t);
        assertEquals(-1, s.lastDelimiterPosition(null, ""));
        assertEquals(-1, s.lastDelimiterPosition(null, "GO"));
        assertEquals(-1, s.lastDelimiterPosition(null, "; "));
        assertEquals(1, s.lastDelimiterPosition(new StringBuffer("ab"), ";"));
        s.setDelimiter("GO");
        assertEquals(-1, s.lastDelimiterPosition(null, "GO "));
        assertEquals(-1, s.lastDelimiterPosition(null, "go"));
        assertEquals(0, s.lastDelimiterPosition(new StringBuffer("ab"), "GO"));
    }

    @Test
    public void testLastDelimiterPositionRowModeNonStrict() {
        SQLExec s = new SQLExec();
        SQLExec.DelimiterType t = new SQLExec.DelimiterType();
        t.setValue("row");
        s.setDelimiterType(t);
        s.setStrictDelimiterMatching(false);
        assertEquals(-1, s.lastDelimiterPosition(null, ""));
        assertEquals(-1, s.lastDelimiterPosition(null, "GO"));
        assertEquals(0, s.lastDelimiterPosition(new StringBuffer("; "), "; "));
        assertEquals(1, s.lastDelimiterPosition(new StringBuffer("ab"), ";"));
        s.setDelimiter("GO");
        assertEquals(1,
                     s.lastDelimiterPosition(new StringBuffer("abcd"), "GO "));
        assertEquals(0, s.lastDelimiterPosition(new StringBuffer("go"), "go"));
        assertEquals(0, s.lastDelimiterPosition(new StringBuffer("ab"), "GO"));
    }

}