Subversion Repositories DevTools

Rev

Rev 6910 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
4543 dpurdie 1
//==============================================================================
2
//
3
//    ERG TRANSIT SYSTEMS      Licensed software
4
//    (C) 2006                 All rights reserved
5
//
6
//==============================================================================
7
//
8
// Description: This program will take an SQL connection information from its
9
//              commad line arguments.
10
//
11
//              The program will listen on stdin for an SQL statement. It will
12
//              then prepare and execute the statement.
13
//
14
//              The results are streamed out of the program on STDOUT
15
//
16
//              The program is intended to assist in replacing the DBI::ODBC
17
//              packages within the JATS deployments scripts.
18
//
19
//
20
// Inputs:
21
//      Arguments:
22
//              url             - Fed into the getConnection
23
//              user            - Fed into the getConnection
24
//              password        - Fed into the getConnection
25
//      StdIn:
26
//              query           - An SQL query
27
//
28
// Output:      Data is streamed out sdtout. It is intended to processed by
29
//              another program, and not a human.
30
//              Each line constits of a a tag and a data field. The tag describes
31
//              the data that follows and the progress of the operation.
32
//
33
//              Output lines:
6912 dpurdie 34
//                      Status:xxxxx                        - Indicates program status
35
//                      Error:xxxxx                         - Error messages
36
//                      Info:ColumnCount:x                  - SQL info: number of Cols of data
37
//                      Info:ColumnInfo:x:name:width:type   - SQL info: Names of all of the columns and other data
38
//                      DataStart:                          - Start of SQL response
39
//                      Data:xxxx,yyyy,zzzz,...             - SQL response
40
//                      DataEnd:                            - End of SQL response
4543 dpurdie 41
//
42
//              The Data: lines contain coma-seperated fields. The fields are
43
//                        encoded as 4 bits per byte added to an ascii-0. A cheap
44
//                        hex encoding.
45
//
46
//              Program exist code:     0: Sucess
47
//                                      1: Error encountered
48
//
49
//==============================================================================
50
 
51
package com.erggroup.jats;
52
import java.io.IOException;
53
import java.io.InputStreamReader;
54
import java.io.BufferedReader;
55
import java.sql.CallableStatement;
56
import java.sql.Statement;
57
import java.sql.Connection;
58
import java.sql.DriverManager;
59
import java.sql.SQLException;
60
import java.sql.ResultSet;
61
import java.sql.ResultSetMetaData;
4619 dpurdie 62
import com.erggroup.jats.TimedBufferedReader;
4543 dpurdie 63
 
