HHH-12519 - Use Forbidden APIs library (Gradle plugin) to check our use of APIs

- initial support; implicit usage of default Locale is a major problem
This commit is contained in:
Steve Ebersole 2018-05-12 20:29:50 -05:00
parent 4208ca0a2f
commit 0695b3ff6e
21 changed files with 167 additions and 61 deletions

View File

@ -24,6 +24,7 @@ buildscript {
classpath 'com.github.lburgazzoli:lb-karaf-features-gen:1.0.0-SNAPSHOT' classpath 'com.github.lburgazzoli:lb-karaf-features-gen:1.0.0-SNAPSHOT'
classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.2' classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.2'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
classpath 'de.thetaphi:forbiddenapis:2.5'
} }
} }

View File

@ -4,6 +4,17 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later * License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/ */
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'de.thetaphi:forbiddenapis:2.5'
}
}
import de.thetaphi.forbiddenapis.gradle.CheckForbiddenApis
import org.apache.tools.ant.filters.ReplaceTokens import org.apache.tools.ant.filters.ReplaceTokens
/** /**
@ -16,6 +27,7 @@ apply from: rootProject.file( 'gradle/databases.gradle' )
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'osgi' apply plugin: 'osgi'
//apply plugin: 'de.thetaphi.forbiddenapis'
apply plugin: 'findbugs' apply plugin: 'findbugs'
apply plugin: 'checkstyle' apply plugin: 'checkstyle'
@ -303,54 +315,85 @@ task nonFatalCheckstyle(type:Checkstyle) {
configFile = rootProject.file( 'shared/config/checkstyle/checkstyle-non-fatal.xml' ) configFile = rootProject.file( 'shared/config/checkstyle/checkstyle-non-fatal.xml' )
} }
if ( JavaVersion.current().isJava9Compatible() ) {
logger.warn( '[WARN] Disabling findbugs, it does not support JDK 9' )
findbugs {
sourceSets = []
}
}
else {
findbugs {
sourceSets = [project.sourceSets.main, project.sourceSets.test]
ignoreFailures = true
toolVersion = '3.0.1'
// for now we need to set this to low so that FindBugs will actually report the DM_CONVERT_CASE warning we care about
reportLevel = 'low'
// remove all low level bug warnings except DM_CONVERT_CASE
excludeFilterConfig = resources.text.fromString( excludeAllLowLevelBugsExcept( 'DM_CONVERT_CASE' ) )
}
// exclude generated java sources and cfg package is a mess mainly from annotation stuff
findbugsMain.doFirst {
classes = classes.filter {
!it.path.contains( 'org/hibernate/hql/internal/antlr' ) &&
!it.path.contains( 'org/hibernate/boot/jaxb/cfg/spi' ) &&
!it.path.contains( 'org/hibernate/sql/ordering/antlr/Generated' ) &&
!it.path.contains( 'org/hibernate/sql/ordering/antlr/OrderByTemplateTokenTypes' ) &&
!it.path.contains( 'org/hibernate/boot/jaxb/hbm/spi/Jaxb' ) &&
!it.path.contains( 'org/hibernate/boot/jaxb/hbm/spi/Adapter' ) &&
!it.path.contains( 'org/hibernate/boot/jaxb/hbm/spi/ObjectFactory' ) &&
!it.path.contains( 'org/hibernate/cfg' ) &&
!it.path.contains( '_\$logger' )
}
}
}
// because cfg package is a mess mainly from annotation stuff // because cfg package is a mess mainly from annotation stuff
checkstyleMain.exclude '**/org/hibernate/cfg/**' checkstyleMain.exclude '**/org/hibernate/cfg/**'
checkstyleMain.exclude '**/org/hibernate/cfg/*' checkstyleMain.exclude '**/org/hibernate/cfg/*'
def excludeAllLowLevelBugsExcept(String[] bugTypes){
def writer = new StringWriter() task forbiddenApisSystemOut(type: CheckForbiddenApis, dependsOn: compileJava) {
def xml = new groovy.xml.MarkupBuilder(writer); classesDirs = project.files( project.sourceSets.main.java.outputDir )
xml.FindBugsFilter { classpath = project.sourceSets.main.compileClasspath + project.sourceSets.main.runtimeClasspath
Match { bundledSignatures += 'jdk-system-out'
Confidence( value: '3' ) suppressAnnotations += ['org.hibernate.internal.build.AllowSysOut', 'org.hibernate.internal.build.AllowPrintStacktrace']
bugTypes.each { bug ->
Not {
Bug( pattern: "${bug}" )
} }
task forbiddenApisUnsafe(type: CheckForbiddenApis, dependsOn: compileJava) {
classesDirs = project.files( project.sourceSets.main.java.outputDir )
classpath = project.sourceSets.main.compileClasspath + project.sourceSets.main.runtimeClasspath
bundledSignatures += "jdk-unsafe-${project.targetCompatibility}".toString()
// unfortunately we currently have many uses of default Locale implicitly (~370) which need to be fixed
// before we can fully enabled this check
//
// No idea how findbugs was missing these b4
ignoreFailures = true
} }
task forbiddenApisNonPortable(type: CheckForbiddenApis, dependsOn: compileJava) {
classesDirs = project.files( project.sourceSets.main.java.outputDir )
classpath = project.sourceSets.main.compileClasspath + project.sourceSets.main.runtimeClasspath
bundledSignatures += 'jdk-non-portable'
} }
}
return writer.toString( ) task forbiddenApis
} project.tasks.withType( CheckForbiddenApis ).each { task -> forbiddenApis.finalizedBy task }
//if ( JavaVersion.current().isJava9Compatible() ) {
// logger.warn( '[WARN] Disabling findbugs, it does not support JDK 9' )
// findbugs {
// sourceSets = []
// }
//}
//else {
// findbugs {
// sourceSets = [project.sourceSets.main, project.sourceSets.test]
// ignoreFailures = true
// toolVersion = '3.0.1'
// // for now we need to set this to low so that FindBugs will actually report the DM_CONVERT_CASE warning we care about
// reportLevel = 'low'
// // remove all low level bug warnings except DM_CONVERT_CASE
// excludeFilterConfig = resources.text.fromString( excludeAllLowLevelBugsExcept( 'DM_CONVERT_CASE' ) )
// }
//
// // exclude generated java sources and cfg package is a mess mainly from annotation stuff
// findbugsMain.doFirst {
// classes = classes.filter {
// !it.path.contains( 'org/hibernate/hql/internal/antlr' ) &&
// !it.path.contains( 'org/hibernate/boot/jaxb/cfg/spi' ) &&
// !it.path.contains( 'org/hibernate/sql/ordering/antlr/Generated' ) &&
// !it.path.contains( 'org/hibernate/sql/ordering/antlr/OrderByTemplateTokenTypes' ) &&
// !it.path.contains( 'org/hibernate/boot/jaxb/hbm/spi/Jaxb' ) &&
// !it.path.contains( 'org/hibernate/boot/jaxb/hbm/spi/Adapter' ) &&
// !it.path.contains( 'org/hibernate/boot/jaxb/hbm/spi/ObjectFactory' ) &&
// !it.path.contains( 'org/hibernate/cfg' ) &&
// !it.path.contains( '_\$logger' )
// }
// }
//}
//
//def excludeAllLowLevelBugsExcept(String[] bugTypes){
// def writer = new StringWriter()
// def xml = new groovy.xml.MarkupBuilder(writer);
// xml.FindBugsFilter {
// Match {
// Confidence( value: '3' )
// bugTypes.each { bug ->
// Not {
// Bug( pattern: "${bug}" )
// }
// }
// }
// }
// return writer.toString( )
//}

View File

@ -68,6 +68,7 @@ tokens
* *
* @param msg The trace message. * @param msg The trace message.
*/ */
@org.hibernate.internal.build.AllowSysOut
protected void trace(String msg) { protected void trace(String msg) {
System.out.println( msg ); System.out.println( msg );
} }

