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 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.2'
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
* 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
/**
@ -16,6 +27,7 @@ apply from: rootProject.file( 'gradle/databases.gradle' )
apply plugin: 'java'
apply plugin: 'osgi'
//apply plugin: 'de.thetaphi.forbiddenapis'
apply plugin: 'findbugs'
apply plugin: 'checkstyle'
@ -303,54 +315,85 @@ task nonFatalCheckstyle(type:Checkstyle) {
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
checkstyleMain.exclude '**/org/hibernate/cfg/**'
checkstyleMain.exclude '**/org/hibernate/cfg/*'
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( )
task forbiddenApisSystemOut(type: CheckForbiddenApis, dependsOn: compileJava) {
classesDirs = project.files( project.sourceSets.main.java.outputDir )
classpath = project.sourceSets.main.compileClasspath + project.sourceSets.main.runtimeClasspath
bundledSignatures += 'jdk-system-out'
suppressAnnotations += ['org.hibernate.internal.build.AllowSysOut', 'org.hibernate.internal.build.AllowPrintStacktrace']
}
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'
}
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.
*/
@org.hibernate.internal.build.AllowSysOut
protected void trace(String msg) {
System.out.println( msg );
}

View File

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

View File

@ -10,7 +10,6 @@ import javassist.CannotCompileException;
import javassist.CtClass;
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.engine.spi.CompositeOwner;
import org.hibernate.engine.spi.CompositeTracker;
@ -71,7 +70,7 @@ public class CompositeEnhancer extends PersistentAttributesEnhancer {
EnhancerConstants.TRACKER_COMPOSITE_FIELD_NAME );
}
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.CtField;
import javassist.Modifier;
import javassist.NotFoundException;
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.SimpleFieldTracker;
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.EnhancerConstants;
import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor;
@ -194,7 +192,7 @@ public class EntityEnhancer extends PersistentAttributesEnhancer {
);
}
catch (CannotCompileException cce) {
cce.printStackTrace();
throw new RuntimeException( "createDirtyTrackerMethodsWithoutCollections failed", cce );
}
}
@ -273,7 +271,7 @@ public class EntityEnhancer extends PersistentAttributesEnhancer {
);
}
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() );
}
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() );
}
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() );
}
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.Formatter;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.build.AllowSysOut;
import org.jboss.logging.Logger;
@ -83,6 +84,7 @@ public class SqlStatementLogger {
* @param statement The SQL statement.
* @param formatter The formatter to use.
*/
@AllowSysOut
public void logStatement(String statement, Formatter formatter) {
if ( format ) {
if ( logToStdout || LOG.isDebugEnabled() ) {

View File

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

View File

@ -254,7 +254,6 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
catch (Exception e) {
LOG.debug( "Unexpected query compilation problem", e );
e.printStackTrace();
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.id.UUIDGenerationStrategy;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.internal.util.BytesHelper;
/**
@ -62,11 +63,12 @@ public class CustomVersionOneStrategy implements UUIDGenerationStrategy {
System.arraycopy( BytesHelper.fromInt( loTime ), 0, loBits, 2, 4 );
System.arraycopy( Helper.getCountBytes(), 0, loBits, 6, 2 );
loBits[0] &= 0x3f;
loBits[0] |= ((byte)2 << (byte)6);
loBits[0] |= ((byte)2 << (byte)6 );
return BytesHelper.asLong( loBits );
}
@AllowSysOut
public static void main(String[] args) {
CustomVersionOneStrategy strategy = new CustomVersionOneStrategy();

View File

@ -9,6 +9,7 @@ package org.hibernate.id.uuid;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.internal.util.BytesHelper;
/**
@ -116,6 +117,7 @@ public final class Helper {
}
@AllowSysOut
public static void main(String[] args) throws UnknownHostException {
byte[] addressBytes = InetAddress.getLocalHost().getAddress();
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.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.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.type.Type;
public final class ArrayHelper {
@ -416,6 +421,7 @@ public final class ArrayHelper {
return destination;
}
@AllowSysOut
public static void main(String... args) {
int[] batchSizes = ArrayHelper.getBatchSizes( 32 );

View File

@ -356,7 +356,6 @@ public class SchemaExport {
}
catch (Exception 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.cfg.AvailableSettings;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.internal.build.AllowSysOut;
import org.hibernate.internal.log.DeprecationLogger;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.tool.schema.Action;
@ -193,6 +194,7 @@ public class SchemaExportTask extends MatchingTask {
}
}
@AllowSysOut
private void doExecution() throws Exception {
final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );

View File

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

View File

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

View File

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

View File

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

View File

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