64
public class ReleaseManagerSelect
65
{
66
  public static void main(String[] args)
67
  {
68
    int EndSelect = 0;
69
 
70
    System.out.println( "Status:Program startup" );
71
 
72
    if ( args.length != 3 )
73
    {
74
      System.out.println( "Error: Not enough arguments. Need 3, Have " + args.length );
75
      System.exit( 1 );
76
    }
77
 
78
    //
79
    //  Extract user parameters
80
    //
81
    String url = args[0];
82
    String user = args[1];
83
    String passwd = args[2];
84
 
85
    System.out.println( "Status:url:" + url );
86
    System.out.println( "Status:user:" + user );
87
    System.out.println( "Status:passwd:" + passwd );
88
 
89
    //
90
    //  Use a read routine that will timeout if no activity occurs
91
    //  the process will exit, otherwise we appear to get stray instances
92
    //  of java running - if the user control-C while running.
93
    //
94
    BufferedReader br = new TimedBufferedReader(new InputStreamReader(System.in));
95
    String query = null;
96
 
97
    //
98
    // Initiate the connection
99
    //
100
    try
101
    {
4619 dpurdie 102
 
103
        //  Load the Oracle JDBC driver
104
        try {
105
            Class.forName("oracle.jdbc.OracleDriver") ;
106
            System.out.println("Oracle JDBC driver loaded ok.");
107
 
108
        } catch (Exception e) {
109
            System.out.println("Exception: " + e.getMessage());
110
            System.exit(1);
111
        }
112
 
4543 dpurdie 113
        Connection conn = DriverManager.getConnection( url, user, passwd);
114
        System.out.println( "Status:Connection Opened" );
115
        System.out.println( "ConnectionOpened:" );
116
 
117
        //
118
        //    Process requests
119
        //
120
        while ( EndSelect == 0 )
121
        {
122
            //
123
            //    Read in the next select request from the input stream
124
            //    Only SELECT statements will do something useful, but this could
125
            //    be extended.
126
            //
127
            System.out.println( "Status:ReadyForQuery");
128
            try {
129
                query = br.readLine();
130
            } catch (IOException ioe) {
131
                System.out.println("Error:IO error trying to read input");
132
                System.exit(1);
133
            }
134
 
135
            if ( query.length() <= 0 )
136
            {
137
              System.out.println( "Status:Zero length query" );
138
              EndSelect = 1;
139
              continue;
140
            }
141
 
142
            //
143
            //  Determine the correct operation
144
            //      SELECT
145
            //      BEGIN
146
            //
147
            String begin = query.toUpperCase();
148
            if ( begin.startsWith("SELECT") )
149
            {
150
                do_select( conn, query );
151
            }
152
            else
153
            {
154
                do_begin( conn, query );
155
            }
156
 
157
            //
158
            //  Ensure end of data is seen, even if an error is encountered
159
            //
160
            System.out.println( "DataEnd:");
161
 
162
        }
163
 
164
    conn.close();
165
    System.out.println( "Status:ConnectionClosed" );
166
    System.exit( 0 );
167
    }
168
 
169
    catch( SQLException e )
170
    {
171
        System.out.println( "Error:main caught java.sql.SQLException " );
172
        System.out.println( "Error:" + e.getMessage().replace('\n', '~' ));
173
        System.out.println( "Status:ConnectionClosed" );
174
        System.exit( 1 );
175
    }
176
  }
177
 
178
    //----------------------------------------------------------------------------
179
    // FUNCTION           : do_begin
180
    //
181
    // DESCRIPTION        : Perform a SELECT operation
182
    //
183
    //
184
    // INPUTS             : conn            - The connection
185
    //                      query           - The query
186
    //
187
    // RETURNS            : nothing
188
    //
189
 
190
    public static void do_begin(  Connection conn, String query )
191
    {
192
        try
193
        {
194
            System.out.println( "Status:begin:" + query );
195
            CallableStatement stmt = conn.prepareCall( query );
196
            stmt.executeUpdate();
197
            stmt.close();
198
            System.out.println( "DataStart:");
199
 
200
        }
201
        catch( SQLException e )
202
        {
203
            System.out.println( "Warning:main caught java.sql.SQLException " );
204
            System.out.println( "Warning:" + e.getMessage().replace('\n', '~' ));
205
        }
206
    }
207
 
208
    //----------------------------------------------------------------------------
209
    // FUNCTION           : do_select
210
    //
211
    // DESCRIPTION        : Perform a SELECT operation
212
    //
213
    //
214
    // INPUTS             : conn            - The connection
215
    //                      query           - The query
216
    //
217
    // RETURNS            : nothing
218
    //
219
    public static void do_select(  Connection conn, String query )
220
    {
221
          System.out.println( "Status:query:" + query );
222
 
223
 
224
          //
225
          //    Execute the query and return the results to the user
226
          //    All the results are streamed to the user in one block
227
          //    It is not possible to interleave requests and fetches at this
228
          //    level. That should be done by the consiming wrapper.
229
          //
230
          try {
231
 
232
              Statement stmt = conn.createStatement();
5908 dpurdie 233
              stmt.setFetchSize(1000);
4543 dpurdie 234
 
235
              System.out.println( "Status:Statement prepared" );
236
 
237
              ResultSet rset = stmt.executeQuery(query);
238
              System.out.println( "Status:Query Done" );
239
 
240
              //
5908 dpurdie 241
              //  Determine the number of columns
4543 dpurdie 242
              //
243
              ResultSetMetaData rsmd = rset.getMetaData();
244
              int numberOfColumns = rsmd.getColumnCount();
245
              System.out.println( "Info:ColumnCount:" + numberOfColumns );
246
 
6910 dpurdie 247
              // The column count starts from 1
248
              for (int i = 1; i <= numberOfColumns; i++ ) {
6912 dpurdie 249
                  System.out.println( "Info:ColumnInfo:" + i 
250
                                      + ":" + rsmd.getColumnName(i) 
251
                                      + ":" + rsmd.getColumnDisplaySize(i) 
252
                                      + ":" + rsmd.getColumnTypeName(i) );
6910 dpurdie 253
              }
254
 
4543 dpurdie 255
              //
256
              //    Return all rows to the user
257
              //
258
              System.out.println( "DataStart:");
259
              while (rset.next ())
260
              {
261
                for ( int ii = 1; ii <= numberOfColumns; ii++ )
262
                {
263
                    if ( ii != 1 )
264
                        System.out.print( "," );
265
                    else
266
                        System.out.print( "Data:" );
267
 
268
 
269
                    String s = rset.getString(ii);
270
                    StringBuffer sb = new StringBuffer (200);
271
 
272
                    //
273
                    // We have the data as text, but it may have characters in it
274
                    // that we can't pass through to our user. Need to esacpe
275
                    //          returns
276
                    //          new lines
277
                    //          commas
278
                    //
279
                    // Convert all data to text bytes. Not quite HEX. Use 0123456789:;<=>?
280
                    // Simple and rude way to ensure that all data gets through
281
                    //
282
                    if ( s != null )
283
                    {
284
                        for (int i = 0; i < s.length (); i++)
285
                          {
286
                               char c = s.charAt (i);       // Extract character
287
                               char c1 = (char)(c & 0x0f);
288
                               char c2 = (char)((c >> 4) & 0x0f);
289
 
290
                               sb.append( (char)(c2 + '0') );
291
                               sb.append( (char)(c1 + '0') );
292
                          }
293
                    }
294
                    System.out.print( sb );
295
                }
296
                System.out.println();
297
              }
298
 
299
              //
300
              //    Release resources
301
              //
302
              rset.close();
303
              stmt.close();
304
 
305
            }
306
            catch( SQLException e )
307
            {
308
              System.out.println( "Warning:main caught java.sql.SQLException " );
309
              System.out.println( "Warning:" + e.getMessage().replace('\n', '~' ));
310
            }
311
    }
312
}
313