View File

@ -7,6 +7,7 @@
package org.hibernate; package org.hibernate;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.build.AllowSysOut;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -51,6 +52,7 @@ public class Version {
* *
* @param args n/a * @param args n/a
*/ */
@AllowSysOut
public static void main(String[] args) { public static void main(String[] args) {
System.out.println( "Hibernate Core {" + getVersionString() + "}" ); System.out.println( "Hibernate Core {" + getVersionString() + "}" );
} }

View File

@ -10,7 +10,6 @@ import javassist.CannotCompileException;
import javassist.CtClass; import javassist.CtClass;
import org.hibernate.bytecode.enhance.internal.tracker.CompositeOwnerTracker; import org.hibernate.bytecode.enhance.internal.tracker.CompositeOwnerTracker;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.bytecode.enhance.spi.EnhancerConstants; import org.hibernate.bytecode.enhance.spi.EnhancerConstants;
import org.hibernate.engine.spi.CompositeOwner; import org.hibernate.engine.spi.CompositeOwner;
import org.hibernate.engine.spi.CompositeTracker; import org.hibernate.engine.spi.CompositeTracker;
@ -71,7 +70,7 @@ public class CompositeEnhancer extends PersistentAttributesEnhancer {
EnhancerConstants.TRACKER_COMPOSITE_FIELD_NAME ); EnhancerConstants.TRACKER_COMPOSITE_FIELD_NAME );
} }
catch (CannotCompileException cce) { catch (CannotCompileException cce) {
cce.printStackTrace(); throw new RuntimeException( "createCompositeTrackerMethod failed", cce );
} }
} }

