This is an automated email from the ASF dual-hosted git repository. pradeep pushed a commit to branch RANGER-5034_master in repository https://gitbox.apache.org/repos/asf/ranger.git
commit f3f58bbec8bbfc678e7c422070b6ceaf113ae5f7 Author: Pradeep AgrawaL <prad...@apache.org> AuthorDate: Mon Dec 30 05:02:32 2024 +0530 RANGER-5034: checkstyle compliance updates - jisql module --- jisql/pom.xml | 5 + .../apache/util/outputformatter/CSVFormatter.java | 60 +- .../util/outputformatter/DefaultFormatter.java | 359 ++++++------ .../util/outputformatter/JisqlFormatter.java | 40 +- .../apache/util/outputformatter/XMLFormatter.java | 67 +-- jisql/src/main/java/org/apache/util/sql/Jisql.java | 633 ++++++++++----------- .../java/org/apache/util/sql/MaskingThread.java | 42 +- .../java/org/apache/util/sql/MySQLPLRunner.java | 221 +++---- 8 files changed, 671 insertions(+), 756 deletions(-) diff --git a/jisql/pom.xml b/jisql/pom.xml index edc42840f..82ec4e919 100644 --- a/jisql/pom.xml +++ b/jisql/pom.xml @@ -27,6 +27,11 @@ <packaging>jar</packaging> <name>Jdbc SQL Connector</name> <description>Jdbc SQL Connector to execute sql statement in any db</description> + <properties> + <checkstyle.failOnViolation>true</checkstyle.failOnViolation> + <checkstyle.skip>false</checkstyle.skip> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + </properties> <dependencies> <dependency> <groupId>net.sf.jopt-simple</groupId> diff --git a/jisql/src/main/java/org/apache/util/outputformatter/CSVFormatter.java b/jisql/src/main/java/org/apache/util/outputformatter/CSVFormatter.java index d55ecbca1..8ad6a1ab7 100644 --- a/jisql/src/main/java/org/apache/util/outputformatter/CSVFormatter.java +++ b/jisql/src/main/java/org/apache/util/outputformatter/CSVFormatter.java @@ -19,21 +19,20 @@ package org.apache.util.outputformatter; +import joptsimple.OptionParser; +import joptsimple.OptionSet; + import java.io.PrintStream; import java.sql.ResultSet; import java.sql.ResultSetMetaData; -import joptsimple.OptionParser; -import joptsimple.OptionSet; /** * This is the default formatter for Jisql. It outputs data in a "normal" * format that is similar to most other database command line formatters. - * */ public class CSVFormatter implements JisqlFormatter { - private char delimiter = ','; - private boolean includeColumnNames = false; - + private char delimiter = ','; + private boolean includeColumnNames; /** * Sets a the supported option list for this formatter. This formatter accepts @@ -49,27 +48,26 @@ public class CSVFormatter implements JisqlFormatter { * </ul> * * @param parser the OptionParser to use. - * */ - public void setSupportedOptions( OptionParser parser ) { - parser.accepts( "delimiter" ).withRequiredArg().ofType( String.class ); - parser.accepts( "colnames" ); + public void setSupportedOptions(OptionParser parser) { + parser.accepts("delimiter").withRequiredArg().ofType(String.class); + parser.accepts("colnames"); } /** * Consumes any options that were specified on the command line. * * @param options the OptionSet that the main driver is using. - * * @throws Exception if there is a problem parsing the command line arguments. - * */ - public void consumeOptions( OptionSet options ) throws Exception { - if( options.has( "delimiter" ) ) - delimiter = ((String)(options.valueOf( "delimiter" ))).charAt( 0 ); + public void consumeOptions(OptionSet options) throws Exception { + if (options.has("delimiter")) { + delimiter = ((String) (options.valueOf("delimiter"))).charAt(0); + } - if( options.has( "colnames" ) ) - includeColumnNames = true; + if (options.has("colnames")) { + includeColumnNames = true; + } } /** @@ -77,11 +75,10 @@ public class CSVFormatter implements JisqlFormatter { * message should contain information on how to call the formatter. * * @param out the PrintStream to display the usage message on. - * */ - public void usage( PrintStream out ) { - out.println("\t-delimiter specifies the character to use as the delimiter. This defaults to \"" + delimiter + "\"" ); - out.println("\t-colnames outputs column names. By default there are no column names." ); + public void usage(PrintStream out) { + out.println("\t-delimiter specifies the character to use as the delimiter. This defaults to \"" + delimiter + "\""); + out.println("\t-colnames outputs column names. By default there are no column names."); } /** @@ -90,46 +87,41 @@ public class CSVFormatter implements JisqlFormatter { * * @param out a PrintStream to send any output to. * @param metaData the ResultSetMetaData for the output. - * */ - public void formatHeader( PrintStream out, ResultSetMetaData metaData ) throws Exception { - if( includeColumnNames ) { + public void formatHeader(PrintStream out, ResultSetMetaData metaData) throws Exception { + if (includeColumnNames) { int numColumns = metaData.getColumnCount(); // // output the column names // for (int i = 1; i <= numColumns; i++) { - out.print( metaData.getColumnName(i).trim() ); - if( (i + 1) <= numColumns ) - out.print( delimiter ); + out.print(metaData.getColumnName(i).trim()); + if ((i + 1) <= numColumns) { + out.print(delimiter); + } } out.println(); } } - /** * Called to output the data. * * @param out the PrintStream to output data to. * @param resultSet the ResultSet for the row. * @param metaData the ResultSetMetaData for the row. - * - * */ - public void formatData( PrintStream out, ResultSet resultSet, ResultSetMetaData metaData ) throws Exception{ + public void formatData(PrintStream out, ResultSet resultSet, ResultSetMetaData metaData) throws Exception { } - /** * Outputs a footer for a query. For the CSVFormatter this method does nothing. * * @param out the PrintStream to output data to. * @param metaData the ResultSetMetaData for the output. - * */ - public void formatFooter( PrintStream out, ResultSetMetaData metaData ) throws Exception { + public void formatFooter(PrintStream out, ResultSetMetaData metaData) throws Exception { } } diff --git a/jisql/src/main/java/org/apache/util/outputformatter/DefaultFormatter.java b/jisql/src/main/java/org/apache/util/outputformatter/DefaultFormatter.java index f58e91e91..683172faf 100644 --- a/jisql/src/main/java/org/apache/util/outputformatter/DefaultFormatter.java +++ b/jisql/src/main/java/org/apache/util/outputformatter/DefaultFormatter.java @@ -18,29 +18,26 @@ */ package org.apache.util.outputformatter; -import java.io.PrintStream; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; - import joptsimple.OptionParser; import joptsimple.OptionSet; +import java.io.PrintStream; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; /** * This is the default formatter for Jisql. It outputs data in a "normal" * format that is similar to most other database command line formatters. - * */ public class DefaultFormatter implements JisqlFormatter { - private boolean trimColumns = false; - private int columnWidth = 2048; // can be overridden with the -w switch - private char spacer = ' '; - private boolean printNull = true; - private boolean leftJustify = false; + private boolean trimColumns; + private int columnWidth = 2048; // can be overridden with the -w switch + private char spacer = ' '; + private boolean printNull = true; + private boolean leftJustify; private boolean printHeader = true; - private boolean debug = false; - private String delimiter = " | "; - + private boolean debug; + private String delimiter = " | "; /** * Sets a the option list for this formatter. This formatter accepts the @@ -64,73 +61,73 @@ public class DefaultFormatter implements JisqlFormatter { * </ul> * * @param parser the OptionParser to use. - * */ - public void setSupportedOptions( OptionParser parser ) { - parser.accepts( "trim" ); - parser.accepts( "w" ).withRequiredArg().ofType( Integer.class ); - parser.accepts( "spacer" ).withRequiredArg().ofType( String.class ); - parser.accepts( "left" ); - parser.accepts( "nonull" ); - parser.accepts( "noheader" ); - parser.accepts( "debug" ); - parser.accepts( "delimiter" ).withRequiredArg().ofType( String.class ); + public void setSupportedOptions(OptionParser parser) { + parser.accepts("trim"); + parser.accepts("w").withRequiredArg().ofType(Integer.class); + parser.accepts("spacer").withRequiredArg().ofType(String.class); + parser.accepts("left"); + parser.accepts("nonull"); + parser.accepts("noheader"); + parser.accepts("debug"); + parser.accepts("delimiter").withRequiredArg().ofType(String.class); } /** * Consumes any options that were specified on the command line. * * @param options the OptionSet that the main driver is using. - * * @throws Exception if there is a problem parsing the command line arguments. - * */ - public void consumeOptions( OptionSet options ) throws Exception { - - if( options.has( "trim" ) ) + public void consumeOptions(OptionSet options) throws Exception { + if (options.has("trim")) { trimColumns = true; + } - if( options.has( "w" ) ) - columnWidth = (Integer)options.valueOf( "w" ); + if (options.has("w")) { + columnWidth = (Integer) options.valueOf("w"); + } - if( options.has( "spacer" ) ) - spacer = ((String)(options.valueOf( "spacer" ))).charAt( 0 ); + if (options.has("spacer")) { + spacer = ((String) (options.valueOf("spacer"))).charAt(0); + } - if( options.has( "left" ) ) + if (options.has("left")) { leftJustify = true; + } - if( options.has( "nonull" ) ) + if (options.has("nonull")) { printNull = false; + } - if( options.has( "noheader" ) ) + if (options.has("noheader")) { printHeader = false; + } - if( options.has( "debug" ) ) + if (options.has("debug")) { debug = true; + } - if( options.hasArgument( "delimiter" ) ) - delimiter = (String)options.valueOf( "delimiter" ); + if (options.hasArgument("delimiter")) { + delimiter = (String) options.valueOf("delimiter"); + } } - - /** * Called to output a usage message to the command line window. This * message should contain information on how to call the formatter. * * @param out the stream to print the output on - * */ - public void usage( PrintStream out ) { + public void usage(PrintStream out) { out.println("\t-w specifies the maximum field width for a column. The default is to output the full width of the column"); out.println("\t-spacer changes the spacer between columns from a single space to the first character of the argument"); out.println("\t-noheader do not print any header columns"); out.println("\t-left left justify the output"); out.println("\t-trim trim the data output. This is useful when specifying a delimiter."); out.println("\t-nonull print the empty string instead of the word \"NULL\" for null values."); - out.println("\t-debug shows extra information about the output." ); - out.println("\t-delimiter specifies the delimiter. The default is \"" + delimiter + "\"." ); - + out.println("\t-debug shows extra information about the output."); + out.println("\t-delimiter specifies the delimiter. The default is \"" + delimiter + "\"."); } /** @@ -139,25 +136,24 @@ public class DefaultFormatter implements JisqlFormatter { * * @param out - a PrintStream to send any output to. * @param metaData - the ResultSetMetaData for the output. - * */ - public void formatHeader( PrintStream out, ResultSetMetaData metaData ) throws Exception { - if( printHeader ) { + public void formatHeader(PrintStream out, ResultSetMetaData metaData) throws Exception { + if (printHeader) { int numColumns = metaData.getColumnCount(); - if( debug ) { - for (int i = 1; i <= numColumns; i++) { - out.print( formatLabel( metaData.getColumnTypeName(i), - metaData.getColumnDisplaySize(i))); + if (debug) { + for (int i = 1; i <= numColumns; i++) { + out.print(formatLabel(metaData.getColumnTypeName(i), + metaData.getColumnDisplaySize(i))); out.print(delimiter); - } + } } // // output the column names // for (int i = 1; i <= numColumns; i++) { - out.print( formatLabel( metaData.getColumnName(i), - metaData.getColumnDisplaySize(i))); + out.print(formatLabel(metaData.getColumnName(i), + metaData.getColumnDisplaySize(i))); out.print(delimiter); } @@ -167,187 +163,188 @@ public class DefaultFormatter implements JisqlFormatter { // output pretty dividers // for (int i = 1; i <= numColumns; i++) { - out.print( formatSeparator( metaData.getColumnName(i), - metaData.getColumnDisplaySize(i))); + out.print(formatSeparator(metaData.getColumnName(i), + metaData.getColumnDisplaySize(i))); - if (i == numColumns) + if (i == numColumns) { out.print("-|"); - else + } else { out.print("-+-"); + } } out.println(); } } - /** * Called to output the data. * * @param out the PrintStream to output data to. * @param resultSet the ResultSet for the row. * @param metaData the ResultSetMetaData for the row. - * - * */ - public void formatData( PrintStream out, ResultSet resultSet, ResultSetMetaData metaData ) throws Exception { - - while( resultSet.next() ) { + public void formatData(PrintStream out, ResultSet resultSet, ResultSetMetaData metaData) throws Exception { + while (resultSet.next()) { int numColumns = metaData.getColumnCount(); for (int i = 1; i <= numColumns; i++) { - out.print( formatValue( metaData.getColumnName(i), - resultSet.getString(i), - metaData.getColumnDisplaySize(i))); - out.print( delimiter ); + out.print(formatValue(metaData.getColumnName(i), + resultSet.getString(i), + metaData.getColumnDisplaySize(i))); + out.print(delimiter); } out.println(); } } - /** * Outputs a footer for a query. This is called after all data has been * exhausted. This method isn't used in the DefaultFormatter. * * @param out the PrintStream to output data to. * @param metaData the ResultSetMetaData for the output. - * */ - public void formatFooter( PrintStream out, ResultSetMetaData metaData ) throws Exception { - } - - + public void formatFooter(PrintStream out, ResultSetMetaData metaData) throws Exception {} /** * Formats a label for output. * * @param s - the label to format * @param width - the width of the field - * * @return the formated label + */ + private String formatLabel(String s, int width) { + if (s == null) { + s = "NULL"; + } + + if (columnWidth != 0) { + if (width > columnWidth) { + width = columnWidth; + } + } + + if (width < s.length()) { + width = s.length(); + } + + int len = s.length(); + + if (len >= width) { + return s.substring(0, width); + } + + int fillWidth = width - len; + StringBuilder fill = new StringBuilder(fillWidth); + for (int i = 0; i < fillWidth; ++i) { + fill.append(spacer); + } + if (leftJustify) { + return s + fill; + } else if (s.startsWith("-")) { + return "-" + fill + s.substring(1); + } else { + return fill + s; + } + } + + /** + * Formats a separator for display. * + * @param s - the field for which the separator is being generated + * @param width - the width of the field + * @return the formated separator */ - private String formatLabel(String s, int width) { - if (s == null) - s = "NULL"; - - if (columnWidth != 0) { - if (width > columnWidth) - width = columnWidth; - } - - if (width < s.length()) - width = s.length(); - - int len = s.length(); - - if (len >= width) - return s.substring(0, width); - - int fillWidth = width - len; - StringBuilder fill = new StringBuilder(fillWidth); - for (int i = 0; i < fillWidth; ++i) - fill.append(spacer); - if (leftJustify) - return s + fill; - else if (s.startsWith("-")) - return "-" + fill + s.substring(1); - else - return fill + s; - } - - /** - * Formats a separator for display. - * - * @param s - the field for which the separator is being generated - * @param width - the width of the field - * - * @return the formated separator - * - */ - private String formatSeparator(String s, int width) { - s = "NULL"; - - if (columnWidth != 0) { - if (width > columnWidth) - width = columnWidth; - } - - if (width < s.length()) - width = s.length(); - - int len = s.length(); - - if (len >= width) - width = len; - - StringBuilder fill = new StringBuilder(width); - for (int i = 0; i < width; ++i) - fill.append('-'); - - if( trimColumns ) - return fill.toString().trim(); - else - return fill.toString(); - } - - /** - * Formats a value for display. - * - * @param label the label associated with the value (for width purposes) - * @param s - the value to format - * @param width - the width of the field from the db. - * - * @return the formatted field. - * - */ - private String formatValue(String label, String s, int width) { - if (s == null) { - if( printNull ) - s = "NULL"; - else + private String formatSeparator(String s, int width) { + s = "NULL"; + + if (columnWidth != 0) { + if (width > columnWidth) { + width = columnWidth; + } + } + + if (width < s.length()) { + width = s.length(); + } + + int len = s.length(); + + if (len >= width) { + width = len; + } + + StringBuilder fill = new StringBuilder(width); + for (int i = 0; i < width; ++i) { + fill.append('-'); + } + + if (trimColumns) { + return fill.toString().trim(); + } else { + return fill.toString(); + } + } + + /** + * Formats a value for display. + * + * @param label the label associated with the value (for width purposes) + * @param s - the value to format + * @param width - the width of the field from the db. + * @return the formatted field. + */ + private String formatValue(String label, String s, int width) { + if (s == null) { + if (printNull) { + s = "NULL"; + } else { s = ""; + } } - if (columnWidth != 0) { - if (width > columnWidth) - width = columnWidth; - } + if (columnWidth != 0) { + if (width > columnWidth) { + width = columnWidth; + } + } - if (width < label.length()) - width = label.length(); + if (width < label.length()) { + width = label.length(); + } - int len = s.length(); + int len = s.length(); - if (len >= width) { - if( trimColumns ) - return s.substring(0, width).trim(); - else - return s.substring(0, width); + if (len >= width) { + if (trimColumns) { + return s.substring(0, width).trim(); + } else { + return s.substring(0, width); + } } - int fillWidth = width - len; - StringBuilder fill = new StringBuilder(fillWidth); - for (int i = 0; i < fillWidth; ++i) - fill.append(spacer); + int fillWidth = width - len; + StringBuilder fill = new StringBuilder(fillWidth); + for (int i = 0; i < fillWidth; ++i) { + fill.append(spacer); + } StringBuilder returnValue = new StringBuilder(); - if (leftJustify) - returnValue.append( s + fill ); - else if (s.startsWith("-")) - returnValue.append( "-" + fill + s.substring(1) ); - else { - returnValue.append( fill + s ); + if (leftJustify) { + returnValue.append(s + fill); + } else if (s.startsWith("-")) { + returnValue.append("-" + fill + s.substring(1)); + } else { + returnValue.append(fill + s); } - if( trimColumns ) { + if (trimColumns) { return returnValue.toString().trim(); - } - else { + } else { return returnValue.toString(); } - } + } } diff --git a/jisql/src/main/java/org/apache/util/outputformatter/JisqlFormatter.java b/jisql/src/main/java/org/apache/util/outputformatter/JisqlFormatter.java index ec6d1f0a2..467b50976 100644 --- a/jisql/src/main/java/org/apache/util/outputformatter/JisqlFormatter.java +++ b/jisql/src/main/java/org/apache/util/outputformatter/JisqlFormatter.java @@ -18,51 +18,44 @@ */ package org.apache.util.outputformatter; -import java.io.PrintStream; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; - import joptsimple.OptionParser; import joptsimple.OptionSet; +import java.io.PrintStream; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; /** * This is the definition of what a JisqlFormatter does. - * */ public interface JisqlFormatter { - - /** + /** * Sets a the option list for this formatter. * * @param parser - the OptionParser to use. */ - void setSupportedOptions( OptionParser parser ); + void setSupportedOptions(OptionParser parser); /** * Consumes any options that were specified on the command line. * * @param options the OptionSet that the main driver is using. Implementing - * classes should add their supported parameters to the list. - * + * classes should add their supported parameters to the list. * @throws Exception if there is a problem parsing the command line arguments. - * Note that Jisql includes jopt-simple so you can use that - * to parse your command line. See - * <a href="http://jopt-simple.sourceforge.net/">http://jopt-simple.sourceforge.net/</a> - * for more information. - * + * Note that Jisql includes jopt-simple so you can use that + * to parse your command line. See + * <a href="http://jopt-simple.sourceforge.net/">http://jopt-simple.sourceforge.net/</a> + * for more information. */ - void consumeOptions( OptionSet options ) throws Exception; + void consumeOptions(OptionSet options) throws Exception; /** * Called to output a usage message to the command line window. This * message should contain information on how to call the formatter. * * @param out where to put the usage message. - * */ - void usage( PrintStream out ); - + void usage(PrintStream out); /** * Outputs a header for a query. This is called before any data is @@ -70,9 +63,8 @@ public interface JisqlFormatter { * * @param out where to put header output. * @param metaData the ResultSetMetaData for the output. - * */ - void formatHeader( PrintStream out, ResultSetMetaData metaData ) throws Exception; + void formatHeader(PrintStream out, ResultSetMetaData metaData) throws Exception; /** * Called to output the data. @@ -80,9 +72,8 @@ public interface JisqlFormatter { * @param out where to put output data. * @param resultSet the ResultSet for the row. * @param metaData the ResultSetMetaData for the row. - * */ - void formatData( PrintStream out, ResultSet resultSet, ResultSetMetaData metaData ) throws Exception; + void formatData(PrintStream out, ResultSet resultSet, ResultSetMetaData metaData) throws Exception; /** * Outputs a footer for a query. This is called after all data has been @@ -90,7 +81,6 @@ public interface JisqlFormatter { * * @param out where to put footer output. * @param metaData the ResultSetMetaData for the output. - * */ - void formatFooter( PrintStream out, ResultSetMetaData metaData ) throws Exception; + void formatFooter(PrintStream out, ResultSetMetaData metaData) throws Exception; } diff --git a/jisql/src/main/java/org/apache/util/outputformatter/XMLFormatter.java b/jisql/src/main/java/org/apache/util/outputformatter/XMLFormatter.java index 93aa26dda..fe565c2ae 100644 --- a/jisql/src/main/java/org/apache/util/outputformatter/XMLFormatter.java +++ b/jisql/src/main/java/org/apache/util/outputformatter/XMLFormatter.java @@ -18,31 +18,27 @@ */ package org.apache.util.outputformatter; +import joptsimple.OptionParser; +import joptsimple.OptionSet; + import java.io.PrintStream; import java.nio.charset.Charset; import java.sql.ResultSet; import java.sql.ResultSetMetaData; -import joptsimple.OptionParser; -import joptsimple.OptionSet; - - /** * This is the default XML formatter for Jisql. It outputs data in an * XML format. - * */ public class XMLFormatter implements JisqlFormatter { - /** * Sets a the option list for this formatter. This is a no-op in the * XMLFormatter. * * @param parser the OptionParser to use. - * */ - public void setSupportedOptions( OptionParser parser ) { - /* no options for the XMLFormatter */ + public void setSupportedOptions(OptionParser parser) { + /* no options for the XMLFormatter */ } /** @@ -50,26 +46,22 @@ public class XMLFormatter implements JisqlFormatter { * no options to set for the XMLFormatter so this method is a no-op. * * @param options the OptionSet that the main driver is using. - * * @throws Exception if there is a problem parsing the command line arguments. - * */ - public void consumeOptions( OptionSet options ) throws Exception { - /* no options for the XMLFormatter */ + public void consumeOptions(OptionSet options) throws Exception { + /* no options for the XMLFormatter */ } /** * Called to output a usage message to the command line window. This * message should contain information on how to call the formatter. * There are no options to set for the XMLFormatter so this method is - * a no-op. - * + * a no-op. */ - public void usage( PrintStream out ) { - /* no options for the XMLFormatter */ + public void usage(PrintStream out) { + /* no options for the XMLFormatter */ } - /** * Outputs a header for a query. For the XMLFormater this outputs the XML * pre-amble. The character encoding defaults to the current character @@ -77,15 +69,13 @@ public class XMLFormatter implements JisqlFormatter { * * @param out a PrintStream to send any output to. * @param metaData the ResultSetMetaData for the output. - * */ - public void formatHeader( PrintStream out, ResultSetMetaData metaData ) throws Exception { - out.print( "<?xml version=\"1.0\" encoding=\"" ); - out.print( Charset.defaultCharset().displayName().toLowerCase() ); - out.println( "\" ?>" ); + public void formatHeader(PrintStream out, ResultSetMetaData metaData) throws Exception { + out.print("<?xml version=\"1.0\" encoding=\""); + out.print(Charset.defaultCharset().displayName().toLowerCase()); + out.println("\" ?>"); } - /** * Called to output the data. Note that for the XMLFormatter null fields are * just output as an empty field. @@ -93,37 +83,34 @@ public class XMLFormatter implements JisqlFormatter { * @param out the PrintStream to output data to. * @param resultSet the ResultSet for the row. * @param metaData the ResultSetMetaData for the row. - * */ - public void formatData( PrintStream out, ResultSet resultSet, ResultSetMetaData metaData ) throws Exception { - - while( resultSet.next() ) { + public void formatData(PrintStream out, ResultSet resultSet, ResultSetMetaData metaData) throws Exception { + while (resultSet.next()) { int numColumns = metaData.getColumnCount(); for (int i = 1; i <= numColumns; i++) { - out.print( "<" ); - out.print( metaData.getColumnName( i ).trim() ); - out.print( ">" ); - String result = resultSet.getString(i); - if( !resultSet.wasNull() ) - out.print( result.trim() ); - out.print( "</" ); - out.print( metaData.getColumnName( i ).trim() ); - out.print( ">" ); + out.print("<"); + out.print(metaData.getColumnName(i).trim()); + out.print(">"); + String result = resultSet.getString(i); + if (!resultSet.wasNull()) { + out.print(result.trim()); + } + out.print("</"); + out.print(metaData.getColumnName(i).trim()); + out.print(">"); } out.println(); } } - /** * Outputs a footer for a query. This method isn't used in the XMLFormatter. * * @param out the PrintStream to output data to. * @param metaData the ResultSetMetaData for the output. - * */ - public void formatFooter( PrintStream out, ResultSetMetaData metaData ) throws Exception { + public void formatFooter(PrintStream out, ResultSetMetaData metaData) throws Exception { } } diff --git a/jisql/src/main/java/org/apache/util/sql/Jisql.java b/jisql/src/main/java/org/apache/util/sql/Jisql.java index b3e272550..f425df347 100644 --- a/jisql/src/main/java/org/apache/util/sql/Jisql.java +++ b/jisql/src/main/java/org/apache/util/sql/Jisql.java @@ -1,19 +1,27 @@ - /* Copyright (C) 2004-2011 Scott Dunbar (sc...@xigole.com) - * - * Licensed 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 +/* + * 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. + * 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.util.sql; +import joptsimple.OptionParser; +import joptsimple.OptionSet; +import org.apache.util.outputformatter.JisqlFormatter; + import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; @@ -31,11 +39,6 @@ import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; -import joptsimple.OptionParser; -import joptsimple.OptionSet; - -import org.apache.util.outputformatter.JisqlFormatter; - /** * A simple utility to provide an interactive session with a SQL server. This * application is conceptually modeled on the Sybase 'isql' program with, @@ -211,55 +214,50 @@ import org.apache.util.outputformatter.JisqlFormatter; * </p> */ public class Jisql { - //Sybase SQL Anywhere JDBC4-Type2 (Native) Driver - private static final String sapJDBC4SqlAnywhereDriverName= "sap.jdbc4.sqlanywhere.IDriver"; - private static final String sybaseJDBC4SqlAnywhereDriverName= "sybase.jdbc4.sqlanywhere.IDriver"; - private static final String sybaseJConnect6DriverName = "com.sybase.jdbc3.jdbc.SybDriver"; - private static final String sybaseJConnect5DriverName = "com.sybase.jdbc2.jdbc.SybDriver"; - private static final String sybaseJConnect4DriverName = "com.sybase.jdbc.SybDriver"; - private static final String oracleThinDriverName = "oracle.jdbc.driver.OracleDriver"; - private static final String db2AppDriverName = "COM.ibm.db2.jdbc.app.DB2Driver"; - private static final String db2NetDriverName = "COM.ibm.db2.jdbc.net.DB2Driver"; - private static final String cloudscapeDriverName = "COM.cloudscape.core.JDBCDriver"; - private static final String msqlDriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; - private static final String pointbaseDriverName = "com.pointbase.jdbc.jdbcUniversalDriver"; - private static final String postgresqlDriverName = "org.postgresql.Driver"; - private static final String mySQLConnectJDriverName = "com.mysql.jdbc.Driver"; - private static final String mySQLCauchoDriverName = "com.caucho.jdbc.mysql.Driver"; - + //Sybase SQL Anywhere JDBC4-Type2 (Native) Driver + private static final String sapJDBC4SqlAnywhereDriverName = "sap.jdbc4.sqlanywhere.IDriver"; + private static final String sybaseJDBC4SqlAnywhereDriverName = "sybase.jdbc4.sqlanywhere.IDriver"; + private static final String sybaseJConnect6DriverName = "com.sybase.jdbc3.jdbc.SybDriver"; + private static final String sybaseJConnect5DriverName = "com.sybase.jdbc2.jdbc.SybDriver"; + private static final String sybaseJConnect4DriverName = "com.sybase.jdbc.SybDriver"; + private static final String oracleThinDriverName = "oracle.jdbc.driver.OracleDriver"; + private static final String db2AppDriverName = "COM.ibm.db2.jdbc.app.DB2Driver"; + private static final String db2NetDriverName = "COM.ibm.db2.jdbc.net.DB2Driver"; + private static final String cloudscapeDriverName = "COM.cloudscape.core.JDBCDriver"; + private static final String msqlDriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; + private static final String pointbaseDriverName = "com.pointbase.jdbc.jdbcUniversalDriver"; + private static final String postgresqlDriverName = "org.postgresql.Driver"; + private static final String mySQLConnectJDriverName = "com.mysql.jdbc.Driver"; + private static final String mySQLCauchoDriverName = "com.caucho.jdbc.mysql.Driver"; private static final String defaultFormatterClassName = "org.apache.util.outputformatter.DefaultFormatter"; - private static final String csvFormatterClassName = "org.apache.util.outputformatter.CSVFormatter"; - private static final String xmlFormatterClassName = "org.apache.util.outputformatter.XMLFormatter"; - - private String driverName = null; - private String connectString = null; - private String userName = null; - private String password = null; - private String passwordFileName = null; + private static final String csvFormatterClassName = "org.apache.util.outputformatter.CSVFormatter"; + private static final String xmlFormatterClassName = "org.apache.util.outputformatter.XMLFormatter"; + + private String driverName; + private String connectString; + private String userName; + private String password; + private String passwordFileName; + private String inputFileName; + private String inputQuery; + private String commandTerminator = "go"; private String formatterClassName = defaultFormatterClassName; - - private JisqlFormatter formatter = null; - - private Connection connection = null; - private boolean printDebug = false; - private boolean printDriverDetails = false; - private Driver driver = null; - private Properties props = null; - private String inputFileName = null; - private String commandTerminator = "go"; - private String inputQuery = null; + private JisqlFormatter formatter; + private Connection connection; + private Driver driver; + private Properties props; + private boolean printDebug; + private boolean printDriverDetails; /** * Runs Jisql with the command line arguments provided. - * */ - public static void main(String argv[]) { + public static void main(String[] argv) { Jisql jisql = new Jisql(); try { jisql.parseArgs(argv); - } - catch (Throwable t) { + } catch (Throwable t) { t.printStackTrace(); jisql.usage(); System.exit(1); @@ -267,8 +265,7 @@ public class Jisql { try { jisql.run(); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); System.exit(1); } @@ -277,72 +274,64 @@ public class Jisql { } public void run() throws Exception { - boolean isExit=false; + boolean isExit = false; try { driver = (Driver) Class.forName(driverName).newInstance(); - props = new Properties(); + props = new Properties(); props.put("user", userName); - if (password != null) + if (password != null) { props.put("password", password); + } connection = DriverManager.getConnection(connectString, props); if (printDriverDetails) { printDriverInfo(); + } else { + if (connectString.toLowerCase().startsWith("jdbc:mysql") && inputFileName != null) { + MySQLPLRunner scriptRunner = new MySQLPLRunner(connection, false, true, printDebug); + scriptRunner.setDelimiter(commandTerminator, false); + FileReader reader = new FileReader(inputFileName); + try { + scriptRunner.runScript(reader); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ioe) { + // Ignore error during closing of the reader stream + } + } + } + } else { + doIsql(); + } } - else { - if(connectString.toLowerCase().startsWith("jdbc:mysql") && inputFileName!=null){ - MySQLPLRunner scriptRunner = new MySQLPLRunner(connection, false, true,printDebug); - scriptRunner.setDelimiter(commandTerminator,false); - FileReader reader = new FileReader(inputFileName); - try { - scriptRunner.runScript(reader); - } - finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException ioe) { - // Ignore error during closing of the reader stream - } - } - } - }else{ - doIsql(); - } - } - } - catch (SQLException sqle) { - printAllExceptions(sqle); - isExit=true; - } - catch (IOException ie) { - isExit=true; - } - catch (ClassNotFoundException cnfe) { - isExit=true; + } catch (SQLException sqle) { + printAllExceptions(sqle); + isExit = true; + } catch (IOException ie) { + isExit = true; + } catch (ClassNotFoundException cnfe) { + isExit = true; System.err.println("Cannot find the driver class \"" + driverName + "\" in the current classpath."); - } - catch (InstantiationException ie) { - isExit=true; + } catch (InstantiationException ie) { + isExit = true; System.err.println("Cannot instantiate the driver class \"" + driverName + "\""); ie.printStackTrace(System.err); - } - catch (IllegalAccessException iae) { - isExit=true; + } catch (IllegalAccessException iae) { + isExit = true; System.err.println("Cannot instantiate the driver class \"" + driverName + "\" because of an IllegalAccessException"); iae.printStackTrace(System.err); - } - finally { + } finally { if (connection != null) { try { connection.close(); - } - catch (SQLException ignore) { + } catch (SQLException ignore) { /* ignored */ } - if(isExit){ - System.exit(1); + if (isExit) { + System.exit(1); } } } @@ -353,189 +342,187 @@ public class Jisql { * either a command line or from a file. Output is handled through the * Formatter. * - * @throws SQLException - * if an exception occurs. - * + * @throws SQLException if an exception occurs. */ public void doIsql() throws IOException, SQLException { - BufferedReader reader = null; - Statement statement = null; - ResultSet resultSet = null; + BufferedReader reader = null; + Statement statement = null; + ResultSet resultSet = null; ResultSetMetaData resultSetMetaData = null; - StringBuilder query = null; + StringBuilder query = null; if (inputFileName != null) { try { reader = new BufferedReader(new FileReader(inputFileName)); - } - catch (FileNotFoundException fnfe) { - System.err.println("Unable to open file \"" + inputFileName + "\""); + } catch (FileNotFoundException fnfe) { + System.err.println("Unable to open file \"" + inputFileName + "\""); fnfe.printStackTrace(System.err); throw fnfe; } - } - else { + } else { reader = new BufferedReader(new InputStreamReader(System.in)); } - if(printDebug) - printAllExceptions(connection.getWarnings()); + if (printDebug) { + printAllExceptions(connection.getWarnings()); + } statement = connection.createStatement(); connection.clearWarnings(); - String trimmedLine=null; + String trimmedLine = null; try { + while (true) { + int linecount = 1; + query = new StringBuilder(); - while (true) { - int linecount = 1; - query = new StringBuilder(); - - try { - if ((inputFileName == null) && (inputQuery == null)) - System.out.print("\nEnter a query:\n"); - - while (true) { + try { if ((inputFileName == null) && (inputQuery == null)) { - System.out.print(linecount++ + " > "); - System.out.flush(); - } - - String line = null; - if (inputQuery == null) - line = reader.readLine(); - else - line = inputQuery.toString(); - - if (line == null || line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")){ - if ((inputFileName != null) && (inputQuery != null)) { - break; - }else{ - return; - } + System.out.print("\nEnter a query:\n"); } - if (line.equals("reset")) { - query = new StringBuilder(); - break; - } - trimmedLine=line.trim(); - if (trimmedLine.startsWith("--") ||trimmedLine.length()<1) { - continue; - } - if(connectString.toLowerCase().startsWith("jdbc:oracle") && inputFileName!=null){ - if (trimmedLine.startsWith("/") ||trimmedLine.length()<2) { - commandTerminator=";"; - continue; - } - if (trimmedLine.toUpperCase().startsWith("DECLARE")) { - commandTerminator="/"; - } - if ((trimmedLine.toUpperCase().startsWith("CREATE OR REPLACE PROCEDURE")) || (trimmedLine.toUpperCase().startsWith("CREATE OR REPLACE FUNCTION"))) { - commandTerminator="/"; - } - } - if(connectString.toLowerCase().startsWith("jdbc:postgresql") && inputFileName!=null){ - if (trimmedLine.toLowerCase().startsWith("select 'delimiter start';")) { - commandTerminator="select 'delimiter end';"; - continue; - } - } + while (true) { + if ((inputFileName == null) && (inputQuery == null)) { + System.out.print(linecount++ + " > "); + System.out.flush(); + } - if (line.trim().equalsIgnoreCase(commandTerminator) || line.trim().endsWith(commandTerminator)) { - if (line.trim().endsWith(commandTerminator)) { - line = line.substring(0, line.length() - commandTerminator.length()); - query.append("\n"); - query.append(line); + String line = null; + if (inputQuery == null) { + line = reader.readLine(); + } else { + line = inputQuery.toString(); } - break; - } - query.append("\n"); - query.append(line); - } + if (line == null || line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) { + if ((inputFileName != null) && (inputQuery != null)) { + break; + } else { + return; + } + } - if (query.toString().length() == 0) - continue; + if (line.equals("reset")) { + query = new StringBuilder(); + break; + } + trimmedLine = line.trim(); + if (trimmedLine.startsWith("--") || trimmedLine.length() < 1) { + continue; + } + if (connectString.toLowerCase().startsWith("jdbc:oracle") && inputFileName != null) { + if (trimmedLine.startsWith("/") || trimmedLine.length() < 2) { + commandTerminator = ";"; + continue; + } + if (trimmedLine.toUpperCase().startsWith("DECLARE")) { + commandTerminator = "/"; + } + if ((trimmedLine.toUpperCase().startsWith("CREATE OR REPLACE PROCEDURE")) || (trimmedLine.toUpperCase().startsWith("CREATE OR REPLACE FUNCTION"))) { + commandTerminator = "/"; + } + } + if (connectString.toLowerCase().startsWith("jdbc:postgresql") && inputFileName != null) { + if (trimmedLine.toLowerCase().startsWith("select 'delimiter start';")) { + commandTerminator = "select 'delimiter end';"; + continue; + } + } - if (printDebug) - System.out.println("executing: " + query.toString()); + if (line.trim().equalsIgnoreCase(commandTerminator) || line.trim().endsWith(commandTerminator)) { + if (line.trim().endsWith(commandTerminator)) { + line = line.substring(0, line.length() - commandTerminator.length()); + query.append("\n"); + query.append(line); + } + break; + } - boolean moreResults = statement.execute(query.toString()); - int rowsAffected = 0; - do { - if(printDebug) - printAllExceptions(statement.getWarnings()); - statement.clearWarnings(); - if (moreResults) { - resultSet = statement.getResultSet(); - if(printDebug) - printAllExceptions(resultSet.getWarnings()); - resultSet.clearWarnings(); - resultSetMetaData = resultSet.getMetaData(); + query.append("\n"); + query.append(line); + } - formatter.formatHeader(System.out, resultSetMetaData); - formatter.formatData(System.out, resultSet, resultSetMetaData); - formatter.formatFooter(System.out, resultSetMetaData); + if (query.toString().length() == 0) { + continue; + } - int rowsSelected = statement.getUpdateCount(); + if (printDebug) { + System.out.println("executing: " + query.toString()); + } - if (rowsSelected >= 0 && printDebug) { - System.out.println(rowsSelected + " rows affected."); + boolean moreResults = statement.execute(query.toString()); + int rowsAffected = 0; + do { + if (printDebug) { + printAllExceptions(statement.getWarnings()); } - } - else { - rowsAffected = statement.getUpdateCount(); - if (printDebug) - printAllExceptions(statement.getWarnings()); statement.clearWarnings(); - if (rowsAffected >= 0 && printDebug) { - System.out.println(rowsAffected + " rows affected."); + if (moreResults) { + resultSet = statement.getResultSet(); + if (printDebug) { + printAllExceptions(resultSet.getWarnings()); + } + resultSet.clearWarnings(); + resultSetMetaData = resultSet.getMetaData(); + + formatter.formatHeader(System.out, resultSetMetaData); + formatter.formatData(System.out, resultSet, resultSetMetaData); + formatter.formatFooter(System.out, resultSetMetaData); + + int rowsSelected = statement.getUpdateCount(); + + if (rowsSelected >= 0 && printDebug) { + System.out.println(rowsSelected + " rows affected."); + } + } else { + rowsAffected = statement.getUpdateCount(); + if (printDebug) { + printAllExceptions(statement.getWarnings()); + } + statement.clearWarnings(); + if (rowsAffected >= 0 && printDebug) { + System.out.println(rowsAffected + " rows affected."); + } } - } - // - // I was having problems with the PostgreSQL driver throwing - // a NullPointerException here so I just catch it and tell - // the loop that it is done if it happens. - // - try { - moreResults = statement.getMoreResults(); - } - catch (NullPointerException npe) { - moreResults = false; + // + // I was having problems with the PostgreSQL driver throwing + // a NullPointerException here so I just catch it and tell + // the loop that it is done if it happens. + // + try { + moreResults = statement.getMoreResults(); + } catch (NullPointerException npe) { + moreResults = false; + } } + + while (moreResults || rowsAffected != -1); + } catch (SQLException sqle) { + printAllExceptions(sqle); + statement.cancel(); + statement.clearWarnings(); + throw sqle; + } catch (Exception e) { + e.printStackTrace(System.err); } - while (moreResults || rowsAffected != -1); + if (inputQuery != null) { + return; + } } - catch (SQLException sqle) { - printAllExceptions(sqle); - statement.cancel(); - statement.clearWarnings(); - throw sqle; + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ioe) { + // Ignore IOE when closing streams + } } - catch (Exception e) { - e.printStackTrace(System.err); + if (resultSet != null) { + try { + resultSet.close(); + } catch (SQLException sqle) { + } } - - if (inputQuery != null) - return; - } - } - finally { - if (reader != null) { - try { - reader.close(); - } - catch(IOException ioe) { - // Ignore IOE when closing streams - } - } - if (resultSet != null) { - try { - resultSet.close(); - } catch (SQLException sqle) { - } - } if (statement != null) { try { statement.close(); @@ -549,9 +536,7 @@ public class Jisql { /** * Prints some information about the JDBC driver in use. * - * @throws SQLException - * if one of the methods called does. - * + * @throws SQLException if one of the methods called does. */ private void printDriverInfo() throws SQLException { System.out.println("driver.getMajorVersion() is " + driver.getMajorVersion()); @@ -564,8 +549,9 @@ public class Jisql { System.out.println("driver property named \"" + info.name + "\""); if (info.choices != null) { System.out.println("choices:"); - for (int j = 0; j < info.choices.length; j++) + for (int j = 0; j < info.choices.length; j++) { System.out.println("\tchoice " + j + ": \"" + info.choices[j] + "\""); + } } System.out.println("description: \"" + info.description + "\""); System.out.println("required parameter?: \"" + info.required + "\""); @@ -585,28 +571,26 @@ public class Jisql { * Parse the command line arguments. This method parses what is needed for * the Jisql driver program and lets the configured formatter do the same. * - * @param argv the command line arguments. - * + * @param argv the command line arguments. * @throws Exception if there are any errors parsing the command line arguments. - * */ - public void parseArgs(String argv[]) throws Throwable { + public void parseArgs(String[] argv) throws Throwable { // // I'm sure that there has to be a better way but I couldn't find a // command lineparser that would let me ignore unknown arguments. so // walk through the list once to find the formatter. then, use the // command line parser to do it "for real" // - String passwordValue=null; - for (int argumentIndex = 0; argumentIndex < argv.length; argumentIndex++) { - if ("-p".equalsIgnoreCase(argv[argumentIndex]) || "-password".equalsIgnoreCase(argv[argumentIndex]) ) { - if(argv.length>argumentIndex + 1){ - passwordValue=argv[argumentIndex + 1]; - argv[argumentIndex + 1]=""; - break; - } - } - } + String passwordValue = null; + for (int argumentIndex = 0; argumentIndex < argv.length; argumentIndex++) { + if ("-p".equalsIgnoreCase(argv[argumentIndex]) || "-password".equalsIgnoreCase(argv[argumentIndex])) { + if (argv.length > argumentIndex + 1) { + passwordValue = argv[argumentIndex + 1]; + argv[argumentIndex + 1] = ""; + break; + } + } + } for (int argumentIndex = 0; argumentIndex < argv.length; argumentIndex++) { if (argv[argumentIndex].equals("-formatter")) { formatterClassName = argv[argumentIndex + 1]; @@ -614,12 +598,13 @@ public class Jisql { } } - if (formatterClassName.compareToIgnoreCase("csv") == 0) + if (formatterClassName.compareToIgnoreCase("csv") == 0) { formatterClassName = csvFormatterClassName; - else if (formatterClassName.compareToIgnoreCase("xml") == 0) + } else if (formatterClassName.compareToIgnoreCase("xml") == 0) { formatterClassName = xmlFormatterClassName; - else if (formatterClassName.compareToIgnoreCase("default") == 0) + } else if (formatterClassName.compareToIgnoreCase("default") == 0) { formatterClassName = defaultFormatterClassName; + } formatter = (JisqlFormatter) Class.forName(formatterClassName).newInstance(); @@ -653,102 +638,112 @@ public class Jisql { if (options.has("driver")) { driverName = (String) options.valueOf("driver"); - if (driverName.compareToIgnoreCase("jconnect4") == 0) + if (driverName.compareToIgnoreCase("jconnect4") == 0) { driverName = sybaseJConnect4DriverName; - else if (driverName.compareToIgnoreCase("jconnect5") == 0) + } else if (driverName.compareToIgnoreCase("jconnect5") == 0) { driverName = sybaseJConnect5DriverName; - else if (driverName.compareToIgnoreCase("jconnect6") == 0) + } else if (driverName.compareToIgnoreCase("jconnect6") == 0) { driverName = sybaseJConnect6DriverName; - else if (driverName.compareToIgnoreCase("oraclethin") == 0) + } else if (driverName.compareToIgnoreCase("oraclethin") == 0) { driverName = oracleThinDriverName; - else if (driverName.compareToIgnoreCase("db2app") == 0) + } else if (driverName.compareToIgnoreCase("db2app") == 0) { driverName = db2AppDriverName; - else if (driverName.compareToIgnoreCase("db2net") == 0) + } else if (driverName.compareToIgnoreCase("db2net") == 0) { driverName = db2NetDriverName; - else if (driverName.compareToIgnoreCase("cloudscape") == 0) + } else if (driverName.compareToIgnoreCase("cloudscape") == 0) { driverName = cloudscapeDriverName; - else if (driverName.compareToIgnoreCase("mssql") == 0) + } else if (driverName.compareToIgnoreCase("mssql") == 0) { driverName = msqlDriverName; - else if (driverName.compareToIgnoreCase("pointbase") == 0) + } else if (driverName.compareToIgnoreCase("pointbase") == 0) { driverName = pointbaseDriverName; - else if (driverName.compareToIgnoreCase("postgresql") == 0) + } else if (driverName.compareToIgnoreCase("postgresql") == 0) { driverName = postgresqlDriverName; - else if (driverName.compareToIgnoreCase("mysqlconj") == 0) + } else if (driverName.compareToIgnoreCase("mysqlconj") == 0) { driverName = mySQLConnectJDriverName; - else if (driverName.compareToIgnoreCase("mysqlcaucho") == 0) + } else if (driverName.compareToIgnoreCase("mysqlcaucho") == 0) { driverName = mySQLCauchoDriverName; - else if (driverName.compareToIgnoreCase("sapsajdbc4") == 0) + } else if (driverName.compareToIgnoreCase("sapsajdbc4") == 0) { driverName = sapJDBC4SqlAnywhereDriverName; - else if (driverName.compareToIgnoreCase("sybasesajdbc4") == 0) + } else if (driverName.compareToIgnoreCase("sybasesajdbc4") == 0) { driverName = sybaseJDBC4SqlAnywhereDriverName; + } } connectString = (String) options.valueOf("cstring"); - if (options.has("c")) + if (options.has("c")) { commandTerminator = (String) options.valueOf("c"); + } - if (options.has("debug")) + if (options.has("debug")) { printDebug = true; + } - if (options.has("user")) + if (options.has("user")) { userName = (String) options.valueOf("user"); - else if (options.has("u")) + } else if (options.has("u")) { userName = (String) options.valueOf("u"); + } - password=passwordValue; + password = passwordValue; - if (options.has("driverinfo")) + if (options.has("driverinfo")) { printDriverDetails = true; + } - if (options.has("input")) + if (options.has("input")) { inputFileName = (String) options.valueOf("input"); + } - if (options.has("pf")) + if (options.has("pf")) { passwordFileName = (String) options.valueOf("pf"); + } - if (options.has("query")) + if (options.has("query")) { inputQuery = (String) options.valueOf("query"); + } - if (driverName == null) + if (driverName == null) { throw new Exception("driver name must exist"); + } - if (connectString == null) + if (connectString == null) { throw new Exception("connect string must exist"); + } - if (userName == null) + if (userName == null) { throw new Exception("user name must exist"); + } if ((password == null) && (passwordFileName == null)) { - password=""; - } - else if (password == null) { - File passwordFile = null; - BufferedReader reader = null; + password = ""; + } else if (password == null) { + File passwordFile = null; + BufferedReader reader = null; passwordFile = new File(passwordFileName); - if (!passwordFile.exists()) + if (!passwordFile.exists()) { throw new Exception("the password file \"" + passwordFileName + "\" does not exist"); + } - if (!passwordFile.isFile()) + if (!passwordFile.isFile()) { throw new Exception("the password file \"" + passwordFileName + "\" is not a normal file"); + } - if (!passwordFile.canRead()) + if (!passwordFile.canRead()) { throw new Exception("the password file \"" + passwordFileName + "\" is not readable"); + } try { - reader = new BufferedReader(new FileReader(passwordFile)); + reader = new BufferedReader(new FileReader(passwordFile)); password = reader.readLine().trim(); - } - catch (Exception e) { + } catch (Exception e) { throw new Exception("An error occured reading the password file", e); - } - finally { + } finally { if (reader != null) { try { reader.close(); - } - catch (Exception ignore) { /* ignored */ + } catch (Exception ignore) { /* ignored */ } } } @@ -761,12 +756,10 @@ public class Jisql { * Walks through a SQLException and prints out every exception. * * @param sqle the Exception to print - * */ private void printAllExceptions(SQLException sqle) { while (sqle != null) { - System.err.println("SQLException : " + "SQL state: " + sqle.getSQLState() + " " + sqle.toString() + " ErrorCode: " - + sqle.getErrorCode()); + System.err.println("SQLException : " + "SQL state: " + sqle.getSQLState() + " " + sqle.toString() + " ErrorCode: " + sqle.getErrorCode()); sqle = sqle.getNextException(); } } @@ -774,30 +767,24 @@ public class Jisql { /** * Prints out the usage message for the Jisql driver and the configured * formatter. - * */ private void usage() { System.err.println(); - System.err.println("usage: java " + getClass().getName() + - " -driver driver -cstring connect_string -user|-u username -password|-p password [-pf password_file] " + - "[-c command_term] [-input file_name] [-debug] [-driverinfo] [-formatter formatter]"); + System.err.println("usage: java " + getClass().getName() + " -driver driver -cstring connect_string -user|-u username -password|-p password [-pf password_file] " + "[-c command_term] [-input file_name] [-debug] [-driverinfo] [-formatter formatter]"); System.err.println("where:"); - System.err - .println("\t-driver specifies the JDBC driver to use. There are several builtin shortcuts - see the docs for details."); + System.err.println("\t-driver specifies the JDBC driver to use. There are several builtin shortcuts - see the docs for details."); System.err.println("\t-cstring specifies the connection string to use. These are driver specific."); System.err.println("\t-user specifies a user name to log into a database server with."); System.err.println("\t-password specifies the user name to log into a database server with."); System.err.println("\t-pf specifies the name of a file that contains the password to log into a database server with."); - System.err.println("\t The first line of file should contain the password and nothing else."); + System.err.println("\t The first line of file should contain the password and nothing else."); System.err.println("\t-c specifies the command terminator. The default is \"" + commandTerminator + "\""); System.err.println("\t-input specifies a file name to read commands from."); - System.err - .println("\t-query specifies an optional single query to run instead of interacting with the command line or a file."); - System.err.println("\t Note that the command must include a command terminator or the command will hang"); + System.err.println("\t-query specifies an optional single query to run instead of interacting with the command line or a file."); + System.err.println("\t Note that the command must include a command terminator or the command will hang"); System.err.println("\t-debug prints to stdout (System.out) debugging information"); System.err.println("\t-driverinfo prints to stdout (System.out) detailed driver information and then exits"); - System.err - .println("\t-formatter specifies either a class name or a pre-configured output formatter. See the docs for details."); + System.err.println("\t-formatter specifies either a class name or a pre-configured output formatter. See the docs for details."); if (formatter != null) { System.err.println("Additional command line arguments of the " + formatter.getClass().getName() + " class are"); diff --git a/jisql/src/main/java/org/apache/util/sql/MaskingThread.java b/jisql/src/main/java/org/apache/util/sql/MaskingThread.java index e4343d059..0a55a8daf 100644 --- a/jisql/src/main/java/org/apache/util/sql/MaskingThread.java +++ b/jisql/src/main/java/org/apache/util/sql/MaskingThread.java @@ -18,44 +18,35 @@ */ package org.apache.util.sql; - -public class MaskingThread extends Thread -{ - private boolean stop = false; - private String prompt = null; +public class MaskingThread extends Thread { + private boolean stop; + private String prompt; /** * @param thePrompt The prompt displayed to the user */ - public MaskingThread(String thePrompt) - { + public MaskingThread(String thePrompt) { prompt = thePrompt; } /** * Begin masking until asked to stop. */ - public void run() - { - while (!stop) - { - try - { + public void run() { + while (!stop) { + try { // attempt masking at this rate (refresh every 1 ms.) sleep(1); - } - catch (InterruptedException iex) - { + } catch (InterruptedException iex) { iex.printStackTrace(); } - if (!stop) - { -// -// sd - note what this does. If your prompt is really short -// and your password is really long this won't work - some -// characters will become visible -// - System.out.print( "\r" + prompt + " \r" + prompt ); + if (!stop) { + // + // sd - note what this does. If your prompt is really short + // and your password is really long this won't work - some + // characters will become visible + // + System.out.print("\r" + prompt + " \r" + prompt); } System.out.flush(); } @@ -64,8 +55,7 @@ public class MaskingThread extends Thread /** * Instruct the thread to stop masking. */ - public void stopMasking() - { + public void stopMasking() { stop = true; } } diff --git a/jisql/src/main/java/org/apache/util/sql/MySQLPLRunner.java b/jisql/src/main/java/org/apache/util/sql/MySQLPLRunner.java index 44f395bc6..7de28c26b 100644 --- a/jisql/src/main/java/org/apache/util/sql/MySQLPLRunner.java +++ b/jisql/src/main/java/org/apache/util/sql/MySQLPLRunner.java @@ -18,7 +18,6 @@ */ package org.apache.util.sql; - import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; @@ -34,41 +33,93 @@ import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; - public class MySQLPLRunner { + private static final String DEFAULT_DELIMITER = ";"; + private static final String DELIMITER_LINE_REGEX = "(?i)delimiter.+"; + private static final String DELIMITER_LINE_SPLIT_REGEX = "(?i)delimiter"; + private final Connection connection; + private final boolean stopOnError; + private final boolean autoCommit; + private PrintWriter logWriter = new PrintWriter(System.out); + private PrintWriter errorLogWriter = new PrintWriter(System.err); + private String delimiter = DEFAULT_DELIMITER; + private boolean fullLineDelimiter; + private boolean printDebug; - private static final String DEFAULT_DELIMITER = ";"; - private Connection connection; - private boolean stopOnError; - private boolean autoCommit; - private PrintWriter logWriter = new PrintWriter(System.out); - private PrintWriter errorLogWriter = new PrintWriter(System.err); - private String delimiter = DEFAULT_DELIMITER; - private boolean fullLineDelimiter = false; - private static final String DELIMITER_LINE_REGEX = "(?i)delimiter.+"; - private static final String DELIMITER_LINE_SPLIT_REGEX = "(?i)delimiter"; - private boolean printDebug = false; /** * Default constructor */ - public MySQLPLRunner(Connection connection, boolean autoCommit, - boolean stopOnError,boolean printDebug) { - this.connection = connection; - this.autoCommit = autoCommit; + public MySQLPLRunner(Connection connection, boolean autoCommit, boolean stopOnError, boolean printDebug) { + this.connection = connection; + this.autoCommit = autoCommit; this.stopOnError = stopOnError; - this.printDebug=printDebug; + this.printDebug = printDebug; + } + + public static void main(String[] args) { + // Creating object of ScriptRunner class + Connection con = null; + String driverName = "com.mysql.jdbc.Driver"; + Properties props = null; + try { + Class.forName(driverName).newInstance(); + props = new Properties(); + + props.put("user", "root"); + + props.put("password", "root"); + String connectString = "jdbc:mysql://localhost:3306/ranger"; + con = DriverManager.getConnection(connectString, props); + + MySQLPLRunner scriptRunner = new MySQLPLRunner(con, false, true, true); + String aSQLScriptFilePath = "/disk1/zero/jisql-2.0.11/xa_core_db.sql"; + + // Executing SQL Script + FileReader reader = new FileReader(aSQLScriptFilePath); + + try { + scriptRunner.runScript(reader); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ioe) { + // Ignore IOException when reader is getting closed + } + } + } + } catch (SQLException sqle) { + sqle.printStackTrace(); + } catch (ClassNotFoundException cnfe) { + System.err.println("Cannot find the driver class \"" + driverName + "\" in the current classpath."); + } catch (InstantiationException ie) { + System.err.println("Cannot instantiate the driver class \"" + driverName + "\""); + ie.printStackTrace(System.err); + } catch (IllegalAccessException iae) { + System.err.println("Cannot instantiate the driver class \"" + driverName + "\" because of an IllegalAccessException"); + iae.printStackTrace(System.err); + } catch (Exception sqle) { + sqle.printStackTrace(); + } finally { + if (con != null) { + try { + con.close(); + } catch (SQLException ignore) { + /* ignored */ + } + } + } } public void setDelimiter(String delimiter, boolean fullLineDelimiter) { - this.delimiter = delimiter; + this.delimiter = delimiter; this.fullLineDelimiter = fullLineDelimiter; } /** * Setter for logWriter property * - * @param logWriter - * - the new value of the logWriter property + * @param logWriter - the new value of the logWriter property */ public void setLogWriter(PrintWriter logWriter) { this.logWriter = logWriter; @@ -77,8 +128,7 @@ public class MySQLPLRunner { /** * Setter for errorLogWriter property * - * @param errorLogWriter - * - the new value of the errorLogWriter property + * @param errorLogWriter - the new value of the errorLogWriter property */ public void setErrorLogWriter(PrintWriter errorLogWriter) { this.errorLogWriter = errorLogWriter; @@ -87,8 +137,7 @@ public class MySQLPLRunner { /** * Runs an SQL script (read in using the Reader parameter) * - * @param reader - * - the source of the script + * @param reader - the source of the script */ public void runScript(Reader reader) throws IOException, SQLException { try { @@ -114,21 +163,17 @@ public class MySQLPLRunner { * Runs an SQL script (read in using the Reader parameter) using the * connection passed in * - * @param conn - * - the connection to use for the script - * @param reader - * - the source of the script - * @throws SQLException - * if any SQL errors occur - * @throws IOException - * if there is an error reading from the Reader + * @param conn - the connection to use for the script + * @param reader - the source of the script + * @throws SQLException if any SQL errors occur + * @throws IOException if there is an error reading from the Reader */ private void runScript(Connection conn, Reader reader) throws IOException, SQLException { StringBuilder command = null; try { LineNumberReader lineReader = new LineNumberReader(reader); - String line = null; + String line = null; while ((line = lineReader.readLine()) != null) { if (command == null) { command = new StringBuilder(); @@ -138,30 +183,24 @@ public class MySQLPLRunner { if (trimmedLine.length() < 1 || trimmedLine.startsWith("--") || trimmedLine.startsWith("//")) { //NOPMD // Do nothing } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) || fullLineDelimiter && trimmedLine.equals(getDelimiter())) { - - Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX); Matcher matcher = pattern.matcher(trimmedLine); if (matcher.matches()) { setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter); continue; - /*line = lineReader.readLine(); - if (line == null) { - break; - } - trimmedLine = line.trim();*/ } if (line != null && line.endsWith(getDelimiter()) && !DEFAULT_DELIMITER.equalsIgnoreCase(getDelimiter())) { - command.append(line.substring(0, line.lastIndexOf(getDelimiter()))); + command.append(line, 0, line.lastIndexOf(getDelimiter())); } else { command.append(line); } command.append(" "); try (Statement statement = conn.createStatement()) { - if (printDebug) + if (printDebug) { println(command); + } //System.out.println(getDelimiter()); boolean hasResults = false; if (stopOnError) { @@ -214,25 +253,20 @@ public class MySQLPLRunner { } Thread.yield(); } - } else{ - Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX); - Matcher matcher = pattern.matcher(trimmedLine); - if (matcher.matches()) { - setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter); - continue; - /*line = lineReader.readLine(); - if (line == null) { - break; - } - trimmedLine = line.trim();*/ - } - command.append(line); - command.append(" "); + } else { + Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX); + Matcher matcher = pattern.matcher(trimmedLine); + if (matcher.matches()) { + setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter); + continue; } - } if (!autoCommit) { - conn.commit(); + command.append(line); + command.append(" "); } - + } + if (!autoCommit) { + conn.commit(); + } } catch (SQLException e) { e.fillInStackTrace(); printlnError("Error executing: " + command); @@ -279,71 +313,4 @@ public class MySQLPLRunner { errorLogWriter.flush(); } } - - public static void main(String args[]){ - // Creating object of ScriptRunner class - Connection con = null; - String driverName = "com.mysql.jdbc.Driver"; - Properties props = null; - try { - Class.forName(driverName).newInstance(); - props = new Properties(); - - props.put("user", "root"); - - props.put("password", "root"); - String connectString = "jdbc:mysql://localhost:3306/ranger"; - con = DriverManager.getConnection(connectString, props); - - - MySQLPLRunner scriptRunner = new MySQLPLRunner(con, false, true,true); - String aSQLScriptFilePath = "/disk1/zero/jisql-2.0.11/xa_core_db.sql"; - - - // Executing SQL Script - FileReader reader = new FileReader(aSQLScriptFilePath); - - try { - scriptRunner.runScript(reader); - } - finally { - if (reader != null) { - try { - reader.close(); - } - catch(IOException ioe) { - // Ignore IOException when reader is getting closed - } - } - } - - - } - catch (SQLException sqle) { - sqle.printStackTrace(); - } - catch (ClassNotFoundException cnfe) { - System.err.println("Cannot find the driver class \"" + driverName + "\" in the current classpath."); - } - catch (InstantiationException ie) { - System.err.println("Cannot instantiate the driver class \"" + driverName + "\""); - ie.printStackTrace(System.err); - } - catch (IllegalAccessException iae) { - System.err.println("Cannot instantiate the driver class \"" + driverName + "\" because of an IllegalAccessException"); - iae.printStackTrace(System.err); - }catch (Exception sqle) { - sqle.printStackTrace(); - } - finally { - if (con != null) { - try { - con.close(); - } - catch (SQLException ignore) { - /* ignored */ - } - } - } - } }