Статьи

Findbugs Предупреждения по образцу

Описания ошибок FindBugs ™ в онлайн-документации кратки и хорошо написаны. К сожалению, некоторые части описаний нелегко понять (даже для опытных разработчиков Java). Может быть трудно понять точную причину предупреждения и / или найти правильный способ устранения.

Если честно — по крайней мере у меня были проблемы с некоторыми предупреждениями в последние годы. Довольно часто я не находил полезного примера кода в сети. Основным недостатком описания ошибок является то, что он редко использует пример кода для демонстрации неправильной и правильной ситуации. Это моя мотивация опубликовать в ближайшие недели серию статей с простыми примерами кода выбранных предупреждений.

Следующие 10 предупреждений рассматриваются в этой статье:

  • BC_IMPOSSIBLE_CAST
  • BC_IMPOSSIBLE_DOWNCAST
  • BC_IMPOSSIBLE_INSTANCEOF
  • BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY
  • DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE
  • ES_COMPARING_STRINGS_WITH_EQ
  • VA_FORMAT_STRING_ILLEGAL
  • RV_RETURN_VALUE_IGNORED NP_ALWAYS_NULL QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT

Следующий пример был скомпилирован с JDK 1.6.0_24, и Findbugs ™ (версия 2.0.1-rc2) покажет все предупреждения с настройками по умолчанию для плагина Findbugs ™ Eclipse (версия 2.0.1.20120511).

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package com.sprunck.samples;
 
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UnknownFormatConversionException;
 
@SuppressWarnings(value = { "null", "unused" })
public class FindbugsWarningsBySampleFirst {
 
    public static void main(final String[] args) {
 
        System.out.println("Findbugs Sample 001 for BC_IMPOSSIBLE_CAST");
        // WRONG
        try {
            FindbugsWarningsBySampleFirst.bcImpossibleCastWRONG();
        } catch (final ClassCastException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        }
        // CORRECT
        FindbugsWarningsBySampleFirst.bcImpossibleCastCORRECT();
 
        System.out.println("Findbugs Sample 002 for BC_IMPOSSIBLE_DOWNCAST");
        // WRONG
        try {
            FindbugsWarningsBySampleFirst.bcImpossibleDowncastWRONG();
        } catch (final ClassCastException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        }
        // CORRECT
        FindbugsWarningsBySampleFirst.bcImpossibleDowncastCORRECT();
 
        System.out.println("Findbugs Sample 003 for BC_IMPOSSIBLE_INSTANCEOF");
        // WRONG
        FindbugsWarningsBySampleFirst.bcImpossibleInstanceOfWRONG();
        // CORRECT
        FindbugsWarningsBySampleFirst.bcImpossibleInstanceOfCORRECT();
 
        System.out.println("Findbugs Sample 004 for BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY");
        // WRONG
        try {
            FindbugsWarningsBySampleFirst.bcImpossibleDowncastOfArrayWRONG();
        } catch (final ClassCastException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        }
        // CORRECT
        FindbugsWarningsBySampleFirst.bcImpossibleDowncastOfArrayCORRECT();
 
        System.out.println("Findbugs Sample 005 for DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE");
        // WRONG
        FindbugsWarningsBySampleFirst.dmiBigDecimalConstructedFromDoubleWRONG();
        // CORRECT
        FindbugsWarningsBySampleFirst.dmiBigDecimalConstructedFromDoubleCORRECT();
 
        System.out.println("Findbugs Sample 006 for ES_COMPARING_STRINGS_WITH_EQ");
        // WRONG
        FindbugsWarningsBySampleFirst.esComparingStringsWithEqWRONG();
        // CORRECT
        FindbugsWarningsBySampleFirst.esComparingStringsWithEqCORRECT();
 
        System.out.println("Findbugs Sample 007 for VA_FORMAT_STRING_ILLEGAL");
        // WRONG
        try {
            FindbugsWarningsBySampleFirst.vaFormatStringIllegalWRONG();
        } catch (final UnknownFormatConversionException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        }
        // CORRECT
        FindbugsWarningsBySampleFirst.vaFormatStringIllegalCORRECT();
 
        System.out.println("Findbugs Sample 008 for RV_RETURN_VALUE_IGNORED");
        // WRONG
        FindbugsWarningsBySampleFirst.rvReturnValueIgnoredWRONG();
        // CORRECT
        FindbugsWarningsBySampleFirst.rvReturnValueIgnoredCORRECT();
 
        System.out.println("Findbugs Sample 009 for NP_ALWAYS_NULL");
        // WRONG
        try {
            FindbugsWarningsBySampleFirst.npAlwaysNullWRONG();
        } catch (final NullPointerException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        }
        // CORRECT
        FindbugsWarningsBySampleFirst.npAlwaysNullCORRECT();
 
        System.out.println("Findbugs Sample 010 for QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT");
        // WRONG
        FindbugsWarningsBySampleFirst.qabQuestionableBooleanAssignmentWRONG();
        // CORRECT
        FindbugsWarningsBySampleFirst.qabQuestionableBooleanAssignmentCORRECT();
 
    }
 