View File

@ -17,7 +17,6 @@ import javassist.CannotCompileException;
import javassist.CtClass; import javassist.CtClass;
import javassist.CtField; import javassist.CtField;
import javassist.Modifier; import javassist.Modifier;
import javassist.NotFoundException; import javassist.NotFoundException;
import org.hibernate.bytecode.enhance.internal.tracker.DirtyTracker; import org.hibernate.bytecode.enhance.internal.tracker.DirtyTracker;
@ -25,7 +24,6 @@ import org.hibernate.bytecode.enhance.internal.tracker.NoopCollectionTracker;
import org.hibernate.bytecode.enhance.internal.tracker.SimpleCollectionTracker; import org.hibernate.bytecode.enhance.internal.tracker.SimpleCollectionTracker;
import org.hibernate.bytecode.enhance.internal.tracker.SimpleFieldTracker; import org.hibernate.bytecode.enhance.internal.tracker.SimpleFieldTracker;
import org.hibernate.bytecode.enhance.spi.CollectionTracker; import org.hibernate.bytecode.enhance.spi.CollectionTracker;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.bytecode.enhance.spi.EnhancementException; import org.hibernate.bytecode.enhance.spi.EnhancementException;
import org.hibernate.bytecode.enhance.spi.EnhancerConstants; import org.hibernate.bytecode.enhance.spi.EnhancerConstants;
import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor; import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor;
@ -194,7 +192,7 @@ public class EntityEnhancer extends PersistentAttributesEnhancer {
); );
} }
catch (CannotCompileException cce) { catch (CannotCompileException cce) {
cce.printStackTrace(); throw new RuntimeException( "createDirtyTrackerMethodsWithoutCollections failed", cce );
} }
} }
@ -273,7 +271,7 @@ public class EntityEnhancer extends PersistentAttributesEnhancer {
); );
} }
catch (CannotCompileException cce) { catch (CannotCompileException cce) {
cce.printStackTrace(); throw new RuntimeException( "createDirtyTrackerMethodsWithCollections failed", cce );
} }
} }
@ -361,7 +359,7 @@ public class EntityEnhancer extends PersistentAttributesEnhancer {
MethodWriter.write( managedCtClass, body.toString() ); MethodWriter.write( managedCtClass, body.toString() );
} }
catch (CannotCompileException cce) { catch (CannotCompileException cce) {
cce.printStackTrace(); throw new RuntimeException( "createCollectionDirtyCheckMethod failed", cce );
} }
} }
@ -395,7 +393,7 @@ public class EntityEnhancer extends PersistentAttributesEnhancer {
MethodWriter.write( managedCtClass, body.toString() ); MethodWriter.write( managedCtClass, body.toString() );
} }
catch (CannotCompileException cce) { catch (CannotCompileException cce) {
cce.printStackTrace(); throw new RuntimeException( "createCollectionDirtyCheckGetFieldsMethod failed", cce );
} }
} }
@ -443,7 +441,7 @@ public class EntityEnhancer extends PersistentAttributesEnhancer {
MethodWriter.write( managedCtClass, body.toString() ); MethodWriter.write( managedCtClass, body.toString() );
} }
catch (CannotCompileException cce) { catch (CannotCompileException cce) {
cce.printStackTrace(); throw cce;
} }
} }

