Subversion Repositories DevTools

Rev

Go to most recent revision | Details | 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;
61
 
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
    {
101
        Connection conn = DriverManager.getConnection( url, user, passwd);
102
        System.out.println( "Status:Connection Opened" );
103
        System.out.println( "ConnectionOpened:" );
104
 
105
        //
106
        //    Process requests
107
        //
108
        while ( EndSelect == 0 )
109
        {
110
            //
111
            //    Read in the next select request from the input stream
112
            //    Only SELECT statements will do something useful, but this could
113
            //    be extended.
114
            //
115
            System.out.println( "Status:ReadyForQuery");
116
            try {
117
                query = br.readLine();
118
            } catch (IOException ioe) {
119
                System.out.println("Error:IO error trying to read input");
120
                System.exit(1);
121
            }
122
 
123
            if ( query.length() <= 0 )
124
            {
125
              System.out.println( "Status:Zero length query" );
126
              EndSelect = 1;
127
              continue;
128
            }
129
 
130
            //
131
            //  Determine the correct operation
132
            //      SELECT
133
            //      BEGIN
134
            //
135
            String begin = query.toUpperCase();
136
            if ( begin.startsWith("SELECT") )
137
            {
138
                do_select( conn, query );
139
            }
140
            else
141
            {
142
                do_begin( conn, query );
143
            }
144
 
145
            //
146
            //  Ensure end of data is seen, even if an error is encountered
147
            //
148
            System.out.println( "DataEnd:");
149
 
150
        }
151
 
152
    conn.close();
153
    System.out.println( "Status:ConnectionClosed" );
154
    System.exit( 0 );
155
    }
156
 
157
    catch( SQLException e )
158
    {
159
        System.out.println( "Error:main caught java.sql.SQLException " );
160
        System.out.println( "Error:" + e.getMessage().replace('\n', '~' ));
161
        System.out.println( "Status:ConnectionClosed" );
162
        System.exit( 1 );
163
    }
164
  }
165
 
166
    //----------------------------------------------------------------------------
167
    // FUNCTION           : do_begin
168
    //
169
    // DESCRIPTION        : Perform a SELECT operation
170
    //
171
    //
172
    // INPUTS             : conn            - The connection
173
    //                      query           - The query
174
    //
175
    // RETURNS            : nothing
176
    //
177
 
178
    public static void do_begin(  Connection conn, String query )
179
    {
180
        try
181
        {
182
            System.out.println( "Status:begin:" + query );
183
            CallableStatement stmt = conn.prepareCall( query );
184
            stmt.executeUpdate();
185
            stmt.close();
186
            System.out.println( "DataStart:");
187
 
188
        }
189
        catch( SQLException e )
190
        {
191
            System.out.println( "Warning:main caught java.sql.SQLException " );
192
            System.out.println( "Warning:" + e.getMessage().replace('\n', '~' ));
193
        }
194
    }
195
 
196
    //----------------------------------------------------------------------------
197
    // FUNCTION           : do_select
198
    //
199
    // DESCRIPTION        : Perform a SELECT operation
200
    //
201
    //
202
    // INPUTS             : conn            - The connection
203
    //                      query           - The query
204
    //
205
    // RETURNS            : nothing
206
    //
207
    public static void do_select(  Connection conn, String query )
208
    {
209
          System.out.println( "Status:query:" + query );
210
 
211
 
212
          //
213
          //    Execute the query and return the results to the user
214
          //    All the results are streamed to the user in one block
215
          //    It is not possible to interleave requests and fetches at this
216
          //    level. That should be done by the consiming wrapper.
217
          //
218
          try {
219
 
220
              Statement stmt = conn.createStatement();
221
 
222
              System.out.println( "Status:Statement prepared" );
223
 
224
              ResultSet rset = stmt.executeQuery(query);
225
              System.out.println( "Status:Query Done" );
226
 
227
              //
228
              //  Determine the numnber of columns
229
              //
230
              ResultSetMetaData rsmd = rset.getMetaData();
231
              int numberOfColumns = rsmd.getColumnCount();
232
              System.out.println( "Info:ColumnCount:" + numberOfColumns );
233
 
234
              //
235
              //    Return all rows to the user
236
              //
237
              System.out.println( "DataStart:");
238
              while (rset.next ())
239
              {
240
                for ( int ii = 1; ii <= numberOfColumns; ii++ )
241
                {
242
                    if ( ii != 1 )
243
                        System.out.print( "," );
244
                    else
245
                        System.out.print( "Data:" );
246
 
247
 
248
                    String s = rset.getString(ii);
249
                    StringBuffer sb = new StringBuffer (200);
250
 
251
                    //
252
                    // We have the data as text, but it may have characters in it
253
                    // that we can't pass through to our user. Need to esacpe
254
                    //          returns
255
                    //          new lines
256
                    //          commas
257
                    //
258
                    // Convert all data to text bytes. Not quite HEX. Use 0123456789:;<=>?
259
                    // Simple and rude way to ensure that all data gets through
260
                    //
261
                    if ( s != null )
262
                    {
263
                        for (int i = 0; i < s.length (); i++)
264
                          {
265
                               char c = s.charAt (i);       // Extract character
266
                               char c1 = (char)(c & 0x0f);
267
                               char c2 = (char)((c >> 4) & 0x0f);
268
 
269
                               sb.append( (char)(c2 + '0') );
270
                               sb.append( (char)(c1 + '0') );
271
                          }
272
                    }
273
                    System.out.print( sb );
274
                }
275
                System.out.println();
276
              }
277
 
278
              //
279
              //    Release resources
280
              //
281
              rset.close();
282
              stmt.close();
283
 
284
            }
285
            catch( SQLException e )
286
            {
287
              System.out.println( "Warning:main caught java.sql.SQLException " );
288
              System.out.println( "Warning:" + e.getMessage().replace('\n', '~' ));
289
            }
290
    }
291
}
292