    private static void bcImpossibleCastWRONG() {
        final Object doubleValue = Double.valueOf(1.0);
        final Long value = (Long) doubleValue;
        System.out.println("   - " + value);
    }
 
    private static void bcImpossibleCastCORRECT() {
        final Object doubleValue = Double.valueOf(1.0);
        final Double value = (Double) doubleValue;
        System.out.println("   - " + value);
    }
 
    private static void bcImpossibleDowncastWRONG() {
        final Object exception = new RuntimeException("abc");
        final SecurityException value = (SecurityException) exception;
        System.out.println("   - " + value.getMessage());
    }
 
    private static void bcImpossibleDowncastCORRECT() {
        final Object exception = new RuntimeException("abc");
        final RuntimeException value = (RuntimeException) exception;
        System.out.println("   - " + value.getMessage());
    }
 
    private static void bcImpossibleInstanceOfWRONG() {
        final Object value = Double.valueOf(1.0);
        System.out.println("   - " + (value instanceof Long));
    }
 
    private static void bcImpossibleInstanceOfCORRECT() {
        final Object value = Double.valueOf(1.0);
        System.out.println("   - " + (value instanceof Double));
    }
 
    private static void bcImpossibleDowncastOfArrayWRONG() {
        final Collection<String> stringVector = new ArrayList<String>();
        stringVector.add("abc");
        stringVector.add("xyz");
        final String[] stringArray = (String[]) stringVector.toArray();
        System.out.println("   - " + stringArray.length);
    }
 
    private static void bcImpossibleDowncastOfArrayCORRECT() {
        final Collection<String> stringVector = new ArrayList<String>();
        stringVector.add("abc");
        stringVector.add("xyz");
        final String[] stringArray = stringVector.toArray(new String[stringVector.size()]);
        System.out.println("   - " + stringArray.length);
    }
 
    private static void dmiBigDecimalConstructedFromDoubleWRONG() {
        final BigDecimal bigDecimal = new BigDecimal(3.1);
        System.out.println("   - " + bigDecimal.toString());
    }
 
    private static void dmiBigDecimalConstructedFromDoubleCORRECT() {
        final BigDecimal bigDecimal = new BigDecimal("3.1");
        System.out.println("   - " + bigDecimal.toString());
    }
 
    private static void esComparingStringsWithEqWRONG() {
        final StringBuilder sb1 = new StringBuilder("1234");
        final StringBuilder sb2 = new StringBuilder("1234");
        final String string1 = sb1.toString();
        final String string2 = sb2.toString();
        System.out.println("   - " + (string1 == string2));
    }
 
    private static void esComparingStringsWithEqCORRECT() {
        final StringBuilder sb1 = new StringBuilder("1234");
        final StringBuilder sb2 = new StringBuilder("1234");
        final String string1 = sb1.toString();
        final String string2 = sb2.toString();
        System.out.println("   - " + string1.equals(string2));
    }
 
    private static void vaFormatStringIllegalWRONG() {
        System.out.println(String.format("   - %>s  %s", "10", "9"));
    }
 
    private static void vaFormatStringIllegalCORRECT() {
        System.out.println(String.format("   - %s > %s", "10", "9"));
    }
 
    private static void rvReturnValueIgnoredWRONG() {
        final BigDecimal bigDecimal = BigDecimal.ONE;
        bigDecimal.add(BigDecimal.ONE);
        System.out.println(String.format("   - " + bigDecimal));
    }
 
    private static void rvReturnValueIgnoredCORRECT() {
        final BigDecimal bigDecimal = BigDecimal.ONE;
        final BigDecimal newValue = bigDecimal.add(BigDecimal.ONE);
        System.out.println(String.format("   - " + newValue));
    }
 
    private static void npAlwaysNullWRONG() {
        final String value = null;
        if (null != value & value.length() > 2) {
            System.out.println(String.format("   - " + value));
        } else {
            System.out.println(String.format("   - value is invalid"));
        }
    }
 