View File

@ -9,6 +9,7 @@ package org.hibernate.engine.jdbc.spi;
import org.hibernate.engine.jdbc.internal.FormatStyle; import org.hibernate.engine.jdbc.internal.FormatStyle;
import org.hibernate.engine.jdbc.internal.Formatter; import org.hibernate.engine.jdbc.internal.Formatter;
import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.build.AllowSysOut;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -83,6 +84,7 @@ public class SqlStatementLogger {
* @param statement The SQL statement. * @param statement The SQL statement.
* @param formatter The formatter to use. * @param formatter The formatter to use.
*/ */
@AllowSysOut
public void logStatement(String statement, Formatter formatter) { public void logStatement(String statement, Formatter formatter) {
if ( format ) { if ( format ) {
if ( logToStdout || LOG.isDebugEnabled() ) { if ( logToStdout || LOG.isDebugEnabled() ) {

View File

@ -8,6 +8,8 @@ package org.hibernate.hql.internal.ast;
import java.io.PrintStream; import java.io.PrintStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import org.hibernate.internal.build.AllowPrintStacktrace;
import antlr.SemanticException; import antlr.SemanticException;
/** /**
@ -45,6 +47,7 @@ public class DetailedSemanticException extends SemanticException {
/** /**
* Prints a stack trace. * Prints a stack trace.
*/ */
@AllowPrintStacktrace
public void printStackTrace() { public void printStackTrace() {
super.printStackTrace(); super.printStackTrace();
if ( cause != null ) { if ( cause != null ) {
@ -57,6 +60,7 @@ public class DetailedSemanticException extends SemanticException {
* *
* @param s the print stream. * @param s the print stream.
*/ */
@AllowPrintStacktrace
public void printStackTrace(PrintStream s) { public void printStackTrace(PrintStream s) {
super.printStackTrace( s ); super.printStackTrace( s );
if ( cause != null ) { if ( cause != null ) {

View File

@ -254,7 +254,6 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
} }
catch (Exception e) { catch (Exception e) {
LOG.debug( "Unexpected query compilation problem", e ); LOG.debug( "Unexpected query compilation problem", e );
e.printStackTrace();
throw new QueryException( "Incorrect query syntax", queryString, e ); throw new QueryException( "Incorrect query syntax", queryString, e );
} }

View File

@ -10,6 +10,7 @@ import java.util.UUID;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.UUIDGenerationStrategy; import org.hibernate.id.UUIDGenerationStrategy;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.internal.util.BytesHelper; import org.hibernate.internal.util.BytesHelper;
/** /**
@ -67,6 +68,7 @@ public class CustomVersionOneStrategy implements UUIDGenerationStrategy {
return BytesHelper.asLong( loBits ); return BytesHelper.asLong( loBits );
} }
@AllowSysOut
public static void main(String[] args) { public static void main(String[] args) {
CustomVersionOneStrategy strategy = new CustomVersionOneStrategy(); CustomVersionOneStrategy strategy = new CustomVersionOneStrategy();

View File

@ -9,6 +9,7 @@ package org.hibernate.id.uuid;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.internal.util.BytesHelper; import org.hibernate.internal.util.BytesHelper;
/** /**
@ -116,6 +117,7 @@ public final class Helper {
} }
@AllowSysOut
public static void main(String[] args) throws UnknownHostException { public static void main(String[] args) throws UnknownHostException {
byte[] addressBytes = InetAddress.getLocalHost().getAddress(); byte[] addressBytes = InetAddress.getLocalHost().getAddress();
System.out.println( "Raw ip address bytes : " + addressBytes.toString() ); System.out.println( "Raw ip address bytes : " + addressBytes.toString() );

View File

@ -0,0 +1,20 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.internal.build;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Used to indicate to the Forbidden APIs library that a specific usage
* of {@link Exception#printStackTrace} is allowable.
*
* @author Steve Ebersole
*/
@Retention( RetentionPolicy.CLASS )
public @interface AllowPrintStacktrace {
}

View File

@ -0,0 +1,20 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.internal.build;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Used to indicate to the Forbidden APIs library that a specific usage
* of {@link System#out} is allowable.
*
* @author Steve Ebersole
*/
@Retention( RetentionPolicy.CLASS )
public @interface AllowSysOut {
}

View File

@ -8,11 +8,16 @@ package org.hibernate.internal.util.collections;
import java.io.Serializable; import java.io.Serializable;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.LockOptions; import org.hibernate.LockOptions;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.type.Type; import org.hibernate.type.Type;
public final class ArrayHelper { public final class ArrayHelper {
@ -416,6 +421,7 @@ public final class ArrayHelper {
return destination; return destination;
} }
@AllowSysOut
public static void main(String... args) { public static void main(String... args) {
int[] batchSizes = ArrayHelper.getBatchSizes( 32 ); int[] batchSizes = ArrayHelper.getBatchSizes( 32 );

View File

@ -356,7 +356,6 @@ public class SchemaExport {
} }
catch (Exception e) { catch (Exception e) {
LOG.unableToCreateSchema( e ); LOG.unableToCreateSchema( e );
e.printStackTrace();
} }
} }

View File

@ -23,6 +23,7 @@ import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.internal.log.DeprecationLogger; import org.hibernate.internal.log.DeprecationLogger;
import org.hibernate.internal.util.collections.ArrayHelper; import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.tool.schema.Action; import org.hibernate.tool.schema.Action;
@ -193,6 +194,7 @@ public class SchemaExportTask extends MatchingTask {
} }
} }
@AllowSysOut
private void doExecution() throws Exception { private void doExecution() throws Exception {
final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build(); final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr ); final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );

View File

@ -154,7 +154,6 @@ public class SchemaUpdate {
} }
catch (Exception e) { catch (Exception e) {
LOG.unableToRunSchemaUpdate( e ); LOG.unableToRunSchemaUpdate( e );
e.printStackTrace();
} }
} }

View File

@ -80,7 +80,6 @@ public class SchemaValidator {
} }
catch (Exception e) { catch (Exception e) {
LOG.unableToRunSchemaUpdate( e ); LOG.unableToRunSchemaUpdate( e );
e.printStackTrace();
} }
} }

View File

@ -6,6 +6,8 @@
*/ */
package org.hibernate.tool.hbm2ddl; package org.hibernate.tool.hbm2ddl;
import org.hibernate.internal.build.AllowSysOut;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
* *
@ -20,6 +22,7 @@ class ScriptExporter implements Exporter {
} }
@Override @Override
@AllowSysOut
public void export(String string) throws Exception { public void export(String string) throws Exception {
System.out.println( string ); System.out.println( string );
} }

View File

@ -6,6 +6,8 @@
*/ */
package org.hibernate.tool.schema.internal.exec; package org.hibernate.tool.schema.internal.exec;
import org.hibernate.internal.build.AllowSysOut;
/** /**
* GenerationTarget implementation for handling generation to System.out * GenerationTarget implementation for handling generation to System.out
* *
@ -28,6 +30,7 @@ public class GenerationTargetToStdout implements GenerationTarget {
} }
@Override @Override
@AllowSysOut
public void accept(String command) { public void accept(String command) {
if ( delimiter != null ) { if ( delimiter != null ) {
command += delimiter; command += delimiter;

View File

@ -10,6 +10,7 @@ import java.io.IOException;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.Writer; import java.io.Writer;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.tool.schema.spi.SchemaManagementException; import org.hibernate.tool.schema.spi.SchemaManagementException;
/** /**
@ -27,6 +28,7 @@ public class ScriptTargetOutputToStdout extends AbstractScriptTargetOutput {
} }
@Override @Override
@AllowSysOut
public void prepare() { public void prepare() {
super.prepare(); super.prepare();
this.writer = new OutputStreamWriter( System.out ); this.writer = new OutputStreamWriter( System.out );