Subversion Repositories DevTools

Rev

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