    private static void npAlwaysNullCORRECT() {
        final String value = null;
        if (null != value && value.length() > 2) {
            System.out.println(String.format("   - " + value));
        } else {
            System.out.println(String.format("   - value is invalid"));
        }
    }
 
    private static void qabQuestionableBooleanAssignmentWRONG() {
        boolean value = false;
        if (value = true) {
            System.out.println(String.format("   - value is true"));
        } else {
            System.out.println(String.format("   - value is false"));
        }
    }
 
    private static void qabQuestionableBooleanAssignmentCORRECT() {
        final boolean value = false;
        if (value == true) {
            System.out.println(String.format("   - value is true"));
        } else {
            System.out.println(String.format("   - value is false"));
        }
    }
 
}

Программа должна распечатать следующий вывод на стандартный вывод:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Findbugs Sample 001 for BC_IMPOSSIBLE_CAST
   - ERROR:java.lang.Double cannot be cast to java.lang.Long
   - 1.0
Findbugs Sample 002 for BC_IMPOSSIBLE_DOWNCAST
   - ERROR:java.lang.RuntimeException cannot be cast to java.lang.SecurityException
   - abc
Findbugs Sample 003 for BC_IMPOSSIBLE_INSTANCEOF
   - false
   - true
Findbugs Sample 004 for BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY
   - ERROR:[Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
   - 2
Findbugs Sample 005 for DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE
   - 3.100000000000000088817841970012523233890533447265625
   - 3.1
Findbugs Sample 006 for ES_COMPARING_STRINGS_WITH_EQ
   - false
   - true
Findbugs Sample 007 for VA_FORMAT_STRING_ILLEGAL
   - ERROR:Conversion = '>'
   - 10 > 9
Findbugs Sample 008 for RV_RETURN_VALUE_IGNORED
   - 1
   - 2
Findbugs Sample 009 for NP_ALWAYS_NULL
   - ERROR:null
   - value is invalid
Findbugs Sample 010 for QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT
   - value is true
   - value is false

Пожалуйста, не стесняйтесь обращаться ко мне, если у вас есть идеи по улучшению и / или вы нашли ошибку в примере кода.

Мы продолжаем со следующими 5 предупреждениями:

  • DMI_CONSTANT_DB_PASSWORD (Безопасность)
  • DMI_EMPTY_DB_PASSWORD (Безопасность)
  • SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE (Безопасность)
  • OBL_UNSATISFIED_OBLIGATION (экспериментальный)
  • OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE (экспериментальный)

Мотивация для серии предупреждений Findbugs ™ по образцу

Описания ошибок FindBugs ™ в онлайн-документации кратки и хорошо написаны. К сожалению, некоторые части описаний нелегко понять (даже для опытных разработчиков Java). Может быть трудно понять точную причину предупреждения и / или найти правильный способ устранения.

Если честно — по крайней мере у меня были проблемы с некоторыми предупреждениями в последние годы. Довольно часто я не находил полезного примера кода в сети. Основным недостатком описания ошибок является то, что он редко использует пример кода для демонстрации неправильной и правильной ситуации. Это моя мотивация опубликовать в ближайшие недели серию статей с простыми примерами кода выбранных предупреждений.

Образец кода

Findbugs ™ (версия 2.0.1-rc2) отобразит все предупреждения с активированными настройками «Безопасность» и «Экспериментальный» плагина Findbugs ™ Eclipse (версия 2.0.1.20120511). Смотрите следующий рисунок:

Образец был скомпилирован с использованием JDK 1.6.0_24 и derby.jar (версия 10.9.1.0) в пути сборки.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package com.sprunck.samples;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class FindbugsWarningsBySampleSecond {
 
    public static void main(final String[] args) {
 
        // Prepare database
        Statement createStatement = null;
        Connection connection = null;
        try {
            System.out.println("Findbugs Sample prepare small in memory database");
            connection = getConnection_dmiConstantDbPasswordCORRECT();
            createStatement = connection.createStatement();
            createStatement.execute("create table T_ADVICE (answer varchar(255), "
                    + "owner varchar(255))");
            createStatement.execute("insert into T_ADVICE ( answer, owner ) values "
                    + "('Don''t Panic', 'Joe')");
            createStatement.execute("insert into T_ADVICE ( answer, owner ) values "
                    + "('Keep Smiling', 'John')");
 
            System.out.println("\nFindbugs Sample for DMI_CONSTANT_DB_PASSWORD");
            // WRONG
            FindbugsWarningsBySampleSecond.getConnection_dmiConstantDbPasswordWRONG();
            // CORRECT
            FindbugsWarningsBySampleSecond.getConnection_dmiConstantDbPasswordCORRECT();
 
            System.out.println("\nFindbugs Sample for DMI_EMPTY_DB_PASSWORD");
            // WRONG
            FindbugsWarningsBySampleSecond.getConnection_dmiEmptyDbPasswordWRONG();
            // CORRECT
            FindbugsWarningsBySampleSecond.getConnection_dmiConstantDbPasswordCORRECT();
 
            System.out.println("\nFindbugs Sample for SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE");
            // WRONG
            FindbugsWarningsBySampleSecond.sqlNonconstantStringPassedToExecuteWRONG("Joe");
            // CORRECT
            FindbugsWarningsBySampleSecond.sqlNonconstantStringPassedToExecuteCORRECT("Joe");
 
            System.out.println("\nFindbugs Sample for OBL_UNSATISFIED_OBLIGATION");
            // WRONG
            FindbugsWarningsBySampleSecond.oblUnsatisfiedObligationWRONG("Joe");
            // CORRECT
            FindbugsWarningsBySampleSecond.oblUnsatisfiedObligationCORRECT("Joe");
 
            System.out.println("\nFindbugs Sample for OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE");
            // WRONG
            FindbugsWarningsBySampleSecond.oblUnsatisfiedObligationExceptionEdgeWRONG("Joe");
            // CORRECT
            FindbugsWarningsBySampleSecond.oblUnsatisfiedObligationExceptionEdgeCORRECT("Joe");
 
        } catch (final SQLException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        } finally {
            if (null != createStatement) {
                try {
                    createStatement.close();
                } catch (final SQLException e) {
                }
            }
            if (null != connection) {
                try {
                    connection.close();
                } catch (final SQLException e) {
                }
            }
 
        }
 
    }
 
    private static Connection getConnection_dmiConstantDbPasswordWRONG() throws SQLException {
 
        Connection connection = null;
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        } catch (final ClassNotFoundException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        }
        connection = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "APP",
                "my-secret-password");
        System.out.println("   - DriverManager.getConnection(\"jdbc:derby:database;"
                + "create=true\", \"test\", \"admin\"))");
 
        return connection;
    }
 
    private static Connection getConnection_dmiEmptyDbPasswordWRONG() throws SQLException {
 
        Connection connection = null;
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        } catch (final ClassNotFoundException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        }
        connection = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "APP", "");
        System.out.println("   - DriverManager.getConnection(\"jdbc:derby:database;create=true\","
                + " \"test\", \"\"))");
        return connection;
    }
 
    private static Connection getConnection_dmiConstantDbPasswordCORRECT() throws SQLException {
 
        Connection connection = null;
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        } catch (final ClassNotFoundException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        }
        connection = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "APP",
                getSecurePassword());
        System.out.println("   - DriverManager.getConnection(\"jdbc:derby:database;"
                + "create=true\", \"test\", pwdDecoder()))");
        return connection;
    }
 
    static String getSecurePassword() {
        // Here we should fetch and decode the password from a secured resource
        return "my-sec" + "ret-password";
    }
 
    private static void sqlNonconstantStringPassedToExecuteWRONG(final String owner) {
 
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            final String query = "SELECT answer FROM T_ADVICE WHERE owner= '" + owner + "'";
            statement = getConnection_dmiConstantDbPasswordCORRECT().createStatement();
            resultSet = statement.executeQuery(query);
            while (resultSet.next()) {
                System.out.println("   - Result (Statement):" + resultSet.getString("ANSWER"));
            }
        } catch (final SQLException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        } finally {
 
            if (null != resultSet) {
                try {
                    resultSet.close();
                } catch (final SQLException e) {
                }
            }
            if (null != statement) {
                try {
                    statement.close();
                } catch (final SQLException e) {
                }
            }
        }
    }
 
    private static void sqlNonconstantStringPassedToExecuteCORRECT(final String owner) {
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            final String query = "SELECT answer FROM T_ADVICE WHERE owner = ?";
            statement = getConnection_dmiConstantDbPasswordCORRECT().prepareStatement(query);
            statement.setString(1, owner);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                System.out.println("   - Result (PreparedStatement):"
                        + resultSet.getString("ANSWER"));
            }
        } catch (final SQLException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        } finally {
            if (null != resultSet) {
                try {
                    resultSet.close();
                } catch (final SQLException e) {
                }
            }
            if (null != statement) {
                try {
                    statement.close();
                } catch (final SQLException e) {
                }
            }
        }
    }
 
    private static void oblUnsatisfiedObligationWRONG(final String owner) {
 
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            final String query = "SELECT answer FROM T_ADVICE WHERE owner = ?";
            statement = getConnection_dmiConstantDbPasswordCORRECT().prepareStatement(query);
            statement.setString(1, owner);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                System.out.println("   - Result (PreparedStatement):"
                        + resultSet.getString("ANSWER"));
            }
        } catch (final SQLException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        } finally {
            if (null != statement) {
                try {
                    statement.close();
                } catch (final SQLException e) {
                }
            }
        }
    }
 
    private static void oblUnsatisfiedObligationCORRECT(final String owner) {
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            final String query = "SELECT answer FROM T_ADVICE WHERE owner = ?";
            statement = getConnection_dmiConstantDbPasswordCORRECT().prepareStatement(query);
            statement.setString(1, owner);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                System.out.println("   - Result (PreparedStatement):"
                        + resultSet.getString("ANSWER"));
            }
        } catch (final SQLException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        } finally {
            if (null != resultSet) {
                try {
                    resultSet.close();
                } catch (final SQLException e) {
                }
            }
            if (null != statement) {
                try {
                    statement.close();
                } catch (final SQLException e) {
                }
            }
        }
    }
 
    private static void oblUnsatisfiedObligationExceptionEdgeWRONG(final String owner) {
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            final String query = "SELECT answer FROM T_ADVICE WHERE owner = ?";
            statement = getConnection_dmiConstantDbPasswordCORRECT().prepareStatement(query);
            statement.setString(1, owner);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                System.out.println("   - Result (PreparedStatement):"
                        + resultSet.getString("ANSWER"));
            }
            if (null != statement) {
                try {
                    statement.close();
                } catch (final SQLException e) {
                }
            }
        } catch (final SQLException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        } finally {
            if (null != resultSet) {
                try {
                    resultSet.close();
                } catch (final SQLException e) {
                }
            }
        }
    }
 
    private static void oblUnsatisfiedObligationExceptionEdgeCORRECT(final String owner) {
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            final String query = "SELECT answer FROM T_ADVICE WHERE owner = ?";
            statement = getConnection_dmiConstantDbPasswordCORRECT().prepareStatement(query);
            statement.setString(1, owner);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                System.out.println("   - Result (PreparedStatement):"
                        + resultSet.getString("ANSWER"));
            }
            if (null != statement) {
                try {
                    statement.close();
                } catch (final SQLException e) {
                }
            }
        } catch (final SQLException e) {
            System.out.println("   - ERROR:" + e.getMessage());
        } finally {
            if (null != resultSet) {
                try {
                    resultSet.close();
                } catch (final SQLException e) {
                }
            }
            if (null != statement) {
                try {
                    statement.close();
                } catch (final SQLException e) {
                }
            }
        }
    }
}

