You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by gn...@apache.org on 2022/02/24 16:01:19 UTC
[maven-build-cache-extension] branch mvn4 updated: Switch a few core plugins to the new api
This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch mvn4
in repository https://gitbox.apache.org/repos/asf/maven-build-cache-extension.git
The following commit(s) were added to refs/heads/mvn4 by this push:
new a0e1f5f Switch a few core plugins to the new api
a0e1f5f is described below
commit a0e1f5f38ac16bd35f699fd37db27e26c554bdaf
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Thu Feb 24 17:00:32 2022 +0100
Switch a few core plugins to the new api
---
pom.xml | 17 ++-
.../BuildCacheMojosExecutionStrategy.java | 67 +++++----
.../org/apache/maven/buildcache/CacheContext.java | 2 +
.../apache/maven/buildcache/CacheController.java | 8 +-
.../maven/buildcache/CacheControllerImpl.java | 165 +++++++++++----------
.../org/apache/maven/buildcache/CacheDiff.java | 20 ++-
.../buildcache/CacheLifecycleParticipant.java | 1 +
.../org/apache/maven/buildcache/CacheResult.java | 2 +
.../org/apache/maven/buildcache/CacheUtils.java | 14 +-
.../buildcache/DefaultMultiModuleSupport.java | 66 +++++----
.../buildcache/DefaultNormalizedModelProvider.java | 62 ++++----
.../buildcache/DefaultProjectInputCalculator.java | 47 +++---
.../buildcache/DefaultRestoredArtifactHandler.java | 28 ++--
.../maven/buildcache/HttpCacheRepositoryImpl.java | 44 +++---
.../maven/buildcache/LifecyclePhasesHelper.java | 15 +-
.../maven/buildcache/LocalCacheRepositoryImpl.java | 49 +++---
.../maven/buildcache/MojoParametersListener.java | 5 +-
.../maven/buildcache/NormalizedModelProvider.java | 4 +-
.../maven/buildcache/PluginScanConfigImpl.java | 2 +-
.../maven/buildcache/RemoteCacheRepository.java | 5 +-
.../buildcache/RemoteCacheRepositoryProvider.java | 2 +-
.../maven/buildcache/RestoredArtifactHandler.java | 10 +-
.../maven/buildcache/ScanConfigProperties.java | 1 +
.../apache/maven/buildcache/WagonConfigurator.java | 18 +--
.../org/apache/maven/buildcache/WagonProvider.java | 4 +-
.../buildcache/WagonRemoteCacheRepository.java | 90 ++++++-----
.../org/apache/maven/buildcache/Xpp3DomUtils.java | 17 +--
.../buildcache/artifact/RestoredArtifact.java | 24 +--
.../maven/buildcache/checksum/DigestUtils.java | 47 +++---
.../apache/maven/buildcache/checksum/KeyUtils.java | 12 +-
.../buildcache/checksum/MavenProjectInput.java | 158 +++++++++++---------
.../apache/maven/buildcache/checksum/WalkKey.java | 4 +-
.../maven/buildcache/hash/CloseableBuffer.java | 8 +-
.../apache/maven/buildcache/hash/HashChecksum.java | 1 +
.../org/apache/maven/buildcache/hash/HexUtils.java | 9 +-
.../java/org/apache/maven/buildcache/hash/SHA.java | 1 +
.../maven/buildcache/hash/ThreadLocalBuffer.java | 4 +-
.../org/apache/maven/buildcache/hash/XXMM.java | 2 +-
.../org/apache/maven/buildcache/xml/Build.java | 26 ++--
.../maven/buildcache/xml/CacheConfigImpl.java | 40 +++--
.../org/apache/maven/buildcache/xml/DtoUtils.java | 11 +-
.../org/apache/maven/buildcache/BuildInfoTest.java | 6 +-
.../buildcache/checksum/MavenProjectInputTest.java | 47 +++---
.../maven/buildcache/checksum/SHAHashTest.java | 8 +
.../maven/buildcache/checksum/XXHashTest.java | 9 ++
.../apache/maven/buildcache/hash/HexUtilsTest.java | 2 +-
.../its/junit/IntegrationTestExtension.java | 35 +++--
47 files changed, 683 insertions(+), 536 deletions(-)
diff --git a/pom.xml b/pom.xml
index 25942d0..3c71790 100644
--- a/pom.xml
+++ b/pom.xml
@@ -58,7 +58,7 @@ under the License.
<wagonVersion>3.5.2-SNAPSHOT</wagonVersion>
<securityDispatcherVersion>2.0</securityDispatcherVersion>
<cipherVersion>2.0</cipherVersion>
- <modelloVersion>1.11</modelloVersion>
+ <modelloVersion>2.0.0</modelloVersion>
<jxpathVersion>1.3</jxpathVersion>
<resolverVersion>1.8.0-SNAPSHOT</resolverVersion>
<slf4jVersion>1.7.32</slf4jVersion>
@@ -157,9 +157,18 @@ under the License.
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-verifier</artifactId>
- <version>1.7.2</version>
+ <version>1.7.3-SNAPSHOT</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>animal-sniffer-annotations</artifactId>
+ <version>1.21</version>
+ <optional>true</optional>
+ <!-- if you are using badly written maven plugins then blame them and add
+ <scope>provided</scope>
+ -->
+ </dependency>
</dependencies>
<build>
@@ -237,7 +246,7 @@ under the License.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
- <version>1.20</version>
+ <version>1.21</version>
<configuration>
<signature>
<groupId>org.codehaus.mojo.signature</groupId>
@@ -268,7 +277,7 @@ under the License.
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
- <version>8.41.1</version>
+ <version>8.43</version>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
diff --git a/src/main/java/org/apache/maven/buildcache/BuildCacheMojosExecutionStrategy.java b/src/main/java/org/apache/maven/buildcache/BuildCacheMojosExecutionStrategy.java
index b79d2f6..19d9580 100644
--- a/src/main/java/org/apache/maven/buildcache/BuildCacheMojosExecutionStrategy.java
+++ b/src/main/java/org/apache/maven/buildcache/BuildCacheMojosExecutionStrategy.java
@@ -65,18 +65,22 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
private static final Logger LOGGER = LoggerFactory.getLogger( BuildCacheMojosExecutionStrategy.class );
private final CacheController cacheController;
+
private final CacheConfig cacheConfig;
+
private final MojoParametersListener mojoListener;
+
private final LifecyclePhasesHelper lifecyclePhasesHelper;
+
private final MavenPluginManager mavenPluginManager;
@Inject
public BuildCacheMojosExecutionStrategy(
- CacheController cacheController,
- CacheConfig cacheConfig,
- MojoParametersListener mojoListener,
- LifecyclePhasesHelper lifecyclePhasesHelper,
- MavenPluginManager mavenPluginManager )
+ CacheController cacheController,
+ CacheConfig cacheConfig,
+ MojoParametersListener mojoListener,
+ LifecyclePhasesHelper lifecyclePhasesHelper,
+ MavenPluginManager mavenPluginManager )
{
this.cacheController = cacheController;
this.cacheConfig = cacheConfig;
@@ -86,9 +90,9 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
}
public void execute( List<MojoExecution> mojoExecutions,
- MavenSession session,
- MojoExecutionRunner mojoExecutionRunner )
- throws LifecycleExecutionException
+ MavenSession session,
+ MojoExecutionRunner mojoExecutionRunner )
+ throws LifecycleExecutionException
{
final MavenProject project = session.getCurrentProject();
final Source source = getSource( mojoExecutions );
@@ -121,8 +125,8 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
for ( MojoExecution mojoExecution : mojoExecutions )
{
if ( source == Source.CLI
- || mojoExecution.getLifecyclePhase() == null
- || lifecyclePhasesHelper.isLaterPhaseThanClean( mojoExecution.getLifecyclePhase() ) )
+ || mojoExecution.getLifecyclePhase() == null
+ || lifecyclePhasesHelper.isLaterPhaseThanClean( mojoExecution.getLifecyclePhase() ) )
{
mojoExecutionRunner.run( mojoExecution );
}
@@ -138,8 +142,9 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
if ( cacheConfig.isFailFast() && !result.isSuccess() )
{
throw new LifecycleExecutionException(
- "Failed to restore project[" + getVersionlessProjectKey( project ) + "] from cache, failing build.",
- project );
+ "Failed to restore project[" + getVersionlessProjectKey( project )
+ + "] from cache, failing build.",
+ project );
}
}
@@ -160,9 +165,9 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
}
private boolean restoreProject( CacheResult cacheResult,
- List<MojoExecution> mojoExecutions,
- MojoExecutionRunner mojoExecutionRunner,
- CacheConfig cacheConfig ) throws LifecycleExecutionException
+ List<MojoExecution> mojoExecutions,
+ MojoExecutionRunner mojoExecutionRunner,
+ CacheConfig cacheConfig ) throws LifecycleExecutionException
{
final Build build = cacheResult.getBuildInfo();
final MavenProject project = cacheResult.getContext().getProject();
@@ -181,13 +186,13 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
if ( cacheController.isForcedExecution( project, cacheCandidate ) )
{
LOGGER.info( "Mojo execution is forced by project property: {}",
- cacheCandidate.getMojoDescriptor().getFullGoalName() );
+ cacheCandidate.getMojoDescriptor().getFullGoalName() );
mojoExecutionRunner.run( cacheCandidate );
}
else
{
restored = verifyCacheConsistency( cacheCandidate, build, project, session,
- mojoExecutionRunner, cacheConfig );
+ mojoExecutionRunner, cacheConfig );
if ( !restored )
{
break;
@@ -216,11 +221,11 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
}
private boolean verifyCacheConsistency( MojoExecution cacheCandidate,
- Build cachedBuild,
- MavenProject project,
- MavenSession session,
- MojoExecutionRunner mojoExecutionRunner,
- CacheConfig cacheConfig ) throws LifecycleExecutionException
+ Build cachedBuild,
+ MavenProject project,
+ MavenSession session,
+ MojoExecutionRunner mojoExecutionRunner,
+ CacheConfig cacheConfig ) throws LifecycleExecutionException
{
long createdTimestamp = System.currentTimeMillis();
boolean consistent = true;
@@ -235,10 +240,10 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
final String fullGoalName = cacheCandidate.getMojoDescriptor().getFullGoalName();
if ( completedExecution != null
- && !isParamsMatched( cacheCandidate, mojo, completedExecution ) )
+ && !isParamsMatched( cacheCandidate, mojo, completedExecution ) )
{
LOGGER.info( "Mojo cached parameters mismatch with actual, forcing full project build. Mojo: {}",
- fullGoalName );
+ fullGoalName );
consistent = false;
}
@@ -251,7 +256,7 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
if ( LOGGER.isDebugEnabled() )
{
LOGGER.debug( "Checked {}, resolved mojo: {}, cached params: {}",
- fullGoalName, mojo, completedExecution );
+ fullGoalName, mojo, completedExecution );
}
}
catch ( PluginContainerException | PluginConfigurationException e )
@@ -269,15 +274,15 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
else
{
LOGGER.info( "Skipping plugin execution (cached): {}",
- cacheCandidate.getMojoDescriptor().getFullGoalName() );
+ cacheCandidate.getMojoDescriptor().getFullGoalName() );
}
return consistent;
}
private boolean isParamsMatched( MojoExecution mojoExecution,
- Mojo mojo,
- CompletedExecution completedExecution )
+ Mojo mojo,
+ CompletedExecution completedExecution )
{
List<TrackedProperty> tracked = cacheConfig.getTrackedProperties( mojoExecution );
@@ -307,14 +312,14 @@ public class BuildCacheMojosExecutionStrategy implements MojosExecutionStrategy
if ( !StringUtils.equals( currentValue, trackedProperty.getSkipValue() ) )
{
LOGGER.info( "Plugin parameter mismatch found. Parameter: {}, expected: {}, actual: {}",
- propertyName, expectedValue, currentValue );
+ propertyName, expectedValue, currentValue );
return false;
}
else
{
LOGGER.warn( "Cache contains plugin execution with skip flag and might be incomplete. "
- + "Property: {}, execution {}",
- propertyName, mojoExecutionKey( mojoExecution ) );
+ + "Property: {}, execution {}",
+ propertyName, mojoExecutionKey( mojoExecution ) );
}
}
}
diff --git a/src/main/java/org/apache/maven/buildcache/CacheContext.java b/src/main/java/org/apache/maven/buildcache/CacheContext.java
index 0841aeb..d4092eb 100644
--- a/src/main/java/org/apache/maven/buildcache/CacheContext.java
+++ b/src/main/java/org/apache/maven/buildcache/CacheContext.java
@@ -31,7 +31,9 @@ public class CacheContext
{
private final MavenProject project;
+
private final ProjectsInputInfo inputInfo;
+
private final MavenSession session;
public CacheContext( MavenProject project, ProjectsInputInfo inputInfo, MavenSession session )
diff --git a/src/main/java/org/apache/maven/buildcache/CacheController.java b/src/main/java/org/apache/maven/buildcache/CacheController.java
index b866bae..4b0ea01 100644
--- a/src/main/java/org/apache/maven/buildcache/CacheController.java
+++ b/src/main/java/org/apache/maven/buildcache/CacheController.java
@@ -32,14 +32,14 @@ public interface CacheController
{
CacheResult findCachedBuild( MavenSession session,
- MavenProject project,
- List<MojoExecution> mojoExecutions );
+ MavenProject project,
+ List<MojoExecution> mojoExecutions );
boolean restoreProjectArtifacts( CacheResult cacheResult );
void save( CacheResult cacheResult,
- List<MojoExecution> mojoExecutions,
- Map<String, MojoExecutionEvent> executionEvents );
+ List<MojoExecution> mojoExecutions,
+ Map<String, MojoExecutionEvent> executionEvents );
boolean isForcedExecution( MavenProject project, MojoExecution execution );
diff --git a/src/main/java/org/apache/maven/buildcache/CacheControllerImpl.java b/src/main/java/org/apache/maven/buildcache/CacheControllerImpl.java
index c9a7936..620b474 100644
--- a/src/main/java/org/apache/maven/buildcache/CacheControllerImpl.java
+++ b/src/main/java/org/apache/maven/buildcache/CacheControllerImpl.java
@@ -106,6 +106,7 @@ public class CacheControllerImpl implements CacheController
{
public static final String FILE_SEPARATOR_SUBST = "_";
+
/**
* Prefix for generated sources stored as a separate artifact in cache
*/
@@ -114,31 +115,43 @@ public class CacheControllerImpl implements CacheController
private static final Logger LOGGER = LoggerFactory.getLogger( CacheControllerImpl.class );
private final MavenProjectHelper projectHelper;
+
private final ArtifactHandlerManager artifactHandlerManager;
+
private final XmlService xmlService;
+
private final CacheConfig cacheConfig;
+
private final LocalCacheRepository localCache;
+
private final RemoteCacheRepository remoteCache;
+
private final ConcurrentMap<String, CacheResult> cacheResults = new ConcurrentHashMap<>();
+
private final LifecyclePhasesHelper lifecyclePhasesHelper;
+
private volatile Map<String, MavenProject> projectIndex;
+
private final ProjectInputCalculator projectInputCalculator;
+
private final RestoredArtifactHandler restoreArtifactHandler;
+
private volatile Scm scm;
@Inject
+ @SuppressWarnings( "checkstyle:ParameterNumber" )
public CacheControllerImpl(
- MavenProjectHelper projectHelper,
- RepositorySystem repoSystem,
- ArtifactHandlerManager artifactHandlerManager,
- XmlService xmlService,
- LocalCacheRepository localCache,
- RemoteCacheRepository remoteCache,
- CacheConfig cacheConfig,
- ProjectInputCalculator projectInputCalculator,
- RestoredArtifactHandler restoreArtifactHandler,
- LifecyclePhasesHelper lifecyclePhasesHelper,
- MavenSession session )
+ MavenProjectHelper projectHelper,
+ RepositorySystem repoSystem,
+ ArtifactHandlerManager artifactHandlerManager,
+ XmlService xmlService,
+ LocalCacheRepository localCache,
+ RemoteCacheRepository remoteCache,
+ CacheConfig cacheConfig,
+ ProjectInputCalculator projectInputCalculator,
+ RestoredArtifactHandler restoreArtifactHandler,
+ LifecyclePhasesHelper lifecyclePhasesHelper,
+ MavenSession session )
{
this.projectHelper = projectHelper;
this.localCache = localCache;
@@ -154,7 +167,7 @@ public class CacheControllerImpl implements CacheController
@Override
@Nonnull
public CacheResult findCachedBuild( MavenSession session, MavenProject project,
- List<MojoExecution> mojoExecutions )
+ List<MojoExecution> mojoExecutions )
{
final String highestRequestPhase = CacheUtils.getLast( mojoExecutions ).getLifecyclePhase();
if ( !lifecyclePhasesHelper.isLaterPhaseThanClean( highestRequestPhase ) )
@@ -206,7 +219,7 @@ public class CacheControllerImpl implements CacheController
LOGGER.error( "Cannot read cached remote build", e );
}
return cachedBuild.map( build -> failure( build, context ) )
- .orElseGet( () -> empty( context ) );
+ .orElseGet( () -> empty( context ) );
}
private CacheResult findLocalBuild( List<MojoExecution> mojoExecutions, CacheContext context )
@@ -225,7 +238,7 @@ public class CacheControllerImpl implements CacheController
LOGGER.error( "Cannot read local build", e );
}
return localBuild.map( build -> failure( build, context ) )
- .orElseGet( () -> empty( context ) );
+ .orElseGet( () -> empty( context ) );
}
private CacheResult analyzeResult( CacheContext context, List<MojoExecution> mojoExecutions, Build build )
@@ -241,9 +254,10 @@ public class CacheControllerImpl implements CacheController
if ( !CACHE_IMPLEMENTATION_VERSION.equals( cacheImplementationVersion ) )
{
LOGGER.warn(
- "Maven and cached build implementations mismatch, caching might not work correctly. "
- + "Implementation version: " + CACHE_IMPLEMENTATION_VERSION + ", cached build: {}",
- build.getCacheImplementationVersion() );
+ "Maven and cached build implementations mismatch, caching might not work correctly. "
+ + "Implementation version: " + CACHE_IMPLEMENTATION_VERSION
+ + ", cached build: {}",
+ build.getCacheImplementationVersion() );
}
List<MojoExecution> cachedSegment = lifecyclePhasesHelper.getCachedSegment( mojoExecutions, build );
@@ -251,7 +265,7 @@ public class CacheControllerImpl implements CacheController
if ( !missingMojos.isEmpty() )
{
LOGGER.warn( "Cached build doesn't contains all requested plugin executions "
- + "(missing: {}), cannot restore", missingMojos );
+ + "(missing: {}), cannot restore", missingMojos );
return failure( build, context );
}
@@ -263,10 +277,10 @@ public class CacheControllerImpl implements CacheController
final String highestRequestPhase = CacheUtils.getLast( mojoExecutions ).getLifecyclePhase();
if ( lifecyclePhasesHelper.isLaterPhaseThanBuild( highestRequestPhase, build )
- && !canIgnoreMissingSegment( build, mojoExecutions ) )
+ && !canIgnoreMissingSegment( build, mojoExecutions ) )
{
LOGGER.info( "Project restored partially. Highest cached goal: {}, requested: {}",
- build.getHighestCompletedGoal(), highestRequestPhase );
+ build.getHighestCompletedGoal(), highestRequestPhase );
return partialSuccess( build, context );
}
@@ -284,7 +298,7 @@ public class CacheControllerImpl implements CacheController
private boolean canIgnoreMissingSegment( Build info, List<MojoExecution> mojoExecutions )
{
final List<MojoExecution> postCachedSegment = lifecyclePhasesHelper.getPostCachedSegment( mojoExecutions,
- info );
+ info );
for ( MojoExecution mojoExecution : postCachedSegment )
{
if ( !cacheConfig.canIgnore( mojoExecution ) )
@@ -314,14 +328,14 @@ public class CacheControllerImpl implements CacheController
artifactInfo.setVersion( project.getVersion() );
// TODO if remote is forced, probably need to refresh or reconcile all files
final Future<File> downloadTask = createDownloadTask(
- cacheResult,
- context,
- project,
- artifactInfo,
- originalVersion );
+ cacheResult,
+ context,
+ project,
+ artifactInfo,
+ originalVersion );
restoredProjectArtifact = restoredArtifact( project.getArtifact(), artifactInfo.getType(),
- artifactInfo.getClassifier(),
- downloadTask );
+ artifactInfo.getClassifier(),
+ downloadTask );
}
for ( Artifact attachedArtifactInfo : build.getAttachedArtifacts() )
@@ -338,24 +352,24 @@ public class CacheControllerImpl implements CacheController
{
// generated sources artifact
final Path attachedArtifactFile = localCache.getArtifactFile( context,
- cacheResult.getSource(), attachedArtifactInfo );
+ cacheResult.getSource(), attachedArtifactInfo );
restoreGeneratedSources( attachedArtifactInfo, attachedArtifactFile, project );
}
}
else
{
Future<File> downloadTask = createDownloadTask(
- cacheResult,
- context,
- project,
- attachedArtifactInfo,
- originalVersion );
+ cacheResult,
+ context,
+ project,
+ attachedArtifactInfo,
+ originalVersion );
final RestoredArtifact restoredAttachedArtifact = restoredArtifact(
- restoredProjectArtifact == null ? project.getArtifact()
- : restoredProjectArtifact,
- attachedArtifactInfo.getType(),
- attachedArtifactInfo.getClassifier(),
- downloadTask );
+ restoredProjectArtifact == null ? project.getArtifact()
+ : restoredProjectArtifact,
+ attachedArtifactInfo.getType(),
+ attachedArtifactInfo.getClassifier(),
+ downloadTask );
restoredAttachedArtifacts.add( restoredAttachedArtifact );
}
}
@@ -381,8 +395,8 @@ public class CacheControllerImpl implements CacheController
* with restored from cache artifacts
*/
private RestoredArtifact restoredArtifact( org.apache.maven.artifact.Artifact parent, String artifactType,
- String artifactClassifier,
- Future<File> artifactFile )
+ String artifactClassifier,
+ Future<File> artifactFile )
{
ArtifactHandler handler = null;
@@ -398,30 +412,30 @@ public class CacheControllerImpl implements CacheController
// todo: probably need update download url to cache
RestoredArtifact artifact = new RestoredArtifact( parent, artifactFile, artifactType, artifactClassifier,
- handler );
+ handler );
artifact.setResolved( true );
return artifact;
}
private Future<File> createDownloadTask( CacheResult cacheResult, CacheContext context, MavenProject project,
- Artifact artifact, String originalVersion )
+ Artifact artifact, String originalVersion )
{
final FutureTask<File> downloadTask = new FutureTask<>( () ->
{
LOGGER.debug( "Downloading artifact {}", artifact.getArtifactId() );
final Path artifactFile = localCache.getArtifactFile( context, cacheResult.getSource(),
- artifact );
+ artifact );
if ( !Files.exists( artifactFile ) )
{
throw new FileNotFoundException(
- "Missing file for cached build, cannot restore. File: " + artifactFile );
+ "Missing file for cached build, cannot restore. File: " + artifactFile );
}
LOGGER.debug( "Downloaded artifact " + artifact.getArtifactId() + " to: " + artifactFile );
return restoreArtifactHandler.adjustArchiveArtifactVersion(
- project,
- originalVersion,
- artifactFile ).toFile();
+ project,
+ originalVersion,
+ artifactFile ).toFile();
} );
if ( !cacheConfig.isLazyRestore() )
{
@@ -432,7 +446,7 @@ public class CacheControllerImpl implements CacheController
@Override
public void save( CacheResult cacheResult, List<MojoExecution> mojoExecutions,
- Map<String, MojoExecutionEvent> executionEvents )
+ Map<String, MojoExecutionEvent> executionEvents )
{
CacheContext context = cacheResult.getContext();
@@ -457,7 +471,7 @@ public class CacheControllerImpl implements CacheController
attachGeneratedSources( project );
attachOutputs( project );
attachedArtifacts = project.getAttachedArtifacts() != null
- ? project.getAttachedArtifacts() : Collections.emptyList();
+ ? project.getAttachedArtifacts() : Collections.emptyList();
attachedArtifactDtos = artifactDtos( attachedArtifacts, algorithm );
projectArtifactDto = artifactDto( project.getArtifact(), algorithm );
}
@@ -471,7 +485,7 @@ public class CacheControllerImpl implements CacheController
List<CompletedExecution> completedExecution = buildExecutionInfo( mojoExecutions, executionEvents );
final Build build = new Build( session.getGoals(), projectArtifactDto, attachedArtifactDtos,
- context.getInputInfo(), completedExecution, hashFactory.getAlgorithm() );
+ context.getInputInfo(), completedExecution, hashFactory.getAlgorithm() );
populateGitInfo( build, session );
build.getDto().set_final( cacheConfig.isSaveFinal() );
cacheResults.put( getVersionlessProjectKey( project ), rebuilded( cacheResult, build ) );
@@ -488,7 +502,7 @@ public class CacheControllerImpl implements CacheController
for ( org.apache.maven.artifact.Artifact attachedArtifact : attachedArtifacts )
{
if ( attachedArtifact.getFile() != null && isOutputArtifact(
- attachedArtifact.getFile().getName() ) )
+ attachedArtifact.getFile().getName() ) )
{
localCache.saveArtifactFile( cacheResult, attachedArtifact );
}
@@ -536,25 +550,25 @@ public class CacheControllerImpl implements CacheController
final ProjectsInputInfo baselineInputs = baseline.getDto().getProjectsInputInfo();
final String checksum = baselineInputs.getChecksum();
Files.write( reportOutputDir.resolve( "buildinfo-baseline-" + checksum + ".xml" ),
- xmlService.toBytes( baseline.getDto() ), TRUNCATE_EXISTING, CREATE );
+ xmlService.toBytes( baseline.getDto() ), TRUNCATE_EXISTING, CREATE );
Files.write( reportOutputDir.resolve( "buildinfo-" + checksum + ".xml" ),
- xmlService.toBytes( build.getDto() ), TRUNCATE_EXISTING, CREATE );
+ xmlService.toBytes( build.getDto() ), TRUNCATE_EXISTING, CREATE );
Files.write( reportOutputDir.resolve( "buildsdiff-" + checksum + ".xml" ),
- xmlService.toBytes( diff ), TRUNCATE_EXISTING, CREATE );
+ xmlService.toBytes( diff ), TRUNCATE_EXISTING, CREATE );
final Optional<DigestItem> pom = CacheDiff.findPom( build.getDto().getProjectsInputInfo() );
if ( pom.isPresent() )
{
Files.write( reportOutputDir.resolve( "effective-pom-" + checksum + ".xml" ),
- pom.get().getValue().getBytes( StandardCharsets.UTF_8 ),
- TRUNCATE_EXISTING, CREATE );
+ pom.get().getValue().getBytes( StandardCharsets.UTF_8 ),
+ TRUNCATE_EXISTING, CREATE );
}
final Optional<DigestItem> baselinePom = CacheDiff.findPom( baselineInputs );
if ( baselinePom.isPresent() )
{
Files.write( reportOutputDir.resolve(
- "effective-pom-baseline-" + baselineInputs.getChecksum() + ".xml" ),
- baselinePom.get().getValue().getBytes( StandardCharsets.UTF_8 ),
- TRUNCATE_EXISTING, CREATE );
+ "effective-pom-baseline-" + baselineInputs.getChecksum() + ".xml" ),
+ baselinePom.get().getValue().getBytes( StandardCharsets.UTF_8 ),
+ TRUNCATE_EXISTING, CREATE );
}
}
catch ( IOException e )
@@ -569,7 +583,7 @@ public class CacheControllerImpl implements CacheController
}
private List<Artifact> artifactDtos( List<org.apache.maven.artifact.Artifact> attachedArtifacts,
- HashAlgorithm digest ) throws IOException
+ HashAlgorithm digest ) throws IOException
{
List<Artifact> result = new ArrayList<>();
for ( org.apache.maven.artifact.Artifact attachedArtifact : attachedArtifacts )
@@ -583,7 +597,7 @@ public class CacheControllerImpl implements CacheController
}
private Artifact artifactDto( org.apache.maven.artifact.Artifact projectArtifact,
- HashAlgorithm algorithm ) throws IOException
+ HashAlgorithm algorithm ) throws IOException
{
final Artifact dto = DtoUtils.createDto( projectArtifact );
if ( projectArtifact.getFile() != null && projectArtifact.getFile().isFile() )
@@ -596,14 +610,14 @@ public class CacheControllerImpl implements CacheController
}
private List<CompletedExecution> buildExecutionInfo( List<MojoExecution> mojoExecutions,
- Map<String, MojoExecutionEvent> executionEvents )
+ Map<String, MojoExecutionEvent> executionEvents )
{
List<CompletedExecution> list = new ArrayList<>();
for ( MojoExecution mojoExecution : mojoExecutions )
{
final String executionKey = CacheUtils.mojoExecutionKey( mojoExecution );
final MojoExecutionEvent executionEvent = executionEvents != null ? executionEvents.get( executionKey )
- : null;
+ : null;
CompletedExecution executionInfo = new CompletedExecution();
executionInfo.setExecutionKey( executionKey );
executionInfo.setMojoClassName( mojoExecution.getMojoDescriptor().getImplementation() );
@@ -656,14 +670,14 @@ public class CacheControllerImpl implements CacheController
if ( tracked )
{
throw new IllegalArgumentException( "Property configured in cache introspection config "
- + "for " + mojo + " is not accessible: " + propertyName );
+ + "for " + mojo + " is not accessible: " + propertyName );
}
}
}
}
private boolean isExcluded( String propertyName, boolean logAll, List<PropertyName> excludedProperties,
- List<PropertyName> forceLogProperties )
+ List<PropertyName> forceLogProperties )
{
if ( !forceLogProperties.isEmpty() )
{
@@ -705,7 +719,7 @@ public class CacheControllerImpl implements CacheController
}
private boolean isCachedSegmentPropertiesPresent( MavenProject project, Build build,
- List<MojoExecution> mojoExecutions )
+ List<MojoExecution> mojoExecutions )
{
for ( MojoExecution mojoExecution : mojoExecutions )
{
@@ -716,14 +730,14 @@ public class CacheControllerImpl implements CacheController
if ( cachedExecution == null )
{
LOGGER.info( "Execution is not cached. Plugin: {}, goal {}",
- mojoExecution.getExecutionId(), mojoExecution.getGoal() );
+ mojoExecution.getExecutionId(), mojoExecution.getGoal() );
return false;
}
if ( !DtoUtils.containsAllProperties( cachedExecution, trackedProperties ) )
{
LOGGER.info( "Build info doesn't match rules. Plugin: {}",
- mojoExecution.getExecutionId() );
+ mojoExecution.getExecutionId() );
return false;
}
}
@@ -747,7 +761,8 @@ public class CacheControllerImpl implements CacheController
String alwaysRunPlugin = tokens[0];
String alwaysRunGoal = tokens.length == 1 ? "*" : tokens[1];
if ( Objects.equals( execution.getPlugin().getArtifactId(), alwaysRunPlugin )
- && ( "*".equals( alwaysRunGoal ) || Objects.equals( execution.getGoal(), alwaysRunGoal ) ) )
+ && ( "*".equals( alwaysRunGoal )
+ || Objects.equals( execution.getGoal(), alwaysRunGoal ) ) )
{
return true;
}
@@ -846,7 +861,7 @@ public class CacheControllerImpl implements CacheController
}
private void restoreGeneratedSources( Artifact artifact, Path artifactFilePath, MavenProject project )
- throws IOException
+ throws IOException
{
final Path targetDir = Paths.get( project.getBuild().getDirectory() );
final Path outputDir = classifierToPath( targetDir, artifact.getClassifier() );
@@ -861,7 +876,7 @@ public class CacheControllerImpl implements CacheController
CacheUtils.unzip( artifactFilePath, outputDir );
}
- //TODO: move to config
+ // TODO: move to config
public void attachGeneratedSources( MavenProject project ) throws IOException
{
final Path targetDir = Paths.get( project.getBuild().getDirectory() );
@@ -886,9 +901,9 @@ public class CacheControllerImpl implements CacheController
{
final Path sourceRootPath = Paths.get( sourceRoot );
if ( Files.isDirectory( sourceRootPath )
- && sourceRootPath.startsWith( targetDir )
- && !( sourceRootPath.startsWith( generatedSourcesDir )
- || sourceRootPath.startsWith( generatedTestSourcesDir ) ) )
+ && sourceRootPath.startsWith( targetDir )
+ && !( sourceRootPath.startsWith( generatedSourcesDir )
+ || sourceRootPath.startsWith( generatedTestSourcesDir ) ) )
{ // dir within target
attachDirIfNotEmpty( sourceRootPath, targetDir, project );
}
diff --git a/src/main/java/org/apache/maven/buildcache/CacheDiff.java b/src/main/java/org/apache/maven/buildcache/CacheDiff.java
index f740faa..d3b33b3 100644
--- a/src/main/java/org/apache/maven/buildcache/CacheDiff.java
+++ b/src/main/java/org/apache/maven/buildcache/CacheDiff.java
@@ -44,8 +44,11 @@ public class CacheDiff
{
private final CacheConfig config;
+
private final Build current;
+
private final Build baseline;
+
private final LinkedList<Mismatch> report;
public CacheDiff( Build current, Build baseline, CacheConfig config )
@@ -126,7 +129,8 @@ public class CacheDiff
addNewMismatch( "source files",
"Remote and local cache contain different sets of input files. "
- + "Added files: " + currentVsBaseline + ". Removed files: " + baselineVsCurrent,
+ + "Added files: " + currentVsBaseline + ". Removed files: "
+ + baselineVsCurrent,
"To match remote and local caches should have identical file sets."
+ " Unnecessary and transient files must be filtered out to make file sets match"
+ " - see configuration guide" );
@@ -182,7 +186,8 @@ public class CacheDiff
+ "Added dependencies: " + currentVsBaseline + ". Removed dependencies: "
+ baselineVsCurrent,
"Remote and local builds should have identical dependencies. "
- + "The difference manifests changes in downstream dependencies or introduced snapshots." );
+ + "The difference manifests changes in downstream dependencies or "
+ + "introduced snapshots." );
return;
}
@@ -197,7 +202,8 @@ public class CacheDiff
addNewMismatch( dependencyKey, currentDependency.getHash(), baselineDependency.getHash(),
"Downstream project or snapshot changed",
"Find downstream project and investigate difference in the downstream project. "
- + "Enable fail fast mode and single threaded execution to simplify debug." );
+ + "Enable fail fast mode and single threaded execution to "
+ + "simplify debug." );
}
}
}
@@ -238,8 +244,8 @@ public class CacheDiff
currentExecution.getExecutionKey(),
"Cached build doesn't contain plugin " + currentExecution.getExecutionKey(),
"Different set of plugins produces different build results. "
- + "Filter out non-critical plugins or make sure remote cache always run full build "
- + "with all plugins" );
+ + "Filter out non-critical plugins or make sure remote cache always "
+ + "run full build with all plugins" );
continue;
}
@@ -283,8 +289,8 @@ public class CacheDiff
"Plugin: " + current.getExecutionKey()
+ " has mismatch in tracked property and cannot be reused",
"Align properties between remote and local build or remove property from tracked "
- + "list if mismatch could be tolerated. In some cases it is possible to add skip value "
- + "to ignore lax mismatch" );
+ + "list if mismatch could be tolerated. In some cases it is possible to add "
+ + "skip value to ignore lax mismatch" );
}
}
}
diff --git a/src/main/java/org/apache/maven/buildcache/CacheLifecycleParticipant.java b/src/main/java/org/apache/maven/buildcache/CacheLifecycleParticipant.java
index 4b46266..1602cbe 100644
--- a/src/main/java/org/apache/maven/buildcache/CacheLifecycleParticipant.java
+++ b/src/main/java/org/apache/maven/buildcache/CacheLifecycleParticipant.java
@@ -33,6 +33,7 @@ public class CacheLifecycleParticipant extends AbstractMavenLifecycleParticipant
{
private final CacheConfig cacheConfig;
+
private final CacheController cacheController;
@Inject
diff --git a/src/main/java/org/apache/maven/buildcache/CacheResult.java b/src/main/java/org/apache/maven/buildcache/CacheResult.java
index 65ad7a8..982ced5 100644
--- a/src/main/java/org/apache/maven/buildcache/CacheResult.java
+++ b/src/main/java/org/apache/maven/buildcache/CacheResult.java
@@ -30,7 +30,9 @@ public class CacheResult
{
private final RestoreStatus status;
+
private final Build build;
+
private final CacheContext context;
private CacheResult( RestoreStatus status, Build build, CacheContext context )
diff --git a/src/main/java/org/apache/maven/buildcache/CacheUtils.java b/src/main/java/org/apache/maven/buildcache/CacheUtils.java
index d02d08e..21364b5 100644
--- a/src/main/java/org/apache/maven/buildcache/CacheUtils.java
+++ b/src/main/java/org/apache/maven/buildcache/CacheUtils.java
@@ -95,11 +95,11 @@ public class CacheUtils
public static String mojoExecutionKey( MojoExecution mojo )
{
return StringUtils.join( Arrays.asList(
- StringUtils.defaultIfEmpty( mojo.getExecutionId(), "emptyExecId" ),
- StringUtils.defaultIfEmpty( mojo.getGoal(), "emptyGoal" ),
- StringUtils.defaultIfEmpty( mojo.getLifecyclePhase(), "emptyLifecyclePhase" ),
- StringUtils.defaultIfEmpty( mojo.getArtifactId(), "emptyArtifactId" ),
- StringUtils.defaultIfEmpty( mojo.getGroupId(), "emptyGroupId" ) ), ":" );
+ StringUtils.defaultIfEmpty( mojo.getExecutionId(), "emptyExecId" ),
+ StringUtils.defaultIfEmpty( mojo.getGoal(), "emptyGoal" ),
+ StringUtils.defaultIfEmpty( mojo.getLifecyclePhase(), "emptyLifecyclePhase" ),
+ StringUtils.defaultIfEmpty( mojo.getArtifactId(), "emptyArtifactId" ),
+ StringUtils.defaultIfEmpty( mojo.getGroupId(), "emptyGroupId" ) ), ":" );
}
public static Path getMultimoduleRoot( MavenSession session )
@@ -158,7 +158,7 @@ public class CacheUtils
SessionData data = session.getRepositorySession().getData();
while ( true )
{
- T t = ( T ) data.get( key );
+ T t = (T) data.get( key );
if ( t == null )
{
t = supplier.get();
@@ -190,7 +190,7 @@ public class CacheUtils
@Override
public FileVisitResult visitFile( Path path, BasicFileAttributes basicFileAttributes )
- throws IOException
+ throws IOException
{
final ZipEntry zipEntry = new ZipEntry( dir.relativize( path ).toString() );
zipOutputStream.putNextEntry( zipEntry );
diff --git a/src/main/java/org/apache/maven/buildcache/DefaultMultiModuleSupport.java b/src/main/java/org/apache/maven/buildcache/DefaultMultiModuleSupport.java
index e40924c..62f027e 100644
--- a/src/main/java/org/apache/maven/buildcache/DefaultMultiModuleSupport.java
+++ b/src/main/java/org/apache/maven/buildcache/DefaultMultiModuleSupport.java
@@ -55,17 +55,21 @@ public class DefaultMultiModuleSupport implements MultiModuleSupport
private static final Logger LOGGER = LoggerFactory.getLogger( DefaultMultiModuleSupport.class );
private final ProjectBuilder projectBuilder;
+
private final CacheConfig cacheConfig;
+
private final MavenSession session;
private volatile boolean built;
+
private volatile Map<String, MavenProject> projectMap;
+
private volatile Map<String, MavenProject> sessionProjectMap;
@Inject
public DefaultMultiModuleSupport( ProjectBuilder projectBuilder,
- CacheConfig cacheConfig,
- MavenSession session )
+ CacheConfig cacheConfig,
+ MavenSession session )
{
this.projectBuilder = projectBuilder;
this.cacheConfig = cacheConfig;
@@ -76,14 +80,14 @@ public class DefaultMultiModuleSupport implements MultiModuleSupport
public boolean isPartOfSession( String groupId, String artifactId, String version )
{
return getProjectMap( session )
- .containsKey( KeyUtils.getProjectKey( groupId, artifactId, version ) );
+ .containsKey( KeyUtils.getProjectKey( groupId, artifactId, version ) );
}
@Override
public Optional<MavenProject> tryToResolveProject( String groupId, String artifactId, String version )
{
return Optional.ofNullable( getMultiModuleProjectsMap()
- .get( KeyUtils.getProjectKey( groupId, artifactId, version ) ) );
+ .get( KeyUtils.getProjectKey( groupId, artifactId, version ) ) );
}
@Override
@@ -91,7 +95,7 @@ public class DefaultMultiModuleSupport implements MultiModuleSupport
{
String projectKey = KeyUtils.getProjectKey( groupId, artifactId, version );
return getProjectMap( session ).containsKey( projectKey )
- || getMultiModuleProjectsMap().containsKey( projectKey );
+ || getMultiModuleProjectsMap().containsKey( projectKey );
}
private Map<String, MavenProject> getProjectMap( MavenSession session )
@@ -101,8 +105,8 @@ public class DefaultMultiModuleSupport implements MultiModuleSupport
return sessionProjectMap;
}
sessionProjectMap = session.getProjects().stream().collect( Collectors.toMap(
- KeyUtils::getProjectKey,
- Function.identity() ) );
+ KeyUtils::getProjectKey,
+ Function.identity() ) );
return sessionProjectMap;
}
@@ -133,9 +137,9 @@ public class DefaultMultiModuleSupport implements MultiModuleSupport
}
Optional<Discovery> multiModuleDiscovery = Optional.ofNullable( cacheConfig.getMultiModule() )
- .map( MultiModule::getDiscovery );
+ .map( MultiModule::getDiscovery );
- //no discovery configuration, use only projects in session
+ // no discovery configuration, use only projects in session
if ( !multiModuleDiscovery.isPresent() )
{
projectMap = buildProjectMap( session.getProjects() );
@@ -143,18 +147,18 @@ public class DefaultMultiModuleSupport implements MultiModuleSupport
}
Set<String> scanProfiles = new TreeSet<>(
- multiModuleDiscovery
- .map( Discovery::getScanProfiles )
- .orElse( Collections.emptyList() ) );
+ multiModuleDiscovery
+ .map( Discovery::getScanProfiles )
+ .orElse( Collections.emptyList() ) );
MavenProject currentProject = session.getCurrentProject();
File multiModulePomFile = getMultiModulePomFile( session );
ProjectBuildingRequest projectBuildingRequest = currentProject.getProjectBuildingRequest();
boolean profilesMatched = projectBuildingRequest.getActiveProfileIds().containsAll( scanProfiles );
- //we are building from root with the same profiles, no need to re-scan the whole multi-module project
+ // we are building from root with the same profiles, no need to re-scan the whole multi-module project
if ( currentProject.getFile().getAbsolutePath().equals( multiModulePomFile.getAbsolutePath() )
- && profilesMatched )
+ && profilesMatched )
{
projectMap = buildProjectMap( session.getProjects() );
return;
@@ -163,34 +167,34 @@ public class DefaultMultiModuleSupport implements MultiModuleSupport
long t0 = System.currentTimeMillis();
ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest( projectBuildingRequest );
- //clear properties because after first build request some properties could be set to profiles
- //these properties could change effective pom when we try to rebuild whole multi module project again
- //for example the first model build process do not resolve ${os.detected.classifier}
- //but once build completed this property is set to profile
- //if we try to rebuild model for the whole project here string interpolator replaces this value
- //and effective pom could be different (depending on OS) if this property is used in pom.xml
+ // clear properties because after first build request some properties could be set to profiles
+ // these properties could change effective pom when we try to rebuild whole multi module project again
+ // for example the first model build process do not resolve ${os.detected.classifier}
+ // but once build completed this property is set to profile
+ // if we try to rebuild model for the whole project here string interpolator replaces this value
+ // and effective pom could be different (depending on OS) if this property is used in pom.xml
buildingRequest.setProfiles(
- buildingRequest.getProfiles().stream()
- .peek( it -> it.setProperties( new Properties() ) )
- .collect( Collectors.toList() ) );
+ buildingRequest.getProfiles().stream()
+ .peek( it -> it.setProperties( new Properties() ) )
+ .collect( Collectors.toList() ) );
if ( !profilesMatched )
{
Set<String> profiles = new LinkedHashSet<>( buildingRequest.getActiveProfileIds() );
- //remove duplicates
+ // remove duplicates
profiles.addAll( scanProfiles );
buildingRequest.setActiveProfileIds( new ArrayList<>( profiles ) );
}
try
{
List<ProjectBuildingResult> buildingResults = projectBuilder.build(
- Collections.singletonList( multiModulePomFile ),
- true,
- buildingRequest );
+ Collections.singletonList( multiModulePomFile ),
+ true,
+ buildingRequest );
LOGGER.info( "Multi module project model calculated [activeProfiles={}, time={} ms ",
- buildingRequest.getActiveProfileIds(), System.currentTimeMillis() - t0 );
+ buildingRequest.getActiveProfileIds(), System.currentTimeMillis() - t0 );
List<MavenProject> projectList = buildingResults.stream().map( ProjectBuildingResult::getProject )
- .collect( Collectors.toList() );
+ .collect( Collectors.toList() );
projectMap = buildProjectMap( projectList );
}
@@ -207,8 +211,8 @@ public class DefaultMultiModuleSupport implements MultiModuleSupport
private Map<String, MavenProject> buildProjectMap( List<MavenProject> projectList )
{
return projectList.stream().collect( Collectors.toMap(
- KeyUtils::getProjectKey,
- Function.identity() ) );
+ KeyUtils::getProjectKey,
+ Function.identity() ) );
}
private static File getMultiModulePomFile( MavenSession session )
diff --git a/src/main/java/org/apache/maven/buildcache/DefaultNormalizedModelProvider.java b/src/main/java/org/apache/maven/buildcache/DefaultNormalizedModelProvider.java
index 4924702..5b100bd 100644
--- a/src/main/java/org/apache/maven/buildcache/DefaultNormalizedModelProvider.java
+++ b/src/main/java/org/apache/maven/buildcache/DefaultNormalizedModelProvider.java
@@ -44,7 +44,9 @@ public class DefaultNormalizedModelProvider implements NormalizedModelProvider
private static final String NORMALIZED_VERSION = "cache-extension-version";
private final CacheConfig cacheConfig;
+
private final MultiModuleSupport multiModuleSupport;
+
private final ConcurrentMap<String, Model> modelCache = new ConcurrentHashMap<>();
@Inject
@@ -59,26 +61,26 @@ public class DefaultNormalizedModelProvider implements NormalizedModelProvider
{
MavenProject validatedProject = Objects.requireNonNull( project, "project" );
return modelCache.computeIfAbsent( BuilderCommon.getKey( validatedProject ),
- k -> normalizedModelInner( validatedProject ) );
+ k -> normalizedModelInner( validatedProject ) );
}
private Model normalizedModelInner( MavenProject project )
{
- //prefer project from multimodule than reactor because effective pom of reactor project
- //could be built with maven local/remote dependencies but not with artifacts from cache
+ // prefer project from multimodule than reactor because effective pom of reactor project
+ // could be built with maven local/remote dependencies but not with artifacts from cache
MavenProject projectToNormalize = multiModuleSupport.tryToResolveProject(
- project.getGroupId(),
- project.getArtifactId(),
- project.getVersion() )
- .orElse( project );
+ project.getGroupId(),
+ project.getArtifactId(),
+ project.getVersion() )
+ .orElse( project );
Model prototype = projectToNormalize.getModel();
- //TODO validate status of the model - it should be in resolved state
+ // TODO validate status of the model - it should be in resolved state
Model resultModel = new Model();
resultModel.setGroupId( prototype.getGroupId() );
resultModel.setArtifactId( prototype.getArtifactId() );
- //does not make sense to add project version to calculate hash
+ // does not make sense to add project version to calculate hash
resultModel.setVersion( NORMALIZED_VERSION );
resultModel.setModules( prototype.getModules() );
@@ -119,31 +121,29 @@ public class DefaultNormalizedModelProvider implements NormalizedModelProvider
}
return plugins.stream().map(
- plugin ->
- {
- Plugin copy = plugin.clone();
- List<String> excludeProperties = cacheConfig.getEffectivePomExcludeProperties( copy );
- removeBlacklistedAttributes( copy.getConfiguration(), excludeProperties );
- for ( PluginExecution execution : copy.getExecutions() )
- {
- removeBlacklistedAttributes( execution.getConfiguration(), excludeProperties );
- }
-
- copy.setDependencies(
- normalizeDependencies(
- copy.getDependencies()
+ plugin ->
+ {
+ Plugin copy = plugin.clone();
+ List<String> excludeProperties = cacheConfig.getEffectivePomExcludeProperties( copy );
+ removeBlacklistedAttributes( copy.getConfiguration(), excludeProperties );
+ for ( PluginExecution execution : copy.getExecutions() )
+ {
+ removeBlacklistedAttributes( execution.getConfiguration(), excludeProperties );
+ }
+
+ copy.setDependencies( normalizeDependencies( copy.getDependencies()
.stream()
.sorted( DefaultNormalizedModelProvider::compareDependencies )
.collect( Collectors.toList() ) ) );
- if ( multiModuleSupport.isPartOfMultiModule(
- copy.getGroupId(),
- copy.getArtifactId(),
- copy.getVersion() ) )
- {
- copy.setVersion( NORMALIZED_VERSION );
- }
- return copy;
- } ).collect( Collectors.toList() );
+ if ( multiModuleSupport.isPartOfMultiModule(
+ copy.getGroupId(),
+ copy.getArtifactId(),
+ copy.getVersion() ) )
+ {
+ copy.setVersion( NORMALIZED_VERSION );
+ }
+ return copy;
+ } ).collect( Collectors.toList() );
}
private void removeBlacklistedAttributes( Object node, List<String> excludeProperties )
diff --git a/src/main/java/org/apache/maven/buildcache/DefaultProjectInputCalculator.java b/src/main/java/org/apache/maven/buildcache/DefaultProjectInputCalculator.java
index c775cfd..f0184a3 100644
--- a/src/main/java/org/apache/maven/buildcache/DefaultProjectInputCalculator.java
+++ b/src/main/java/org/apache/maven/buildcache/DefaultProjectInputCalculator.java
@@ -43,24 +43,29 @@ public class DefaultProjectInputCalculator implements ProjectInputCalculator
private static final Logger LOGGER = LoggerFactory.getLogger( DefaultProjectInputCalculator.class );
private final MavenSession mavenSession;
+
private final RemoteCacheRepository remoteCache;
+
private final CacheConfig cacheConfig;
+
private final RepositorySystem repoSystem;
+
private final NormalizedModelProvider normalizedModelProvider;
+
private final MultiModuleSupport multiModuleSupport;
private final ConcurrentMap<String, ProjectsInputInfo> checkSumMap = new ConcurrentHashMap<>();
private static final ThreadLocal<Set<String>> CURRENTLY_CALCULATING = ThreadLocal.withInitial(
- LinkedHashSet::new );
+ LinkedHashSet::new );
@Inject
public DefaultProjectInputCalculator( MavenSession mavenSession,
- RemoteCacheRepository remoteCache,
- CacheConfig cacheConfig,
- RepositorySystem repoSystem,
- NormalizedModelProvider rawModelProvider,
- MultiModuleSupport multiModuleSupport )
+ RemoteCacheRepository remoteCache,
+ CacheConfig cacheConfig,
+ RepositorySystem repoSystem,
+ NormalizedModelProvider rawModelProvider,
+ MultiModuleSupport multiModuleSupport )
{
this.mavenSession = mavenSession;
this.remoteCache = remoteCache;
@@ -74,12 +79,12 @@ public class DefaultProjectInputCalculator implements ProjectInputCalculator
public ProjectsInputInfo calculateInput( MavenProject project )
{
LOGGER.info( "Going to calculate checksum for project [groupId=" + project.getGroupId()
- + ", artifactId=" + project.getArtifactId() + "]" );
+ + ", artifactId=" + project.getArtifactId() + "]" );
String key = BuilderCommon.getKey( project );
- //NOTE: Do not use ConcurrentHashMap.computeIfAbsent() here because of recursive calls
- //this could lead to runtime exception - IllegalStateException("Recursive update")
- //in jdk 8 the result of attempt to modify items with the same hash code could lead to infinite loop
+ // NOTE: Do not use ConcurrentHashMap.computeIfAbsent() here because of recursive calls
+ // this could lead to runtime exception - IllegalStateException("Recursive update")
+ // in jdk 8 the result of attempt to modify items with the same hash code could lead to infinite loop
ProjectsInputInfo projectsInputInfo = checkSumMap.get( key );
if ( projectsInputInfo != null )
{
@@ -92,27 +97,27 @@ public class DefaultProjectInputCalculator implements ProjectInputCalculator
}
private ProjectsInputInfo calculateInputInternal( String key,
- MavenProject project )
+ MavenProject project )
{
Set<String> projectsSet = CURRENTLY_CALCULATING.get();
if ( !projectsSet.add( key ) )
{
throw new IllegalStateException( "Checksum for project is already calculating. "
- + "Is there a cyclic dependencies? [project=" + key
- + ", setOfCalculatingProjects=" + projectsSet + "]" );
+ + "Is there a cyclic dependencies? [project=" + key
+ + ", setOfCalculatingProjects=" + projectsSet + "]" );
}
try
{
final MavenProjectInput input = new MavenProjectInput(
- project,
- normalizedModelProvider,
- multiModuleSupport,
- this,
- mavenSession,
- cacheConfig,
- repoSystem,
- remoteCache );
+ project,
+ normalizedModelProvider,
+ multiModuleSupport,
+ this,
+ mavenSession,
+ cacheConfig,
+ repoSystem,
+ remoteCache );
return input.calculateChecksum();
}
catch ( Exception e )
diff --git a/src/main/java/org/apache/maven/buildcache/DefaultRestoredArtifactHandler.java b/src/main/java/org/apache/maven/buildcache/DefaultRestoredArtifactHandler.java
index 564fc0e..d8be8d4 100644
--- a/src/main/java/org/apache/maven/buildcache/DefaultRestoredArtifactHandler.java
+++ b/src/main/java/org/apache/maven/buildcache/DefaultRestoredArtifactHandler.java
@@ -47,6 +47,7 @@ public class DefaultRestoredArtifactHandler implements RestoredArtifactHandler
{
private static final Logger LOGGER = LoggerFactory.getLogger( DefaultRestoredArtifactHandler.class );
+
private static final String DIR_NAME = "cache-build-tmp";
private final boolean adjustMetaInfVersion;
@@ -59,35 +60,35 @@ public class DefaultRestoredArtifactHandler implements RestoredArtifactHandler
@Override
public Path adjustArchiveArtifactVersion( MavenProject project, String originalArtifactVersion, Path artifactFile )
- throws IOException
+ throws IOException
{
if ( !adjustMetaInfVersion )
{
- //option is disabled in cache configuration, return file as is
+ // option is disabled in cache configuration, return file as is
return artifactFile;
}
File file = artifactFile.toFile();
if ( project.getVersion().equals( originalArtifactVersion ) || !CacheUtils.isArchive( file ) )
{
- //versions of artifact and building project are the same or this is not an archive, return file as is
+ // versions of artifact and building project are the same or this is not an archive, return file as is
return artifactFile;
}
File tempDirName = Paths.get( project.getBuild().getDirectory() )
- .normalize()
- .resolve( DIR_NAME )
- .toFile();
+ .normalize()
+ .resolve( DIR_NAME )
+ .toFile();
if ( tempDirName.mkdirs() )
{
LOGGER.debug( "Temporary directory to restore artifact was created [artifactFile={}, "
- + "originalVersion={}, tempDir={}]",
- artifactFile, originalArtifactVersion, tempDirName );
+ + "originalVersion={}, tempDir={}]",
+ artifactFile, originalArtifactVersion, tempDirName );
}
String currentVersion = project.getVersion();
File tmpJarFile = File.createTempFile( artifactFile.toFile().getName(),
- '.' + FilenameUtils.getExtension( file.getName() ), tempDirName );
+ '.' + FilenameUtils.getExtension( file.getName() ), tempDirName );
tmpJarFile.deleteOnExit();
String originalImplVersion = Attributes.Name.IMPLEMENTATION_VERSION + ": " + originalArtifactVersion;
String implVersion = Attributes.Name.IMPLEMENTATION_VERSION + ": " + currentVersion;
@@ -98,9 +99,9 @@ public class DefaultRestoredArtifactHandler implements RestoredArtifactHandler
try ( JarFile jarFile = new JarFile( artifactFile.toFile() ) )
{
try ( JarOutputStream jos = new JarOutputStream(
- new BufferedOutputStream( new FileOutputStream( tmpJarFile ) ) ) )
+ new BufferedOutputStream( new FileOutputStream( tmpJarFile ) ) ) )
{
- //Copy original jar file to the temporary one.
+ // Copy original jar file to the temporary one.
Enumeration<JarEntry> jarEntries = jarFile.entries();
byte[] buffer = new byte[1024];
while ( jarEntries.hasMoreElements() )
@@ -109,7 +110,8 @@ public class DefaultRestoredArtifactHandler implements RestoredArtifactHandler
String entryName = entry.getName();
if ( entryName.startsWith( "META-INF/maven" )
- && ( entryName.endsWith( "plugin.xml" ) || entryName.endsWith( "plugin-help.xml" ) ) )
+ && ( entryName.endsWith( "plugin.xml" )
+ || entryName.endsWith( "plugin-help.xml" ) ) )
{
replaceEntry( jarFile, entry, commonXmlOriginalVersion, commonXmlVersion, jos );
continue;
@@ -148,7 +150,7 @@ public class DefaultRestoredArtifactHandler implements RestoredArtifactHandler
}
private static void replaceEntry( JarFile jarFile, JarEntry entry,
- String toReplace, String replacement, JarOutputStream jos ) throws IOException
+ String toReplace, String replacement, JarOutputStream jos ) throws IOException
{
String fullManifest = IOUtils.toString( jarFile.getInputStream( entry ), StandardCharsets.UTF_8.name() );
String modified = fullManifest.replaceAll( toReplace, replacement );
diff --git a/src/main/java/org/apache/maven/buildcache/HttpCacheRepositoryImpl.java b/src/main/java/org/apache/maven/buildcache/HttpCacheRepositoryImpl.java
index 748fcee..d7de753 100644
--- a/src/main/java/org/apache/maven/buildcache/HttpCacheRepositoryImpl.java
+++ b/src/main/java/org/apache/maven/buildcache/HttpCacheRepositoryImpl.java
@@ -62,11 +62,13 @@ public class HttpCacheRepositoryImpl implements RemoteCacheRepository
{
public static final String BUILDINFO_XML = "buildinfo.xml";
+
public static final String CACHE_REPORT_XML = "build-cache-report.xml";
private static final Logger LOGGER = LoggerFactory.getLogger( HttpCacheRepositoryImpl.class );
private final XmlService xmlService;
+
private final CacheConfig cacheConfig;
@Inject
@@ -78,17 +80,17 @@ public class HttpCacheRepositoryImpl implements RemoteCacheRepository
@SuppressWarnings( "checkstyle:constantname" )
private static final ThreadLocal<HttpClient> httpClient = ThreadLocal
- .withInitial( HttpCacheRepositoryImpl::newHttpClient );
+ .withInitial( HttpCacheRepositoryImpl::newHttpClient );
@SuppressWarnings( "checkstyle:magicnumber" )
private static CloseableHttpClient newHttpClient()
{
int timeoutSeconds = 60;
RequestConfig config = RequestConfig.custom()
- .setConnectTimeout( timeoutSeconds * 1000 )
- .setConnectionRequestTimeout( timeoutSeconds * 1000 )
- .setSocketTimeout( timeoutSeconds * 1000 )
- .build();
+ .setConnectTimeout( timeoutSeconds * 1000 )
+ .setConnectionRequestTimeout( timeoutSeconds * 1000 )
+ .setSocketTimeout( timeoutSeconds * 1000 )
+ .build();
return HttpClientBuilder.create().setDefaultRequestConfig( config ).build();
}
@@ -98,7 +100,7 @@ public class HttpCacheRepositoryImpl implements RemoteCacheRepository
{
final String resourceUrl = getResourceUrl( context, BUILDINFO_XML );
return getResourceContent( resourceUrl )
- .map( content -> new Build( xmlService.loadBuild( content ), CacheSource.REMOTE ) );
+ .map( content -> new Build( xmlService.loadBuild( content ), CacheSource.REMOTE ) );
}
@Nonnull
@@ -110,7 +112,7 @@ public class HttpCacheRepositoryImpl implements RemoteCacheRepository
@Override
public void saveBuildInfo( CacheResult cacheResult, Build build )
- throws IOException
+ throws IOException
{
final String resourceUrl = getResourceUrl( cacheResult.getContext(), BUILDINFO_XML );
putToRemoteCache( new ByteArrayInputStream( xmlService.toBytes( build.getDto() ) ), resourceUrl );
@@ -121,16 +123,16 @@ public class HttpCacheRepositoryImpl implements RemoteCacheRepository
{
MavenProject rootProject = session.getTopLevelProject();
final String resourceUrl = cacheConfig.getUrl() + "/" + MavenProjectInput.CACHE_IMPLEMENTATION_VERSION
- + "/" + rootProject.getGroupId()
- + "/" + rootProject.getArtifactId()
- + "/" + buildId
- + "/" + CACHE_REPORT_XML;
+ + "/" + rootProject.getGroupId()
+ + "/" + rootProject.getArtifactId()
+ + "/" + buildId
+ + "/" + CACHE_REPORT_XML;
putToRemoteCache( new ByteArrayInputStream( xmlService.toBytes( cacheReport ) ), resourceUrl );
}
@Override
public void saveArtifactFile( CacheResult cacheResult,
- org.apache.maven.artifact.Artifact artifact ) throws IOException
+ org.apache.maven.artifact.Artifact artifact ) throws IOException
{
final String resourceUrl = getResourceUrl( cacheResult.getContext(), CacheUtils.normalizedName( artifact ) );
try ( InputStream inputStream = Files.newInputStream( artifact.getFile().toPath() ) )
@@ -199,13 +201,13 @@ public class HttpCacheRepositoryImpl implements RemoteCacheRepository
public String getResourceUrl( CacheContext context, String filename )
{
return getResourceUrl( filename, context.getProject().getGroupId(), context.getProject().getArtifactId(),
- context.getInputInfo().getChecksum() );
+ context.getInputInfo().getChecksum() );
}
private String getResourceUrl( String filename, String groupId, String artifactId, String checksum )
{
return cacheConfig.getUrl() + "/" + MavenProjectInput.CACHE_IMPLEMENTATION_VERSION + "/" + groupId + "/"
- + artifactId + "/" + checksum + "/" + filename;
+ + artifactId + "/" + checksum + "/" + filename;
}
/**
@@ -234,7 +236,7 @@ public class HttpCacheRepositoryImpl implements RemoteCacheRepository
public Optional<Build> findBaselineBuild( MavenProject project )
{
Optional<List<ProjectReport>> cachedProjectsHolder = findCacheInfo()
- .map( CacheReport::getProjects );
+ .map( CacheReport::getProjects );
if ( !cachedProjectsHolder.isPresent() )
{
@@ -243,9 +245,9 @@ public class HttpCacheRepositoryImpl implements RemoteCacheRepository
final List<ProjectReport> projects = cachedProjectsHolder.get();
final Optional<ProjectReport> projectReportHolder = projects.stream()
- .filter( p -> project.getArtifactId().equals( p.getArtifactId() )
- && project.getGroupId().equals( p.getGroupId() ) )
- .findFirst();
+ .filter( p -> project.getArtifactId().equals( p.getArtifactId() )
+ && project.getGroupId().equals( p.getGroupId() ) )
+ .findFirst();
if ( !projectReportHolder.isPresent() )
{
@@ -263,14 +265,14 @@ public class HttpCacheRepositoryImpl implements RemoteCacheRepository
else
{
url = getResourceUrl( BUILDINFO_XML, project.getGroupId(),
- project.getArtifactId(), projectReport.getChecksum() );
+ project.getArtifactId(), projectReport.getChecksum() );
LOGGER.info( "Baseline project record doesn't have url, trying default location {}", url );
}
try
{
return getResourceContent( url )
- .map( content -> new Build( xmlService.loadBuild( content ), CacheSource.REMOTE ) );
+ .map( content -> new Build( xmlService.loadBuild( content ), CacheSource.REMOTE ) );
}
catch ( Exception e )
{
@@ -292,7 +294,7 @@ public class HttpCacheRepositoryImpl implements RemoteCacheRepository
catch ( Exception e )
{
LOGGER.error( "Error downloading baseline report from: {}, skipping diff.",
- cacheConfig.getBaselineCacheUrl(), e );
+ cacheConfig.getBaselineCacheUrl(), e );
report = Optional.empty();
}
cacheReportSupplier.compareAndSet( null, report );
diff --git a/src/main/java/org/apache/maven/buildcache/LifecyclePhasesHelper.java b/src/main/java/org/apache/maven/buildcache/LifecyclePhasesHelper.java
index bef2c5a..337aa60 100644
--- a/src/main/java/org/apache/maven/buildcache/LifecyclePhasesHelper.java
+++ b/src/main/java/org/apache/maven/buildcache/LifecyclePhasesHelper.java
@@ -36,17 +36,20 @@ public class LifecyclePhasesHelper
{
private final DefaultLifecycles defaultLifecycles;
+
private final List<String> phases;
+
private final String lastCleanPhase;
@Inject
public LifecyclePhasesHelper( DefaultLifecycles defaultLifecycles,
- @Named( "clean" ) Lifecycle cleanLifecycle )
+ @Named( "clean" )
+ Lifecycle cleanLifecycle )
{
this.defaultLifecycles = Objects.requireNonNull( defaultLifecycles );
this.phases = defaultLifecycles.getLifeCycles().stream()
- .flatMap( lf -> lf.getPhases().stream() )
- .collect( Collectors.toList() );
+ .flatMap( lf -> lf.getPhases().stream() )
+ .collect( Collectors.toList() );
this.lastCleanPhase = CacheUtils.getLast( cleanLifecycle.getPhases() );
}
@@ -64,8 +67,8 @@ public class LifecyclePhasesHelper
}
/**
- * Check if the given phase is later than the other in maven lifecycle.
- * Example: isLaterPhase("install", "clean") returns true;
+ * Check if the given phase is later than the other in maven lifecycle. Example: isLaterPhase("install", "clean")
+ * returns true;
*/
public boolean isLaterPhase( String phase, String other )
{
@@ -90,7 +93,7 @@ public class LifecyclePhasesHelper
for ( MojoExecution mojoExecution : mojoExecutions )
{
if ( mojoExecution.getLifecyclePhase() == null
- || isLaterPhaseThanClean( mojoExecution.getLifecyclePhase() ) )
+ || isLaterPhaseThanClean( mojoExecution.getLifecyclePhase() ) )
{
break;
}
diff --git a/src/main/java/org/apache/maven/buildcache/LocalCacheRepositoryImpl.java b/src/main/java/org/apache/maven/buildcache/LocalCacheRepositoryImpl.java
index f94190c..0a67ba1 100644
--- a/src/main/java/org/apache/maven/buildcache/LocalCacheRepositoryImpl.java
+++ b/src/main/java/org/apache/maven/buildcache/LocalCacheRepositoryImpl.java
@@ -78,24 +78,32 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
{
private static final String BUILDINFO_XML = "buildinfo.xml";
+
private static final String LOOKUPINFO_XML = "lookupinfo.xml";
+
private static final long ONE_HOUR_MILLIS = HOURS.toMillis( 1 );
+
private static final long ONE_MINUTE_MILLIS = MINUTES.toMillis( 1 );
+
private static final long ONE_DAY_MILLIS = DAYS.toMillis( 1 );
+
private static final String EMPTY = "";
private static final Logger LOGGER = LoggerFactory.getLogger( LocalCacheRepositoryImpl.class );
private final RemoteCacheRepository remoteRepository;
+
private final XmlService xmlService;
+
private final CacheConfig cacheConfig;
+
private final Map<Pair<MavenSession, Dependency>, Optional<Build>> bestBuildCache = new ConcurrentHashMap<>();
@Inject
public LocalCacheRepositoryImpl(
- RemoteCacheRepository remoteRepository,
- XmlService xmlService,
- CacheConfig cacheConfig )
+ RemoteCacheRepository remoteRepository,
+ XmlService xmlService,
+ CacheConfig cacheConfig )
{
this.remoteRepository = remoteRepository;
this.xmlService = xmlService;
@@ -158,11 +166,11 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
if ( Files.exists( lookupInfoPath ) )
{
final BasicFileAttributes fileAttributes = Files.readAttributes( lookupInfoPath,
- BasicFileAttributes.class );
+ BasicFileAttributes.class );
final long lastModified = fileAttributes.lastModifiedTime().toMillis();
final long created = fileAttributes.creationTime().toMillis();
final long now = System.currentTimeMillis();
- // throttle remote cache calls, maven like
+ // throttle remote cache calls, maven like
if ( now < created + ONE_HOUR_MILLIS && now < lastModified + ONE_MINUTE_MILLIS )
{ // fresh file, allow lookup every minute
LOGGER.info( "Skipping remote lookup, last unsuccessful lookup less than 1m ago." );
@@ -243,22 +251,23 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
{
final String artifactId = context.getProject().getArtifactId();
throw new RuntimeException(
- "Failed to cleanup local cache of " + artifactId + " on build failure, it might be inconsistent",
- e );
+ "Failed to cleanup local cache of " + artifactId
+ + " on build failure, it might be inconsistent",
+ e );
}
}
@Nonnull
@Override
public Optional<Build> findBestMatchingBuild(
- MavenSession session, Dependency dependency )
+ MavenSession session, Dependency dependency )
{
return bestBuildCache.computeIfAbsent( Pair.of( session, dependency ), this::findBestMatchingBuildImpl );
}
@Nonnull
private Optional<Build> findBestMatchingBuildImpl(
- Pair<MavenSession, Dependency> dependencySession )
+ Pair<MavenSession, Dependency> dependencySession )
{
try
{
@@ -266,7 +275,7 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
final Dependency dependency = dependencySession.getRight();
final Path artifactCacheDir = artifactCacheDir( session, dependency.getGroupId(),
- dependency.getArtifactId() );
+ dependency.getArtifactId() );
final Map<Pair<String, String>, Collection<Pair<Build, Path>>> filesByVersion = new HashMap<>();
@@ -283,7 +292,7 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
{
final org.apache.maven.buildcache.xml.build.Build dto = xmlService.loadBuild( file );
final Pair<Build, Path> buildInfoAndFile = Pair.of( new Build( dto, CacheSource.LOCAL ),
- path );
+ path );
final String cachedVersion = dto.getArtifact().getVersion();
final String cachedBranch = getScmRef( dto.getScm() );
add( filesByVersion, Pair.of( cachedVersion, cachedBranch ), buildInfoAndFile );
@@ -300,7 +309,7 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
{
// version is unusable nothing we can do here
LOGGER.info( "Build info is not compatible to current maven "
- + "implementation: {}", file, e );
+ + "implementation: {}", file, e );
}
}
return FileVisitResult.CONTINUE;
@@ -333,12 +342,12 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
{
// ok lets take all
bestMatched = filesByVersion.values().stream()
- .flatMap( Collection::stream ).collect( Collectors.toList() );
+ .flatMap( Collection::stream ).collect( Collectors.toList() );
}
return bestMatched.stream()
- .max( Comparator.comparing( p -> lastModifiedTime( p.getRight() ) ) )
- .map( Pair::getLeft );
+ .max( Comparator.comparing( p -> lastModifiedTime( p.getRight() ) ) )
+ .map( Pair::getLeft );
}
catch ( IOException e )
{
@@ -388,7 +397,7 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
@Override
public void saveBuildInfo( CacheResult cacheResult, Build build )
- throws IOException
+ throws IOException
{
final Path path = localBuildPath( cacheResult.getContext(), BUILDINFO_XML, true );
Files.write( path, xmlService.toBytes( build.getDto() ), TRUNCATE_EXISTING, CREATE );
@@ -404,7 +413,7 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
Path path = getMultimoduleRoot( session ).resolve( "target" ).resolve( "maven-incremental" );
Files.createDirectories( path );
Files.write( path.resolve( "cache-report." + buildId + ".xml" ), xmlService.toBytes( cacheReport ),
- TRUNCATE_EXISTING, CREATE );
+ TRUNCATE_EXISTING, CREATE );
if ( cacheConfig.isRemoteCacheEnabled() && cacheConfig.isSaveToRemote() )
{
LOGGER.info( "Saving cache report on build completion" );
@@ -414,7 +423,7 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
@Override
public void saveArtifactFile( CacheResult cacheResult, org.apache.maven.artifact.Artifact artifact )
- throws IOException
+ throws IOException
{
// safe artifacts to cache
File artifactFile = artifact.getFile();
@@ -430,7 +439,7 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
{
final MavenProject project = context.getProject();
final Path artifactCacheDir = artifactCacheDir( context.getSession(), project.getGroupId(),
- project.getArtifactId() );
+ project.getArtifactId() );
return artifactCacheDir.resolve( context.getInputInfo().getChecksum() );
}
@@ -438,7 +447,7 @@ public class LocalCacheRepositoryImpl implements LocalCacheRepository
{
final String localRepositoryRoot = session.getLocalRepository().getBasedir();
final Path path = Paths.get( localRepositoryRoot, "..", "cache", CACHE_IMPLEMENTATION_VERSION, groupId,
- artifactId ).normalize();
+ artifactId ).normalize();
if ( !Files.exists( path ) )
{
Files.createDirectories( path );
diff --git a/src/main/java/org/apache/maven/buildcache/MojoParametersListener.java b/src/main/java/org/apache/maven/buildcache/MojoParametersListener.java
index dd0b39b..84ac5e4 100644
--- a/src/main/java/org/apache/maven/buildcache/MojoParametersListener.java
+++ b/src/main/java/org/apache/maven/buildcache/MojoParametersListener.java
@@ -41,7 +41,8 @@ public class MojoParametersListener implements MojoExecutionListener
private static final Logger LOGGER = LoggerFactory.getLogger( MojoParametersListener.class );
@SuppressWarnings( "checkstyle:LineLength" )
- private final ConcurrentMap<MavenProject, Map<String, MojoExecutionEvent>> projectExecutions = new ConcurrentHashMap<>();
+ private final ConcurrentMap<MavenProject, Map<String, MojoExecutionEvent>> projectExecutions =
+ new ConcurrentHashMap<>();
@Override
public void beforeMojoExecution( MojoExecutionEvent event )
@@ -71,7 +72,7 @@ public class MojoParametersListener implements MojoExecutionListener
@Override
public void afterExecutionFailure( MojoExecutionEvent event )
{
- //do nothing
+ // do nothing
}
public Map<String, MojoExecutionEvent> getProjectExecutions( MavenProject project )
diff --git a/src/main/java/org/apache/maven/buildcache/NormalizedModelProvider.java b/src/main/java/org/apache/maven/buildcache/NormalizedModelProvider.java
index b72d998..d4a57f6 100644
--- a/src/main/java/org/apache/maven/buildcache/NormalizedModelProvider.java
+++ b/src/main/java/org/apache/maven/buildcache/NormalizedModelProvider.java
@@ -31,8 +31,8 @@ public interface NormalizedModelProvider
{
/**
- * @param project - the project which model will be calculated for
- * @return normalized model for project
+ * @param project - the project which model will be calculated for
+ * @return normalized model for project
*/
Model normalizedModel( MavenProject project );
diff --git a/src/main/java/org/apache/maven/buildcache/PluginScanConfigImpl.java b/src/main/java/org/apache/maven/buildcache/PluginScanConfigImpl.java
index a311f21..ce8d867 100644
--- a/src/main/java/org/apache/maven/buildcache/PluginScanConfigImpl.java
+++ b/src/main/java/org/apache/maven/buildcache/PluginScanConfigImpl.java
@@ -49,7 +49,7 @@ public class PluginScanConfigImpl implements PluginScanConfig
{
// include or exclude is a choice element, could be only obe property set
- //noinspection ConstantConditions
+ // noinspection ConstantConditions
final List<TagScanConfig> includes = dto.getIncludes();
if ( !includes.isEmpty() )
{
diff --git a/src/main/java/org/apache/maven/buildcache/RemoteCacheRepository.java b/src/main/java/org/apache/maven/buildcache/RemoteCacheRepository.java
index 7e5768f..83a7373 100644
--- a/src/main/java/org/apache/maven/buildcache/RemoteCacheRepository.java
+++ b/src/main/java/org/apache/maven/buildcache/RemoteCacheRepository.java
@@ -33,9 +33,8 @@ public interface RemoteCacheRepository extends CacheRepository
{
/**
- * Download an artifact to the given location.
- * Returns <code>true</code> if success, <code>false</code> if the artifact does not exists
- * and throws an <code>IOException</code> if a problem occurs.
+ * Download an artifact to the given location. Returns <code>true</code> if success, <code>false</code> if the
+ * artifact does not exists and throws an <code>IOException</code> if a problem occurs.
*/
boolean getArtifactContent( CacheContext context, Artifact artifact, Path target ) throws IOException;
diff --git a/src/main/java/org/apache/maven/buildcache/RemoteCacheRepositoryProvider.java b/src/main/java/org/apache/maven/buildcache/RemoteCacheRepositoryProvider.java
index 7137d10..eb2fff7 100644
--- a/src/main/java/org/apache/maven/buildcache/RemoteCacheRepositoryProvider.java
+++ b/src/main/java/org/apache/maven/buildcache/RemoteCacheRepositoryProvider.java
@@ -40,7 +40,7 @@ public class RemoteCacheRepositoryProvider implements Provider<RemoteCacheReposi
@Inject
public RemoteCacheRepositoryProvider( CacheConfig config, PlexusContainer container )
- throws ComponentLookupException
+ throws ComponentLookupException
{
config.initialize();
String hint = config.getTransport();
diff --git a/src/main/java/org/apache/maven/buildcache/RestoredArtifactHandler.java b/src/main/java/org/apache/maven/buildcache/RestoredArtifactHandler.java
index e22b63c..584f5e0 100644
--- a/src/main/java/org/apache/maven/buildcache/RestoredArtifactHandler.java
+++ b/src/main/java/org/apache/maven/buildcache/RestoredArtifactHandler.java
@@ -25,10 +25,10 @@ import org.apache.maven.project.MavenProject;
public interface RestoredArtifactHandler
{
- //we might store in cache artifact which was build with previous version
- //1.0-SNAPSHOT is kept in cache but real version of project is 2.0
- //for pom packaging this is done automatically by maven but for jar and other there might be
- //sensitive metadata with previous version. Versions mismatch could lead errors
+ // we might store in cache artifact which was build with previous version
+ // 1.0-SNAPSHOT is kept in cache but real version of project is 2.0
+ // for pom packaging this is done automatically by maven but for jar and other there might be
+ // sensitive metadata with previous version. Versions mismatch could lead errors
Path adjustArchiveArtifactVersion( MavenProject project, String originalArtifactVersion, Path artifactFile )
- throws IOException;
+ throws IOException;
}
diff --git a/src/main/java/org/apache/maven/buildcache/ScanConfigProperties.java b/src/main/java/org/apache/maven/buildcache/ScanConfigProperties.java
index 67afb49..98f4d2e 100644
--- a/src/main/java/org/apache/maven/buildcache/ScanConfigProperties.java
+++ b/src/main/java/org/apache/maven/buildcache/ScanConfigProperties.java
@@ -25,6 +25,7 @@ public class ScanConfigProperties
{
private final boolean recursive;
+
private final String glob;
public ScanConfigProperties( boolean recursive, String glob )
diff --git a/src/main/java/org/apache/maven/buildcache/WagonConfigurator.java b/src/main/java/org/apache/maven/buildcache/WagonConfigurator.java
index a41c0cc..08a7c03 100644
--- a/src/main/java/org/apache/maven/buildcache/WagonConfigurator.java
+++ b/src/main/java/org/apache/maven/buildcache/WagonConfigurator.java
@@ -55,7 +55,7 @@ public class WagonConfigurator
}
public void configure( Wagon wagon, Object configuration )
- throws Exception
+ throws Exception
{
requireNonNull( wagon, "wagon cannot be null" );
requireNonNull( configuration, "configuration cannot be null" );
@@ -63,16 +63,16 @@ public class WagonConfigurator
PlexusConfiguration config;
if ( configuration instanceof PlexusConfiguration )
{
- config = ( PlexusConfiguration ) configuration;
+ config = (PlexusConfiguration) configuration;
}
else if ( configuration instanceof Xpp3Dom )
{
- config = new XmlPlexusConfiguration( ( Xpp3Dom ) configuration );
+ config = new XmlPlexusConfiguration( (Xpp3Dom) configuration );
}
else
{
throw new IllegalArgumentException( "unexpected configuration type: "
- + configuration.getClass().getName() );
+ + configuration.getClass().getName() );
}
WagonComponentConfigurator configurator = new WagonComponentConfigurator();
@@ -81,19 +81,19 @@ public class WagonConfigurator
}
static class WagonComponentConfigurator
- extends AbstractComponentConfigurator
+ extends AbstractComponentConfigurator
{
@Override
public void configureComponent( Object component, PlexusConfiguration configuration,
- ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm,
- ConfigurationListener listener )
- throws ComponentConfigurationException
+ ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm,
+ ConfigurationListener listener )
+ throws ComponentConfigurationException
{
ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter();
converter.processConfiguration( converterLookup, component, containerRealm, configuration,
- expressionEvaluator, listener );
+ expressionEvaluator, listener );
}
}
diff --git a/src/main/java/org/apache/maven/buildcache/WagonProvider.java b/src/main/java/org/apache/maven/buildcache/WagonProvider.java
index f98c52a..9bfc490 100644
--- a/src/main/java/org/apache/maven/buildcache/WagonProvider.java
+++ b/src/main/java/org/apache/maven/buildcache/WagonProvider.java
@@ -48,13 +48,13 @@ public class WagonProvider
}
public Wagon lookup( String roleHint )
- throws ComponentLookupException
+ throws ComponentLookupException
{
return container.lookup( Wagon.class, roleHint );
}
public void release( Wagon wagon )
- throws ComponentLifecycleException
+ throws ComponentLifecycleException
{
if ( wagon != null )
{
diff --git a/src/main/java/org/apache/maven/buildcache/WagonRemoteCacheRepository.java b/src/main/java/org/apache/maven/buildcache/WagonRemoteCacheRepository.java
index b5ca255..364f03c 100644
--- a/src/main/java/org/apache/maven/buildcache/WagonRemoteCacheRepository.java
+++ b/src/main/java/org/apache/maven/buildcache/WagonRemoteCacheRepository.java
@@ -82,41 +82,59 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
{
public static final String BUILDINFO_XML = "buildinfo.xml";
+
public static final String CACHE_REPORT_XML = "cache-report.xml";
private static final String CONFIG_PROP_CONFIG = "remote.caching.wagon.config";
+
private static final String CONFIG_PROP_FILE_MODE = "remote.caching.wagon.perms.fileMode";
+
private static final String CONFIG_PROP_DIR_MODE = "remote.caching.wagon.perms.dirMode";
+
private static final String CONFIG_PROP_GROUP = "remote.caching.wagon.perms.group";
private static final Logger LOGGER = LoggerFactory.getLogger( HttpCacheRepositoryImpl.class );
private final MavenSession mavenSession;
+
private final XmlService xmlService;
+
private final CacheConfig cacheConfig;
+
private final WagonConfigurator wagonConfigurator;
+
private final WagonProvider wagonProvider;
private final RemoteRepository repository;
+
private final AuthenticationContext repoAuthContext;
+
private final AuthenticationContext proxyAuthContext;
+
private final String wagonHint;
+
private final Repository wagonRepo;
+
private final AuthenticationInfo wagonAuth;
+
private final ProxyInfoProvider wagonProxy;
+
private final Properties headers;
+
private final AtomicBoolean closed = new AtomicBoolean();
+
private final Queue<Wagon> wagons = new ConcurrentLinkedQueue<>();
+
private final AtomicReference<Optional<CacheReport>> cacheReportSupplier = new AtomicReference<>();
@Inject
public WagonRemoteCacheRepository( MavenSession mavenSession,
- XmlService xmlService,
- CacheConfig cacheConfig,
- WagonProvider wagonProvider,
- WagonConfigurator wagonConfigurator,
- RepositorySystem repositorySystem )
- throws RepositoryException
+ XmlService xmlService,
+ CacheConfig cacheConfig,
+ WagonProvider wagonProvider,
+ WagonConfigurator wagonConfigurator,
+ RepositorySystem repositorySystem )
+ throws RepositoryException
{
this.xmlService = xmlService;
this.cacheConfig = cacheConfig;
@@ -130,15 +148,15 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
cacheConfig.initialize();
RemoteRepository repo = new RemoteRepository.Builder(
- cacheConfig.getId(), "cache", cacheConfig.getUrl() ).build();
+ cacheConfig.getId(), "cache", cacheConfig.getUrl() ).build();
RemoteRepository mirror = session.getMirrorSelector().getMirror( repo );
RemoteRepository repoOrMirror = mirror != null ? mirror : repo;
Proxy proxy = session.getProxySelector().getProxy( repoOrMirror );
Authentication auth = session.getAuthenticationSelector().getAuthentication( repoOrMirror );
repository = new RemoteRepository.Builder( repoOrMirror )
- .setProxy( proxy )
- .setAuthentication( auth )
- .build();
+ .setProxy( proxy )
+ .setAuthentication( auth )
+ .build();
wagonRepo = new Repository( repository.getId(), repository.getUrl() );
wagonRepo.setPermissions( getPermissions( repository.getId(), session ) );
@@ -167,10 +185,10 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
this.headers = new Properties();
this.headers.put( "User-Agent", ConfigUtils.getString( session, ConfigurationProperties.DEFAULT_USER_AGENT,
- ConfigurationProperties.USER_AGENT ) );
+ ConfigurationProperties.USER_AGENT ) );
Map<?, ?> headers = ConfigUtils.getMap( session, null,
- ConfigurationProperties.HTTP_HEADERS + "." + repository.getId(),
- ConfigurationProperties.HTTP_HEADERS );
+ ConfigurationProperties.HTTP_HEADERS + "." + repository.getId(),
+ ConfigurationProperties.HTTP_HEADERS );
if ( headers != null )
{
this.headers.putAll( headers );
@@ -315,19 +333,19 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
{
final String resourceUrl = doGetResourceUrl( context, BUILDINFO_XML );
return doGet( resourceUrl )
- .map( content -> new Build( xmlService.loadBuild( content ), CacheSource.REMOTE ) );
+ .map( content -> new Build( xmlService.loadBuild( content ), CacheSource.REMOTE ) );
}
@Override
public boolean getArtifactContent( CacheContext context, Artifact artifact, Path target )
- throws IOException
+ throws IOException
{
return doGet( doGetResourceUrl( context, artifact.getFileName() ), target );
}
@Override
public void saveBuildInfo( CacheResult cacheResult, Build build )
- throws IOException
+ throws IOException
{
final String resourceUrl = doGetResourceUrl( cacheResult.getContext(), BUILDINFO_XML );
doPut( resourceUrl, xmlService.toBytes( build.getDto() ) );
@@ -343,7 +361,7 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
@Override
public void saveArtifactFile( CacheResult cacheResult,
- org.apache.maven.artifact.Artifact artifact ) throws IOException
+ org.apache.maven.artifact.Artifact artifact ) throws IOException
{
final String resourceUrl = doGetResourceUrl( cacheResult.getContext(), CacheUtils.normalizedName( artifact ) );
doPut( resourceUrl, artifact.getFile().toPath() );
@@ -354,8 +372,8 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
{
String base = cacheConfig.getUrl();
return base.endsWith( "/" )
- ? base + doGetResourceUrl( context, filename )
- : base + "/" + doGetResourceUrl( context, filename );
+ ? base + doGetResourceUrl( context, filename )
+ : base + "/" + doGetResourceUrl( context, filename );
}
public String doGetResourceUrl( CacheContext context, String filename )
@@ -371,14 +389,14 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
private String doGetResourceUrl( String filename, String groupId, String artifactId, String checksum )
{
return MavenProjectInput.CACHE_IMPLEMENTATION_VERSION + "/" + groupId + "/"
- + artifactId + "/" + checksum + "/" + filename;
+ + artifactId + "/" + checksum + "/" + filename;
}
@Override
public Optional<Build> findBaselineBuild( MavenProject project )
{
Optional<List<ProjectReport>> cachedProjectsHolder = findCacheInfo()
- .map( CacheReport::getProjects );
+ .map( CacheReport::getProjects );
if ( !cachedProjectsHolder.isPresent() )
{
@@ -387,9 +405,9 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
final List<ProjectReport> projects = cachedProjectsHolder.get();
final Optional<ProjectReport> projectReportHolder = projects.stream()
- .filter( p -> project.getArtifactId().equals( p.getArtifactId() )
- && project.getGroupId().equals( p.getGroupId() ) )
- .findFirst();
+ .filter( p -> project.getArtifactId().equals( p.getArtifactId() )
+ && project.getGroupId().equals( p.getGroupId() ) )
+ .findFirst();
if ( !projectReportHolder.isPresent() )
{
@@ -413,7 +431,7 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
try
{
return doGet( url )
- .map( content -> new Build( xmlService.loadBuild( content ), CacheSource.REMOTE ) );
+ .map( content -> new Build( xmlService.loadBuild( content ), CacheSource.REMOTE ) );
}
catch ( Exception e )
{
@@ -435,7 +453,7 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
catch ( Exception e )
{
LOGGER.error( "Error downloading baseline report from: {}, skipping diff.",
- cacheConfig.getBaselineCacheUrl(), e );
+ cacheConfig.getBaselineCacheUrl(), e );
report = Optional.empty();
}
cacheReportSupplier.compareAndSet( null, report );
@@ -472,8 +490,8 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
{
if ( wagon instanceof StreamingWagon )
{
- ( ( StreamingWagon ) wagon ).putFromStream(
- new ByteArrayInputStream( data ), url, data.length, 0 );
+ ( (StreamingWagon) wagon ).putFromStream(
+ new ByteArrayInputStream( data ), url, data.length, 0 );
}
else
{
@@ -510,7 +528,7 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
if ( wagon instanceof StreamingWagon )
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ( ( StreamingWagon ) wagon ).getToStream( url, baos );
+ ( (StreamingWagon) wagon ).getToStream( url, baos );
return Optional.of( baos.toByteArray() );
}
else
@@ -596,7 +614,7 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
}
private void connectWagon( Wagon wagon )
- throws WagonException
+ throws WagonException
{
if ( !headers.isEmpty() )
{
@@ -617,17 +635,17 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
RepositorySystemSession session = mavenSession.getRepositorySession();
int connectTimeout = ConfigUtils.getInteger( session, ConfigurationProperties.DEFAULT_CONNECT_TIMEOUT,
- ConfigurationProperties.CONNECT_TIMEOUT );
+ ConfigurationProperties.CONNECT_TIMEOUT );
int requestTimeout = ConfigUtils.getInteger( session, ConfigurationProperties.DEFAULT_REQUEST_TIMEOUT,
- ConfigurationProperties.REQUEST_TIMEOUT );
+ ConfigurationProperties.REQUEST_TIMEOUT );
wagon.setTimeout( Math.max( Math.max( connectTimeout, requestTimeout ), 0 ) );
wagon.setInteractive( ConfigUtils.getBoolean( session, ConfigurationProperties.DEFAULT_INTERACTIVE,
- ConfigurationProperties.INTERACTIVE ) );
+ ConfigurationProperties.INTERACTIVE ) );
Object configuration = ConfigUtils.getObject( session, null,
- CONFIG_PROP_CONFIG + "." + repository.getId() );
+ CONFIG_PROP_CONFIG + "." + repository.getId() );
if ( configuration != null && wagonConfigurator != null )
{
try
@@ -637,7 +655,7 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
catch ( Exception e )
{
LOGGER.warn( "Could not apply configuration for {} to Wagon {}",
- repository.getId(), wagon.getClass().getName(), e );
+ repository.getId(), wagon.getClass().getName(), e );
}
}
@@ -660,7 +678,7 @@ public class WagonRemoteCacheRepository implements RemoteCacheRepository
}
private Wagon pollWagon()
- throws Exception
+ throws Exception
{
Wagon wagon = wagons.poll();
diff --git a/src/main/java/org/apache/maven/buildcache/Xpp3DomUtils.java b/src/main/java/org/apache/maven/buildcache/Xpp3DomUtils.java
index c4c389c..2060bea 100644
--- a/src/main/java/org/apache/maven/buildcache/Xpp3DomUtils.java
+++ b/src/main/java/org/apache/maven/buildcache/Xpp3DomUtils.java
@@ -19,11 +19,10 @@
package org.apache.maven.buildcache;
/**
- * This utility class is used to work around the classloading problem described
- * in https://issues.apache.org/jira/browse/MNG-7160.
- * The simple workaround described in MNG-7160 is not possible because this
- * extension uses both the XPP3 classes and other utility classes. We thus rely on
- * reflection for all access to plugin configuration.
+ * This utility class is used to work around the classloading problem described in
+ * https://issues.apache.org/jira/browse/MNG-7160. The simple workaround described in MNG-7160 is not possible because
+ * this extension uses both the XPP3 classes and other utility classes. We thus rely on reflection for all access to
+ * plugin configuration.
*/
public class Xpp3DomUtils
{
@@ -32,7 +31,7 @@ public class Xpp3DomUtils
{
try
{
- return ( Object[] ) node.getClass().getMethod( "getChildren" ).invoke( node );
+ return (Object[]) node.getClass().getMethod( "getChildren" ).invoke( node );
}
catch ( Exception e )
{
@@ -44,7 +43,7 @@ public class Xpp3DomUtils
{
try
{
- return ( String ) node.getClass().getMethod( "getName" ).invoke( node );
+ return (String) node.getClass().getMethod( "getName" ).invoke( node );
}
catch ( Exception e )
{
@@ -56,7 +55,7 @@ public class Xpp3DomUtils
{
try
{
- return ( String ) node.getClass().getMethod( "getValue" ).invoke( node );
+ return (String) node.getClass().getMethod( "getValue" ).invoke( node );
}
catch ( Exception e )
{
@@ -80,7 +79,7 @@ public class Xpp3DomUtils
{
try
{
- return ( String ) node.getClass().getMethod( "getAttribute", String.class ).invoke( node, attribute );
+ return (String) node.getClass().getMethod( "getAttribute", String.class ).invoke( node, attribute );
}
catch ( Exception e )
{
diff --git a/src/main/java/org/apache/maven/buildcache/artifact/RestoredArtifact.java b/src/main/java/org/apache/maven/buildcache/artifact/RestoredArtifact.java
index 198ac2a..a0daa23 100644
--- a/src/main/java/org/apache/maven/buildcache/artifact/RestoredArtifact.java
+++ b/src/main/java/org/apache/maven/buildcache/artifact/RestoredArtifact.java
@@ -33,8 +33,8 @@ import org.slf4j.LoggerFactory;
import static java.util.Objects.requireNonNull;
/**
- * Overrides default file behavior with async file holder to restore files from cache lazy. Similar to {@link
- * org.apache.maven.project.artifact.AttachedArtifact}
+ * Overrides default file behavior with async file holder to restore files from cache lazy. Similar to
+ * {@link org.apache.maven.project.artifact.AttachedArtifact}
*/
public class RestoredArtifact extends DefaultArtifact
{
@@ -44,10 +44,10 @@ public class RestoredArtifact extends DefaultArtifact
private volatile Future<File> fileFuture;
public RestoredArtifact( Artifact parent, Future<File> fileFuture, String type, String classifier,
- ArtifactHandler handler )
+ ArtifactHandler handler )
{
super( parent.getGroupId(), parent.getArtifactId(), parent.getVersionRange(), parent.getScope(), type,
- classifier, handler, parent.isOptional() );
+ classifier, handler, parent.isOptional() );
this.fileFuture = requireNonNull( fileFuture, "fileFuture == null" );
}
@@ -65,20 +65,20 @@ public class RestoredArtifact extends DefaultArtifact
try
{
LOGGER.trace( "Artifact file {} is not yet retrieved, downloading directly",
- getDependencyConflictId() );
- ( ( RunnableFuture<?> ) fileFuture ).run();
+ getDependencyConflictId() );
+ ( (RunnableFuture<?>) fileFuture ).run();
}
catch ( RuntimeException e )
{
throw new InvalidArtifactRTException( getGroupId(), getArtifactId(),
- getVersion(), getType(),
- "Error retrieving artifact file", e );
+ getVersion(), getType(),
+ "Error retrieving artifact file", e );
}
}
else
{
LOGGER.trace( "Artifact file {} is not yet retrieved, waiting for download to complete",
- getDependencyConflictId() );
+ getDependencyConflictId() );
}
}
@@ -90,13 +90,13 @@ public class RestoredArtifact extends DefaultArtifact
{
Thread.currentThread().interrupt();
throw new InvalidArtifactRTException( getGroupId(), getArtifactId(),
- getVersion(), getType(), "Interrupted while retrieving artifact file", e );
+ getVersion(), getType(), "Interrupted while retrieving artifact file", e );
}
catch ( ExecutionException e )
{
throw new InvalidArtifactRTException( getGroupId(), getArtifactId(),
- getVersion(), getType(), "Error retrieving artifact file",
- e.getCause() );
+ getVersion(), getType(), "Error retrieving artifact file",
+ e.getCause() );
}
}
diff --git a/src/main/java/org/apache/maven/buildcache/checksum/DigestUtils.java b/src/main/java/org/apache/maven/buildcache/checksum/DigestUtils.java
index 9f54259..bcfe9c0 100644
--- a/src/main/java/org/apache/maven/buildcache/checksum/DigestUtils.java
+++ b/src/main/java/org/apache/maven/buildcache/checksum/DigestUtils.java
@@ -47,7 +47,7 @@ public class DigestUtils
private static final Logger LOGGER = LoggerFactory.getLogger( DigestUtils.class );
private static final ThreadLocal<UniversalDetector> ENCODING_DETECTOR = ThreadLocal
- .withInitial( () -> new UniversalDetector( null ) );
+ .withInitial( () -> new UniversalDetector( null ) );
public static DigestItem pom( HashChecksum checksum, String effectivePom )
{
@@ -98,36 +98,37 @@ public class DigestUtils
}
}
- // TODO add support for .gitattributes to statically configure file type before falling back to probe based content checks
+ // TODO add support for .gitattributes to statically configure file type before falling back to probe based content
+ // checks
private static boolean isText( String contentType )
{
return startsWith( contentType, "text/" )
- || containsAny( contentType, "+json", "+xml" ) // common mime type suffixes
- || equalsAny( contentType, // some common text types
- "application/json",
- "application/rtf",
- "application/x-sh",
- "application/xml",
- "application/javascript",
- "application/sql" );
+ || containsAny( contentType, "+json", "+xml" ) // common mime type suffixes
+ || equalsAny( contentType, // some common text types
+ "application/json",
+ "application/rtf",
+ "application/x-sh",
+ "application/xml",
+ "application/javascript",
+ "application/sql" );
}
private static boolean isBinary( String contentType )
{
return startsWithAny( contentType, "image/", "audio/", "video/", "font/" )
- || containsAny( contentType, "+zip", "+gzip" )
- || equalsAny( contentType,
- "application/octet-stream",
- "application/java-archive",
- "application/x-bzip",
- "application/x-bzip2",
- "application/zip",
- "application/gzip",
- "application/x-tar",
- "application/msword",
- "application/vnd.ms-excel",
- "application/vnd.ms-powerpoint",
- "application/pdf" );
+ || containsAny( contentType, "+zip", "+gzip" )
+ || equalsAny( contentType,
+ "application/octet-stream",
+ "application/java-archive",
+ "application/x-bzip",
+ "application/x-bzip2",
+ "application/zip",
+ "application/gzip",
+ "application/x-tar",
+ "application/msword",
+ "application/vnd.ms-excel",
+ "application/vnd.ms-powerpoint",
+ "application/pdf" );
}
public static DigestItem dependency( HashChecksum checksum, String key, String hash )
diff --git a/src/main/java/org/apache/maven/buildcache/checksum/KeyUtils.java b/src/main/java/org/apache/maven/buildcache/checksum/KeyUtils.java
index ce790d2..1d07642 100644
--- a/src/main/java/org/apache/maven/buildcache/checksum/KeyUtils.java
+++ b/src/main/java/org/apache/maven/buildcache/checksum/KeyUtils.java
@@ -48,13 +48,13 @@ public class KeyUtils
public static String getArtifactKey( Artifact artifact )
{
return getArtifactKey( artifact.getGroupId(), artifact.getArtifactId(), artifact.getType(),
- artifact.getClassifier(), artifact.getVersion() );
+ artifact.getClassifier(), artifact.getVersion() );
}
public static String getVersionlessArtifactKey( org.apache.maven.artifact.Artifact artifact )
{
return getVersionlessArtifactKey( artifact.getGroupId(), artifact.getArtifactId(), artifact.getType(),
- artifact.getClassifier() );
+ artifact.getClassifier() );
}
/**
@@ -63,17 +63,17 @@ public class KeyUtils
public static String getArtifactKey( Artifact artifact, String type )
{
return getArtifactKey( artifact.getGroupId(), artifact.getArtifactId(), type,
- artifact.getClassifier(), artifact.getVersion() );
+ artifact.getClassifier(), artifact.getVersion() );
}
public static String getArtifactKey( org.apache.maven.artifact.Artifact artifact )
{
return getArtifactKey( artifact.getGroupId(), artifact.getArtifactId(), artifact.getType(),
- artifact.getClassifier(), artifact.getVersion() );
+ artifact.getClassifier(), artifact.getVersion() );
}
public static String getArtifactKey( String groupId, String artifactId, String type,
- String classifier, String version )
+ String classifier, String version )
{
if ( classifier != null )
{
@@ -86,7 +86,7 @@ public class KeyUtils
}
public static String getVersionlessArtifactKey( String groupId, String artifactId, String type,
- String classifier )
+ String classifier )
{
if ( classifier != null )
{
diff --git a/src/main/java/org/apache/maven/buildcache/checksum/MavenProjectInput.java b/src/main/java/org/apache/maven/buildcache/checksum/MavenProjectInput.java
index a717421..c5054a7 100644
--- a/src/main/java/org/apache/maven/buildcache/checksum/MavenProjectInput.java
+++ b/src/main/java/org/apache/maven/buildcache/checksum/MavenProjectInput.java
@@ -104,21 +104,25 @@ public class MavenProjectInput
* property name to pass glob value. The glob to be used to list directory files in plugins scanning
*/
private static final String CACHE_INPUT_GLOB_NAME = "maven.build.cache.input.glob";
+
/**
* default glob, bbsdk/abfx specific
*/
public static final String DEFAULT_GLOB = "{*.java,*.groovy,*.yaml,*.svcd,*.proto,*assembly.xml,assembly"
- + "*.xml,*logback.xml,*.vm,*.ini,*.jks,*.properties,*.sh,*.bat}";
+ + "*.xml,*logback.xml,*.vm,*.ini,*.jks,*.properties,*.sh,*.bat}";
+
/**
* property name prefix to pass input files with project properties. smth like maven.build.cache.input.1 will be
* accepted
*/
private static final String CACHE_INPUT_NAME = "maven.build.cache.input";
+
/**
* property name prefix to exclude files from input. smth like maven.build.cache.exclude.1 should be set in project
* props
*/
private static final String CACHE_EXCLUDE_NAME = "maven.build.cache.exclude";
+
/**
* Flag to control if we should check values from plugin configs as file system objects
*/
@@ -127,28 +131,40 @@ public class MavenProjectInput
private static final Logger LOGGER = LoggerFactory.getLogger( MavenProjectInput.class );
private final MavenProject project;
+
private final MavenSession session;
+
private final RemoteCacheRepository remoteCache;
+
private final RepositorySystem repoSystem;
+
private final CacheConfig config;
+
private final PathIgnoringCaseComparator fileComparator;
+
private final List<Path> filteredOutPaths;
+
private final NormalizedModelProvider normalizedModelProvider;
+
private final MultiModuleSupport multiModuleSupport;
+
private final ProjectInputCalculator projectInputCalculator;
+
private final Path baseDirPath;
+
private final String dirGlob;
+
private final boolean processPlugins;
@SuppressWarnings( "checkstyle:parameternumber" )
public MavenProjectInput( MavenProject project,
- NormalizedModelProvider normalizedModelProvider,
- MultiModuleSupport multiModuleSupport,
- ProjectInputCalculator projectInputCalculator,
- MavenSession session,
- CacheConfig config,
- RepositorySystem repoSystem,
- RemoteCacheRepository remoteCache )
+ NormalizedModelProvider normalizedModelProvider,
+ MultiModuleSupport multiModuleSupport,
+ ProjectInputCalculator projectInputCalculator,
+ MavenSession session,
+ CacheConfig config,
+ RepositorySystem repoSystem,
+ RemoteCacheRepository remoteCache )
{
this.project = project;
this.normalizedModelProvider = normalizedModelProvider;
@@ -162,11 +178,12 @@ public class MavenProjectInput
Properties properties = project.getProperties();
this.dirGlob = properties.getProperty( CACHE_INPUT_GLOB_NAME, config.getDefaultGlob() );
this.processPlugins = Boolean.parseBoolean(
- properties.getProperty( CACHE_PROCESS_PLUGINS, config.isProcessPlugins() ) );
+ properties.getProperty( CACHE_PROCESS_PLUGINS, config.isProcessPlugins() ) );
org.apache.maven.model.Build build = project.getBuild();
filteredOutPaths = new ArrayList<>( Arrays.asList( normalizedPath( build.getDirectory() ), // target by default
- normalizedPath( build.getOutputDirectory() ), normalizedPath( build.getTestOutputDirectory() ) ) );
+ normalizedPath( build.getOutputDirectory() ),
+ normalizedPath( build.getTestOutputDirectory() ) ) );
List<Exclude> excludes = config.getGlobalExcludePaths();
for ( Exclude excludePath : excludes )
@@ -256,7 +273,7 @@ public class MavenProjectInput
LOGGER.debug( "Hash calculated, item: {}, hash: {}", item.getType(), item.getHash() );
}
LOGGER.info( "Project inputs calculated in {} ms. {} checksum [{}] calculated in {} ms.",
- t1 - t0, config.getHashFactory().getAlgorithm(), projectsInputInfoType.getChecksum(), t2 - t1 );
+ t1 - t0, config.getHashFactory().getAlgorithm(), projectsInputInfoType.getChecksum(), t2 - t1 );
return projectsInputInfoType;
}
@@ -279,7 +296,7 @@ public class MavenProjectInput
if ( !matches )
{
LOGGER.info( "Mismatch in effective poms. Current: {}, remote: {}",
- effectivePomChecksum.getHash(), pomItem.getHash() );
+ effectivePomChecksum.getHash(), pomItem.getHash() );
}
LOGGER.info( "Effective pom: {}", matches ? "MATCHED" : "OUT OF DATE" );
}
@@ -291,7 +308,7 @@ public class MavenProjectInput
for ( DigestItem it : baselineBuild.getItems() )
{
if ( it.getType().equals( fileDigest.getType() )
- && fileDigest.getValue().equals( it.getValue().trim() ) )
+ && fileDigest.getValue().equals( it.getValue().trim() ) )
{
baselineFileDigest = Optional.of( it );
break;
@@ -306,13 +323,13 @@ public class MavenProjectInput
if ( !matched )
{
LOGGER.info( "Mismatch in {}: {}. Local hash: {}, remote: {}",
- fileDigest.getType(), fileDigest.getValue(), fileDigest.getHash(), hash );
+ fileDigest.getType(), fileDigest.getValue(), fileDigest.getHash(), hash );
}
}
else
{
LOGGER.info( "Mismatch in {}: {}. Not found in remote cache",
- fileDigest.getType(), fileDigest.getValue() );
+ fileDigest.getType(), fileDigest.getValue() );
}
return matched;
}
@@ -330,7 +347,7 @@ public class MavenProjectInput
writer = WriterFactory.newXmlWriter( output );
new MavenXpp3Writer().write( writer, prototype );
- //normalize env specifics
+ // normalize env specifics
final String[] searchList =
{ baseDirPath.toString(), "\\", "windows", "linux"
};
@@ -389,8 +406,8 @@ public class MavenProjectInput
long walkKnownPathsFinished = System.currentTimeMillis() - start;
LOGGER.info( "Scanning plugins configurations to find input files. Probing is {}", processPlugins
- ? "enabled, values will be checked for presence in file system"
- : "disabled, only tags with attribute " + CACHE_INPUT_NAME + "=\"true\" will be added" );
+ ? "enabled, values will be checked for presence in file system"
+ : "disabled, only tags with attribute " + CACHE_INPUT_NAME + "=\"true\" will be added" );
if ( processPlugins )
{
@@ -410,7 +427,7 @@ public class MavenProjectInput
}
LOGGER.info( "Found {} input files. Project dir processing: {}, plugins: {} millis",
- sorted.size(), walkKnownPathsFinished, pluginsFinished );
+ sorted.size(), walkKnownPathsFinished, pluginsFinished );
LOGGER.debug( "Src input: {}", sorted );
return sorted;
@@ -420,10 +437,10 @@ public class MavenProjectInput
* entry point for directory walk
*/
private void startWalk( Path candidate,
- String glob,
- boolean recursive,
- List<Path> collectedFiles,
- Set<WalkKey> visitedDirs )
+ String glob,
+ boolean recursive,
+ List<Path> collectedFiles,
+ Set<WalkKey> visitedDirs )
{
Path normalized = candidate.isAbsolute() ? candidate : baseDirPath.resolve( candidate );
normalized = normalized.toAbsolutePath().normalize();
@@ -492,7 +509,7 @@ public class MavenProjectInput
if ( mergedConfig.isSkip() )
{
LOGGER.debug( "Skipping plugin execution config scan (skip by config): {}, execId: {}",
- plugin.getArtifactId(), exec.getId() );
+ plugin.getArtifactId(), exec.getId() );
continue;
}
@@ -502,25 +519,25 @@ public class MavenProjectInput
if ( execConfiguration != null )
{
addInputsFromPluginConfigs( Xpp3DomUtils.getChildren( execConfiguration ), mergedConfig, files,
- visitedDirs );
+ visitedDirs );
}
}
}
}
private Path walkDir( final WalkKey key,
- final List<Path> collectedFiles,
- final Set<WalkKey> visitedDirs ) throws IOException
+ final List<Path> collectedFiles,
+ final Set<WalkKey> visitedDirs ) throws IOException
{
return Files.walkFileTree( key.getPath(), new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult preVisitDirectory( Path path,
- BasicFileAttributes basicFileAttributes ) throws IOException
+ BasicFileAttributes basicFileAttributes ) throws IOException
{
WalkKey currentDirKey = new WalkKey( path.toAbsolutePath().normalize(), key.getGlob(),
- key.isRecursive() );
+ key.isRecursive() );
if ( isHidden( path ) )
{
LOGGER.debug( "Skipping subtree (hidden): {}", path );
@@ -538,11 +555,11 @@ public class MavenProjectInput
}
walkDirectoryFiles(
- path,
- collectedFiles,
- key.getGlob(),
- entry -> filteredOutPaths.stream()
- .anyMatch( it -> it.getFileName().equals( entry.getFileName() ) ) );
+ path,
+ collectedFiles,
+ key.getGlob(),
+ entry -> filteredOutPaths.stream()
+ .anyMatch( it -> it.getFileName().equals( entry.getFileName() ) ) );
if ( !key.isRecursive() )
{
@@ -557,8 +574,8 @@ public class MavenProjectInput
}
private void addInputsFromPluginConfigs( Object[] configurationChildren,
- PluginScanConfig scanConfig,
- List<Path> files, HashSet<WalkKey> visitedDirs )
+ PluginScanConfig scanConfig,
+ List<Path> files, HashSet<WalkKey> visitedDirs )
{
if ( configurationChildren == null )
{
@@ -573,7 +590,7 @@ public class MavenProjectInput
if ( !scanConfig.accept( tagName ) )
{
LOGGER.debug( "Skipping property (scan config)): {}, value: {}",
- tagName, stripToEmpty( tagValue ) );
+ tagName, stripToEmpty( tagValue ) );
continue;
}
@@ -586,7 +603,7 @@ public class MavenProjectInput
if ( "true".equals( Xpp3DomUtils.getAttribute( configChild, CACHE_INPUT_NAME ) ) )
{
LOGGER.info( "Found tag marked with {} attribute. Tag: {}, value: {}",
- CACHE_INPUT_NAME, tagName, tagValue );
+ CACHE_INPUT_NAME, tagName, tagValue );
startWalk( Paths.get( tagValue ), glob, propertyConfig.isRecursive(), files, visitedDirs );
}
else
@@ -598,7 +615,7 @@ public class MavenProjectInput
if ( "descriptorRef".equals( tagName ) )
{ // hardcoded logic for assembly plugin which could reference files omitting .xml suffix
startWalk( Paths.get( tagValue + ".xml" ), glob, propertyConfig.isRecursive(), files,
- visitedDirs );
+ visitedDirs );
}
}
}
@@ -609,13 +626,13 @@ public class MavenProjectInput
{
// small optimization to not probe not-paths
boolean blacklisted = isBlank( text )
- || equalsAnyIgnoreCase( text, "true", "false", "utf-8", "null", "\\" ) // common values
- || contains( text, "*" ) // tag value is a glob or regex - unclear how to process
- || ( contains( text, ":" ) && !contains( text, ":\\" ) )// artifactId
- || startsWithAny( text, "com.", "org.", "io.", "java.", "javax." ) // java packages
- || startsWithAny( text, "${env." ) // env variables in maven notation
- || startsWithAny( text, "http:", "https:", "scm:", "ssh:", "git:", "svn:", "cp:",
- "classpath:" ); // urls identified by common protocols
+ || equalsAnyIgnoreCase( text, "true", "false", "utf-8", "null", "\\" ) // common values
+ || contains( text, "*" ) // tag value is a glob or regex - unclear how to process
+ || ( contains( text, ":" ) && !contains( text, ":\\" ) )// artifactId
+ || startsWithAny( text, "com.", "org.", "io.", "java.", "javax." ) // java packages
+ || startsWithAny( text, "${env." ) // env variables in maven notation
+ || startsWithAny( text, "http:", "https:", "scm:", "ssh:", "git:", "svn:", "cp:",
+ "classpath:" ); // urls identified by common protocols
if ( !blacklisted )
{
try
@@ -697,10 +714,10 @@ public class MavenProjectInput
// saved to index by the end of dependency build
MavenProject dependencyProject = multiModuleSupport.tryToResolveProject(
- dependency.getGroupId(),
- dependency.getArtifactId(),
- dependency.getVersion() )
- .orElse( null );
+ dependency.getGroupId(),
+ dependency.getArtifactId(),
+ dependency.getVersion() )
+ .orElse( null );
boolean isSnapshot = isSnapshot( dependency.getVersion() );
if ( dependencyProject == null && !isSnapshot )
{
@@ -708,39 +725,39 @@ public class MavenProjectInput
continue;
}
String projectHash;
- if ( dependencyProject != null ) //part of multi module
+ if ( dependencyProject != null ) // part of multi module
{
projectHash = projectInputCalculator.calculateInput( dependencyProject ).getChecksum();
}
- else //this is a snapshot dependency
+ else // this is a snapshot dependency
{
DigestItem resolved = resolveArtifact(
- repoSystem.createDependencyArtifact( dependency ),
- false );
+ repoSystem.createDependencyArtifact( dependency ),
+ false );
projectHash = resolved.getHash();
}
result.put(
- KeyUtils.getVersionlessArtifactKey( repoSystem.createDependencyArtifact( dependency ) ),
- projectHash );
+ KeyUtils.getVersionlessArtifactKey( repoSystem.createDependencyArtifact( dependency ) ),
+ projectHash );
}
return result;
}
@Nonnull
private DigestItem resolveArtifact( final Artifact dependencyArtifact,
- boolean isOffline ) throws IOException
+ boolean isOffline ) throws IOException
{
ArtifactResolutionRequest request = new ArtifactResolutionRequest()
- .setArtifact( dependencyArtifact )
- .setResolveRoot( true )
- .setResolveTransitively( false )
- .setLocalRepository( session.getLocalRepository() )
- .setRemoteRepositories( project.getRemoteArtifactRepositories() )
- .setOffline( session.isOffline() || isOffline )
- .setForceUpdate( session.getRequest().isUpdateSnapshots() )
- .setServers( session.getRequest().getServers() )
- .setMirrors( session.getRequest().getMirrors() )
- .setProxies( session.getRequest().getProxies() );
+ .setArtifact( dependencyArtifact )
+ .setResolveRoot( true )
+ .setResolveTransitively( false )
+ .setLocalRepository( session.getLocalRepository() )
+ .setRemoteRepositories( project.getRemoteArtifactRepositories() )
+ .setOffline( session.isOffline() || isOffline )
+ .setForceUpdate( session.getRequest().isUpdateSnapshots() )
+ .setServers( session.getRequest().getServers() )
+ .setMirrors( session.getRequest().getMirrors() )
+ .setProxies( session.getRequest().getProxies() );
final ArtifactResolutionResult result = repoSystem.resolve( request );
@@ -752,14 +769,15 @@ public class MavenProjectInput
if ( !result.getMissingArtifacts().isEmpty() )
{
throw new DependencyNotResolvedException(
- "Cannot resolve artifact: " + dependencyArtifact + ", missing: " + result.getMissingArtifacts() );
+ "Cannot resolve artifact: " + dependencyArtifact + ", missing: "
+ + result.getMissingArtifacts() );
}
if ( result.getArtifacts().size() != 1 )
{
throw new IllegalStateException(
- "Unexpected number of artifacts returned. Requested: " + dependencyArtifact
- + ", expected: 1, actual: " + result.getArtifacts() );
+ "Unexpected number of artifacts returned. Requested: " + dependencyArtifact
+ + ", expected: 1, actual: " + result.getArtifacts() );
}
final Artifact resolved = result.getArtifacts().iterator().next();
diff --git a/src/main/java/org/apache/maven/buildcache/checksum/WalkKey.java b/src/main/java/org/apache/maven/buildcache/checksum/WalkKey.java
index 2d5803d..611a5cf 100644
--- a/src/main/java/org/apache/maven/buildcache/checksum/WalkKey.java
+++ b/src/main/java/org/apache/maven/buildcache/checksum/WalkKey.java
@@ -27,7 +27,9 @@ public class WalkKey
{
private final Path normalized;
+
private final String glob;
+
private final boolean recursive;
public WalkKey( Path normalized, String glob, boolean recursive )
@@ -49,7 +51,7 @@ public class WalkKey
return false;
}
- WalkKey key = ( WalkKey ) o;
+ WalkKey key = (WalkKey) o;
if ( recursive != key.recursive )
{
diff --git a/src/main/java/org/apache/maven/buildcache/hash/CloseableBuffer.java b/src/main/java/org/apache/maven/buildcache/hash/CloseableBuffer.java
index c884d1b..4b7253f 100644
--- a/src/main/java/org/apache/maven/buildcache/hash/CloseableBuffer.java
+++ b/src/main/java/org/apache/maven/buildcache/hash/CloseableBuffer.java
@@ -122,8 +122,10 @@ public class CloseableBuffer implements AutoCloseable
{
private static final Method ATTACHMENT = getMethod( "sun.nio.ch.DirectBuffer",
- "attachment" );
+ "attachment" );
+
private static final Method CLEANER = getMethod( "sun.nio.ch.DirectBuffer", "cleaner" );
+
private static final Method CLEAN = getMethod( "sun.misc.Cleaner", "clean" );
public static boolean isSupported()
@@ -159,6 +161,7 @@ public class CloseableBuffer implements AutoCloseable
// Java 9: getMethod("jdk.internal.misc.Unsafe", "invokeCleaner", ByteBuffer.class);
private static final Method INVOKE_CLEANER = getMethod( "sun.misc.Unsafe", "invokeCleaner", ByteBuffer.class );
+
private static final Object UNSAFE = getField( "sun.misc.Unsafe", "theUnsafe" );
public static boolean isSupported()
@@ -168,8 +171,7 @@ public class CloseableBuffer implements AutoCloseable
/**
* Calling the above code in JDK9+ gives a reflection warning on stderr,
- * Unsafe.theUnsafe.invokeCleaner(byteBuffer)
- * makes the same call, but does not print the reflection warning
+ * Unsafe.theUnsafe.invokeCleaner(byteBuffer) makes the same call, but does not print the reflection warning
*/
@Override
public boolean clean( ByteBuffer buffer )
diff --git a/src/main/java/org/apache/maven/buildcache/hash/HashChecksum.java b/src/main/java/org/apache/maven/buildcache/hash/HashChecksum.java
index e9099e9..8ce5939 100644
--- a/src/main/java/org/apache/maven/buildcache/hash/HashChecksum.java
+++ b/src/main/java/org/apache/maven/buildcache/hash/HashChecksum.java
@@ -28,6 +28,7 @@ public class HashChecksum
{
private final Hash.Algorithm algorithm;
+
private final Hash.Checksum checksum;
HashChecksum( Hash.Algorithm algorithm, Hash.Checksum checksum )
diff --git a/src/main/java/org/apache/maven/buildcache/hash/HexUtils.java b/src/main/java/org/apache/maven/buildcache/hash/HexUtils.java
index 1b18a37..f6b9f0a 100644
--- a/src/main/java/org/apache/maven/buildcache/hash/HexUtils.java
+++ b/src/main/java/org/apache/maven/buildcache/hash/HexUtils.java
@@ -28,6 +28,7 @@ public class HexUtils
{
private static final byte[] ENC_ARRAY;
+
private static final byte[] DEC_ARRAY;
static
@@ -36,12 +37,12 @@ public class HexUtils
DEC_ARRAY = new byte[256];
for ( byte i = 0; i < 10; i++ )
{
- ENC_ARRAY[i] = ( byte ) ( '0' + i );
+ ENC_ARRAY[i] = (byte) ( '0' + i );
DEC_ARRAY['0' + i] = i;
}
for ( byte i = 10; i < 16; i++ )
{
- ENC_ARRAY[i] = ( byte ) ( 'a' + i - 10 );
+ ENC_ARRAY[i] = (byte) ( 'a' + i - 10 );
DEC_ARRAY['a' + i - 10] = i;
DEC_ARRAY['A' + i - 10] = i;
}
@@ -70,7 +71,7 @@ public class HexUtils
int idx = 0;
for ( int i = 0; i < size; i += 2 )
{
- bytes[idx++] = ( byte ) ( DEC_ARRAY[hex.charAt( i )] << 4 | DEC_ARRAY[hex.charAt( i + 1 )] );
+ bytes[idx++] = (byte) ( DEC_ARRAY[hex.charAt( i )] << 4 | DEC_ARRAY[hex.charAt( i + 1 )] );
}
return bytes;
}
@@ -80,7 +81,7 @@ public class HexUtils
byte[] result = new byte[8];
for ( int i = 7; i >= 0; i-- )
{
- result[i] = ( byte ) ( value & 0xFF );
+ result[i] = (byte) ( value & 0xFF );
value >>= 8;
}
return result;
diff --git a/src/main/java/org/apache/maven/buildcache/hash/SHA.java b/src/main/java/org/apache/maven/buildcache/hash/SHA.java
index 0292e03..80aab46 100644
--- a/src/main/java/org/apache/maven/buildcache/hash/SHA.java
+++ b/src/main/java/org/apache/maven/buildcache/hash/SHA.java
@@ -30,6 +30,7 @@ public class SHA implements Hash.Factory
{
private static final ThreadLocal<MessageDigest> ALGORITHM = new ThreadLocal<>();
+
private static final ThreadLocal<MessageDigest> CHECKSUM = new ThreadLocal<>();
private final String algorithm;
diff --git a/src/main/java/org/apache/maven/buildcache/hash/ThreadLocalBuffer.java b/src/main/java/org/apache/maven/buildcache/hash/ThreadLocalBuffer.java
index ef42774..4f35b62 100644
--- a/src/main/java/org/apache/maven/buildcache/hash/ThreadLocalBuffer.java
+++ b/src/main/java/org/apache/maven/buildcache/hash/ThreadLocalBuffer.java
@@ -21,6 +21,7 @@ package org.apache.maven.buildcache.hash;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
+import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
/**
* ThreadLocalBuffer
@@ -69,9 +70,10 @@ public class ThreadLocalBuffer
return buffer.getBuffer().capacity();
}
+ @IgnoreJRERequirement
private static ByteBuffer clear( CloseableBuffer buffer )
{
- return ( ByteBuffer ) buffer.getBuffer().clear();
+ return (ByteBuffer) buffer.getBuffer().clear();
}
private static void close( CloseableBuffer buffer )
diff --git a/src/main/java/org/apache/maven/buildcache/hash/XXMM.java b/src/main/java/org/apache/maven/buildcache/hash/XXMM.java
index 6d7682e..ac143d7 100644
--- a/src/main/java/org/apache/maven/buildcache/hash/XXMM.java
+++ b/src/main/java/org/apache/maven/buildcache/hash/XXMM.java
@@ -58,7 +58,7 @@ public class XXMM implements Hash.Factory
public byte[] hash( Path path ) throws IOException
{
try ( FileChannel channel = FileChannel.open( path, READ );
- CloseableBuffer buffer = CloseableBuffer.mappedBuffer( channel, READ_ONLY ) )
+ CloseableBuffer buffer = CloseableBuffer.mappedBuffer( channel, READ_ONLY ) )
{
return HexUtils.toByteArray( XX.INSTANCE.hashBytes( buffer.getBuffer() ) );
}
diff --git a/src/main/java/org/apache/maven/buildcache/xml/Build.java b/src/main/java/org/apache/maven/buildcache/xml/Build.java
index 6ce7422..87afcd5 100644
--- a/src/main/java/org/apache/maven/buildcache/xml/Build.java
+++ b/src/main/java/org/apache/maven/buildcache/xml/Build.java
@@ -47,15 +47,17 @@ public class Build
{
final org.apache.maven.buildcache.xml.build.Build dto;
+
CacheSource source;
+
volatile Map<String, CompletedExecution> execMap;
public Build( List<String> goals,
- Artifact artifact,
- List<Artifact> attachedArtifacts,
- ProjectsInputInfo projectsInputInfo,
- List<CompletedExecution> completedExecutions,
- String hashAlgorithm )
+ Artifact artifact,
+ List<Artifact> attachedArtifacts,
+ ProjectsInputInfo projectsInputInfo,
+ List<CompletedExecution> completedExecutions,
+ String hashAlgorithm )
{
this.dto = new org.apache.maven.buildcache.xml.build.Build();
this.dto.setCacheImplementationVersion( MavenProjectInput.CACHE_IMPLEMENTATION_VERSION );
@@ -89,7 +91,7 @@ public class Build
}
public static List<Artifact> createAttachedArtifacts( List<org.apache.maven.artifact.Artifact> artifacts,
- HashAlgorithm algorithm ) throws IOException
+ HashAlgorithm algorithm ) throws IOException
{
List<Artifact> attachedArtifacts = new ArrayList<>();
for ( org.apache.maven.artifact.Artifact artifact : artifacts )
@@ -107,8 +109,8 @@ public class Build
public List<MojoExecution> getMissingExecutions( List<MojoExecution> mojos )
{
return mojos.stream()
- .filter( mojo -> !hasCompletedExecution( mojoExecutionKey( mojo ) ) )
- .collect( Collectors.toList() );
+ .filter( mojo -> !hasCompletedExecution( mojoExecutionKey( mojo ) ) )
+ .collect( Collectors.toList() );
}
private boolean hasCompletedExecution( String mojoExecutionKey )
@@ -177,9 +179,9 @@ public class Build
private boolean isEquals( Dependency dependency, Artifact artifact )
{
return Objects.equals( dependency.getGroupId(), artifact.getGroupId() )
- && Objects.equals( dependency.getArtifactId(), artifact.getArtifactId() )
- && Objects.equals( dependency.getType(), artifact.getType() )
- && Objects.equals( dependency.getClassifier(), artifact.getClassifier() );
+ && Objects.equals( dependency.getArtifactId(), artifact.getArtifactId() )
+ && Objects.equals( dependency.getType(), artifact.getType() )
+ && Objects.equals( dependency.getClassifier(), artifact.getClassifier() );
}
private Map<String, CompletedExecution> getExecutionMap()
@@ -195,7 +197,7 @@ public class Build
return execMap;
}
execMap = executionsList.stream()
- .collect( Collectors.toMap( CompletedExecution::getExecutionKey, v -> v ) );
+ .collect( Collectors.toMap( CompletedExecution::getExecutionKey, v -> v ) );
return execMap;
}
}
diff --git a/src/main/java/org/apache/maven/buildcache/xml/CacheConfigImpl.java b/src/main/java/org/apache/maven/buildcache/xml/CacheConfigImpl.java
index bab8e15..dae58d5 100644
--- a/src/main/java/org/apache/maven/buildcache/xml/CacheConfigImpl.java
+++ b/src/main/java/org/apache/maven/buildcache/xml/CacheConfigImpl.java
@@ -78,23 +78,35 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
{
public static final String CONFIG_PATH_PROPERTY_NAME = "maven.build.cache.configPath";
+
public static final String CACHE_ENABLED_PROPERTY_NAME = "maven.build.cache.enabled";
+
public static final String SAVE_TO_REMOTE_PROPERTY_NAME = "maven.build.cache.remote.save.enabled";
+
public static final String SAVE_NON_OVERRIDEABLE_NAME = "maven.build.cache.remote.save.final";
+
public static final String FAIL_FAST_PROPERTY_NAME = "maven.build.cache.failFast";
+
public static final String BASELINE_BUILD_URL_PROPERTY_NAME = "maven.build.cache.baselineUrl";
+
public static final String LAZY_RESTORE_PROPERTY_NAME = "maven.build.cache.lazyRestore";
+
public static final String RESTORE_GENERATED_SOURCES_PROPERTY_NAME = "maven.build.cache.restoreGeneratedSources";
+
public static final String ALWAYS_RUN_PLUGINS = "maven.build.cache.alwaysRunPlugins";
private static final Logger LOGGER = LoggerFactory.getLogger( CacheConfigImpl.class );
private final XmlService xmlService;
+
private final MavenSession session;
private CacheState state;
+
private CacheConfig cacheConfig;
+
private HashFactory hashFactory;
+
private List<Pattern> excludePatterns;
@Inject
@@ -128,13 +140,13 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
else
{
configPath = getMultimoduleRoot( session ).resolve( ".mvn" )
- .resolve( "maven-build-cache-config.xml" );
+ .resolve( "maven-build-cache-config.xml" );
}
if ( !Files.exists( configPath ) )
{
LOGGER.info( "Cache configuration is not available at configured path {}, "
- + "cache is enabled with defaults", configPath );
+ + "cache is enabled with defaults", configPath );
cacheConfig = new CacheConfig();
}
else
@@ -148,7 +160,7 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
catch ( Exception e )
{
throw new IllegalArgumentException(
- "Cannot initialize cache because xml config is not valid or not available", e );
+ "Cannot initialize cache because xml config is not valid or not available", e );
}
}
fillWithDefaults( cacheConfig );
@@ -230,7 +242,7 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
return true;
}
return cacheConfig.getExecutionControl() != null && cacheConfig.getExecutionControl().getReconcile() != null
- && cacheConfig.getExecutionControl().getReconcile().isLogAllProperties();
+ && cacheConfig.getExecutionControl().getReconcile().isLogAllProperties();
}
private GoalReconciliation findReconciliationConfig( MojoExecution mojoExecution )
@@ -253,7 +265,7 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
final String goal = mojoExecution.getGoal();
if ( isPluginMatch( mojoExecution.getPlugin(), goalReconciliationConfig ) && StringUtils.equals( goal,
- goalReconciliationConfig.getGoal() ) )
+ goalReconciliationConfig.getGoal() ) )
{
return goalReconciliationConfig;
}
@@ -337,9 +349,9 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
private boolean isPluginMatch( Plugin plugin, CoordinatesBase pluginConfig )
{
return StringUtils.equals( pluginConfig.getArtifactId(),
- plugin.getArtifactId() )
- && ( pluginConfig.getGroupId() == null || StringUtils.equals(
- pluginConfig.getGroupId(), plugin.getGroupId() ) );
+ plugin.getArtifactId() )
+ && ( pluginConfig.getGroupId() == null || StringUtils.equals(
+ pluginConfig.getGroupId(), plugin.getGroupId() ) );
}
@Nonnull
@@ -366,7 +378,7 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
if ( pluginScanConfig != null )
{
final ExecutionConfigurationScan executionScanConfig = findExecutionScanConfig( exec,
- pluginScanConfig.getExecutions() );
+ pluginScanConfig.getExecutions() );
if ( executionScanConfig != null && executionScanConfig.getDirScan() != null )
{
return new PluginScanConfigImpl( executionScanConfig.getDirScan() );
@@ -377,7 +389,7 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
}
private ExecutionConfigurationScan findExecutionScanConfig( PluginExecution execution,
- List<ExecutionConfigurationScan> scanConfigs )
+ List<ExecutionConfigurationScan> scanConfigs )
{
for ( ExecutionConfigurationScan executionScanConfig : scanConfigs )
{
@@ -466,7 +478,7 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
for ( ExecutionIdsList executionConfig : executionIds )
{
if ( isPluginMatch( execution.getPlugin(), executionConfig ) && executionConfig.getExecIds().contains(
- execution.getExecutionId() ) )
+ execution.getExecutionId() ) )
{
return true;
}
@@ -476,7 +488,7 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
for ( GoalsList pluginGoals : pluginsGoalsList )
{
if ( isPluginMatch( execution.getPlugin(), pluginGoals ) && pluginGoals.getGoals().contains(
- execution.getGoal() ) )
+ execution.getGoal() ) )
{
return true;
}
@@ -589,8 +601,8 @@ public class CacheConfigImpl implements org.apache.maven.buildcache.xml.CacheCon
public boolean adjustMetaInfVersion()
{
return Optional.ofNullable( getConfiguration().getProjectVersioning() )
- .map( ProjectVersioning::isAdjustMetaInf )
- .orElse( false );
+ .map( ProjectVersioning::isAdjustMetaInf )
+ .orElse( false );
}
@Nonnull
diff --git a/src/main/java/org/apache/maven/buildcache/xml/DtoUtils.java b/src/main/java/org/apache/maven/buildcache/xml/DtoUtils.java
index 3726be5..2e04e1f 100644
--- a/src/main/java/org/apache/maven/buildcache/xml/DtoUtils.java
+++ b/src/main/java/org/apache/maven/buildcache/xml/DtoUtils.java
@@ -113,10 +113,10 @@ public class DtoUtils
}
public static void addProperty( CompletedExecution execution,
- String propertyName,
- Object value,
- String baseDirPath,
- boolean tracked )
+ String propertyName,
+ Object value,
+ String baseDirPath,
+ boolean tracked )
{
final PropertyValue valueType = new PropertyValue();
valueType.setName( propertyName );
@@ -131,7 +131,8 @@ public class DtoUtils
}
public static boolean containsAllProperties(
- @Nonnull CompletedExecution cachedExecution, List<TrackedProperty> trackedProperties )
+ @Nonnull
+ CompletedExecution cachedExecution, List<TrackedProperty> trackedProperties )
{
if ( trackedProperties == null || trackedProperties.isEmpty() )
{
diff --git a/src/test/java/org/apache/maven/buildcache/BuildInfoTest.java b/src/test/java/org/apache/maven/buildcache/BuildInfoTest.java
index a392ee7..3eac852 100644
--- a/src/test/java/org/apache/maven/buildcache/BuildInfoTest.java
+++ b/src/test/java/org/apache/maven/buildcache/BuildInfoTest.java
@@ -72,10 +72,10 @@ public class BuildInfoTest
buildInfo.setHashFunction( "SHA-256" );
buildInfo.setGoals( Collections.singletonList( "install" ) );
final org.apache.maven.artifact.Artifact attachedArtifact = new DefaultArtifact( "ag", "aa", "av", "as", "at",
- "ac",
- new DefaultArtifactHandler() );
+ "ac",
+ new DefaultArtifactHandler() );
buildInfo.setAttachedArtifacts( Build.createAttachedArtifacts( Collections.singletonList( attachedArtifact ),
- HashFactory.XX.createAlgorithm() ) );
+ HashFactory.XX.createAlgorithm() ) );
buildInfo.setProjectsInputInfo( main );
buildInfo.setExecutions( createExecutions() );
diff --git a/src/test/java/org/apache/maven/buildcache/checksum/MavenProjectInputTest.java b/src/test/java/org/apache/maven/buildcache/checksum/MavenProjectInputTest.java
index 79c2a58..376b6fd 100644
--- a/src/test/java/org/apache/maven/buildcache/checksum/MavenProjectInputTest.java
+++ b/src/test/java/org/apache/maven/buildcache/checksum/MavenProjectInputTest.java
@@ -34,31 +34,32 @@ public class MavenProjectInputTest
@Test
public void testAddInputsRelativePath()
{
- // MavenProjectInput inputs = new MavenProjectInput(config, new ArrayList<Path>(), Paths.get("src\\test\\resources\\org"), GLOB);
- // ArrayList<Path> files = new ArrayList<>();
- // inputs.listDirOrFile("../../resources", inputs.dirGlob, files, new HashSet<Path>());
- // assertEquals(4, files.size());
+ // MavenProjectInput inputs = new MavenProjectInput(config, new ArrayList<Path>(),
+ // Paths.get("src\\test\\resources\\org"), GLOB);
+ // ArrayList<Path> files = new ArrayList<>();
+ // inputs.listDirOrFile("../../resources", inputs.dirGlob, files, new HashSet<Path>());
+ // assertEquals(4, files.size());
}
@Test
public void testAddInputsAbsolutePath()
{
- // Path baseDirPath = Paths.get("src\\test\\resources\\org");
- // MavenProjectInput inputs = new MavenProjectInput(config, new ArrayList<Path>(), baseDirPath, GLOB);
- // ArrayList<Path> files = new ArrayList<>();
- // Path candidatePath = baseDirPath.resolve("../../resources").normalize().toAbsolutePath();
- // inputs.listDirOrFile(candidatePath.toString(), inputs.dirGlob, files, new HashSet<Path>());
- // assertEquals(4, files.size()); // pom is filtered out by hardcoded if
+ // Path baseDirPath = Paths.get("src\\test\\resources\\org");
+ // MavenProjectInput inputs = new MavenProjectInput(config, new ArrayList<Path>(), baseDirPath, GLOB);
+ // ArrayList<Path> files = new ArrayList<>();
+ // Path candidatePath = baseDirPath.resolve("../../resources").normalize().toAbsolutePath();
+ // inputs.listDirOrFile(candidatePath.toString(), inputs.dirGlob, files, new HashSet<Path>());
+ // assertEquals(4, files.size()); // pom is filtered out by hardcoded if
}
@Test
public void testGlobInput()
{
- // Path baseDirPath = Paths.get("src\\test\\resources");
- // MavenProjectInput inputs = new MavenProjectInput(config, new ArrayList<Path>(), baseDirPath, GLOB);
- // ArrayList<Path> files = new ArrayList<>();
- // inputs.tryAddInputs("*.java", files, new HashSet<Path>());
- // assertEquals(0, files.size()); // pom is filtered out by hardcoded if
+ // Path baseDirPath = Paths.get("src\\test\\resources");
+ // MavenProjectInput inputs = new MavenProjectInput(config, new ArrayList<Path>(), baseDirPath, GLOB);
+ // ArrayList<Path> files = new ArrayList<>();
+ // inputs.tryAddInputs("*.java", files, new HashSet<Path>());
+ // assertEquals(0, files.size()); // pom is filtered out by hardcoded if
}
@Test
@@ -66,10 +67,10 @@ public class MavenProjectInputTest
{
List<Path> directoryFiles = new ArrayList<>();
MavenProjectInput.walkDirectoryFiles(
- Paths.get( "src/test/resources/test-folder" ),
- directoryFiles,
- MavenProjectInput.DEFAULT_GLOB,
- it -> false );
+ Paths.get( "src/test/resources/test-folder" ),
+ directoryFiles,
+ MavenProjectInput.DEFAULT_GLOB,
+ it -> false );
assertEquals( 0, directoryFiles.size() ); // pom is filtered out by hardcoded if
}
@@ -78,10 +79,10 @@ public class MavenProjectInputTest
{
List<Path> directoryFiles = new ArrayList<>();
MavenProjectInput.walkDirectoryFiles(
- Paths.get( "src/test/resources/test-folder" ),
- directoryFiles,
- GLOB,
- it -> false );
+ Paths.get( "src/test/resources/test-folder" ),
+ directoryFiles,
+ GLOB,
+ it -> false );
assertEquals( 1, directoryFiles.size() ); // pom is filtered out by hardcoded if
}
}
diff --git a/src/test/java/org/apache/maven/buildcache/checksum/SHAHashTest.java b/src/test/java/org/apache/maven/buildcache/checksum/SHAHashTest.java
index aeb45e9..b19b0fa 100644
--- a/src/test/java/org/apache/maven/buildcache/checksum/SHAHashTest.java
+++ b/src/test/java/org/apache/maven/buildcache/checksum/SHAHashTest.java
@@ -30,15 +30,23 @@ public class SHAHashTest
{
private static final byte[] HELLO_ARRAY = "hello".getBytes( StandardCharsets.UTF_8 );
+
private static final byte[] WORLD_ARRAY = "world".getBytes( StandardCharsets.UTF_8 );
+
private static final String EMPTY_HASH = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
private static final String HELLO_HASH = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
+
private static final String WORLD_HASH = "486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7";
+
private static final String HELLO_CHECKSUM = "9595c9df90075148eb06860365df33584b75bff782a510c6cd4883a419833d50";
+
private static final String WORLD_CHECKSUM = "63e5c163c81ee9a3ed99d365ff963ecea340cc455deeac7c4b63ac75b9cf4706";
+
private static final String FULL_CHECKSUM = "7305db9b2abccd706c256db3d97e5ff48d677cfe4d3a5904afb7da0e3950e1e2";
private static final HashAlgorithm ALGORITHM = SHA256.createAlgorithm();
+
private static final HashChecksum CHECKSUM = SHA256.createChecksum( 0 );
@Test
diff --git a/src/test/java/org/apache/maven/buildcache/checksum/XXHashTest.java b/src/test/java/org/apache/maven/buildcache/checksum/XXHashTest.java
index 2c895bf..79188ad 100644
--- a/src/test/java/org/apache/maven/buildcache/checksum/XXHashTest.java
+++ b/src/test/java/org/apache/maven/buildcache/checksum/XXHashTest.java
@@ -32,14 +32,23 @@ public class XXHashTest
{
private static final byte[] HELLO_ARRAY = "hello".getBytes( StandardCharsets.UTF_8 );
+
private static final byte[] WORLD_ARRAY = "world".getBytes( StandardCharsets.UTF_8 );
+
private static final long HELLO_LONG = 2794345569481354659L;
+
private static final long WORLD_LONG = -1767385783675760145L;
+
private static final String EMPTY_HASH = "ef46db3751d8e999";
+
private static final String HELLO_HASH = "26c7827d889f6da3";
+
private static final String WORLD_HASH = "e778fbfe66ee51ef";
+
private static final String HELLO_CHECKSUM = "c07c10338a825a5d";
+
private static final String WORLD_CHECKSUM = "cb21505d7a714523";
+
private static final String FULL_CHECKSUM = "b8ca8fa824d335e9";
private static final HashAlgorithm ALGORITHM = XX.createAlgorithm();
diff --git a/src/test/java/org/apache/maven/buildcache/hash/HexUtilsTest.java b/src/test/java/org/apache/maven/buildcache/hash/HexUtilsTest.java
index ac2234e..325b6ac 100644
--- a/src/test/java/org/apache/maven/buildcache/hash/HexUtilsTest.java
+++ b/src/test/java/org/apache/maven/buildcache/hash/HexUtilsTest.java
@@ -29,7 +29,7 @@ public class HexUtilsTest
@Test
public void testEncodeToHex()
{
- //array length = 8 left padded with zeroes
+ // array length = 8 left padded with zeroes
assertEquals( "0000000000000000", HexUtils.encode( new byte[8] ) );
assertEquals( "00", HexUtils.encode( new byte[1] ) );
diff --git a/src/test/java/org/apache/maven/buildcache/its/junit/IntegrationTestExtension.java b/src/test/java/org/apache/maven/buildcache/its/junit/IntegrationTestExtension.java
index dc9fcdc..f4e7ef1 100644
--- a/src/test/java/org/apache/maven/buildcache/its/junit/IntegrationTestExtension.java
+++ b/src/test/java/org/apache/maven/buildcache/its/junit/IntegrationTestExtension.java
@@ -48,7 +48,9 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
{
private static boolean initialized;
+
private static Path maven3;
+
private static Path maven4;
@Override
@@ -61,13 +63,13 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
public boolean supportsTestTemplate( ExtensionContext context )
{
return context.getTestMethod()
- .filter( m -> m.isAnnotationPresent( Test.class ) )
- .isPresent();
+ .filter( m -> m.isAnnotationPresent( Test.class ) )
+ .isPresent();
}
@Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(
- ExtensionContext extensionContext )
+ ExtensionContext extensionContext )
{
Method m = extensionContext.getRequiredTestMethod();
return Stream.of( maven3, maven4 ).map( p -> new MavenTemplate( m, p ) );
@@ -80,14 +82,14 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
return;
}
String root = Objects.requireNonNull( System.getProperty( "maven.multiModuleProjectDirectory" ),
- "The 'maven.multiModuleProjectDirectory' system property need to be set" );
+ "The 'maven.multiModuleProjectDirectory' system property need to be set" );
// maven3
Path maven3Zip = Paths.get( root, "maven/maven3/apache-maven/target/apache-maven-bin.zip" );
if ( !Files.exists( maven3Zip ) )
{
throw new IllegalStateException( "Unable to find " + maven3Zip + "\n"
- + "Please build the maven3 and maven4 distributions using the build-maven.sh script" );
+ + "Please build the maven3 and maven4 distributions using the build-maven.sh script" );
}
Path outMaven3 = Paths.get( "target/maven3" );
deleteDir( outMaven3 );
@@ -101,7 +103,7 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
if ( !Files.exists( maven4Zip ) )
{
throw new IllegalStateException( "Unable to find " + maven4Zip + "\n"
- + "Please build the maven3 and maven4 distributions using the build-maven.sh script" );
+ + "Please build the maven3 and maven4 distributions using the build-maven.sh script" );
}
Path outMaven4 = Paths.get( "target/maven4" );
deleteDir( outMaven4 );
@@ -157,6 +159,7 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
{
private final Method method;
+
private final Path mavenPath;
public MavenTemplate( Method method, Path mavenPath )
@@ -174,8 +177,8 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
@Override
public List<Extension> getAdditionalExtensions()
{
- return Arrays.asList( ( TestInstancePostProcessor ) this::postProcessTestInstance,
- new VerifierParameterResolver() );
+ return Arrays.asList( (TestInstancePostProcessor) this::postProcessTestInstance,
+ new VerifierParameterResolver() );
}
protected void postProcessTestInstance( Object testInstance, ExtensionContext context ) throws Exception
@@ -194,7 +197,7 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
throw new IllegalStateException( "@IntegrationTest must be set" );
}
final Path testDir = Paths.get( "target/maven-tests/" + className + "/" + methodName + "/"
- + ( mavenPath == maven3 ? "maven3" : "maven4" ) ).toAbsolutePath();
+ + ( mavenPath == maven3 ? "maven3" : "maven4" ) ).toAbsolutePath();
deleteDir( testDir );
Files.createDirectories( testDir );
final Path testExecutionDir;
@@ -203,7 +206,7 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
if ( !Files.exists( testSrcDir ) )
{
throw new IllegalStateException( "@IntegrationTest(\"" + testSrcDir
- + "\") points at a path that does not exist: " + testSrcDir );
+ + "\") points at a path that does not exist: " + testSrcDir );
}
testExecutionDir = testDir.resolve( "project" );
try ( Stream<Path> files = Files.walk( testSrcDir ) )
@@ -236,16 +239,16 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
@Override
public boolean supportsParameter( ParameterContext parameterContext,
- ExtensionContext extensionContext )
- throws ParameterResolutionException
+ ExtensionContext extensionContext )
+ throws ParameterResolutionException
{
return parameterContext.getParameter().getType() == Verifier.class;
}
@Override
public Object resolveParameter( ParameterContext parameterContext,
- ExtensionContext context )
- throws ParameterResolutionException
+ ExtensionContext context )
+ throws ParameterResolutionException
{
String prevMavenHome = System.getProperty( "maven.home" );
try
@@ -260,7 +263,7 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
final String className = context.getRequiredTestClass().getSimpleName();
String methodName = context.getRequiredTestMethod().getName();
final Path testDir = Paths.get( "target/mvnd-tests/" + className + "/" + methodName + "/"
- + ( mavenPath == maven3 ? "maven3" : "maven4" ) ).toAbsolutePath();
+ + ( mavenPath == maven3 ? "maven3" : "maven4" ) ).toAbsolutePath();
deleteDir( testDir );
Files.createDirectories( testDir );
@@ -269,7 +272,7 @@ public class IntegrationTestExtension implements BeforeAllCallback, TestTemplate
if ( !Files.exists( testSrcDir ) )
{
throw new IllegalStateException( "@IntegrationTest(\"" + testSrcDir
- + "\") points at a path that does not exist: " + testSrcDir );
+ + "\") points at a path that does not exist: " + testSrcDir );
}
final Path testExecutionDir = testDir.resolve( "project" );