Программа должна распечатать следующий вывод на стандартный вывод:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Findbugs Sample prepare small in memory database
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", pwdDecoder()))
 
Findbugs Sample for DMI_CONSTANT_DB_PASSWORD
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", "admin"))
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", pwdDecoder()))
 
Findbugs Sample for DMI_EMPTY_DB_PASSWORD
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", ""))
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", pwdDecoder()))
 
Findbugs Sample for SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", pwdDecoder()))
   - Result (Statement):Don't Panic
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", pwdDecoder()))
   - Result (PreparedStatement):Don't Panic
 
Findbugs Sample for OBL_UNSATISFIED_OBLIGATION
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", pwdDecoder()))
   - Result (PreparedStatement):Don't Panic
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", pwdDecoder()))
   - Result (PreparedStatement):Don't Panic
 
Findbugs Sample for OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", pwdDecoder()))
   - Result (PreparedStatement):Don't Panic
   - DriverManager.getConnection("jdbc:derby:database;create=true", "test", pwdDecoder()))
   - Result (PreparedStatement):Don't Panic

Пожалуйста, не стесняйтесь обращаться ко мне, если у вас есть идеи по улучшению и / или вы нашли ошибку в примере кода.

Справка: предупреждения Findbugs ™ по образцу — часть I ,   Примеры предупреждений Findbugs ™ — часть II от нашего партнера по JCG Маркуса Шпрунка в блоге Software Engineering Candies .