From 913f2320e75268013d8baa4993f446c778adece0 Mon Sep 17 00:00:00 2001 From: twogee Date: Thu, 6 Jul 2017 08:04:24 +0200 Subject: [PATCH 1/6] Add generics and Java 7 syntax to core --- src/java/org/apache/ivy/Ivy14.java | 207 ++++++------- src/java/org/apache/ivy/Main.java | 60 ++-- src/java/org/apache/ivy/ant/BuildOBRTask.java | 3 - .../org/apache/ivy/ant/IvyArtifactReport.java | 8 +- src/java/org/apache/ivy/ant/IvyBuildList.java | 11 +- .../org/apache/ivy/ant/IvyBuildNumber.java | 9 +- .../org/apache/ivy/ant/IvyCacheFileset.java | 6 +- src/java/org/apache/ivy/ant/IvyCacheTask.java | 6 +- src/java/org/apache/ivy/ant/IvyConfigure.java | 4 +- .../org/apache/ivy/ant/IvyDependencyTree.java | 3 +- .../ivy/ant/IvyDependencyUpdateChecker.java | 6 +- .../apache/ivy/ant/IvyPostResolveTask.java | 5 +- .../apache/ivy/ant/IvyRepositoryReport.java | 5 +- src/java/org/apache/ivy/ant/IvyRetrieve.java | 3 +- src/java/org/apache/ivy/core/IvyContext.java | 63 ++-- .../org/apache/ivy/core/IvyPatternHelper.java | 49 ++-- .../apache/ivy/core/cache/ArtifactOrigin.java | 2 +- .../cache/DefaultRepositoryCacheManager.java | 28 +- .../cache/DefaultResolutionCacheManager.java | 25 +- .../cache/ModuleDescriptorMemoryCache.java | 8 +- .../ivy/core/cache/ParserSettingsMonitor.java | 26 +- .../apache/ivy/core/check/CheckEngine.java | 50 ++-- .../ivy/core/deliver/DeliverEngine.java | 47 ++- .../apache/ivy/core/event/EventManager.java | 10 +- .../ivy/core/event/FilteredIvyListener.java | 6 +- .../org/apache/ivy/core/event/IvyEvent.java | 2 +- .../apache/ivy/core/event/IvyEventFilter.java | 42 ++- .../publish/EndArtifactPublishEvent.java | 3 - .../publish/StartArtifactPublishEvent.java | 3 - .../ivy/core/install/InstallEngine.java | 49 ++-- .../core/install/InstallEngineSettings.java | 4 +- .../ivy/core/install/InstallOptions.java | 9 +- .../module/descriptor/AbstractArtifact.java | 6 +- .../AbstractIncludeExcludeRule.java | 7 +- .../core/module/descriptor/Configuration.java | 28 +- .../module/descriptor/ConfigurationGroup.java | 12 +- .../descriptor/ConfigurationIntersection.java | 12 +- .../module/descriptor/DefaultArtifact.java | 4 +- .../DefaultDependencyArtifactDescriptor.java | 6 +- .../DefaultDependencyDescriptor.java | 276 +++++++++--------- .../module/descriptor/DefaultExcludeRule.java | 2 +- .../descriptor/DefaultExtendsDescriptor.java | 6 +- .../module/descriptor/DefaultIncludeRule.java | 2 +- .../descriptor/DefaultModuleDescriptor.java | 159 +++++----- .../module/descriptor/ExtraInfoHolder.java | 4 +- .../core/module/descriptor/MDArtifact.java | 8 +- .../module/descriptor/ModuleDescriptor.java | 2 +- .../core/module/id/ArtifactRevisionId.java | 5 +- .../ivy/core/module/id/MatcherLookup.java | 40 +-- .../apache/ivy/core/module/id/ModuleId.java | 14 +- .../ivy/core/module/id/ModuleRevisionId.java | 10 +- .../ivy/core/module/id/ModuleRules.java | 29 +- .../ivy/core/module/status/StatusManager.java | 44 ++- .../ivy/core/pack/PackagingManager.java | 7 +- .../apache/ivy/core/pack/PackingRegistry.java | 2 +- .../org/apache/ivy/core/pack/ZipPacking.java | 12 +- .../ivy/core/publish/PublishEngine.java | 22 +- .../core/report/ArtifactDownloadReport.java | 9 +- .../report/ConfigurationResolveReport.java | 35 +-- .../ivy/core/report/DownloadReport.java | 15 +- .../apache/ivy/core/report/ResolveReport.java | 66 ++--- .../RepositoryManagementEngine.java | 72 ++--- .../org/apache/ivy/core/resolve/IvyNode.java | 82 +++--- .../ivy/core/resolve/IvyNodeCallers.java | 30 +- .../ivy/core/resolve/IvyNodeEviction.java | 50 ++-- .../apache/ivy/core/resolve/IvyNodeUsage.java | 20 +- .../apache/ivy/core/resolve/ResolveData.java | 57 ++-- .../ivy/core/resolve/ResolveEngine.java | 180 ++++++------ .../ivy/core/resolve/ResolveOptions.java | 7 +- .../apache/ivy/core/resolve/VisitData.java | 4 +- .../apache/ivy/core/resolve/VisitNode.java | 6 +- .../ivy/core/retrieve/RetrieveEngine.java | 67 ++--- .../ivy/core/retrieve/RetrieveOptions.java | 7 +- .../ivy/core/retrieve/RetrieveReport.java | 12 +- .../apache/ivy/core/search/SearchEngine.java | 132 ++++----- .../apache/ivy/core/settings/IvySettings.java | 56 ++-- .../ivy/core/settings/XmlSettingsParser.java | 176 ++++++----- .../core/sort/CollectionOfModulesToSort.java | 6 +- .../ivy/core/sort/ModuleDescriptorSorter.java | 6 +- .../apache/ivy/core/sort/ModuleInSort.java | 10 +- .../org/apache/ivy/core/sort/SortEngine.java | 11 +- .../ivy/osgi/core/ManifestHeaderValue.java | 2 +- .../apache/ivy/osgi/core/ManifestParser.java | 2 +- .../ivy/osgi/filter/OSGiFilterParser.java | 2 +- .../ivy/osgi/obr/xml/RequirementAdapter.java | 4 +- .../ivy/osgi/repo/AbstractOSGiResolver.java | 9 +- .../ivy/osgi/repo/EditableRepoDescriptor.java | 9 +- .../osgi/repo/ModuleDescriptorWrapper.java | 2 +- .../ivy/osgi/updatesite/UpdateSiteLoader.java | 7 +- .../org/apache/ivy/osgi/util/ParseUtil.java | 4 +- .../apache/ivy/osgi/util/VersionRange.java | 4 +- .../LatestCompatibleConflictManager.java | 10 +- .../latest/AbstractLatestStrategy.java | 3 +- .../parser/xml/XmlModuleDescriptorParser.java | 10 +- .../xml/XmlModuleDescriptorUpdater.java | 62 ++-- .../parser/xml/XmlModuleDescriptorWriter.java | 201 +++++-------- .../repository/sftp/SFTPRepository.java | 14 +- .../ivy/plugins/repository/ssh/Scp.java | 10 +- .../ivy/plugins/repository/ssh/SshCache.java | 3 +- .../repository/vsftp/VsftpRepository.java | 26 +- .../AbstractPatternsBasedResolver.java | 11 +- .../plugins/resolver/AbstractResolver.java | 1 + .../ivy/plugins/resolver/BasicResolver.java | 10 +- .../ivy/plugins/resolver/ChainResolver.java | 1 + .../plugins/resolver/FileSystemResolver.java | 21 +- .../ivy/plugins/resolver/VsftpResolver.java | 2 +- .../OpenPGPSignatureGenerator.java | 7 +- .../ivy/plugins/trigger/AbstractTrigger.java | 6 +- .../apache/ivy/plugins/trigger/Trigger.java | 3 +- .../plugins/version/ChainVersionMatcher.java | 9 +- .../analyser/JarJarDependencyAnalyser.java | 16 +- .../org/apache/ivy/util/Configurator.java | 20 +- src/java/org/apache/ivy/util/Credentials.java | 10 +- src/java/org/apache/ivy/util/MemoryUtil.java | 2 +- .../apache/ivy/util/MessageLoggerHelper.java | 2 +- src/java/org/apache/ivy/util/StringUtils.java | 7 +- .../org/apache/ivy/util/filter/AndFilter.java | 14 +- .../apache/ivy/util/filter/FilterHelper.java | 6 +- .../org/apache/ivy/util/filter/NoFilter.java | 8 +- .../org/apache/ivy/util/filter/NotFilter.java | 10 +- .../org/apache/ivy/util/filter/OrFilter.java | 14 +- .../ivy/util/url/HttpClientHandler.java | 2 +- .../ivy/util/url/URLHandlerRegistry.java | 2 +- .../org/apache/ivy/ant/IvyConfigureTest.java | 3 +- .../org/apache/ivy/ant/IvyDeliverTest.java | 9 +- .../org/apache/ivy/ant/IvyPublishTest.java | 8 +- .../org/apache/ivy/ant/IvyResourcesTest.java | 12 +- test/java/org/apache/ivy/ant/IvyTaskTest.java | 3 +- .../module/descriptor/IvyMakePomTest.java | 23 +- .../core/module/id/ModuleRevisionIdTest.java | 14 +- .../ivy/core/module/id/ModuleRulesTest.java | 34 +-- .../ivy/core/retrieve/RetrieveTest.java | 15 +- .../core/settings/XmlSettingsParserTest.java | 28 +- .../ivy/osgi/core/OsgiLatestStrategyTest.java | 8 +- .../osgi/updatesite/UpdateSiteLoaderTest.java | 8 +- .../conflict/LatestConflictManagerTest.java | 10 +- .../m2/PomModuleDescriptorParserTest.java | 126 ++++---- .../xml/XmlModuleDescriptorParserTest.java | 23 +- .../parser/xml/XmlModuleUpdaterTest.java | 16 +- .../plugins/resolver/ChainResolverTest.java | 18 +- .../plugins/resolver/IBiblioResolverTest.java | 16 +- .../plugins/resolver/IvyRepResolverTest.java | 14 +- .../apache/ivy/util/IvyPatternHelperTest.java | 4 +- .../ivy/util/url/ArtifactoryListingTest.java | 8 +- 144 files changed, 1652 insertions(+), 1913 deletions(-) diff --git a/src/java/org/apache/ivy/Ivy14.java b/src/java/org/apache/ivy/Ivy14.java index 28bc4ca07..5e1de65a6 100644 --- a/src/java/org/apache/ivy/Ivy14.java +++ b/src/java/org/apache/ivy/Ivy14.java @@ -26,6 +26,7 @@ import java.util.Date; import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.ivy.core.deliver.DeliverOptions; import org.apache.ivy.core.deliver.PublishingDependencyRevisionResolver; @@ -117,18 +118,18 @@ public void deliver(ModuleRevisionId mrid, String revision, File cache, String d deliver(mrid, revision, cache, destIvyPattern, status, pubdate, pdrResolver, validate, true); } - public Map determineArtifactsToCopy(ModuleId moduleId, String[] confs, File cache, - String destFilePattern, String destIvyPattern, Filter artifactFilter) - throws ParseException, IOException { + public Map> determineArtifactsToCopy(ModuleId moduleId, + String[] confs, File cache, String destFilePattern, String destIvyPattern, + Filter artifactFilter) throws ParseException, IOException { return ivy.getRetrieveEngine().determineArtifactsToCopy( - new ModuleRevisionId(moduleId, Ivy.getWorkingRevision()), - destFilePattern, + new ModuleRevisionId(moduleId, Ivy.getWorkingRevision()), destFilePattern, new RetrieveOptions().setConfs(confs).setDestIvyPattern(destIvyPattern) .setArtifactFilter(artifactFilter)); } - public Map determineArtifactsToCopy(ModuleId moduleId, String[] confs, File cache, - String destFilePattern, String destIvyPattern) throws ParseException, IOException { + public Map> determineArtifactsToCopy(ModuleId moduleId, + String[] confs, File cache, String destFilePattern, String destIvyPattern) + throws ParseException, IOException { return ivy.getRetrieveEngine().determineArtifactsToCopy( new ModuleRevisionId(moduleId, Ivy.getWorkingRevision()), destFilePattern, new RetrieveOptions().setConfs(confs).setDestIvyPattern(destIvyPattern)); @@ -147,26 +148,20 @@ public ResolvedModuleRevision findModule(ModuleRevisionId id) { public IvyNode[] getDependencies(ModuleDescriptor md, String[] confs, File cache, Date date, ResolveReport report, boolean validate, boolean transitive) { - return ivy.getResolveEngine().getDependencies( - md, - newResolveOptions(confs, null, cache, date, validate, false, transitive, false, true, - true, FilterHelper.NO_FILTER), report); + return ivy.getResolveEngine().getDependencies(md, newResolveOptions(confs, null, cache, + date, validate, false, transitive, false, true, true, FilterHelper.NO_FILTER), report); } public IvyNode[] getDependencies(ModuleDescriptor md, String[] confs, File cache, Date date, ResolveReport report, boolean validate) { - return ivy.getResolveEngine().getDependencies( - md, - newResolveOptions(confs, null, cache, date, validate, false, true, false, true, true, - FilterHelper.NO_FILTER), report); + return ivy.getResolveEngine().getDependencies(md, newResolveOptions(confs, null, cache, + date, validate, false, true, false, true, true, FilterHelper.NO_FILTER), report); } public IvyNode[] getDependencies(URL ivySource, String[] confs, File cache, Date date, boolean validate) throws ParseException, IOException { - return ivy.getResolveEngine().getDependencies( - ivySource, - newResolveOptions(confs, null, cache, date, validate, false, true, false, true, true, - FilterHelper.NO_FILTER)); + return ivy.getResolveEngine().getDependencies(ivySource, newResolveOptions(confs, null, + cache, date, validate, false, true, false, true, true, FilterHelper.NO_FILTER)); } public String getVariable(String name) { @@ -174,11 +169,12 @@ public String getVariable(String name) { } public ResolveReport install(ModuleRevisionId mrid, String from, String to, boolean transitive, - boolean validate, boolean overwrite, Filter artifactFilter, File cache, + boolean validate, boolean overwrite, Filter artifactFilter, File cache, String matcherName) throws IOException { - return ivy.install(mrid, from, to, new InstallOptions().setTransitive(transitive) - .setValidate(validate).setOverwrite(overwrite).setArtifactFilter(artifactFilter) - .setMatcherName(matcherName)); + return ivy.install(mrid, from, to, + new InstallOptions().setTransitive(transitive).setValidate(validate) + .setOverwrite(overwrite).setArtifactFilter(artifactFilter) + .setMatcherName(matcherName)); } public void interrupt() { @@ -225,36 +221,30 @@ public String[] listRevisions(String org, String module) { return ivy.listRevisions(org, module); } - public String[] listTokenValues(String token, Map otherTokenValues) { + public String[] listTokenValues(String token, Map otherTokenValues) { return ivy.listTokenValues(token, otherTokenValues); } - public Collection publish(ModuleDescriptor md, DependencyResolver resolver, - Collection srcArtifactPattern, String srcIvyPattern, Artifact[] extraArtifacts, + public Collection publish(ModuleDescriptor md, DependencyResolver resolver, + Collection srcArtifactPattern, String srcIvyPattern, Artifact[] extraArtifacts, boolean overwrite, String conf) throws IOException { - return ivy.getPublishEngine().publish( - md, - srcArtifactPattern, - resolver, + return ivy.getPublishEngine().publish(md, srcArtifactPattern, resolver, new PublishOptions().setSrcIvyPattern(srcIvyPattern).setExtraArtifacts(extraArtifacts) .setOverwrite(overwrite).setConfs(splitConfs(conf))); } - public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, - Collection srcArtifactPattern, String resolverName, String srcIvyPattern, + public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, + Collection srcArtifactPattern, String resolverName, String srcIvyPattern, String status, Date pubdate, Artifact[] extraArtifacts, boolean validate, boolean overwrite, boolean update, String conf) throws IOException { - return ivy.publish( - mrid, - srcArtifactPattern, - resolverName, + return ivy.publish(mrid, srcArtifactPattern, resolverName, new PublishOptions().setStatus(status).setPubdate(pubdate).setPubrevision(pubrevision) .setSrcIvyPattern(srcIvyPattern).setExtraArtifacts(extraArtifacts) .setUpdate(update).setValidate(validate).setOverwrite(overwrite) .setConfs(splitConfs(conf))); } - public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, + public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, String srcArtifactPattern, String resolverName, String srcIvyPattern, boolean validate, boolean overwrite) throws IOException { return ivy.publish(mrid, Collections.singleton(srcArtifactPattern), resolverName, @@ -262,7 +252,7 @@ public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, .setValidate(validate).setOverwrite(overwrite)); } - public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, + public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, String srcArtifactPattern, String resolverName, String srcIvyPattern, boolean validate) throws IOException { return ivy.publish(mrid, Collections.singleton(srcArtifactPattern), resolverName, @@ -270,14 +260,11 @@ public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, .setValidate(validate)); } - public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, + public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, String srcArtifactPattern, String resolverName, String srcIvyPattern, String status, Date pubdate, Artifact[] extraArtifacts, boolean validate, boolean overwrite, boolean update, String conf) throws IOException { - return ivy.publish( - mrid, - Collections.singleton(srcArtifactPattern), - resolverName, + return ivy.publish(mrid, Collections.singleton(srcArtifactPattern), resolverName, new PublishOptions().setStatus(status).setPubdate(pubdate).setPubrevision(pubrevision) .setSrcIvyPattern(srcIvyPattern).setExtraArtifacts(extraArtifacts) .setUpdate(update).setValidate(validate).setOverwrite(overwrite) @@ -290,17 +277,15 @@ public ResolveReport resolve(File ivySource) throws ParseException, IOException public ResolveReport resolve(ModuleDescriptor md, String[] confs, File cache, Date date, boolean validate, boolean useCacheOnly, boolean transitive, boolean useOrigin, - boolean download, boolean outputReport, Filter artifactFilter) throws ParseException, - IOException { - return ivy.resolve( - md, - newResolveOptions(confs, null, cache, date, validate, useCacheOnly, transitive, - useOrigin, download, outputReport, artifactFilter)); + boolean download, boolean outputReport, Filter artifactFilter) + throws ParseException, IOException { + return ivy.resolve(md, newResolveOptions(confs, null, cache, date, validate, useCacheOnly, + transitive, useOrigin, download, outputReport, artifactFilter)); } - private ResolveOptions newResolveOptions(String[] confs, String revision, File cache, - Date date, boolean validate, boolean useCacheOnly, boolean transitive, - boolean useOrigin, boolean download, boolean outputReport, Filter artifactFilter) { + private ResolveOptions newResolveOptions(String[] confs, String revision, File cache, Date date, + boolean validate, boolean useCacheOnly, boolean transitive, boolean useOrigin, + boolean download, boolean outputReport, Filter artifactFilter) { if (useOrigin) { ivy.getSettings().useDeprecatedUseOrigin(); } @@ -311,98 +296,77 @@ private ResolveOptions newResolveOptions(String[] confs, String revision, File c public ResolveReport resolve(ModuleDescriptor md, String[] confs, File cache, Date date, boolean validate, boolean useCacheOnly, boolean transitive, boolean download, - boolean outputReport, Filter artifactFilter) throws ParseException, IOException { - return ivy.resolve( - md, - newResolveOptions(confs, null, cache, date, validate, useCacheOnly, transitive, false, - download, outputReport, artifactFilter)); + boolean outputReport, Filter artifactFilter) + throws ParseException, IOException { + return ivy.resolve(md, newResolveOptions(confs, null, cache, date, validate, useCacheOnly, + transitive, false, download, outputReport, artifactFilter)); } public ResolveReport resolve(ModuleDescriptor md, String[] confs, File cache, Date date, - boolean validate, boolean useCacheOnly, boolean transitive, Filter artifactFilter) - throws ParseException, IOException { - return ivy.resolve( - md, - newResolveOptions(confs, null, cache, date, validate, useCacheOnly, transitive, false, - true, true, artifactFilter)); + boolean validate, boolean useCacheOnly, boolean transitive, + Filter artifactFilter) throws ParseException, IOException { + return ivy.resolve(md, newResolveOptions(confs, null, cache, date, validate, useCacheOnly, + transitive, false, true, true, artifactFilter)); } public ResolveReport resolve(ModuleDescriptor md, String[] confs, File cache, Date date, - boolean validate, boolean useCacheOnly, Filter artifactFilter) throws ParseException, - IOException { - return ivy.resolve( - md, - newResolveOptions(confs, null, cache, date, validate, useCacheOnly, true, false, true, - true, artifactFilter)); + boolean validate, boolean useCacheOnly, Filter artifactFilter) + throws ParseException, IOException { + return ivy.resolve(md, newResolveOptions(confs, null, cache, date, validate, useCacheOnly, + true, false, true, true, artifactFilter)); } public ResolveReport resolve(ModuleRevisionId mrid, String[] confs, boolean transitive, boolean changing, File cache, Date date, boolean validate, boolean useCacheOnly, - boolean useOrigin, Filter artifactFilter) throws ParseException, IOException { - return ivy.resolve( - mrid, - newResolveOptions(confs, null, cache, date, validate, useCacheOnly, transitive, - useOrigin, true, true, artifactFilter), changing); + boolean useOrigin, Filter artifactFilter) throws ParseException, IOException { + return ivy.resolve(mrid, newResolveOptions(confs, null, cache, date, validate, useCacheOnly, + transitive, useOrigin, true, true, artifactFilter), changing); } public ResolveReport resolve(ModuleRevisionId mrid, String[] confs, boolean transitive, boolean changing, File cache, Date date, boolean validate, boolean useCacheOnly, - Filter artifactFilter) throws ParseException, IOException { - return ivy.resolve( - mrid, - newResolveOptions(confs, null, cache, date, validate, useCacheOnly, transitive, false, - true, true, artifactFilter), changing); + Filter artifactFilter) throws ParseException, IOException { + return ivy.resolve(mrid, newResolveOptions(confs, null, cache, date, validate, useCacheOnly, + transitive, false, true, true, artifactFilter), changing); } - public ResolveReport resolve(ModuleRevisionId mrid, String[] confs) throws ParseException, - IOException { - return ivy.resolve( - mrid, - newResolveOptions(confs, null, ivy.getSettings().getDefaultCache(), null, true, false, - true, false, true, true, FilterHelper.NO_FILTER), false); + public ResolveReport resolve(ModuleRevisionId mrid, String[] confs) + throws ParseException, IOException { + return ivy.resolve(mrid, newResolveOptions(confs, null, ivy.getSettings().getDefaultCache(), + null, true, false, true, false, true, true, FilterHelper.NO_FILTER), false); } public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, Date date, boolean validate, boolean useCacheOnly, boolean transitive, - boolean useOrigin, Filter artifactFilter) throws ParseException, IOException { - return ivy.resolve( - ivySource, - newResolveOptions(confs, revision, cache, date, validate, useCacheOnly, transitive, - useOrigin, true, true, artifactFilter)); + boolean useOrigin, Filter artifactFilter) throws ParseException, IOException { + return ivy.resolve(ivySource, newResolveOptions(confs, revision, cache, date, validate, + useCacheOnly, transitive, useOrigin, true, true, artifactFilter)); } public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, Date date, boolean validate, boolean useCacheOnly, boolean transitive, - Filter artifactFilter) throws ParseException, IOException { - return ivy.resolve( - ivySource, - newResolveOptions(confs, revision, cache, date, validate, useCacheOnly, transitive, - false, true, true, artifactFilter)); + Filter artifactFilter) throws ParseException, IOException { + return ivy.resolve(ivySource, newResolveOptions(confs, revision, cache, date, validate, + useCacheOnly, transitive, false, true, true, artifactFilter)); } public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, - Date date, boolean validate, boolean useCacheOnly, Filter artifactFilter) + Date date, boolean validate, boolean useCacheOnly, Filter artifactFilter) throws ParseException, IOException { - return ivy.resolve( - ivySource, - newResolveOptions(confs, revision, cache, date, validate, useCacheOnly, true, false, - true, true, artifactFilter)); + return ivy.resolve(ivySource, newResolveOptions(confs, revision, cache, date, validate, + useCacheOnly, true, false, true, true, artifactFilter)); } public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, Date date, boolean validate, boolean useCacheOnly) throws ParseException, IOException { - return ivy.resolve( - ivySource, - newResolveOptions(confs, revision, cache, date, validate, useCacheOnly, true, false, - true, true, FilterHelper.NO_FILTER)); + return ivy.resolve(ivySource, newResolveOptions(confs, revision, cache, date, validate, + useCacheOnly, true, false, true, true, FilterHelper.NO_FILTER)); } public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, Date date, boolean validate) throws ParseException, IOException { - return ivy.resolve( - ivySource, - newResolveOptions(confs, revision, cache, date, validate, false, true, false, true, - true, FilterHelper.NO_FILTER)); + return ivy.resolve(ivySource, newResolveOptions(confs, revision, cache, date, validate, + false, true, false, true, true, FilterHelper.NO_FILTER)); } public ResolveReport resolve(URL ivySource) throws ParseException, IOException { @@ -410,7 +374,7 @@ public ResolveReport resolve(URL ivySource) throws ParseException, IOException { } public int retrieve(ModuleId moduleId, String[] confs, File cache, String destFilePattern, - String destIvyPattern, Filter artifactFilter, boolean sync, boolean useOrigin, + String destIvyPattern, Filter artifactFilter, boolean sync, boolean useOrigin, boolean makeSymlinks) { try { return ivy.retrieve(new ModuleRevisionId(moduleId, Ivy.getWorkingRevision()), @@ -424,7 +388,8 @@ public int retrieve(ModuleId moduleId, String[] confs, File cache, String destFi } public int retrieve(ModuleId moduleId, String[] confs, File cache, String destFilePattern, - String destIvyPattern, Filter artifactFilter, boolean sync, boolean useOrigin) { + String destIvyPattern, Filter artifactFilter, boolean sync, + boolean useOrigin) { try { return ivy.retrieve(new ModuleRevisionId(moduleId, Ivy.getWorkingRevision()), destFilePattern, @@ -436,12 +401,11 @@ public int retrieve(ModuleId moduleId, String[] confs, File cache, String destFi } public int retrieve(ModuleId moduleId, String[] confs, File cache, String destFilePattern, - String destIvyPattern, Filter artifactFilter) { + String destIvyPattern, Filter artifactFilter) { try { return ivy.retrieve(new ModuleRevisionId(moduleId, Ivy.getWorkingRevision()), - destFilePattern, - new RetrieveOptions().setConfs(confs).setDestIvyPattern(destIvyPattern) - .setArtifactFilter(artifactFilter)); + destFilePattern, new RetrieveOptions().setConfs(confs) + .setDestIvyPattern(destIvyPattern).setArtifactFilter(artifactFilter)); } catch (IOException e) { throw new RuntimeException(e); } @@ -471,16 +435,15 @@ public void setVariable(String varName, String value) { ivy.setVariable(varName, value); } - public List sortModuleDescriptors(Collection moduleDescriptors) { - return ivy - .sortModuleDescriptors(moduleDescriptors, new SortOptions() - .setNonMatchingVersionReporter(new SilentNonMatchingVersionReporter())); + public List sortModuleDescriptors( + Collection moduleDescriptors) { + return ivy.sortModuleDescriptors(moduleDescriptors, new SortOptions() + .setNonMatchingVersionReporter(new SilentNonMatchingVersionReporter())); } - public List sortNodes(Collection nodes) { - return ivy - .sortNodes(nodes, new SortOptions() - .setNonMatchingVersionReporter(new SilentNonMatchingVersionReporter())); + public List sortNodes(Collection nodes) { + return ivy.sortNodes(nodes, new SortOptions() + .setNonMatchingVersionReporter(new SilentNonMatchingVersionReporter())); } public String substitute(String str) { diff --git a/src/java/org/apache/ivy/Main.java b/src/java/org/apache/ivy/Main.java index c2563194f..ad8c4a6f7 100644 --- a/src/java/org/apache/ivy/Main.java +++ b/src/java/org/apache/ivy/Main.java @@ -30,7 +30,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.StringTokenizer; @@ -278,8 +277,8 @@ static void run(CommandLineParser parser, String[] args) throws Exception { "working")); DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, ModuleRevisionId.newInstance(dep[0], dep[1], dep[2]), false, false, true); - for (int i = 0; i < confs.length; i++) { - dd.addDependencyConfiguration("default", confs[i]); + for (String conf : confs) { + dd.addDependencyConfiguration("default", conf); } md.addDependency(dd); XmlModuleDescriptorWriter.write(md, ivyfile); @@ -319,8 +318,8 @@ static void run(CommandLineParser parser, String[] args) throws Exception { } if (line.hasOption("retrieve")) { String retrievePattern = settings.substitute(line.getOptionValue("retrieve")); - if (retrievePattern.indexOf("[") == -1) { - retrievePattern = retrievePattern + "/lib/[conf]/[artifact].[ext]"; + if (!retrievePattern.contains("[")) { + retrievePattern += "/lib/[conf]/[artifact].[ext]"; } String ivyPattern = settings.substitute(line.getOptionValue("ivypattern")); ivy.retrieve( @@ -366,7 +365,7 @@ static void run(CommandLineParser parser, String[] args) throws Exception { } if (line.hasOption("main")) { // check if the option cp has been set - List fileList = getExtraClasspathFileList(line); + List fileList = getExtraClasspathFileList(line); // merge -args and left over args String[] fargs = line.getOptionValues("args"); @@ -399,13 +398,12 @@ static void run(CommandLineParser parser, String[] args) throws Exception { * @return a List of files to include as extra classpath entries, or null if no cp * option was provided. */ - private static List/* */getExtraClasspathFileList(CommandLine line) { - List fileList = null; + private static List getExtraClasspathFileList(CommandLine line) { + List fileList = null; if (line.hasOption("cp")) { - fileList = new ArrayList/* */(); - String[] cpArray = line.getOptionValues("cp"); - for (int index = 0; index < cpArray.length; index++) { - StringTokenizer tokenizer = new StringTokenizer(cpArray[index], + fileList = new ArrayList<>(); + for (String cp : line.getOptionValues("cp")) { + StringTokenizer tokenizer = new StringTokenizer(cp, System.getProperty("path.separator")); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); @@ -472,19 +470,18 @@ private static void outputCachePath(Ivy ivy, File cache, ModuleDescriptor md, St String outFile) { try { String pathSeparator = System.getProperty("path.separator"); - StringBuffer buf = new StringBuffer(); - Collection all = new LinkedHashSet(); + StringBuilder buf = new StringBuilder(); + Collection all = new LinkedHashSet<>(); ResolutionCacheManager cacheMgr = ivy.getResolutionCacheManager(); XmlReportParser parser = new XmlReportParser(); - for (int i = 0; i < confs.length; i++) { + for (String conf : confs) { String resolveId = ResolveOptions.getDefaultResolveId(md); - File report = cacheMgr.getConfigurationResolveReportInCache(resolveId, confs[i]); + File report = cacheMgr.getConfigurationResolveReportInCache(resolveId, conf); parser.parse(report); all.addAll(Arrays.asList(parser.getArtifactReports())); } - for (Iterator iter = all.iterator(); iter.hasNext();) { - ArtifactDownloadReport artifact = (ArtifactDownloadReport) iter.next(); + for (ArtifactDownloadReport artifact : all) { if (artifact.getLocalFile() != null) { buf.append(artifact.getLocalFile().getCanonicalPath()); buf.append(pathSeparator); @@ -505,13 +502,12 @@ private static void outputCachePath(Ivy ivy, File cache, ModuleDescriptor md, St @SuppressWarnings("resource") private static void invoke(Ivy ivy, File cache, ModuleDescriptor md, String[] confs, - List fileList, String mainclass, String[] args) { - List urls = new ArrayList(); + List fileList, String mainclass, String[] args) { + List urls = new ArrayList<>(); // Add option cp (extra classpath) urls if (fileList != null && fileList.size() > 0) { - for (Iterator iter = fileList.iterator(); iter.hasNext();) { - File file = (File) iter.next(); + for (File file: fileList) { try { urls.add(file.toURI().toURL()); } catch (MalformedURLException e) { @@ -521,19 +517,17 @@ private static void invoke(Ivy ivy, File cache, ModuleDescriptor md, String[] co } try { - Collection all = new LinkedHashSet(); + Collection all = new LinkedHashSet<>(); ResolutionCacheManager cacheMgr = ivy.getResolutionCacheManager(); XmlReportParser parser = new XmlReportParser(); - for (int i = 0; i < confs.length; i++) { + for (String conf : confs) { String resolveId = ResolveOptions.getDefaultResolveId(md); - File report = cacheMgr.getConfigurationResolveReportInCache(resolveId, confs[i]); + File report = cacheMgr.getConfigurationResolveReportInCache(resolveId, conf); parser.parse(report); all.addAll(Arrays.asList(parser.getArtifactReports())); } - for (Iterator iter = all.iterator(); iter.hasNext();) { - ArtifactDownloadReport artifact = (ArtifactDownloadReport) iter.next(); - + for (ArtifactDownloadReport artifact : all) { if (artifact.getLocalFile() != null) { urls.add(artifact.getLocalFile().toURI().toURL()); } @@ -542,21 +536,19 @@ private static void invoke(Ivy ivy, File cache, ModuleDescriptor md, String[] co throw new RuntimeException("impossible to build ivy cache path: " + ex.getMessage(), ex); } - URLClassLoader classLoader = new URLClassLoader((URL[]) urls.toArray(new URL[urls.size()]), + URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), Main.class.getClassLoader()); try { - Class c = classLoader.loadClass(mainclass); + Class c = classLoader.loadClass(mainclass); - Method mainMethod = c.getMethod("main", new Class[] {String[].class}); + Method mainMethod = c.getMethod("main", String[].class); Thread.currentThread().setContextClassLoader(classLoader); mainMethod.invoke(null, new Object[] {(args == null ? new String[0] : args)}); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("Could not find class: " + mainclass, cnfe); - } catch (SecurityException e) { - throw new RuntimeException("Could not find main method: " + mainclass, e); - } catch (NoSuchMethodException e) { + } catch (SecurityException | NoSuchMethodException e) { throw new RuntimeException("Could not find main method: " + mainclass, e); } catch (IllegalAccessException e) { throw new RuntimeException("No permissions to invoke main method: " + mainclass, e); diff --git a/src/java/org/apache/ivy/ant/BuildOBRTask.java b/src/java/org/apache/ivy/ant/BuildOBRTask.java index 226167a34..f380484b4 100644 --- a/src/java/org/apache/ivy/ant/BuildOBRTask.java +++ b/src/java/org/apache/ivy/ant/BuildOBRTask.java @@ -161,9 +161,6 @@ public void doExecute() throws BuildException { } catch (ParseException e) { throw new BuildException("Impossible to parse the artifact reports: " + e.getMessage(), e); - } catch (IOException e) { - throw new BuildException("Impossible to read the artifact reports: " - + e.getMessage(), e); } } diff --git a/src/java/org/apache/ivy/ant/IvyArtifactReport.java b/src/java/org/apache/ivy/ant/IvyArtifactReport.java index aff8c4c8d..e996fab38 100644 --- a/src/java/org/apache/ivy/ant/IvyArtifactReport.java +++ b/src/java/org/apache/ivy/ant/IvyArtifactReport.java @@ -28,7 +28,6 @@ import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; @@ -168,8 +167,7 @@ private void generateXml(IvyNode[] dependencies, } private TransformerHandler createTransformerHandler(FileOutputStream fileOutputStream) - throws TransformerFactoryConfigurationError, TransformerConfigurationException, - SAXException { + throws TransformerConfigurationException { SAXTransformerFactory transformerFact = (SAXTransformerFactory) SAXTransformerFactory .newInstance(); TransformerHandler saxHandler = transformerFact.newTransformerHandler(); @@ -201,8 +199,8 @@ private void startArtifact(TransformerHandler saxHandler, Artifact artifact) } private void writeOriginLocationIfPresent(RepositoryCacheManager cache, - TransformerHandler saxHandler, ArtifactDownloadReport artifact) throws IOException, - SAXException { + TransformerHandler saxHandler, ArtifactDownloadReport artifact) + throws SAXException { ArtifactOrigin origin = artifact.getArtifactOrigin(); if (!ArtifactOrigin.isUnknown(origin)) { String originName = origin.getLocation(); diff --git a/src/java/org/apache/ivy/ant/IvyBuildList.java b/src/java/org/apache/ivy/ant/IvyBuildList.java index 84cc0c683..9ff9b7596 100644 --- a/src/java/org/apache/ivy/ant/IvyBuildList.java +++ b/src/java/org/apache/ivy/ant/IvyBuildList.java @@ -25,7 +25,6 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; -import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; @@ -273,14 +272,12 @@ public void doExecute() throws BuildException { sortedModules = keptModules; } StringBuilder order = new StringBuilder(); - for (ListIterator iter = sortedModules.listIterator(); iter.hasNext();) { - ModuleDescriptor md = iter.next(); - order.append(md.getModuleRevisionId().getModuleId()); - if (iter.hasNext()) { + for (ModuleDescriptor md : sortedModules) { + if (order.length() > 0) { order.append(", "); } - File buildFile = buildFiles.get(md); - addBuildFile(path, buildFile); + order.append(md.getModuleRevisionId().getModuleId()); + addBuildFile(path, buildFiles.get(md)); } if (OnMissingDescriptor.TAIL.equals(onMissingDescriptor)) { for (File buildFile : noDescriptor) { diff --git a/src/java/org/apache/ivy/ant/IvyBuildNumber.java b/src/java/org/apache/ivy/ant/IvyBuildNumber.java index 863447276..3216532bf 100644 --- a/src/java/org/apache/ivy/ant/IvyBuildNumber.java +++ b/src/java/org/apache/ivy/ant/IvyBuildNumber.java @@ -153,10 +153,10 @@ public void doExecute() throws BuildException { if (revision == null || revision.length() == 0) { revision = "latest.integration"; } else if (!revision.endsWith("+")) { - revision = revision + "+"; + revision += "+"; } if (!prefix.endsWith(".") && prefix.length() > 0) { - prefix = prefix + "."; + prefix += "."; } SearchEngine searcher = new SearchEngine(settings); @@ -205,13 +205,14 @@ public String getName() { VersionMatcher matcher = settings.getVersionMatcher(); LatestStrategy latestStrategy = settings.getLatestStrategy("latest-revision"); - List sorted = latestStrategy.sort(infos); + List sorted = latestStrategy.sort(infos); ModuleRevisionId askedMrid = ModuleRevisionId.newInstance(organisation, module, branch, revision); String foundRevision = null; - for (ListIterator iter = sorted.listIterator(sorted.size()); iter.hasPrevious();) { + ListIterator iter = sorted.listIterator(sorted.size()); + while (iter.hasPrevious()) { ResolvedModuleRevisionArtifactInfo info = (ResolvedModuleRevisionArtifactInfo) iter .previous(); diff --git a/src/java/org/apache/ivy/ant/IvyCacheFileset.java b/src/java/org/apache/ivy/ant/IvyCacheFileset.java index 56bcc6d59..0c9280423 100644 --- a/src/java/org/apache/ivy/ant/IvyCacheFileset.java +++ b/src/java/org/apache/ivy/ant/IvyCacheFileset.java @@ -167,11 +167,11 @@ File getBaseDir(final File file1, final File file2) { if (file1 == null || file2 == null) { return null; } - final Iterator file1Parents = getParents(file1).iterator(); - final Iterator file2Parents = getParents(file2.getAbsoluteFile()).iterator(); + final Iterator file1Parents = getParents(file1).iterator(); + final Iterator file2Parents = getParents(file2.getAbsoluteFile()).iterator(); File result = null; while (file1Parents.hasNext() && file2Parents.hasNext()) { - File next = (File) file1Parents.next(); + File next = file1Parents.next(); if (next.equals(file2Parents.next())) { result = next; } else { diff --git a/src/java/org/apache/ivy/ant/IvyCacheTask.java b/src/java/org/apache/ivy/ant/IvyCacheTask.java index 72c14a748..6b3e10e89 100644 --- a/src/java/org/apache/ivy/ant/IvyCacheTask.java +++ b/src/java/org/apache/ivy/ant/IvyCacheTask.java @@ -18,7 +18,6 @@ package org.apache.ivy.ant; import java.io.File; -import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; @@ -44,7 +43,7 @@ public abstract class IvyCacheTask extends IvyPostResolveTask { protected List getArtifactReports() throws BuildException, - ParseException, IOException { + ParseException { Collection artifacts = getAllArtifactReports(); List ret = new ArrayList<>(); for (ArtifactDownloadReport artifactReport : artifacts) { @@ -56,8 +55,7 @@ protected List getArtifactReports() throws BuildExceptio return ret; } - private Collection getAllArtifactReports() throws ParseException, - IOException { + private Collection getAllArtifactReports() throws ParseException { String[] confs = splitConfs(getConf()); Collection all = new LinkedHashSet<>(); diff --git a/src/java/org/apache/ivy/ant/IvyConfigure.java b/src/java/org/apache/ivy/ant/IvyConfigure.java index f41cb5c1e..94747fa82 100644 --- a/src/java/org/apache/ivy/ant/IvyConfigure.java +++ b/src/java/org/apache/ivy/ant/IvyConfigure.java @@ -48,8 +48,8 @@ public class IvyConfigure extends Task { */ public static final String OVERRIDE_NOT_ALLOWED = "notallowed"; - private static final Collection OVERRIDE_VALUES = Arrays.asList(OVERRIDE_TRUE, - OVERRIDE_FALSE, OVERRIDE_NOT_ALLOWED); + private static final Collection OVERRIDE_VALUES = Arrays.asList(OVERRIDE_TRUE, + OVERRIDE_FALSE, OVERRIDE_NOT_ALLOWED); private String override = OVERRIDE_NOT_ALLOWED; diff --git a/src/java/org/apache/ivy/ant/IvyDependencyTree.java b/src/java/org/apache/ivy/ant/IvyDependencyTree.java index 7c30f253e..181706323 100644 --- a/src/java/org/apache/ivy/ant/IvyDependencyTree.java +++ b/src/java/org/apache/ivy/ant/IvyDependencyTree.java @@ -117,8 +117,7 @@ private boolean hasDependencies(final IvyNode module) { private void populateDependencyTree(IvyNode dependency) { registerNodeIfNecessary(dependency.getId()); - for (int i = 0; i < dependency.getAllCallers().length; i++) { - Caller caller = dependency.getAllCallers()[i]; + for (Caller caller : dependency.getAllCallers()) { addDependency(caller.getModuleRevisionId(), dependency); } } diff --git a/src/java/org/apache/ivy/ant/IvyDependencyUpdateChecker.java b/src/java/org/apache/ivy/ant/IvyDependencyUpdateChecker.java index 1eb628d4a..e6499d532 100644 --- a/src/java/org/apache/ivy/ant/IvyDependencyUpdateChecker.java +++ b/src/java/org/apache/ivy/ant/IvyDependencyUpdateChecker.java @@ -51,13 +51,11 @@ public void doExecute() throws BuildException { originalModuleDescriptor.getModuleRevisionId(), originalModuleDescriptor.getStatus(), originalModuleDescriptor.getPublicationDate()); // copy configurations - for (int i = 0; i < originalModuleDescriptor.getConfigurations().length; i++) { - Configuration configuration = originalModuleDescriptor.getConfigurations()[i]; + for (Configuration configuration : originalModuleDescriptor.getConfigurations()) { latestModuleDescriptor.addConfiguration(configuration); } // clone dependency and add new one with the requested revisionToCheck - for (int i = 0; i < originalModuleDescriptor.getDependencies().length; i++) { - DependencyDescriptor dependencyDescriptor = originalModuleDescriptor.getDependencies()[i]; + for (DependencyDescriptor dependencyDescriptor : originalModuleDescriptor.getDependencies()) { ModuleRevisionId upToDateMrid = ModuleRevisionId.newInstance( dependencyDescriptor.getDependencyRevisionId(), revisionToCheck); latestModuleDescriptor.addDependency(dependencyDescriptor.clone(upToDateMrid)); diff --git a/src/java/org/apache/ivy/ant/IvyPostResolveTask.java b/src/java/org/apache/ivy/ant/IvyPostResolveTask.java index bcca68cae..e78858580 100644 --- a/src/java/org/apache/ivy/ant/IvyPostResolveTask.java +++ b/src/java/org/apache/ivy/ant/IvyPostResolveTask.java @@ -23,6 +23,7 @@ import org.apache.ivy.Ivy; import org.apache.ivy.core.cache.ResolutionCacheManager; +import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleId; import org.apache.ivy.core.module.id.ModuleRevisionId; @@ -61,7 +62,7 @@ public abstract class IvyPostResolveTask extends IvyTask { private File file; - private Filter artifactFilter = null; + private Filter artifactFilter = null; private boolean useOrigin = false; @@ -384,7 +385,7 @@ public void setRevision(String rev) { revision = rev; } - public Filter getArtifactFilter() { + public Filter getArtifactFilter() { return artifactFilter; } diff --git a/src/java/org/apache/ivy/ant/IvyRepositoryReport.java b/src/java/org/apache/ivy/ant/IvyRepositoryReport.java index da27edd0e..6ce744528 100644 --- a/src/java/org/apache/ivy/ant/IvyRepositoryReport.java +++ b/src/java/org/apache/ivy/ant/IvyRepositoryReport.java @@ -129,8 +129,7 @@ public void doExecute() throws BuildException { } } - private void genreport(ResolutionCacheManager cache, String organisation, String module) - throws IOException { + private void genreport(ResolutionCacheManager cache, String organisation, String module) { // first process the report with xslt XSLTProcess xslt = new XSLTProcess(); xslt.setTaskName(getTaskName()); @@ -187,7 +186,7 @@ private String getDotStylePath(File cache) throws IOException { } private void gen(ResolutionCacheManager cache, String organisation, String module, - String style, String ext) throws IOException { + String style, String ext) { XSLTProcess xslt = new XSLTProcess(); xslt.setTaskName(getTaskName()); xslt.setProject(getProject()); diff --git a/src/java/org/apache/ivy/ant/IvyRetrieve.java b/src/java/org/apache/ivy/ant/IvyRetrieve.java index 0fc0f7fdb..f90403a27 100644 --- a/src/java/org/apache/ivy/ant/IvyRetrieve.java +++ b/src/java/org/apache/ivy/ant/IvyRetrieve.java @@ -22,6 +22,7 @@ import java.util.Collection; import org.apache.ivy.core.LogOptions; +import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.retrieve.RetrieveOptions; import org.apache.ivy.core.retrieve.RetrieveReport; import org.apache.ivy.util.filter.Filter; @@ -94,7 +95,7 @@ public void doExecute() throws BuildException { pattern = getProperty(pattern, getSettings(), "ivy.retrieve.pattern"); try { - Filter artifactFilter = getArtifactFilter(); + Filter artifactFilter = getArtifactFilter(); RetrieveReport report = getIvyInstance().retrieve( getResolvedMrid(), ((RetrieveOptions) new RetrieveOptions().setLog(getLog())) diff --git a/src/java/org/apache/ivy/core/IvyContext.java b/src/java/org/apache/ivy/core/IvyContext.java index ab7351142..b26d69e18 100644 --- a/src/java/org/apache/ivy/core/IvyContext.java +++ b/src/java/org/apache/ivy/core/IvyContext.java @@ -41,13 +41,13 @@ */ public class IvyContext { - private static ThreadLocal/* > */current = new ThreadLocal(); + private static ThreadLocal> current = new ThreadLocal<>(); private Ivy defaultIvy; - private WeakReference/* */ivy = new WeakReference(null); + private WeakReference ivy = new WeakReference<>(null); - private Map contextMap = new HashMap(); + private Map contextMap = new HashMap<>(); private Thread operatingThread; @@ -61,24 +61,24 @@ public IvyContext() { public IvyContext(IvyContext ctx) { defaultIvy = ctx.defaultIvy; ivy = ctx.ivy; - contextMap = new HashMap(ctx.contextMap); + contextMap = new HashMap<>(ctx.contextMap); operatingThread = ctx.operatingThread; resolveData = ctx.resolveData; dd = ctx.dd; } public static IvyContext getContext() { - Stack cur = getCurrentStack(); + Stack cur = getCurrentStack(); if (cur.isEmpty()) { cur.push(new IvyContext()); } - return (IvyContext) cur.peek(); + return cur.peek(); } - private static Stack/* */getCurrentStack() { - Stack cur = (Stack) current.get(); + private static Stack getCurrentStack() { + Stack cur = current.get(); if (cur == null) { - cur = new Stack(); + cur = new Stack<>(); current.set(cur); } return cur; @@ -133,7 +133,7 @@ public static IvyContext pushContext(IvyContext context) { * @return the popped context */ public static IvyContext popContext() { - return (IvyContext) getCurrentStack().pop(); + return getCurrentStack().pop(); } /** @@ -153,9 +153,9 @@ public static IvyContext popContext() { */ public static Object peekInContextStack(String key) { Object value = null; - Stack contextStack = getCurrentStack(); + Stack contextStack = getCurrentStack(); for (int i = contextStack.size() - 1; i >= 0 && value == null; i--) { - IvyContext ctx = (IvyContext) contextStack.get(i); + IvyContext ctx = contextStack.get(i); value = ctx.peek(key); } return value; @@ -191,8 +191,7 @@ public Ivy getIvy() { * @return the current ivy instance, or null if there is no current ivy instance. */ public Ivy peekIvy() { - Ivy ivy = (Ivy) this.ivy.get(); - return ivy; + return this.ivy.get(); } private Ivy getDefaultIvy() { @@ -209,7 +208,7 @@ private Ivy getDefaultIvy() { } public void setIvy(Ivy ivy) { - this.ivy = new WeakReference(ivy); + this.ivy = new WeakReference<>(ivy); operatingThread = Thread.currentThread(); } @@ -221,13 +220,14 @@ public CircularDependencyStrategy getCircularDependencyStrategy() { return getSettings().getCircularDependencyStrategy(); } - public Object get(String key) { - WeakReference ref = (WeakReference) contextMap.get(key); - return ref == null ? null : ref.get(); + @SuppressWarnings("unchecked") + public T get(String key) { + WeakReference ref = (WeakReference) contextMap.get(key); + return (ref == null) ? null : ref.get(); } - public void set(String key, Object value) { - contextMap.put(key, new WeakReference(value)); + public void set(String key, T value) { + contextMap.put(key, new WeakReference<>(value)); } /** @@ -238,6 +238,7 @@ public void set(String key, Object value) { * context key for the string * @return top object from the list (index 0) or null if no key or list empty */ + @SuppressWarnings("unchecked") public Object peek(String key) { synchronized (contextMap) { Object o = contextMap.get(key); @@ -245,11 +246,10 @@ public Object peek(String key) { return null; } if (o instanceof List) { - if (((List) o).size() == 0) { + if (((List) o).size() == 0) { return null; } - Object ret = ((List) o).get(0); - return ret; + return ((List) o).get(0); } else { throw new RuntimeException("Cannot top from non List object " + o); } @@ -264,6 +264,7 @@ public Object peek(String key) { * context key for the string * @return top object from the list (index 0) or null if no key or list empty */ + @SuppressWarnings("unchecked") public Object pop(String key) { synchronized (contextMap) { Object o = contextMap.get(key); @@ -271,11 +272,10 @@ public Object pop(String key) { return null; } if (o instanceof List) { - if (((List) o).size() == 0) { + if (((List) o).size() == 0) { return null; } - Object ret = ((List) o).remove(0); - return ret; + return ((List) o).remove(0); } else { throw new RuntimeException("Cannot pop from non List object " + o); } @@ -293,6 +293,7 @@ public Object pop(String key) { * expected value of the key * @return true if the r */ + @SuppressWarnings("unchecked") public boolean pop(String key, Object expectedValue) { synchronized (contextMap) { Object o = contextMap.get(key); @@ -300,14 +301,14 @@ public boolean pop(String key, Object expectedValue) { return false; } if (o instanceof List) { - if (((List) o).size() == 0) { + if (((List) o).size() == 0) { return false; } - Object top = ((List) o).get(0); + Object top = ((List) o).get(0); if (!top.equals(expectedValue)) { return false; } - ((List) o).remove(0); + ((List) o).remove(0); return true; } else { throw new RuntimeException("Cannot pop from non List object " + o); @@ -330,11 +331,11 @@ public boolean pop(String key, Object expectedValue) { public void push(String key, Object value) { synchronized (contextMap) { if (!contextMap.containsKey(key)) { - contextMap.put(key, new LinkedList()); + contextMap.put(key, new LinkedList<>()); } Object o = contextMap.get(key); if (o instanceof List) { - ((List) o).add(0, value); + ((List) o).add(0, value); } else { throw new RuntimeException("Cannot push to non List object " + o); } diff --git a/src/java/org/apache/ivy/core/IvyPatternHelper.java b/src/java/org/apache/ivy/core/IvyPatternHelper.java index e8fb47eff..70bebcde9 100644 --- a/src/java/org/apache/ivy/core/IvyPatternHelper.java +++ b/src/java/org/apache/ivy/core/IvyPatternHelper.java @@ -19,7 +19,6 @@ import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; @@ -118,20 +117,19 @@ public static String substitute(String pattern, String org, String module, Strin } public static String substitute(String pattern, String org, String module, String revision, - String artifact, String type, String ext, String conf, Map extraModuleAttributes, - Map extraArtifactAttributes) { + String artifact, String type, String ext, String conf, Map extraModuleAttributes, + Map extraArtifactAttributes) { return substitute(pattern, org, module, null, revision, artifact, type, ext, conf, null, extraModuleAttributes, extraArtifactAttributes); } public static String substitute(String pattern, String org, String module, String branch, String revision, String artifact, String type, String ext, String conf, - ArtifactOrigin origin, Map extraModuleAttributes, Map extraArtifactAttributes) { - Map tokens = new HashMap(); + ArtifactOrigin origin, Map extraModuleAttributes, Map extraArtifactAttributes) { + Map tokens = new HashMap<>(); if (extraModuleAttributes != null) { - for (Iterator entries = extraModuleAttributes.entrySet().iterator(); entries.hasNext();) { - Map.Entry entry = (Map.Entry) entries.next(); - String token = (String) entry.getKey(); + for (Map.Entry entry : extraModuleAttributes.entrySet()) { + String token = entry.getKey(); if (token.indexOf(':') > 0) { token = token.substring(token.indexOf(':') + 1); } @@ -139,10 +137,8 @@ public static String substitute(String pattern, String org, String module, Strin } } if (extraArtifactAttributes != null) { - for (Iterator entries = extraArtifactAttributes.entrySet().iterator(); entries - .hasNext();) { - Map.Entry entry = (Map.Entry) entries.next(); - String token = (String) entry.getKey(); + for (Map.Entry entry : extraArtifactAttributes.entrySet()) { + String token = entry.getKey(); if (token.indexOf(':') > 0) { token = token.substring(token.indexOf(':') + 1); } @@ -172,16 +168,16 @@ public static String substitute(String pattern, String org, String module, Strin // CheckStyle:ParameterNumber ON - public static String substituteVariables(String pattern, Map variables) { - return substituteVariables(pattern, new IvyVariableContainerImpl(variables), new Stack()); + public static String substituteVariables(String pattern, Map variables) { + return substituteVariables(pattern, new IvyVariableContainerImpl(variables), new Stack()); } public static String substituteVariables(String pattern, IvyVariableContainer variables) { - return substituteVariables(pattern, variables, new Stack()); + return substituteVariables(pattern, variables, new Stack()); } private static String substituteVariables(String pattern, IvyVariableContainer variables, - Stack substituting) { + Stack substituting) { // if you supply null, null is what you get if (pattern == null) { return null; @@ -201,7 +197,7 @@ private static String substituteVariables(String pattern, IvyVariableContainer v if (val != null) { int index = substituting.indexOf(var); if (index != -1) { - List cycle = new ArrayList(substituting.subList(index, substituting.size())); + List cycle = new ArrayList<>(substituting.subList(index, substituting.size())); cycle.add(var); throw new IllegalArgumentException("cyclic variable definition: cycle = " + cycle); @@ -222,8 +218,9 @@ private static String substituteVariables(String pattern, IvyVariableContainer v } } + @SuppressWarnings({"rawtypes", "unchecked"}) public static String substituteTokens(String pattern, Map tokens) { - Map tokensCopy = new HashMap(tokens); + Map tokensCopy = new HashMap<>(tokens); if (tokensCopy.containsKey(ORGANISATION_KEY) && !tokensCopy.containsKey(ORGANISATION_KEY2)) { tokensCopy.put(ORGANISATION_KEY2, tokensCopy.get(ORGANISATION_KEY)); } @@ -233,7 +230,7 @@ public static String substituteTokens(String pattern, Map tokens) { tokensCopy.put(ORGANISATION_PATH_KEY, org == null ? "" : org.replace('.', '/')); } - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); char[] chars = pattern.toCharArray(); @@ -367,12 +364,12 @@ public static String getTokenString(String token) { return "[" + token + "]"; } - public static String substituteParams(String pattern, Map params) { - return substituteParams(pattern, new IvyVariableContainerImpl(params), new Stack()); + public static String substituteParams(String pattern, Map params) { + return substituteParams(pattern, new IvyVariableContainerImpl(params), new Stack()); } private static String substituteParams(String pattern, IvyVariableContainer params, - Stack substituting) { + Stack substituting) { // TODO : refactor this with substituteVariables // if you supply null, null is what you get if (pattern == null) { @@ -388,7 +385,7 @@ private static String substituteParams(String pattern, IvyVariableContainer para if (val != null) { int index = substituting.indexOf(var); if (index != -1) { - List cycle = new ArrayList(substituting.subList(index, substituting.size())); + List cycle = new ArrayList<>(substituting.subList(index, substituting.size())); cycle.add(var); throw new IllegalArgumentException("cyclic param definition: cycle = " + cycle); } @@ -420,7 +417,7 @@ private static class OriginalArtifactNameValue { private String revision; - private Map extraModuleAttributes; + private Map extraModuleAttributes; // artifact properties private String artifactName; @@ -429,14 +426,14 @@ private static class OriginalArtifactNameValue { private String artifactExt; - private Map extraArtifactAttributes; + private Map extraArtifactAttributes; // cached origin; private ArtifactOrigin origin; public OriginalArtifactNameValue(String org, String moduleName, String branch, String revision, String artifactName, String artifactType, String artifactExt, - Map extraModuleAttributes, Map extraArtifactAttributes) { + Map extraModuleAttributes, Map extraArtifactAttributes) { this.org = org; this.moduleName = moduleName; this.branch = branch; diff --git a/src/java/org/apache/ivy/core/cache/ArtifactOrigin.java b/src/java/org/apache/ivy/core/cache/ArtifactOrigin.java index b3449a2fc..e65a683ce 100644 --- a/src/java/org/apache/ivy/core/cache/ArtifactOrigin.java +++ b/src/java/org/apache/ivy/core/cache/ArtifactOrigin.java @@ -150,7 +150,7 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) { + if (!(o instanceof ArtifactOrigin)) { return false; } diff --git a/src/java/org/apache/ivy/core/cache/DefaultRepositoryCacheManager.java b/src/java/org/apache/ivy/core/cache/DefaultRepositoryCacheManager.java index 1a1fa0f5c..c0d2eb595 100644 --- a/src/java/org/apache/ivy/core/cache/DefaultRepositoryCacheManager.java +++ b/src/java/org/apache/ivy/core/cache/DefaultRepositoryCacheManager.java @@ -119,7 +119,7 @@ public class DefaultRepositoryCacheManager implements RepositoryCacheManager, Iv private Boolean useOrigin; - private ModuleRules ttlRules = new ModuleRules(); + private ModuleRules ttlRules = new ModuleRules<>(); private Long defaultTTL = null; @@ -127,7 +127,7 @@ public class DefaultRepositoryCacheManager implements RepositoryCacheManager, Iv private PackagingManager packagingManager = new PackagingManager(); - private final List configuredTTLs = new ArrayList(); + private final List configuredTTLs = new ArrayList<>(); public DefaultRepositoryCacheManager() { } @@ -202,17 +202,17 @@ public void setBasedir(File cache) { public long getDefaultTTL() { if (defaultTTL == null) { - defaultTTL = Long.valueOf(parseDuration(settings.getVariable("ivy.cache.ttl.default"))); + defaultTTL = parseDuration(settings.getVariable("ivy.cache.ttl.default")); } - return defaultTTL.longValue(); + return defaultTTL; } public void setDefaultTTL(long defaultTTL) { - this.defaultTTL = Long.valueOf(defaultTTL); + this.defaultTTL = defaultTTL; } public void setDefaultTTL(String defaultTTL) { - this.defaultTTL = Long.valueOf(parseDuration(defaultTTL)); + this.defaultTTL = parseDuration(defaultTTL); } public String getDataFilePattern() { @@ -254,7 +254,7 @@ public void setChangingPattern(String changingPattern) { } public void addTTL(Map attributes, PatternMatcher matcher, long duration) { - ttlRules.defineRule(new MapMatcher(attributes, matcher), new Long(duration)); + ttlRules.defineRule(new MapMatcher(attributes, matcher), duration); } public void addConfiguredTtl(final Map attributes) { @@ -330,7 +330,7 @@ public boolean isCheckmodified() { return getSettings() != null && Boolean .parseBoolean(getSettings().getVariable("ivy.resolver.default.check.modified")); } - return checkmodified.booleanValue(); + return checkmodified; } public void setCheckmodified(boolean check) { @@ -937,7 +937,7 @@ public void saveResolvedRevision(String resolverName, ModuleRevisionId mrid, Str public long getTTL(ModuleRevisionId mrid) { Long ttl = ttlRules.getRule(mrid); - return ttl == null ? getDefaultTTL() : ttl.longValue(); + return ttl == null ? getDefaultTTL() : ttl; } @Override @@ -1128,7 +1128,7 @@ && checkCacheUptodate(archiveFile, resource, savedOrigin, origin, } } else { long start = System.currentTimeMillis(); - origin.setLastChecked(new Long(start)); + origin.setLastChecked(start); try { ResolvedResource artifactRef = new ResolvedResource(resource, Ivy.getWorkingRevision()); @@ -1216,7 +1216,7 @@ private boolean checkCacheUptodate(File archiveFile, Resource resource, ArtifactOrigin savedOrigin, ArtifactOrigin origin, long ttl) { long time = System.currentTimeMillis(); if (savedOrigin.getLastChecked() != null - && (time - savedOrigin.getLastChecked().longValue()) < ttl) { + && (time - savedOrigin.getLastChecked()) < ttl) { // still in the ttl period, no need to check, trust the cache return archiveFile.exists() || !savedOrigin.isExists(); } @@ -1224,7 +1224,7 @@ private boolean checkCacheUptodate(File archiveFile, Resource resource, // the the file doesn't exist in the cache, obviously not up to date return false; } - origin.setLastChecked(Long.valueOf(time)); + origin.setLastChecked(time); // check if the local resource is up to date regarding the remote one return archiveFile.lastModified() >= resource.getLastModified(); } @@ -1580,7 +1580,7 @@ public void cleanUp() { private static final class ConfiguredTTL { // attributes on the TTL, that don't contribute to module matching - private static final Set attributesNotContributingToMatching = new HashSet(); + private static final Set attributesNotContributingToMatching = new HashSet<>(); static { attributesNotContributingToMatching.add("duration"); attributesNotContributingToMatching.add("matcher"); @@ -1596,7 +1596,7 @@ private ConfiguredTTL(final long duration, final String matcher, final Map attrs = new HashMap(attributes); + final Map attrs = new HashMap<>(attributes); for (final String removable : attributesNotContributingToMatching) { attrs.remove(removable); } diff --git a/src/java/org/apache/ivy/core/cache/DefaultResolutionCacheManager.java b/src/java/org/apache/ivy/core/cache/DefaultResolutionCacheManager.java index d1ccfc311..e143df26a 100644 --- a/src/java/org/apache/ivy/core/cache/DefaultResolutionCacheManager.java +++ b/src/java/org/apache/ivy/core/cache/DefaultResolutionCacheManager.java @@ -195,22 +195,21 @@ public void saveResolvedModuleDescriptor(ModuleDescriptor md) throws ParseExcept private void saveLocalParents(ModuleRevisionId baseMrevId, ModuleDescriptor md, File mdFile, Properties paths) throws ParseException, IOException { - ExtendsDescriptor[] parents = md.getInheritedDescriptors(); - for (int i = 0; i < parents.length; i++) { - if (!parents[i].isLocal()) { + for (ExtendsDescriptor parent : md.getInheritedDescriptors()) { + if (!parent.isLocal()) { // we store only local parents in the cache! continue; } - ModuleDescriptor parent = parents[i].getParentMd(); + ModuleDescriptor parentMd = parent.getParentMd(); ModuleRevisionId pRevId = ModuleRevisionId.newInstance(baseMrevId, baseMrevId.getRevision() + "-parent." + paths.size()); File parentFile = getResolvedIvyFileInCache(pRevId); - parent.toIvyFile(parentFile); + parentMd.toIvyFile(parentFile); - paths.setProperty(mdFile.getName() + "|" + parents[i].getLocation(), + paths.setProperty(mdFile.getName() + "|" + parent.getLocation(), parentFile.getAbsolutePath()); - saveLocalParents(baseMrevId, parent, parentFile, paths); + saveLocalParents(baseMrevId, parentMd, parentFile, paths); } } @@ -226,9 +225,9 @@ private static class CacheParserSettings implements ParserSettings { private ParserSettings delegate; - private Map parentPaths; + private Map parentPaths; - public CacheParserSettings(ParserSettings delegate, Map parentPaths) { + public CacheParserSettings(ParserSettings delegate, Map parentPaths) { this.delegate = delegate; this.parentPaths = parentPaths; } @@ -237,7 +236,7 @@ public String substitute(String value) { return delegate.substitute(value); } - public Map substitute(Map strings) { + public Map substitute(Map strings) { return delegate.substitute(strings); } @@ -288,18 +287,18 @@ public String getVariable(String value) { private static final class MapURLResolver extends RelativeUrlResolver { - private Map paths; + private Map paths; private RelativeUrlResolver delegate; - private MapURLResolver(Map paths, RelativeUrlResolver delegate) { + private MapURLResolver(Map paths, RelativeUrlResolver delegate) { this.paths = paths; this.delegate = delegate; } public URL getURL(URL context, String url) throws MalformedURLException { String path = context.getPath(); - if (path.indexOf('/') >= 0) { + if (path.contains("/")) { String file = path.substring(path.lastIndexOf('/') + 1); if (paths.containsKey(file + "|" + url)) { diff --git a/src/java/org/apache/ivy/core/cache/ModuleDescriptorMemoryCache.java b/src/java/org/apache/ivy/core/cache/ModuleDescriptorMemoryCache.java index cd2b0bda1..357c130b8 100644 --- a/src/java/org/apache/ivy/core/cache/ModuleDescriptorMemoryCache.java +++ b/src/java/org/apache/ivy/core/cache/ModuleDescriptorMemoryCache.java @@ -37,7 +37,7 @@ class ModuleDescriptorMemoryCache { private final int maxSize; - private final LinkedHashMap/* */valueMap; + private final LinkedHashMap valueMap; /** * Create a cache of the given size @@ -46,7 +46,7 @@ class ModuleDescriptorMemoryCache { */ public ModuleDescriptorMemoryCache(int size) { this.maxSize = size; - this.valueMap = new LinkedHashMap(size); + this.valueMap = new LinkedHashMap<>(size); } public ModuleDescriptor get(File ivyFile, ParserSettings ivySettings, boolean validated, @@ -76,7 +76,7 @@ ModuleDescriptor getFromCache(File ivyFile, ParserSettings ivySettings, boolean // cache is disabled return null; } - CacheEntry entry = (CacheEntry) valueMap.get(ivyFile); + CacheEntry entry = valueMap.get(ivyFile); if (entry != null) { if (entry.isStale(validated, ivySettings)) { Message.debug("Entry is found in the ModuleDescriptorCache but entry should be " @@ -104,7 +104,7 @@ void putInCache(File url, ParserSettingsMonitor ivySettingsMonitor, boolean vali } if (valueMap.size() >= maxSize) { Message.debug("ModuleDescriptorCache is full, remove one entry"); - Iterator it = valueMap.values().iterator(); + Iterator it = valueMap.values().iterator(); it.next(); it.remove(); } diff --git a/src/java/org/apache/ivy/core/cache/ParserSettingsMonitor.java b/src/java/org/apache/ivy/core/cache/ParserSettingsMonitor.java index c0a971da6..f38357893 100644 --- a/src/java/org/apache/ivy/core/cache/ParserSettingsMonitor.java +++ b/src/java/org/apache/ivy/core/cache/ParserSettingsMonitor.java @@ -19,10 +19,8 @@ import java.io.File; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; -import java.util.Map.Entry; import org.apache.ivy.core.RelativeUrlResolver; import org.apache.ivy.core.module.id.ModuleId; @@ -50,11 +48,11 @@ class ParserSettingsMonitor { private ParserSettings delegatedSettings; - private final Map/* */substitutes; + private final Map substitutes; public ParserSettingsMonitor(ParserSettings settings) { this.delegatedSettings = settings; - this.substitutes = new HashMap(); + this.substitutes = new HashMap<>(); } /** @@ -79,13 +77,10 @@ public void endMonitoring() { * Only the info that was actually used is compared. */ public boolean hasChanged(ParserSettings newSettings) { - for (Iterator it = substitutes.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Entry) it.next(); - String key = (String) entry.getKey(); - Object oldValue = entry.getValue(); - String newValue = newSettings.substitute(key); - if (!oldValue.equals(newValue)) { - Message.debug("settings variable has changed for : " + entry.getKey()); + for (Map.Entry entry : substitutes.entrySet()) { + String key = entry.getKey(); + if (!entry.getValue().equals(newSettings.substitute(key))) { + Message.debug("settings variable has changed for : " + key); return true; } } @@ -134,11 +129,10 @@ public Namespace getContextNamespace() { return delegatedSettings.getContextNamespace(); } - public Map substitute(Map strings) { - Map substituted = new LinkedHashMap(); - for (Iterator it = strings.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - substituted.put(entry.getKey(), substitute((String) entry.getValue())); + public Map substitute(Map strings) { + Map substituted = new LinkedHashMap<>(); + for (Map.Entry entry : strings.entrySet()) { + substituted.put(entry.getKey(), substitute(entry.getValue())); } return substituted; } diff --git a/src/java/org/apache/ivy/core/check/CheckEngine.java b/src/java/org/apache/ivy/core/check/CheckEngine.java index 8f85f4ba2..d48df8a2a 100644 --- a/src/java/org/apache/ivy/core/check/CheckEngine.java +++ b/src/java/org/apache/ivy/core/check/CheckEngine.java @@ -22,7 +22,6 @@ import java.text.ParseException; import java.util.Arrays; import java.util.HashSet; -import java.util.Iterator; import java.util.Set; import org.apache.ivy.core.module.descriptor.Artifact; @@ -67,56 +66,47 @@ public boolean check(URL ivyFile, String resolvername) { // check publications if possible if (resolvername != null) { DependencyResolver resolver = settings.getResolver(resolvername); - String[] confs = md.getConfigurationsNames(); - Set artifacts = new HashSet(); - for (int i = 0; i < confs.length; i++) { - artifacts.addAll(Arrays.asList(md.getArtifacts(confs[i]))); + Set artifacts = new HashSet<>(); + for (String conf : md.getConfigurationsNames()) { + artifacts.addAll(Arrays.asList(md.getArtifacts(conf))); } - for (Iterator iter = artifacts.iterator(); iter.hasNext();) { - Artifact art = (Artifact) iter.next(); - if (!resolver.exists(art)) { - Message.info("declared publication not found: " + art); + for (Artifact artifact : artifacts) { + if (!resolver.exists(artifact)) { + Message.info("declared publication not found: " + artifact); result = false; } } } // check dependencies - DependencyDescriptor[] dds = md.getDependencies(); ResolveData data = new ResolveData(resolveEngine, new ResolveOptions()); - for (int i = 0; i < dds.length; i++) { + for (DependencyDescriptor dd : md.getDependencies()) { // check master confs - String[] masterConfs = dds[i].getModuleConfigurations(); - for (int j = 0; j < masterConfs.length; j++) { - if (!"*".equals(masterConfs[j].trim()) - && md.getConfiguration(masterConfs[j]) == null) { + for (String masterConf : dd.getModuleConfigurations()) { + if (!"*".equals(masterConf.trim()) && md.getConfiguration(masterConf) == null) { Message.info("dependency required in non existing conf for " + ivyFile - + " \n\tin " + dds[i] + ": " + masterConfs[j]); + + " \n\tin " + dd + ": " + masterConf); result = false; } } // resolve - DependencyResolver resolver = settings - .getResolver(dds[i].getDependencyRevisionId()); - ResolvedModuleRevision rmr = resolver.getDependency(dds[i], data); + DependencyResolver resolver = settings.getResolver(dd.getDependencyRevisionId()); + ResolvedModuleRevision rmr = resolver.getDependency(dd, data); if (rmr == null) { - Message.info("dependency not found in " + ivyFile + ":\n\t" + dds[i]); + Message.info("dependency not found in " + ivyFile + ":\n\t" + dd); result = false; } else { - String[] depConfs = dds[i].getDependencyConfigurations(md - .getConfigurationsNames()); - for (int j = 0; j < depConfs.length; j++) { - if (!Arrays.asList(rmr.getDescriptor().getConfigurationsNames()).contains( - depConfs[j])) { + for (String depConf : dd.getDependencyConfigurations(md.getConfigurationsNames())) { + if (!Arrays.asList(rmr.getDescriptor().getConfigurationsNames()) + .contains(depConf)) { Message.info("dependency configuration is missing for " + ivyFile - + "\n\tin " + dds[i] + ": " + depConfs[j]); + + "\n\tin " + dd + ": " + depConf); result = false; } - Artifact[] arts = rmr.getDescriptor().getArtifacts(depConfs[j]); - for (int k = 0; k < arts.length; k++) { - if (!resolver.exists(arts[k])) { + for (Artifact art : rmr.getDescriptor().getArtifacts(depConf)) { + if (!resolver.exists(art)) { Message.info("dependency artifact is missing for " + ivyFile - + "\n\t in " + dds[i] + ": " + arts[k]); + + "\n\t in " + dd + ": " + art); result = false; } } diff --git a/src/java/org/apache/ivy/core/deliver/DeliverEngine.java b/src/java/org/apache/ivy/core/deliver/DeliverEngine.java index 11a843adf..4a7c05031 100644 --- a/src/java/org/apache/ivy/core/deliver/DeliverEngine.java +++ b/src/java/org/apache/ivy/core/deliver/DeliverEngine.java @@ -24,7 +24,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; @@ -115,9 +114,9 @@ public void deliver(ModuleRevisionId mrid, String revision, String destIvyPatter md.setResolvedPublicationDate(options.getPubdate()); // 2) parse resolvedRevisions From properties file - Map resolvedRevisions = new HashMap(); // Map (ModuleId -> String revision) - Map resolvedBranches = new HashMap(); // Map (ModuleId -> String branch) - Map dependenciesStatus = new HashMap(); // Map (ModuleId -> String status) + Map resolvedRevisions = new HashMap<>(); // Map (ModuleId -> String revision) + Map resolvedBranches = new HashMap<>(); // Map (ModuleId -> String branch) + Map dependenciesStatus = new HashMap<>(); // Map (ModuleId -> String status) File ivyProperties = getCache().getResolvedIvyPropertiesInCache(mrid); if (!ivyProperties.exists()) { throw new IllegalStateException("ivy properties not found in cache for " + mrid @@ -128,8 +127,8 @@ public void deliver(ModuleRevisionId mrid, String revision, String destIvyPatter props.load(in); in.close(); - for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { - String depMridStr = (String) iter.next(); + for (Object o : props.keySet()) { + String depMridStr = (String) o; String[] parts = props.getProperty(depMridStr).split(" "); ModuleRevisionId decodedMrid = ModuleRevisionId.decode(depMridStr); if (options.isResolveDynamicRevisions()) { @@ -155,29 +154,23 @@ public void deliver(ModuleRevisionId mrid, String revision, String destIvyPatter } // 3) use pdrResolver to resolve dependencies info - Map resolvedDependencies = new HashMap(); // Map (ModuleRevisionId -> String revision) - DependencyDescriptor[] dependencies = md.getDependencies(); - for (int i = 0; i < dependencies.length; i++) { - String rev = (String) resolvedRevisions.get(dependencies[i].getDependencyRevisionId()); + Map resolvedDependencies = new HashMap<>(); + // Map (ModuleRevisionId -> String revision) + for (DependencyDescriptor dependency : md.getDependencies()) { + String rev = resolvedRevisions.get(dependency.getDependencyRevisionId()); if (rev == null) { - rev = dependencies[i].getDependencyRevisionId().getRevision(); + rev = dependency.getDependencyRevisionId().getRevision(); } - String bra = (String) resolvedBranches.get(dependencies[i].getDependencyRevisionId()); + String bra = resolvedBranches.get(dependency.getDependencyRevisionId()); if (bra == null || "null".equals(bra)) { - bra = dependencies[i].getDependencyRevisionId().getBranch(); + bra = dependency.getDependencyRevisionId().getBranch(); } - String depStatus = (String) dependenciesStatus.get(dependencies[i] - .getDependencyRevisionId()); - ModuleRevisionId mrid2 = null; - if (bra == null) { - mrid2 = ModuleRevisionId - .newInstance(dependencies[i].getDependencyRevisionId(), rev); - } else { - mrid2 = ModuleRevisionId.newInstance(dependencies[i].getDependencyRevisionId(), - bra, rev); - } - resolvedDependencies.put(dependencies[i].getDependencyRevisionId(), options - .getPdrResolver().resolve(md, options.getStatus(), mrid2, depStatus)); + String depStatus = dependenciesStatus.get(dependency.getDependencyRevisionId()); + ModuleRevisionId mrid2 = (bra == null) + ? ModuleRevisionId.newInstance(dependency.getDependencyRevisionId(), rev) + : ModuleRevisionId.newInstance(dependency.getDependencyRevisionId(), bra, rev); + resolvedDependencies.put(dependency.getDependencyRevisionId(), + options.getPdrResolver().resolve(md, options.getStatus(), mrid2, depStatus)); } // 4) copy the source resolved ivy to the destination specified, @@ -188,7 +181,7 @@ public void deliver(ModuleRevisionId mrid, String revision, String destIvyPatter Message.info("\tdelivering ivy file to " + publishedIvy); String[] confs = ConfigurationUtils.replaceWildcards(options.getConfs(), md); - Set confsToRemove = new HashSet(Arrays.asList(md.getConfigurationsNames())); + Set confsToRemove = new HashSet<>(Arrays.asList(md.getConfigurationsNames())); confsToRemove.removeAll(Arrays.asList(confs)); try { @@ -203,7 +196,7 @@ public void deliver(ModuleRevisionId mrid, String revision, String destIvyPatter .setMerge(options.isMerge()) .setMergedDescriptor(md) .setConfsToExclude( - (String[]) confsToRemove.toArray(new String[confsToRemove.size()])); + confsToRemove.toArray(new String[confsToRemove.size()])); if (!resolvedBranches.isEmpty()) { opts = opts.setResolvedBranches(resolvedBranches); } diff --git a/src/java/org/apache/ivy/core/event/EventManager.java b/src/java/org/apache/ivy/core/event/EventManager.java index 743b7d40a..5186b5fd6 100644 --- a/src/java/org/apache/ivy/core/event/EventManager.java +++ b/src/java/org/apache/ivy/core/event/EventManager.java @@ -37,17 +37,17 @@ public void addIvyListener(IvyListener listener, String eventName) { addIvyListener(listener, new IvyEventFilter(eventName, null, null)); } - public void addIvyListener(IvyListener listener, Filter filter) { + public void addIvyListener(IvyListener listener, Filter filter) { listeners.add(IvyListener.class, new FilteredIvyListener(listener, filter)); } public void removeIvyListener(IvyListener listener) { listeners.remove(IvyListener.class, listener); IvyListener[] listeners = this.listeners.getListeners(IvyListener.class); - for (int i = 0; i < listeners.length; i++) { - if (listeners[i] instanceof FilteredIvyListener) { - if (listener.equals(((FilteredIvyListener) listeners[i]).getIvyListener())) { - this.listeners.remove(IvyListener.class, listeners[i]); + for (IvyListener listen : listeners) { + if (listen instanceof FilteredIvyListener) { + if (listener.equals(((FilteredIvyListener) listen).getIvyListener())) { + this.listeners.remove(IvyListener.class, listen); } } } diff --git a/src/java/org/apache/ivy/core/event/FilteredIvyListener.java b/src/java/org/apache/ivy/core/event/FilteredIvyListener.java index e52512d8e..88b5c67f9 100644 --- a/src/java/org/apache/ivy/core/event/FilteredIvyListener.java +++ b/src/java/org/apache/ivy/core/event/FilteredIvyListener.java @@ -22,9 +22,9 @@ public class FilteredIvyListener implements IvyListener { private IvyListener listener; - private Filter filter; + private Filter filter; - public FilteredIvyListener(IvyListener listener, Filter filter) { + public FilteredIvyListener(IvyListener listener, Filter filter) { this.listener = listener; this.filter = filter; } @@ -33,7 +33,7 @@ public IvyListener getIvyListener() { return listener; } - public Filter getFilter() { + public Filter getFilter() { return filter; } diff --git a/src/java/org/apache/ivy/core/event/IvyEvent.java b/src/java/org/apache/ivy/core/event/IvyEvent.java index 68e13b35c..82e2d7f47 100644 --- a/src/java/org/apache/ivy/core/event/IvyEvent.java +++ b/src/java/org/apache/ivy/core/event/IvyEvent.java @@ -84,7 +84,7 @@ protected void addConfsAttribute(String[] confs) { addAttribute("conf", StringUtils.join(confs, ", ")); } - protected void addAttributes(Map attributes) { + protected void addAttributes(Map attributes) { this.attributes.putAll(attributes); } diff --git a/src/java/org/apache/ivy/core/event/IvyEventFilter.java b/src/java/org/apache/ivy/core/event/IvyEventFilter.java index ac9251f9c..29585136a 100644 --- a/src/java/org/apache/ivy/core/event/IvyEventFilter.java +++ b/src/java/org/apache/ivy/core/event/IvyEventFilter.java @@ -67,7 +67,7 @@ * * @since 1.4 */ -public class IvyEventFilter implements Filter { +public class IvyEventFilter implements Filter { private static final String NOT = "NOT "; private static final String OR = " OR "; @@ -76,28 +76,27 @@ public class IvyEventFilter implements Filter { private PatternMatcher matcher; - private Filter nameFilter; + private Filter nameFilter; - private Filter attFilter; + private Filter attFilter; public IvyEventFilter(String event, String filterExpression, PatternMatcher matcher) { - this.matcher = matcher == null ? ExactPatternMatcher.INSTANCE : matcher; + this.matcher = (matcher == null) ? ExactPatternMatcher.INSTANCE : matcher; if (event == null) { - nameFilter = NoFilter.INSTANCE; + nameFilter = NoFilter.instance(); } else { final Matcher eventNameMatcher = this.matcher.getMatcher(event); - nameFilter = new Filter() { - public boolean accept(Object o) { - IvyEvent e = (IvyEvent) o; + nameFilter = new Filter() { + public boolean accept(IvyEvent e) { return eventNameMatcher.matches(e.getName()); } }; } - attFilter = filterExpression == null || filterExpression.trim().length() == 0 ? NoFilter.INSTANCE - : parseExpression(filterExpression); + attFilter = (filterExpression == null || filterExpression.trim().length() == 0) + ? NoFilter. instance() : parseExpression(filterExpression); } - private Filter parseExpression(String filterExpression) { + private Filter parseExpression(String filterExpression) { // expressions handled for the moment: (informal grammar) // EXP := SIMPLE_EXP | AND_EXP | OR_EXP | NOT_EXP // AND_EXP := EXP && EXP @@ -111,7 +110,7 @@ private Filter parseExpression(String filterExpression) { index = filterExpression.indexOf(OR); if (index == -1) { if (filterExpression.startsWith(NOT)) { - return new NotFilter(parseExpression(filterExpression.substring(NOT.length()))); + return new NotFilter<>(parseExpression(filterExpression.substring(NOT.length()))); } else { index = filterExpression.indexOf("="); if (index == -1) { @@ -124,15 +123,14 @@ private Filter parseExpression(String filterExpression) { for (int i = 0; i < values.length; i++) { matchers[i] = matcher.getMatcher(values[i].trim()); } - return new Filter() { - public boolean accept(Object o) { - IvyEvent e = (IvyEvent) o; - String val = (String) e.getAttributes().get(attname); + return new Filter() { + public boolean accept(IvyEvent e) { + String val = e.getAttributes().get(attname); if (val == null) { return false; } - for (int i = 0; i < matchers.length; i++) { - if (matchers[i].matches(val)) { + for (Matcher matcher : matchers) { + if (matcher.matches(val)) { return true; } } @@ -141,17 +139,17 @@ public boolean accept(Object o) { }; } } else { - return new OrFilter(parseExpression(filterExpression.substring(0, index)), + return new OrFilter<>(parseExpression(filterExpression.substring(0, index)), parseExpression(filterExpression.substring(index + OR.length()))); } } else { - return new AndFilter(parseExpression(filterExpression.substring(0, index)), + return new AndFilter<>(parseExpression(filterExpression.substring(0, index)), parseExpression(filterExpression.substring(index + AND.length()))); } } - public boolean accept(Object o) { - return o instanceof IvyEvent && nameFilter.accept(o) && attFilter.accept(o); + public boolean accept(IvyEvent e) { + return nameFilter.accept(e) && attFilter.accept(e); } } diff --git a/src/java/org/apache/ivy/core/event/publish/EndArtifactPublishEvent.java b/src/java/org/apache/ivy/core/event/publish/EndArtifactPublishEvent.java index c2e08dd38..53e453929 100644 --- a/src/java/org/apache/ivy/core/event/publish/EndArtifactPublishEvent.java +++ b/src/java/org/apache/ivy/core/event/publish/EndArtifactPublishEvent.java @@ -30,9 +30,6 @@ */ public class EndArtifactPublishEvent extends PublishEvent { - @SuppressWarnings("unused") - private static final long serialVersionUID = -65690169431499422L; - public static final String NAME = "post-publish-artifact"; public static final String STATUS_SUCCESSFUL = "successful"; diff --git a/src/java/org/apache/ivy/core/event/publish/StartArtifactPublishEvent.java b/src/java/org/apache/ivy/core/event/publish/StartArtifactPublishEvent.java index 42a8068ed..36ead5a48 100644 --- a/src/java/org/apache/ivy/core/event/publish/StartArtifactPublishEvent.java +++ b/src/java/org/apache/ivy/core/event/publish/StartArtifactPublishEvent.java @@ -30,9 +30,6 @@ */ public class StartArtifactPublishEvent extends PublishEvent { - @SuppressWarnings("unused") - private static final long serialVersionUID = -1134274781039590219L; - public static final String NAME = "pre-publish-artifact"; public StartArtifactPublishEvent(DependencyResolver resolver, Artifact artifact, File data, diff --git a/src/java/org/apache/ivy/core/install/InstallEngine.java b/src/java/org/apache/ivy/core/install/InstallEngine.java index 47e45e75b..db9a4cbfa 100644 --- a/src/java/org/apache/ivy/core/install/InstallEngine.java +++ b/src/java/org/apache/ivy/core/install/InstallEngine.java @@ -93,28 +93,23 @@ public ResolveReport install(ModuleRevisionId mrid, String from, String to, ExactPatternMatcher.ANY_EXPRESSION), ExactPatternMatcher.INSTANCE, new NoConflictManager()); - for (int c = 0; c < options.getConfs().length; c++) { - final String[] depConfs = options.getConfs(); - - for (int j = 0; j < depConfs.length; j++) { - final String depConf = depConfs[j].trim(); - - if (MatcherHelper.isExact(matcher, mrid)) { - DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, mrid, - false, false, options.isTransitive()); + for (String dc : options.getConfs()) { + final String depConf = dc.trim(); + + if (MatcherHelper.isExact(matcher, mrid)) { + DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, mrid, + false, false, options.isTransitive()); + dd.addDependencyConfiguration("default", depConf); + md.addDependency(dd); + } else { + ModuleRevisionId[] mrids = searchEngine.listModules(fromResolver, mrid, matcher); + + for (ModuleRevisionId imrid : mrids) { + Message.info("\tfound " + imrid + " to install: adding to the list"); + DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, + imrid, false, false, options.isTransitive()); dd.addDependencyConfiguration("default", depConf); md.addDependency(dd); - } else { - ModuleRevisionId[] mrids = searchEngine.listModules(fromResolver, mrid, - matcher); - - for (int i = 0; i < mrids.length; i++) { - Message.info("\tfound " + mrids[i] + " to install: adding to the list"); - DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, - mrids[i], false, false, options.isTransitive()); - dd.addDependencyConfiguration("default", depConf); - md.addDependency(dd); - } } } } @@ -134,8 +129,8 @@ public ResolveReport install(ModuleRevisionId mrid, String from, String to, // now that everything is in cache, we can publish all these modules Message.info(":: installing in " + to + " ::"); - for (int i = 0; i < dependencies.length; i++) { - ModuleDescriptor depmd = dependencies[i].getDescriptor(); + for (IvyNode dependency : dependencies) { + ModuleDescriptor depmd = dependency.getDescriptor(); if (depmd != null) { ModuleRevisionId depMrid = depmd.getModuleRevisionId(); Message.verbose("installing " + depMrid); @@ -145,15 +140,15 @@ public ResolveReport install(ModuleRevisionId mrid, String from, String to, // publish artifacts ArtifactDownloadReport[] artifacts = report.getArtifactsReports(depMrid); - for (int j = 0; j < artifacts.length; j++) { - if (artifacts[j].getLocalFile() != null) { - toResolver.publish(artifacts[j].getArtifact(), - artifacts[j].getLocalFile(), options.isOverwrite()); + for (ArtifactDownloadReport artifact : artifacts) { + if (artifact.getLocalFile() != null) { + toResolver.publish(artifact.getArtifact(), artifact.getLocalFile(), + options.isOverwrite()); } } // publish metadata - MetadataArtifactDownloadReport artifactDownloadReport = dependencies[i] + MetadataArtifactDownloadReport artifactDownloadReport = dependency .getModuleRevision().getReport(); File localIvyFile = artifactDownloadReport.getLocalFile(); toResolver.publish(depmd.getMetadataArtifact(), localIvyFile, diff --git a/src/java/org/apache/ivy/core/install/InstallEngineSettings.java b/src/java/org/apache/ivy/core/install/InstallEngineSettings.java index 9f3426b38..0aa56dd54 100644 --- a/src/java/org/apache/ivy/core/install/InstallEngineSettings.java +++ b/src/java/org/apache/ivy/core/install/InstallEngineSettings.java @@ -29,7 +29,7 @@ public interface InstallEngineSettings extends ParserSettings { DependencyResolver getResolver(String from); - Collection getResolverNames(); + Collection getResolverNames(); ReportOutputter[] getReportOutputters(); @@ -41,6 +41,6 @@ public interface InstallEngineSettings extends ParserSettings { PatternMatcher getMatcher(String matcherName); - Collection getMatcherNames(); + Collection getMatcherNames(); } diff --git a/src/java/org/apache/ivy/core/install/InstallOptions.java b/src/java/org/apache/ivy/core/install/InstallOptions.java index 5bb4182e2..ee6beeb12 100644 --- a/src/java/org/apache/ivy/core/install/InstallOptions.java +++ b/src/java/org/apache/ivy/core/install/InstallOptions.java @@ -17,6 +17,7 @@ */ package org.apache.ivy.core.install; +import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.plugins.matcher.PatternMatcher; import org.apache.ivy.util.filter.Filter; import org.apache.ivy.util.filter.FilterHelper; @@ -32,7 +33,7 @@ public class InstallOptions { private String[] confs = {"*"}; - private Filter artifactFilter = FilterHelper.NO_FILTER; + private Filter artifactFilter = FilterHelper.NO_FILTER; private String matcherName = PatternMatcher.EXACT; @@ -63,12 +64,12 @@ public InstallOptions setOverwrite(boolean overwrite) { return this; } - public Filter getArtifactFilter() { + public Filter getArtifactFilter() { return artifactFilter; } - public InstallOptions setArtifactFilter(Filter artifactFilter) { - this.artifactFilter = artifactFilter == null ? FilterHelper.NO_FILTER : artifactFilter; + public InstallOptions setArtifactFilter(Filter artifactFilter) { + this.artifactFilter = (artifactFilter == null) ? FilterHelper.NO_FILTER : artifactFilter; return this; } diff --git a/src/java/org/apache/ivy/core/module/descriptor/AbstractArtifact.java b/src/java/org/apache/ivy/core/module/descriptor/AbstractArtifact.java index 95b175c5f..74bb54fb6 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/AbstractArtifact.java +++ b/src/java/org/apache/ivy/core/module/descriptor/AbstractArtifact.java @@ -62,7 +62,7 @@ public String getAttribute(String attName) { return getId().getAttribute(attName); } - public Map getAttributes() { + public Map getAttributes() { return getId().getAttributes(); } @@ -70,11 +70,11 @@ public String getExtraAttribute(String attName) { return getId().getExtraAttribute(attName); } - public Map getExtraAttributes() { + public Map getExtraAttributes() { return getId().getExtraAttributes(); } - public Map getQualifiedExtraAttributes() { + public Map getQualifiedExtraAttributes() { return getId().getQualifiedExtraAttributes(); } diff --git a/src/java/org/apache/ivy/core/module/descriptor/AbstractIncludeExcludeRule.java b/src/java/org/apache/ivy/core/module/descriptor/AbstractIncludeExcludeRule.java index 6c29ad20a..bdea406b1 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/AbstractIncludeExcludeRule.java +++ b/src/java/org/apache/ivy/core/module/descriptor/AbstractIncludeExcludeRule.java @@ -35,11 +35,12 @@ public abstract class AbstractIncludeExcludeRule extends UnmodifiableExtendableI private ArtifactId id; - private Collection confs = new ArrayList(); + private final Collection confs = new ArrayList<>(); private PatternMatcher patternMatcher; - public AbstractIncludeExcludeRule(ArtifactId aid, PatternMatcher matcher, Map extraAttributes) { + public AbstractIncludeExcludeRule(ArtifactId aid, PatternMatcher matcher, + Map extraAttributes) { super(null, extraAttributes); id = aid; patternMatcher = matcher; @@ -81,7 +82,7 @@ public ArtifactId getId() { } public String[] getConfigurations() { - return (String[]) confs.toArray(new String[confs.size()]); + return confs.toArray(new String[confs.size()]); } public PatternMatcher getMatcher() { diff --git a/src/java/org/apache/ivy/core/module/descriptor/Configuration.java b/src/java/org/apache/ivy/core/module/descriptor/Configuration.java index cb808dc2c..56d96c48b 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/Configuration.java +++ b/src/java/org/apache/ivy/core/module/descriptor/Configuration.java @@ -60,11 +60,11 @@ public String toString() { public static Collection findConfigurationExtending(String conf, Configuration[] confs) { - Collection extendingConfs = new ArrayList(); - for (int i = 0; i < confs.length; i++) { - if (confs[i] != null && Arrays.asList(confs[i].getExtends()).contains(conf)) { - extendingConfs.add(confs[i]); - extendingConfs.addAll(findConfigurationExtending(confs[i].getName(), confs)); + Collection extendingConfs = new ArrayList<>(); + for (Configuration cf : confs) { + if (cf != null && Arrays.asList(cf.getExtends()).contains(conf)) { + extendingConfs.add(cf); + extendingConfs.addAll(findConfigurationExtending(cf.getName(), confs)); } } return extendingConfs; @@ -219,16 +219,16 @@ public void replaceWildcards(ModuleDescriptor md) { Configuration[] configs = md.getConfigurations(); - Set newExtends = new LinkedHashSet(); - for (int j = 0; j < extendsFrom.length; j++) { - if ("*".equals(extendsFrom[j])) { + Set newExtends = new LinkedHashSet<>(); + for (String extend : extendsFrom) { + if ("*".equals(extend)) { addOther(configs, null, newExtends); - } else if ("*(public)".equals(extendsFrom[j])) { + } else if ("*(public)".equals(extend)) { addOther(configs, Visibility.PUBLIC, newExtends); - } else if ("*(private)".equals(extendsFrom[j])) { + } else if ("*(private)".equals(extend)) { addOther(configs, Visibility.PRIVATE, newExtends); } else { - newExtends.add(extendsFrom[j]); + newExtends.add(extend); } } @@ -236,10 +236,10 @@ public void replaceWildcards(ModuleDescriptor md) { } private void addOther(Configuration[] allConfigs, Visibility visibility, Set configs) { - for (int i = 0; i < allConfigs.length; i++) { - String currentName = allConfigs[i].getName(); + for (Configuration allConfig : allConfigs) { + String currentName = allConfig.getName(); if (!name.equals(currentName) - && ((visibility == null) || visibility.equals(allConfigs[i].getVisibility()))) { + && (visibility == null || visibility.equals(allConfig.getVisibility()))) { configs.add(currentName); } } diff --git a/src/java/org/apache/ivy/core/module/descriptor/ConfigurationGroup.java b/src/java/org/apache/ivy/core/module/descriptor/ConfigurationGroup.java index 5f827a720..80182dab9 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/ConfigurationGroup.java +++ b/src/java/org/apache/ivy/core/module/descriptor/ConfigurationGroup.java @@ -17,7 +17,6 @@ */ package org.apache.ivy.core.module.descriptor; -import java.util.Iterator; import java.util.Map; /** @@ -25,9 +24,9 @@ */ public class ConfigurationGroup extends Configuration { - private final Map/* */members; + private final Map members; - public ConfigurationGroup(String confName, Map /* */members) { + public ConfigurationGroup(String confName, Map members) { super(confName); this.members = members; } @@ -43,7 +42,7 @@ public ConfigurationGroup(String confName, Map /* */memb * @return the list of configurations' names this object is an intersection of. */ public String[] getMembersConfigurationNames() { - return (String[]) members.keySet().toArray(new String[members.size()]); + return members.keySet().toArray(new String[members.size()]); } /** @@ -56,12 +55,11 @@ public String[] getMembersConfigurationNames() { * @return the member {@link Configuration} object for the given conf name */ public Configuration getMemberConfiguration(String confName) { - return (Configuration) members.get(confName); + return members.get(confName); } public Visibility getVisibility() { - for (Iterator it = members.values().iterator(); it.hasNext();) { - Configuration c = (Configuration) it.next(); + for (Configuration c : members.values()) { if (c != null && Visibility.PRIVATE.equals(c.getVisibility())) { return Visibility.PRIVATE; } diff --git a/src/java/org/apache/ivy/core/module/descriptor/ConfigurationIntersection.java b/src/java/org/apache/ivy/core/module/descriptor/ConfigurationIntersection.java index 36f2bc341..406fd0799 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/ConfigurationIntersection.java +++ b/src/java/org/apache/ivy/core/module/descriptor/ConfigurationIntersection.java @@ -17,7 +17,6 @@ */ package org.apache.ivy.core.module.descriptor; -import java.util.Iterator; import java.util.Map; /** @@ -25,10 +24,10 @@ */ public class ConfigurationIntersection extends Configuration { - private final Map/* */intersectedConfs; + private final Map intersectedConfs; public ConfigurationIntersection(String confName, - Map /* */intersectedConfs) { + Map intersectedConfs) { super(confName); this.intersectedConfs = intersectedConfs; } @@ -44,7 +43,7 @@ public ConfigurationIntersection(String confName, * @return the list of configurations' names this object is an intersection of. */ public String[] getIntersectedConfigurationNames() { - return (String[]) intersectedConfs.keySet().toArray(new String[intersectedConfs.size()]); + return intersectedConfs.keySet().toArray(new String[intersectedConfs.size()]); } /** @@ -57,12 +56,11 @@ public String[] getIntersectedConfigurationNames() { * @return the intersected {@link Configuration} object for the given conf name */ public Configuration getIntersectedConfiguration(String confName) { - return (Configuration) intersectedConfs.get(confName); + return intersectedConfs.get(confName); } public Visibility getVisibility() { - for (Iterator it = intersectedConfs.values().iterator(); it.hasNext();) { - Configuration c = (Configuration) it.next(); + for (Configuration c : intersectedConfs.values()) { if (c != null && Visibility.PRIVATE.equals(c.getVisibility())) { return Visibility.PRIVATE; } diff --git a/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java b/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java index 3ea103df9..05880b27a 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java +++ b/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java @@ -84,12 +84,12 @@ public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, - String ext, Map extraAttributes) { + String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, - String ext, URL url, Map extraAttributes) { + String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } diff --git a/src/java/org/apache/ivy/core/module/descriptor/DefaultDependencyArtifactDescriptor.java b/src/java/org/apache/ivy/core/module/descriptor/DefaultDependencyArtifactDescriptor.java index 4785a3ff2..c7d5537b7 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/DefaultDependencyArtifactDescriptor.java +++ b/src/java/org/apache/ivy/core/module/descriptor/DefaultDependencyArtifactDescriptor.java @@ -29,7 +29,7 @@ public class DefaultDependencyArtifactDescriptor extends UnmodifiableExtendableItem implements DependencyArtifactDescriptor, ConfigurationAware { - private Collection confs = new ArrayList(); + private final Collection confs = new ArrayList<>(); private URL url; @@ -50,7 +50,7 @@ public class DefaultDependencyArtifactDescriptor extends UnmodifiableExtendableI * @param extraAttributes ditto */ public DefaultDependencyArtifactDescriptor(DependencyDescriptor dd, String name, String type, - String ext, URL url, Map extraAttributes) { + String ext, URL url, Map extraAttributes) { super(null, extraAttributes); Checks.checkNotNull(dd, "dd"); Checks.checkNotNull(name, "name"); @@ -109,7 +109,7 @@ public String getExt() { } public String[] getConfigurations() { - return (String[]) confs.toArray(new String[confs.size()]); + return confs.toArray(new String[confs.size()]); } public URL getUrl() { diff --git a/src/java/org/apache/ivy/core/module/descriptor/DefaultDependencyDescriptor.java b/src/java/org/apache/ivy/core/module/descriptor/DefaultDependencyDescriptor.java index a3e86e795..30677ebb3 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/DefaultDependencyDescriptor.java +++ b/src/java/org/apache/ivy/core/module/descriptor/DefaultDependencyDescriptor.java @@ -22,7 +22,6 @@ import java.util.Collection; import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -101,25 +100,25 @@ public static DefaultDependencyDescriptor transformInstance(DependencyDescriptor if (moduleConfs.length == 1 && "*".equals(moduleConfs[0])) { if (dd instanceof DefaultDependencyDescriptor) { DefaultDependencyDescriptor ddd = (DefaultDependencyDescriptor) dd; - newdd.confs = new LinkedHashMap(ddd.confs); - newdd.setExcludeRules(new LinkedHashMap(ddd.getExcludeRules())); - newdd.setIncludeRules(new LinkedHashMap(ddd.getIncludeRules())); - newdd.setDependencyArtifacts(new LinkedHashMap(ddd.getDependencyArtifacts())); + newdd.confs = new LinkedHashMap<>(ddd.confs); + newdd.setExcludeRules(new LinkedHashMap<>(ddd.getExcludeRules())); + newdd.setIncludeRules(new LinkedHashMap<>(ddd.getIncludeRules())); + newdd.setDependencyArtifacts(new LinkedHashMap<>(ddd.getDependencyArtifacts())); } else { throw new IllegalArgumentException( "dependency descriptor transformation does not support * module confs " + "with descriptors which aren't DefaultDependencyDescriptor"); } } else { - for (int i = 0; i < moduleConfs.length; i++) { - newdd.confs.put(moduleConfs[i], - new ArrayList(Arrays.asList(dd.getDependencyConfigurations(moduleConfs[i])))); - newdd.getExcludeRules().put(moduleConfs[i], - new ArrayList(Arrays.asList(dd.getExcludeRules(moduleConfs[i])))); - newdd.getIncludeRules().put(moduleConfs[i], - new ArrayList(Arrays.asList(dd.getIncludeRules(moduleConfs[i])))); - newdd.getDependencyArtifacts().put(moduleConfs[i], - new ArrayList(Arrays.asList(dd.getDependencyArtifacts(moduleConfs[i])))); + for (String moduleConf : moduleConfs) { + newdd.confs.put(moduleConf, + new ArrayList<>(Arrays.asList(dd.getDependencyConfigurations(moduleConf)))); + newdd.getExcludeRules().put(moduleConf, + new ArrayList<>(Arrays.asList(dd.getExcludeRules(moduleConf)))); + newdd.getIncludeRules().put(moduleConf, + new ArrayList<>(Arrays.asList(dd.getIncludeRules(moduleConf)))); + newdd.getDependencyArtifacts().put(moduleConf, + new ArrayList<>(Arrays.asList(dd.getDependencyArtifacts(moduleConf)))); } } if (fromSystem) { @@ -132,16 +131,19 @@ public static DefaultDependencyDescriptor transformInstance(DependencyDescriptor private ModuleRevisionId dynamicRevId; - private Map/* > */confs = new LinkedHashMap(); + private Map> confs = new LinkedHashMap<>(); // Map (String masterConf -> Collection(DependencyArtifactDescriptor)) - private Map dependencyArtifacts; // initialized on demand only for memory consumption reason + // initialized on demand only for memory consumption reasons + private Map> dependencyArtifacts; // Map (String masterConf -> Collection(IncludeRule)) - private Map includeRules; // initialized on demand only for memory consumption reason + // initialized on demand only for memory consumption reasons + private Map> includeRules; // Map (String masterConf -> Collection(ExcludeRule)) - private Map excludeRules; // initialized on demand only for memory consumption reason + // initialized on demand only for memory consumption reasons + private Map> excludeRules; /** * Used to indicate that this revision must be used in case of conflicts, independently of @@ -189,10 +191,10 @@ private DefaultDependencyDescriptor(DefaultDependencyDescriptor dd, ModuleRevisi isTransitive = dd.isTransitive; namespace = dd.namespace; confs.putAll(dd.confs); - excludeRules = dd.excludeRules == null ? null : new LinkedHashMap(dd.excludeRules); - includeRules = dd.includeRules == null ? null : new LinkedHashMap(dd.includeRules); - dependencyArtifacts = dd.dependencyArtifacts == null ? null : new LinkedHashMap( - dd.dependencyArtifacts); + excludeRules = (dd.excludeRules == null) ? null : new LinkedHashMap<>(dd.excludeRules); + includeRules = (dd.includeRules == null) ? null : new LinkedHashMap<>(dd.includeRules); + dependencyArtifacts = (dd.dependencyArtifacts == null) ? null + : new LinkedHashMap<>(dd.dependencyArtifacts); sourceModule = dd.sourceModule; } @@ -236,7 +238,7 @@ public ModuleRevisionId getDynamicConstraintDependencyRevisionId() { } public String[] getModuleConfigurations() { - return (String[]) confs.keySet().toArray(new String[confs.keySet().size()]); + return confs.keySet().toArray(new String[confs.keySet().size()]); } public String[] getDependencyConfigurations(String moduleConfiguration) { @@ -265,11 +267,10 @@ public String[] getDependencyConfigurations(String moduleConfiguration, Configuration c = md.getConfiguration(moduleConfiguration); if (c instanceof ConfigurationIntersection) { ConfigurationIntersection intersection = (ConfigurationIntersection) c; - Set /* */intersectedDepConfs = new HashSet(); - String[] intersected = intersection.getIntersectedConfigurationNames(); - for (int i = 0; i < intersected.length; i++) { - Collection depConfs = getDependencyConfigurationsIncludingExtending( - intersected[i], requestedConfiguration); + Set intersectedDepConfs = new HashSet<>(); + for (String intersect : intersection.getIntersectedConfigurationNames()) { + Collection depConfs = getDependencyConfigurationsIncludingExtending( + intersect, requestedConfiguration); if (intersectedDepConfs.isEmpty()) { intersectedDepConfs.addAll(depConfs); } else { @@ -280,10 +281,9 @@ public String[] getDependencyConfigurations(String moduleConfiguration, // nothing to do, intersection of 'something' // with 'everything' is 'something' } else { - Set /* */intersectedDepConfsCopy = intersectedDepConfs; - intersectedDepConfs = new HashSet(); - for (Iterator it = intersectedDepConfsCopy.iterator(); it.hasNext();) { - String intersectedDepConf = (String) it.next(); + Set intersectedDepConfsCopy = intersectedDepConfs; + intersectedDepConfs = new HashSet<>(); + for (String intersectedDepConf : intersectedDepConfsCopy) { if (depConfs.contains(intersectedDepConf)) { // the conf is present in both sets, // so it is in the intersection @@ -295,36 +295,34 @@ public String[] getDependencyConfigurations(String moduleConfiguration, * confs yet: it would require supporting parenthesis grouping in * configurations intersection interpretation * - * for (Iterator it2 = depConfs.iterator(); it2.hasNext();) { - * String depConf = (String) it2.next(); - * if (depConf.startsWith("*")) { - * if (intersectedDepConf .indexOf("(" + depConf + ")") != -1) { - * intersectedDepConfs.add(intersectedDepConf); - * } else { - * intersectedDepConfs.add( "(" + intersectedDepConf + ")+(" + depConf + ")"); - * } - * } else if (intersectedDepConf.startsWith("*")) { - * if (depConf .indexOf("(" + intersectedDepConf + ")") != -1) { - * intersectedDepConfs.add(depConf); - * } else { - * intersectedDepConfs.add( depConf + "+" + intersectedDepConf); - * } - * } + * for (String depConf : depConfs) { + * if (depConf.startsWith("*")) { + * if (intersectedDepConf.contains("(" + depConf + ")")) { + * intersectedDepConfs.add(intersectedDepConf); + * } else { + * intersectedDepConfs.add("(" + intersectedDepConf + ")+(" + depConf + ")"); + * } + * } else if (intersectedDepConf.startsWith("*")) { + * if (depConf.contains("(" + intersectedDepConf + ")")) { + * intersectedDepConfs.add(depConf); + * } else { + * intersectedDepConfs.add(depConf + "+" + intersectedDepConf); + * } + * } * } */ } } } } - List confsList = (List) confs.get(moduleConfiguration); + List confsList = confs.get(moduleConfiguration); if (confsList != null) { intersectedDepConfs.addAll(confsList); } if (intersectedDepConfs.isEmpty()) { - List defConfs = (List) confs.get("*"); + List defConfs = confs.get("*"); if (defConfs != null) { - for (Iterator it = defConfs.iterator(); it.hasNext();) { - String mappedConf = (String) it.next(); + for (String mappedConf : defConfs) { if (mappedConf != null && mappedConf.startsWith("@+")) { return new String[] {moduleConfiguration + mappedConf.substring(1)}; } else if (mappedConf != null && mappedConf.equals("@")) { @@ -333,28 +331,26 @@ public String[] getDependencyConfigurations(String moduleConfiguration, } } } - return (String[]) intersectedDepConfs - .toArray(new String[intersectedDepConfs.size()]); + return intersectedDepConfs.toArray(new String[intersectedDepConfs.size()]); } else if (c instanceof ConfigurationGroup) { ConfigurationGroup group = (ConfigurationGroup) c; - Set /* */groupDepConfs = new HashSet(); - String[] members = group.getMembersConfigurationNames(); - for (int i = 0; i < members.length; i++) { - Collection depConfs = getDependencyConfigurationsIncludingExtending(members[i], - requestedConfiguration); + Set groupDepConfs = new HashSet<>(); + for (String member : group.getMembersConfigurationNames()) { + Collection depConfs = getDependencyConfigurationsIncludingExtending( + member, requestedConfiguration); groupDepConfs.addAll(depConfs); } - return (String[]) groupDepConfs.toArray(new String[groupDepConfs.size()]); + return groupDepConfs.toArray(new String[groupDepConfs.size()]); } } - List confsList = (List) confs.get(moduleConfiguration); + List confsList = confs.get(moduleConfiguration); if (confsList == null) { // there is no mapping defined for this configuration, add the 'other' mappings. - confsList = (List) confs.get("%"); + confsList = confs.get("%"); } - List defConfs = (List) confs.get("*"); - Collection ret = new LinkedHashSet(); + List defConfs = confs.get("*"); + Collection ret = new LinkedHashSet<>(); if (confsList != null) { ret.addAll(confsList); } @@ -362,9 +358,8 @@ public String[] getDependencyConfigurations(String moduleConfiguration, ret.addAll(defConfs); } - Collection replacedRet = new LinkedHashSet(); - for (Iterator iter = ret.iterator(); iter.hasNext();) { - String c = (String) iter.next(); + Collection replacedRet = new LinkedHashSet<>(); + for (String c : ret) { String replacedConf = replaceSelfFallbackPattern(c, moduleConfiguration); if (replacedConf == null) { replacedConf = replaceThisFallbackPattern(c, requestedConfiguration); @@ -376,31 +371,29 @@ public String[] getDependencyConfigurations(String moduleConfiguration, } ret = replacedRet; if (ret.remove("*")) { - StringBuffer r = new StringBuffer("*"); + StringBuilder r = new StringBuilder("*"); // merge excluded configurations as one conf like *!A!B - for (Iterator iter = ret.iterator(); iter.hasNext();) { - String c = (String) iter.next(); + for (String c : ret) { if (c.startsWith("!")) { r.append(c); } } return new String[] {r.toString()}; } - return (String[]) ret.toArray(new String[ret.size()]); + return ret.toArray(new String[ret.size()]); } - private Collection getDependencyConfigurationsIncludingExtending(String conf, + private Collection getDependencyConfigurationsIncludingExtending(String conf, String requestedConfiguration) { - Set/* */allDepConfs = new LinkedHashSet(); + Set allDepConfs = new LinkedHashSet<>(); allDepConfs .addAll(Arrays.asList(getDependencyConfigurations(conf, requestedConfiguration))); - Collection extendingConfs = Configuration.findConfigurationExtending(conf, + Collection extendingConfs = Configuration.findConfigurationExtending(conf, md.getConfigurations()); - for (Iterator it = extendingConfs.iterator(); it.hasNext();) { - Configuration extendingConf = (Configuration) it.next(); - allDepConfs.addAll(Arrays.asList(getDependencyConfigurations(extendingConf.getName(), - requestedConfiguration))); + for (Configuration extendingConf : extendingConfs) { + allDepConfs.addAll(Arrays.asList( + getDependencyConfigurations(extendingConf.getName(), requestedConfiguration))); } return allDepConfs; } @@ -433,10 +426,10 @@ protected static String replaceFallbackConfigurationPattern(final Pattern patter if (matcher.matches()) { String mappedConf = moduleConfiguration; if (matcher.group(1) != null) { - mappedConf = mappedConf + matcher.group(1); + mappedConf += matcher.group(1); } if (matcher.group(2) != null) { - mappedConf = mappedConf + matcher.group(2); + mappedConf += matcher.group(2); } return mappedConf; } @@ -444,40 +437,42 @@ protected static String replaceFallbackConfigurationPattern(final Pattern patter } public String[] getDependencyConfigurations(String[] moduleConfigurations) { - Set confs = new LinkedHashSet(); - for (int i = 0; i < moduleConfigurations.length; i++) { - confs.addAll(Arrays.asList(getDependencyConfigurations(moduleConfigurations[i]))); + Set confs = new LinkedHashSet<>(); + for (String moduleConfiguration : moduleConfigurations) { + confs.addAll(Arrays.asList(getDependencyConfigurations(moduleConfiguration))); } if (confs.contains("*")) { return new String[] {"*"}; } - return (String[]) confs.toArray(new String[confs.size()]); + return confs.toArray(new String[confs.size()]); } public DependencyArtifactDescriptor[] getDependencyArtifacts(String moduleConfiguration) { - Collection artifacts = getCollectionForConfiguration(moduleConfiguration, - dependencyArtifacts); - return (DependencyArtifactDescriptor[]) artifacts - .toArray(new DependencyArtifactDescriptor[artifacts.size()]); + Collection artifacts = getCollectionForConfiguration( + moduleConfiguration, dependencyArtifacts); + return artifacts.toArray(new DependencyArtifactDescriptor[artifacts.size()]); } public IncludeRule[] getIncludeRules(String moduleConfiguration) { - Collection rules = getCollectionForConfiguration(moduleConfiguration, includeRules); - return (IncludeRule[]) rules.toArray(new IncludeRule[rules.size()]); + Collection rules = getCollectionForConfiguration(moduleConfiguration, + includeRules); + return rules.toArray(new IncludeRule[rules.size()]); } public ExcludeRule[] getExcludeRules(String moduleConfiguration) { - Collection rules = getCollectionForConfiguration(moduleConfiguration, excludeRules); - return (ExcludeRule[]) rules.toArray(new ExcludeRule[rules.size()]); + Collection rules = getCollectionForConfiguration(moduleConfiguration, + excludeRules); + return rules.toArray(new ExcludeRule[rules.size()]); } - private Set getCollectionForConfiguration(String moduleConfiguration, Map collectionMap) { + private Set getCollectionForConfiguration(String moduleConfiguration, + Map> collectionMap) { if (collectionMap == null || collectionMap.isEmpty()) { return Collections.emptySet(); } - Collection artifacts = (Collection) collectionMap.get(moduleConfiguration); - Collection defArtifacts = (Collection) collectionMap.get("*"); - Set ret = new LinkedHashSet(); + Collection artifacts = collectionMap.get(moduleConfiguration); + Collection defArtifacts = collectionMap.get("*"); + Set ret = new LinkedHashSet<>(); if (artifacts != null) { ret.addAll(artifacts); } @@ -488,59 +483,56 @@ private Set getCollectionForConfiguration(String moduleConfiguration, Map collec } public DependencyArtifactDescriptor[] getDependencyArtifacts(String[] moduleConfigurations) { - Set artifacts = new LinkedHashSet(); - for (int i = 0; i < moduleConfigurations.length; i++) { - artifacts.addAll(Arrays.asList(getDependencyArtifacts(moduleConfigurations[i]))); + Set artifacts = new LinkedHashSet<>(); + for (String moduleConfiguration : moduleConfigurations) { + artifacts.addAll(Arrays.asList(getDependencyArtifacts(moduleConfiguration))); } - return (DependencyArtifactDescriptor[]) artifacts - .toArray(new DependencyArtifactDescriptor[artifacts.size()]); + return artifacts.toArray(new DependencyArtifactDescriptor[artifacts.size()]); } public IncludeRule[] getIncludeRules(String[] moduleConfigurations) { - Set rules = new LinkedHashSet(); - for (int i = 0; i < moduleConfigurations.length; i++) { - rules.addAll(Arrays.asList(getIncludeRules(moduleConfigurations[i]))); + Set rules = new LinkedHashSet<>(); + for (String moduleConfiguration : moduleConfigurations) { + rules.addAll(Arrays.asList(getIncludeRules(moduleConfiguration))); } - return (IncludeRule[]) rules.toArray(new IncludeRule[rules.size()]); + return rules.toArray(new IncludeRule[rules.size()]); } public ExcludeRule[] getExcludeRules(String[] moduleConfigurations) { - Set rules = new LinkedHashSet(); - for (int i = 0; i < moduleConfigurations.length; i++) { - rules.addAll(Arrays.asList(getExcludeRules(moduleConfigurations[i]))); + Set rules = new LinkedHashSet<>(); + for (String moduleConfiguration : moduleConfigurations) { + rules.addAll(Arrays.asList(getExcludeRules(moduleConfiguration))); } - return (ExcludeRule[]) rules.toArray(new ExcludeRule[rules.size()]); + return rules.toArray(new ExcludeRule[rules.size()]); } public DependencyArtifactDescriptor[] getAllDependencyArtifacts() { if (dependencyArtifacts == null) { return new DependencyArtifactDescriptor[0]; } - Set ret = mergeAll(dependencyArtifacts); - return (DependencyArtifactDescriptor[]) ret.toArray(new DependencyArtifactDescriptor[ret - .size()]); + Set ret = mergeAll(dependencyArtifacts); + return ret.toArray(new DependencyArtifactDescriptor[ret.size()]); } public IncludeRule[] getAllIncludeRules() { if (includeRules == null) { return new IncludeRule[0]; } - Set ret = mergeAll(includeRules); - return (IncludeRule[]) ret.toArray(new IncludeRule[ret.size()]); + Set ret = mergeAll(includeRules); + return ret.toArray(new IncludeRule[ret.size()]); } public ExcludeRule[] getAllExcludeRules() { if (excludeRules == null) { return new ExcludeRule[0]; } - Set ret = mergeAll(excludeRules); - return (ExcludeRule[]) ret.toArray(new ExcludeRule[ret.size()]); + Set ret = mergeAll(excludeRules); + return ret.toArray(new ExcludeRule[ret.size()]); } - private Set mergeAll(Map artifactsMap) { - Set ret = new LinkedHashSet(); - for (Iterator it = artifactsMap.values().iterator(); it.hasNext();) { - Collection artifacts = (Collection) it.next(); + private Set mergeAll(Map> artifactsMap) { + Set ret = new LinkedHashSet<>(); + for (Collection artifacts : artifactsMap.values()) { ret.addAll(artifacts); } return ret; @@ -561,17 +553,16 @@ public void addDependencyConfiguration(String masterConf, String depConf) { } if (config instanceof ConfigurationGroup) { ConfigurationGroup group = (ConfigurationGroup) config; - String[] members = group.getMembersConfigurationNames(); - for (int i = 0; i < members.length; i++) { - addDependencyConfiguration(members[i], depConf); + for (String member : group.getMembersConfigurationNames()) { + addDependencyConfiguration(member, depConf); } return; } } - List confsList = (List) confs.get(masterConf); + List confsList = confs.get(masterConf); if (confsList == null) { - confsList = new ArrayList(); + confsList = new ArrayList<>(); confs.put(masterConf, confsList); } if (!confsList.contains(depConf)) { @@ -591,10 +582,11 @@ public void addExcludeRule(String masterConf, ExcludeRule rule) { addObjectToConfiguration(masterConf, rule, getExcludeRules()); } - private void addObjectToConfiguration(String callerConf, Object toAdd, Map confsMap) { - Collection col = (Collection) confsMap.get(callerConf); + private void addObjectToConfiguration(String callerConf, T toAdd, + Map> confsMap) { + Collection col = confsMap.get(callerConf); if (col == null) { - col = new ArrayList(); + col = new ArrayList<>(); confsMap.put(callerConf, col); } col.add(toAdd); @@ -613,9 +605,8 @@ public boolean doesExclude(String[] moduleConfigurations, ArtifactId artifactId) artifactId = NameSpaceHelper .transform(artifactId, namespace.getFromSystemTransformer()); } - ExcludeRule[] rules = getExcludeRules(moduleConfigurations); - for (int i = 0; i < rules.length; i++) { - if (MatcherHelper.matches(rules[i].getMatcher(), rules[i].getId(), artifactId)) { + for (ExcludeRule rule : getExcludeRules(moduleConfigurations)) { + if (MatcherHelper.matches(rule.getMatcher(), rule.getId(), artifactId)) { return true; } } @@ -657,7 +648,7 @@ public String getAttribute(String attName) { return revId.getAttribute(attName); } - public Map getAttributes() { + public Map getAttributes() { return revId.getAttributes(); } @@ -665,11 +656,11 @@ public String getExtraAttribute(String attName) { return revId.getExtraAttribute(attName); } - public Map getExtraAttributes() { + public Map getExtraAttributes() { return revId.getExtraAttributes(); } - public Map getQualifiedExtraAttributes() { + public Map getQualifiedExtraAttributes() { return revId.getQualifiedExtraAttributes(); } @@ -677,35 +668,36 @@ public DependencyDescriptor asSystem() { return asSystem; } - private void setDependencyArtifacts(Map dependencyArtifacts) { + private void setDependencyArtifacts( + Map> dependencyArtifacts) { this.dependencyArtifacts = dependencyArtifacts; } - private Map getDependencyArtifacts() { + private Map> getDependencyArtifacts() { if (dependencyArtifacts == null) { - dependencyArtifacts = new LinkedHashMap(); + dependencyArtifacts = new LinkedHashMap<>(); } return dependencyArtifacts; } - private void setIncludeRules(Map includeRules) { + private void setIncludeRules(Map> includeRules) { this.includeRules = includeRules; } - private Map getIncludeRules() { + private Map> getIncludeRules() { if (includeRules == null) { - includeRules = new LinkedHashMap(); + includeRules = new LinkedHashMap<>(); } return includeRules; } - private void setExcludeRules(Map excludeRules) { + private void setExcludeRules(Map> excludeRules) { this.excludeRules = excludeRules; } - private Map getExcludeRules() { + private Map> getExcludeRules() { if (excludeRules == null) { - excludeRules = new LinkedHashMap(); + excludeRules = new LinkedHashMap<>(); } return excludeRules; } diff --git a/src/java/org/apache/ivy/core/module/descriptor/DefaultExcludeRule.java b/src/java/org/apache/ivy/core/module/descriptor/DefaultExcludeRule.java index 52acf82f1..e99dd0ca5 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/DefaultExcludeRule.java +++ b/src/java/org/apache/ivy/core/module/descriptor/DefaultExcludeRule.java @@ -24,7 +24,7 @@ public class DefaultExcludeRule extends AbstractIncludeExcludeRule implements ExcludeRule { - public DefaultExcludeRule(ArtifactId aid, PatternMatcher matcher, Map extraAttributes) { + public DefaultExcludeRule(ArtifactId aid, PatternMatcher matcher, Map extraAttributes) { super(aid, matcher, extraAttributes); } diff --git a/src/java/org/apache/ivy/core/module/descriptor/DefaultExtendsDescriptor.java b/src/java/org/apache/ivy/core/module/descriptor/DefaultExtendsDescriptor.java index 1900a0571..33753a083 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/DefaultExtendsDescriptor.java +++ b/src/java/org/apache/ivy/core/module/descriptor/DefaultExtendsDescriptor.java @@ -29,7 +29,7 @@ public class DefaultExtendsDescriptor implements ExtendsDescriptor { private String location; - private List extendsTypes; + private final List extendsTypes; private boolean local; @@ -42,7 +42,7 @@ public DefaultExtendsDescriptor(ModuleDescriptor parent, String location, String this.parent = parent; this.location = location; this.local = local; - this.extendsTypes = new ArrayList(types.length); + this.extendsTypes = new ArrayList<>(types.length); extendsTypes.addAll(Arrays.asList(types)); } @@ -63,7 +63,7 @@ public String getLocation() { } public String[] getExtendsTypes() { - return (String[]) extendsTypes.toArray(new String[extendsTypes.size()]); + return extendsTypes.toArray(new String[extendsTypes.size()]); } public boolean isAllInherited() { diff --git a/src/java/org/apache/ivy/core/module/descriptor/DefaultIncludeRule.java b/src/java/org/apache/ivy/core/module/descriptor/DefaultIncludeRule.java index 87ddc5863..82828de6d 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/DefaultIncludeRule.java +++ b/src/java/org/apache/ivy/core/module/descriptor/DefaultIncludeRule.java @@ -24,7 +24,7 @@ public class DefaultIncludeRule extends AbstractIncludeExcludeRule implements IncludeRule { - public DefaultIncludeRule(ArtifactId aid, PatternMatcher matcher, Map extraAttributes) { + public DefaultIncludeRule(ArtifactId aid, PatternMatcher matcher, Map extraAttributes) { super(aid, matcher, extraAttributes); } diff --git a/src/java/org/apache/ivy/core/module/descriptor/DefaultModuleDescriptor.java b/src/java/org/apache/ivy/core/module/descriptor/DefaultModuleDescriptor.java index 85b9c7439..2d2b97b18 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/DefaultModuleDescriptor.java +++ b/src/java/org/apache/ivy/core/module/descriptor/DefaultModuleDescriptor.java @@ -67,30 +67,30 @@ public static DefaultModuleDescriptor newCallerInstance(ModuleRevisionId mrid, S DefaultModuleDescriptor moduleDescriptor = new DefaultModuleDescriptor( ModuleRevisionId.newInstance(mrid.getOrganisation(), mrid.getName() + "-caller", "working"), "integration", null, true); - for (int i = 0; i < confs.length; i++) { - moduleDescriptor.addConfiguration(new Configuration(confs[i])); + for (String conf : confs) { + moduleDescriptor.addConfiguration(new Configuration(conf)); } moduleDescriptor.setLastModified(System.currentTimeMillis()); DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(moduleDescriptor, mrid, true, changing, transitive); - for (int j = 0; j < confs.length; j++) { - dd.addDependencyConfiguration(confs[j], confs[j]); + for (String conf : confs) { + dd.addDependencyConfiguration(conf, conf); } moduleDescriptor.addDependency(dd); return moduleDescriptor; } - public static DefaultModuleDescriptor newCallerInstance(ModuleRevisionId[] mrid, + public static DefaultModuleDescriptor newCallerInstance(ModuleRevisionId[] mrids, boolean transitive, boolean changing) { DefaultModuleDescriptor moduleDescriptor = new DefaultModuleDescriptor( ModuleRevisionId.newInstance("caller", "all-caller", "working"), "integration", null, true); moduleDescriptor.addConfiguration(new Configuration(DEFAULT_CONFIGURATION)); moduleDescriptor.setLastModified(System.currentTimeMillis()); - for (int i = 0; i < mrid.length; i++) { + for (ModuleRevisionId mrid : mrids) { DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(moduleDescriptor, - mrid[i], true, changing, transitive); + mrid, true, changing, transitive); dd.addDependencyConfiguration(DEFAULT_CONFIGURATION, "*"); moduleDescriptor.addDependency(dd); } @@ -104,15 +104,14 @@ public static DefaultModuleDescriptor newDefaultInstance(ModuleRevisionId mrid, null, true); moduleDescriptor.addConfiguration(new Configuration(DEFAULT_CONFIGURATION)); if (artifacts != null && artifacts.length > 0) { - for (int i = 0; i < artifacts.length; i++) { + for (DependencyArtifactDescriptor artifact : artifacts) { moduleDescriptor.addArtifact(DEFAULT_CONFIGURATION, - new MDArtifact(moduleDescriptor, artifacts[i].getName(), - artifacts[i].getType(), artifacts[i].getExt(), artifacts[i].getUrl(), - artifacts[i].getExtraAttributes())); + new MDArtifact(moduleDescriptor, artifact.getName(), artifact.getType(), + artifact.getExt(), artifact.getUrl(), artifact.getExtraAttributes())); } } else { - moduleDescriptor.addArtifact(DEFAULT_CONFIGURATION, new MDArtifact(moduleDescriptor, - mrid.getName(), "jar", "jar")); + moduleDescriptor.addArtifact(DEFAULT_CONFIGURATION, + new MDArtifact(moduleDescriptor, mrid.getName(), "jar", "jar")); } moduleDescriptor.setLastModified(System.currentTimeMillis()); return moduleDescriptor; @@ -131,7 +130,7 @@ public static DefaultModuleDescriptor newBasicInstance(ModuleRevisionId mrid, /** * Transforms the given module descriptor of the given namespace and return a new module * descriptor in the system namespace. Note that dependency exclude rules are not converted - * in system namespace, because they aren't transformable (the name space hasn't the ability to + * in system namespace, because they aren't transformable (the namespace lacks the ability to * convert regular expressions) * * @param md ModuleDescriptor @@ -150,9 +149,8 @@ public static ModuleDescriptor transformInstance(ModuleDescriptor md, Namespace nmd.publicationDate = md.getPublicationDate(); nmd.resolvedPublicationDate = md.getResolvedPublicationDate(); - ExtendsDescriptor[] ed = md.getInheritedDescriptors(); - for (int i = 0; i < ed.length; ++i) { - ModuleDescriptor parentMd = ed[i].getParentMd(); + for (ExtendsDescriptor ed : md.getInheritedDescriptors()) { + ModuleDescriptor parentMd = ed.getParentMd(); DefaultModuleDescriptor parentNmd = new DefaultModuleDescriptor(parentMd.getParser(), parentMd.getResource()); parentNmd.revId = t.transform(parentMd.getModuleRevisionId()); @@ -161,28 +159,26 @@ public static ModuleDescriptor transformInstance(ModuleDescriptor md, Namespace parentNmd.publicationDate = parentMd.getPublicationDate(); parentNmd.resolvedPublicationDate = parentMd.getResolvedPublicationDate(); - nmd.inheritedDescriptors.add(new DefaultExtendsDescriptor(parentNmd, ed[i] - .getLocation(), ed[i].getExtendsTypes())); + nmd.inheritedDescriptors.add(new DefaultExtendsDescriptor(parentNmd, ed.getLocation(), + ed.getExtendsTypes())); } - DependencyDescriptor[] dd = md.getDependencies(); - for (int i = 0; i < dd.length; i++) { - nmd.dependencies.add(NameSpaceHelper.toSystem(dd[i], ns)); + for (DependencyDescriptor dd : md.getDependencies()) { + nmd.dependencies.add(NameSpaceHelper.toSystem(dd, ns)); } - Configuration[] confs = md.getConfigurations(); - for (int i = 0; i < confs.length; i++) { - nmd.configurations.put(confs[i].getName(), confs[i]); - Artifact[] arts = md.getArtifacts(confs[i].getName()); - for (int j = 0; j < arts.length; j++) { - nmd.addArtifact(confs[i].getName(), NameSpaceHelper.transform(arts[j], t)); + + for (Configuration conf : md.getConfigurations()) { + final String confName = conf.getName(); + nmd.configurations.put(confName, conf); + for (Artifact art : md.getArtifacts(confName)) { + nmd.addArtifact(confName, NameSpaceHelper.transform(art, t)); } } nmd.setDefault(md.isDefault()); if (md instanceof DefaultModuleDescriptor) { DefaultModuleDescriptor dmd = (DefaultModuleDescriptor) md; - nmd.conflictManagers = (ModuleRules) dmd.conflictManagers.clone(); - nmd.dependencyDescriptorMediators = (ModuleRules) dmd.dependencyDescriptorMediators - .clone(); + nmd.conflictManagers = dmd.conflictManagers.clone(); + nmd.dependencyDescriptorMediators = dmd.dependencyDescriptorMediators.clone(); } else { Message.warn("transformed module descriptor is not a default module descriptor: " + "impossible to copy conflict manager and version mediation configuration: " @@ -209,24 +205,24 @@ public static ModuleDescriptor transformInstance(ModuleDescriptor md, Namespace private Date resolvedPublicationDate; - private List dependencies = new ArrayList(); + private List dependencies = new ArrayList<>(); - private Map configurations = new LinkedHashMap(); + private Map configurations = new LinkedHashMap<>(); - private Map> artifactsByConf = new HashMap>(); + private Map> artifactsByConf = new HashMap<>(); - private Collection artifacts = new LinkedHashSet(); + private Collection artifacts = new LinkedHashSet<>(); // all artifacts could also be found in the artifactsByConf map, but here we can // preserve the order private boolean isDefault = false; - private ModuleRules conflictManagers = new ModuleRules(); + private ModuleRules conflictManagers = new ModuleRules<>(); - private ModuleRules dependencyDescriptorMediators = new ModuleRules(); + private ModuleRules dependencyDescriptorMediators = new ModuleRules<>(); - private List licenses = new ArrayList(); + private List licenses = new ArrayList<>(); private String homePage; @@ -246,15 +242,15 @@ public static ModuleDescriptor transformInstance(ModuleDescriptor md, Namespace private Resource resource; - private List excludeRules = new ArrayList(); + private List excludeRules = new ArrayList<>(); private Artifact metadataArtifact; - private List inheritedDescriptors = new ArrayList(); + private List inheritedDescriptors = new ArrayList<>(); - private Map extraAttributesNamespaces = new LinkedHashMap(); + private Map extraAttributesNamespaces = new LinkedHashMap<>(); - private List extraInfos = new ArrayList(); + private List extraInfos = new ArrayList<>(); public DefaultModuleDescriptor(ModuleRevisionId id, String status, Date pubDate) { this(id, status, pubDate, false); @@ -378,14 +374,13 @@ public void addArtifact(String conf, Artifact artifact) { } if (c instanceof ConfigurationGroup) { ConfigurationGroup group = (ConfigurationGroup) c; - String[] members = group.getMembersConfigurationNames(); - for (int i = 0; i < members.length; i++) { - addArtifact(members[i], artifact); + for (String member : group.getMembersConfigurationNames()) { + addArtifact(member, artifact); } } else { Collection artifacts = artifactsByConf.get(conf); if (artifacts == null) { - artifacts = new ArrayList(); + artifacts = new ArrayList<>(); artifactsByConf.put(conf, artifacts); } artifacts.add(artifact); @@ -418,7 +413,7 @@ public String[] getConfigurationsNames() { } public String[] getPublicConfigurationsNames() { - List ret = new ArrayList(); + List ret = new ArrayList<>(); for (Configuration conf : configurations.values()) { if (conf.getVisibility() == Configuration.Visibility.PUBLIC) { ret.add(conf.getName()); @@ -442,7 +437,7 @@ public Configuration getConfiguration(String confName) { String attValue = m.group(2); // this is a conf group, let's search for its members - Map members = new LinkedHashMap(); + Map members = new LinkedHashMap<>(); for (Configuration conf : configurations.values()) { if (attValue.equals(conf.getAttribute(attName))) { members.put(conf.getName(), conf); @@ -456,15 +451,15 @@ public Configuration getConfiguration(String confName) { if (confs.length <= 1) { return null; } - Map intersectedConfs = new LinkedHashMap(); - for (int i = 0; i < confs.length; i++) { - Configuration c = configurations.get(confs[i]); + Map intersectedConfs = new LinkedHashMap<>(); + for (String conf : confs) { + Configuration c = configurations.get(conf); if (c == null) { - Message.verbose("missing configuration '" + confs[i] + "' from intersection " + Message.verbose("missing configuration '" + conf + "' from intersection " + confName + " in " + this); return null; } - intersectedConfs.put(confs[i], c); + intersectedConfs.put(conf, c); } return new ConfigurationIntersection(confName, intersectedConfs); } @@ -479,10 +474,9 @@ public Artifact[] getArtifacts(String conf) { Collection artifacts = artifactsByConf.get(conf); if (c instanceof ConfigurationIntersection) { ConfigurationIntersection intersection = (ConfigurationIntersection) c; - String[] intersected = intersection.getIntersectedConfigurationNames(); - Set intersectedArtifacts = new LinkedHashSet(); - for (int j = 0; j < intersected.length; j++) { - Collection arts = getArtifactsIncludingExtending(intersected[j]); + Set intersectedArtifacts = new LinkedHashSet<>(); + for (String intersect : intersection.getIntersectedConfigurationNames()) { + Collection arts = getArtifactsIncludingExtending(intersect); if (intersectedArtifacts.isEmpty()) { intersectedArtifacts.addAll(arts); } else { @@ -495,10 +489,9 @@ public Artifact[] getArtifacts(String conf) { return intersectedArtifacts.toArray(new Artifact[intersectedArtifacts.size()]); } else if (c instanceof ConfigurationGroup) { ConfigurationGroup group = (ConfigurationGroup) c; - String[] members = group.getMembersConfigurationNames(); - Set groupArtifacts = new LinkedHashSet(); - for (int i = 0; i < members.length; i++) { - groupArtifacts.addAll(getArtifactsIncludingExtending(members[i])); + Set groupArtifacts = new LinkedHashSet<>(); + for (String member : group.getMembersConfigurationNames()) { + groupArtifacts.addAll(getArtifactsIncludingExtending(member)); } if (artifacts != null) { groupArtifacts.addAll(artifacts); @@ -516,7 +509,7 @@ public Artifact[] getArtifacts(String conf) { private Collection getArtifactsIncludingExtending(String conf) { Collection extendingConfs = Configuration.findConfigurationExtending(conf, getConfigurations()); - Set artifacts = new LinkedHashSet(); + Set artifacts = new LinkedHashSet<>(); Collection arts = artifactsByConf.get(conf); if (arts != null) { artifacts.addAll(arts); @@ -572,10 +565,7 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { + if (!(obj instanceof DefaultModuleDescriptor)) { return false; } DefaultModuleDescriptor other = (DefaultModuleDescriptor) obj; @@ -614,7 +604,7 @@ public void addConflictManager(ModuleId moduleId, PatternMatcher matcher, } public ConflictManager getConflictManager(ModuleId moduleId) { - return (ConflictManager) conflictManagers.getRule(moduleId); + return conflictManagers.getRule(moduleId); } public void addDependencyDescriptorMediator(ModuleId moduleId, PatternMatcher matcher, @@ -624,15 +614,14 @@ public void addDependencyDescriptorMediator(ModuleId moduleId, PatternMatcher ma } public DependencyDescriptor mediate(DependencyDescriptor dd) { - Object[] mediators = dependencyDescriptorMediators.getRules(dd.getDependencyId()); - for (int i = 0; i < mediators.length; i++) { - dd = ((DependencyDescriptorMediator) mediators[i]).mediate(dd); + for (DependencyDescriptorMediator mediator : dependencyDescriptorMediators.getRules(dd.getDependencyId())) { + dd = mediator.mediate(dd); } return dd; } - public ModuleRules getAllDependencyDescriptorMediators() { - return (ModuleRules) dependencyDescriptorMediators.clone(); + public ModuleRules getAllDependencyDescriptorMediators() { + return dependencyDescriptorMediators.clone(); } public void addLicense(License license) { @@ -689,12 +678,11 @@ public void setNamespace(Namespace ns) { * configurations existence and cycles are checked */ public void check() { - Stack confs = new Stack(); + Stack confs = new Stack<>(); for (Configuration conf : configurations.values()) { - String[] ext = conf.getExtends(); - for (int i = 0; i < ext.length; i++) { + for (String ext : conf.getExtends()) { confs.push(conf.getName()); - checkConf(confs, ext[i].trim()); + checkConf(confs, ext.trim()); confs.pop(); } } @@ -703,7 +691,7 @@ public void check() { private void checkConf(Stack confs, String confName) { int index = confs.indexOf(confName); if (index != -1) { - StringBuffer cycle = new StringBuffer(); + StringBuilder cycle = new StringBuilder(); for (; index < confs.size(); index++) { cycle.append(confs.get(index)).append(" => "); } @@ -716,10 +704,9 @@ private void checkConf(Stack confs, String confName) { throw new IllegalStateException("unknown configuration '" + confName + "'. It is extended by " + confs.get(confs.size() - 1)); } - String[] ext = conf.getExtends(); - for (int i = 0; i < ext.length; i++) { + for (String ext : conf.getExtends()) { confs.push(conf.getName()); - checkConf(confs, ext[i].trim()); + checkConf(confs, ext.trim()); confs.pop(); } } @@ -797,9 +784,8 @@ public boolean doesExclude(String[] moduleConfigurations, ArtifactId artifactId) artifactId = NameSpaceHelper .transform(artifactId, namespace.getFromSystemTransformer()); } - ExcludeRule[] rules = getExcludeRules(moduleConfigurations); - for (int i = 0; i < rules.length; i++) { - if (MatcherHelper.matches(rules[i].getMatcher(), rules[i].getId(), artifactId)) { + for (ExcludeRule rule : getExcludeRules(moduleConfigurations)) { + if (MatcherHelper.matches(rule.getMatcher(), rule.getId(), artifactId)) { return true; } } @@ -811,7 +797,7 @@ public ExcludeRule[] getAllExcludeRules() { } public ExcludeRule[] getExcludeRules(String[] moduleConfigurations) { - Set rules = new LinkedHashSet(); + Set rules = new LinkedHashSet<>(); for (ExcludeRule rule : excludeRules) { String[] ruleConfs = rule.getConfigurations(); if (containsAny(ruleConfs, moduleConfigurations)) { @@ -822,7 +808,7 @@ public ExcludeRule[] getExcludeRules(String[] moduleConfigurations) { } private boolean containsAny(String[] arr1, String[] arr2) { - return new ArrayList(Arrays.asList(arr1)).removeAll(Arrays.asList(arr2)); + return new ArrayList<>(Arrays.asList(arr1)).removeAll(Arrays.asList(arr2)); } public Map getExtraAttributesNamespaces() { @@ -840,7 +826,7 @@ public void addExtraInfo(String infoKey, String value) { @Deprecated public Map getExtraInfo() { - Map map = new HashMap(); + Map map = new HashMap<>(); for (ExtraInfoHolder extraInfo : extraInfos) { populateExtraInfoMap(map, extraInfo); } @@ -877,6 +863,5 @@ public ExtraInfoHolder getExtraInfoByTagName(String tagName) { } } return null; - } } diff --git a/src/java/org/apache/ivy/core/module/descriptor/ExtraInfoHolder.java b/src/java/org/apache/ivy/core/module/descriptor/ExtraInfoHolder.java index 142237860..7a7cfe471 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/ExtraInfoHolder.java +++ b/src/java/org/apache/ivy/core/module/descriptor/ExtraInfoHolder.java @@ -26,11 +26,11 @@ public class ExtraInfoHolder { private String name; - private Map attributes = new LinkedHashMap(); + private Map attributes = new LinkedHashMap<>(); private String content; - private List nestedExtraInfoHolder = new ArrayList(); + private List nestedExtraInfoHolder = new ArrayList<>(); public ExtraInfoHolder() { diff --git a/src/java/org/apache/ivy/core/module/descriptor/MDArtifact.java b/src/java/org/apache/ivy/core/module/descriptor/MDArtifact.java index 0efabbda8..ecd511ba4 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/MDArtifact.java +++ b/src/java/org/apache/ivy/core/module/descriptor/MDArtifact.java @@ -43,9 +43,9 @@ public static Artifact newIvyArtifact(ModuleDescriptor md) { private String ext; - private List/* */confs = new ArrayList(); + private final List confs = new ArrayList<>(); - private Map extraAttributes = null; + private Map extraAttributes = null; private URL url; @@ -61,7 +61,7 @@ public MDArtifact(ModuleDescriptor md, String name, String type, String ext, boo } public MDArtifact(ModuleDescriptor md, String name, String type, String ext, URL url, - Map extraAttributes) { + Map extraAttributes) { if (md == null) { throw new NullPointerException("null module descriptor not allowed"); } @@ -109,7 +109,7 @@ public String getExt() { } public String[] getConfigurations() { - return (String[]) confs.toArray(new String[confs.size()]); + return confs.toArray(new String[confs.size()]); } public void addConfiguration(String conf) { diff --git a/src/java/org/apache/ivy/core/module/descriptor/ModuleDescriptor.java b/src/java/org/apache/ivy/core/module/descriptor/ModuleDescriptor.java index 03694aa46..da92131bd 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/ModuleDescriptor.java +++ b/src/java/org/apache/ivy/core/module/descriptor/ModuleDescriptor.java @@ -212,7 +212,7 @@ public interface ModuleDescriptor extends ExtendableItem, ArtifactInfo, * @return all the {@link DependencyDescriptorMediator}s used by this * {@link ModuleDescriptor}, as an instance of {@link ModuleRules}. */ - public ModuleRules/* */getAllDependencyDescriptorMediators(); + public ModuleRules getAllDependencyDescriptorMediators(); /** * @return the list of xml namespaces used by extra attributes, as Map from prefix to namespace diff --git a/src/java/org/apache/ivy/core/module/id/ArtifactRevisionId.java b/src/java/org/apache/ivy/core/module/id/ArtifactRevisionId.java index 3c10cc4b5..c55b0f028 100644 --- a/src/java/org/apache/ivy/core/module/id/ArtifactRevisionId.java +++ b/src/java/org/apache/ivy/core/module/id/ArtifactRevisionId.java @@ -34,7 +34,7 @@ public static ArtifactRevisionId newInstance(ModuleRevisionId mrid, String name, } public static ArtifactRevisionId newInstance(ModuleRevisionId mrid, String name, String type, - String ext, Map extraAttributes) { + String ext, Map extraAttributes) { return new ArtifactRevisionId(new ArtifactId(mrid.getModuleId(), name, type, ext), mrid, extraAttributes); } @@ -47,7 +47,8 @@ public ArtifactRevisionId(ArtifactId artifactId, ModuleRevisionId mrid) { this(artifactId, mrid, null); } - public ArtifactRevisionId(ArtifactId artfId, ModuleRevisionId mdlRevId, Map extraAttributes) { + public ArtifactRevisionId(ArtifactId artfId, ModuleRevisionId mdlRevId, + Map extraAttributes) { super(null, extraAttributes); artifactId = artfId; mrid = mdlRevId; diff --git a/src/java/org/apache/ivy/core/module/id/MatcherLookup.java b/src/java/org/apache/ivy/core/module/id/MatcherLookup.java index 56c0ca719..5d223aed6 100644 --- a/src/java/org/apache/ivy/core/module/id/MatcherLookup.java +++ b/src/java/org/apache/ivy/core/module/id/MatcherLookup.java @@ -57,9 +57,9 @@ public class MatcherLookup { private static final String DEFAULT = "{org:" + "default" + ", module:" + "default" + "}"; - private Map> lookup = new HashMap>(); + private Map> lookup = new HashMap<>(); - private List non_exact_matchers = new ArrayList(); + private List nonExactMatchers = new ArrayList<>(); /** * Add matcher. @@ -73,16 +73,16 @@ public class MatcherLookup { */ public void add(MapMatcher matcher) { if (!(matcher.getPatternMatcher() instanceof ExactPatternMatcher)) { - non_exact_matchers.add(matcher); + nonExactMatchers.add(matcher); return; } String key = key(matcher.getAttributes()); - List exact_matchers = lookup.get(key); - if (exact_matchers == null) { - exact_matchers = new ArrayList(); - lookup.put(key, exact_matchers); + List exactMatchers = lookup.get(key); + if (exactMatchers == null) { + exactMatchers = new ArrayList<>(); + lookup.put(key, exactMatchers); } - exact_matchers.add(matcher); + exactMatchers.add(matcher); } /** @@ -92,30 +92,30 @@ public void add(MapMatcher matcher) { * @return a list of matchers that can apply to module withs specified attributes */ public List get(Map attrs) { - List matchers = new ArrayList(); - // Step 1: find matchers from non_exact_matchers list - if (!non_exact_matchers.isEmpty()) { - for (MapMatcher matcher : non_exact_matchers) { + List matchers = new ArrayList<>(); + // Step 1: find matchers from nonExactMatchers list + if (!nonExactMatchers.isEmpty()) { + for (MapMatcher matcher : nonExactMatchers) { if (matcher.matches(attrs)) { matchers.add(matcher); } } } - // Step 2: find matchers from exact_matchers list of key + // Step 2: find matchers from exactMatchers list of key String key = key(attrs); - List exact_matchers = lookup.get(key); - if (exact_matchers != null) { - for (MapMatcher matcher : exact_matchers) { + List exactMatchers = lookup.get(key); + if (exactMatchers != null) { + for (MapMatcher matcher : exactMatchers) { if (matcher.matches(attrs)) { matchers.add(matcher); } } } - // Step 3: (iff key != DEFAULT) find matchers from exact_matchers of DEFAULT + // Step 3: (iff key != DEFAULT) find matchers from exactMatchers of DEFAULT if (!DEFAULT.equals(key)) { - List default_exact_matchers = lookup.get(DEFAULT); - if (default_exact_matchers != null) { - for (MapMatcher matcher : default_exact_matchers) { + List defaultExactMatchers = lookup.get(DEFAULT); + if (defaultExactMatchers != null) { + for (MapMatcher matcher : defaultExactMatchers) { if (matcher.matches(attrs)) { matchers.add(matcher); } diff --git a/src/java/org/apache/ivy/core/module/id/ModuleId.java b/src/java/org/apache/ivy/core/module/id/ModuleId.java index b2866b6c5..1c605f13e 100644 --- a/src/java/org/apache/ivy/core/module/id/ModuleId.java +++ b/src/java/org/apache/ivy/core/module/id/ModuleId.java @@ -35,7 +35,7 @@ public class ModuleId implements Comparable { static final String ENCODE_SEPARATOR = ":#@#:"; - private static final Map> CACHE = new WeakHashMap>(); + private static final Map> CACHE = new WeakHashMap<>(); /** * Returns a ModuleId for the given organization and module name. @@ -72,7 +72,7 @@ public static ModuleId intern(ModuleId moduleId) { } if (r == null) { r = moduleId; - CACHE.put(r, new WeakReference(r)); + CACHE.put(r, new WeakReference<>(r)); } } @@ -85,7 +85,7 @@ public static ModuleId intern(ModuleId moduleId) { private int hash; - private Map attributes = new HashMap(); + private Map attributes = new HashMap<>(); /** * Constructor. @@ -129,11 +129,9 @@ public boolean equals(Object obj) { return false; } ModuleId other = (ModuleId) obj; - if (other.organisation == null) { - return organisation == null && other.name.equals(name); - } else { - return other.organisation.equals(organisation) && other.name.equals(name); - } + return (other.organisation == null) + ? organisation == null && other.name.equals(name) + : other.organisation.equals(organisation) && other.name.equals(name); } @Override diff --git a/src/java/org/apache/ivy/core/module/id/ModuleRevisionId.java b/src/java/org/apache/ivy/core/module/id/ModuleRevisionId.java index a31d50a0c..957915926 100644 --- a/src/java/org/apache/ivy/core/module/id/ModuleRevisionId.java +++ b/src/java/org/apache/ivy/core/module/id/ModuleRevisionId.java @@ -47,7 +47,7 @@ public class ModuleRevisionId extends UnmodifiableExtendableItem { private static final String REV_STRICT_CHARS_PATTERN = "[a-zA-Z0-9\\-/\\._+=,\\[\\]\\{\\}\\(\\):@]"; - private static final Map> CACHE = new WeakHashMap>(); + private static final Map> CACHE = new WeakHashMap<>(); /** * Pattern to use to matched mrid text representation. @@ -157,7 +157,7 @@ public static ModuleRevisionId intern(ModuleRevisionId moduleRevisionId) { } if (r == null) { r = moduleRevisionId; - CACHE.put(r, new WeakReference(r)); + CACHE.put(r, new WeakReference<>(r)); } } @@ -259,8 +259,8 @@ public String toString() { } public String encodeToString() { - StringBuffer buf = new StringBuffer(); - Map attributes = new HashMap(getAttributes()); + StringBuilder buf = new StringBuilder(); + Map attributes = new HashMap<>(getAttributes()); attributes.keySet().removeAll(getExtraAttributes().keySet()); attributes.putAll(getQualifiedExtraAttributes()); @@ -280,7 +280,7 @@ public static ModuleRevisionId decode(String encoded) { throw new IllegalArgumentException("badly encoded module revision id: '" + encoded + "'"); } - Map attributes = new HashMap(); + Map attributes = new HashMap<>(); for (int i = 0; i < parts.length; i += 2) { String attName = parts[i]; if (!attName.startsWith(ENCODE_PREFIX)) { diff --git a/src/java/org/apache/ivy/core/module/id/ModuleRules.java b/src/java/org/apache/ivy/core/module/id/ModuleRules.java index 128dff4a1..19b3d67d7 100644 --- a/src/java/org/apache/ivy/core/module/id/ModuleRules.java +++ b/src/java/org/apache/ivy/core/module/id/ModuleRules.java @@ -53,9 +53,9 @@ */ public class ModuleRules { - private Map rules = new LinkedHashMap(); + private Map rules = new LinkedHashMap<>(); - private MatcherLookup matcher_lookup = new MatcherLookup(); + private MatcherLookup matcherLookup = new MatcherLookup(); /** * Constructs an empty ModuleRules. @@ -64,9 +64,9 @@ public ModuleRules() { } private ModuleRules(Map rules) { - this.rules = new LinkedHashMap(rules); + this.rules = new LinkedHashMap<>(rules); for (MapMatcher matcher : rules.keySet()) { - matcher_lookup.add(matcher); + matcherLookup.add(matcher); } } @@ -83,7 +83,7 @@ public void defineRule(MapMatcher condition, T rule) { Checks.checkNotNull(rule, "rule"); rules.put(condition, rule); - matcher_lookup.add(condition); + matcherLookup.add(condition); } /** @@ -108,7 +108,7 @@ public T getRule(ModuleId mid) { * the {@link ModuleId} to search the rule for. Must not be null. * @return an array of rule objects matching the given {@link ModuleId}. */ - public T[] getRules(ModuleId mid) { + public List getRules(ModuleId mid) { return getRules(mid.getAttributes(), NoFilter. instance()); } @@ -172,7 +172,7 @@ public T getRule(ModuleRevisionId mrid, Filter filter) { } private T getRule(Map moduleAttributes, Filter filter) { - List matchers = matcher_lookup.get(moduleAttributes); + List matchers = matcherLookup.get(moduleAttributes); for (MapMatcher midm : matchers) { T rule = rules.get(midm); if (filter.accept(rule)) { @@ -195,23 +195,23 @@ private T getRule(Map moduleAttributes, Filter filter) { * {@link ModuleRevisionId}. Must not be null. * @return an array of rule objects matching the given {@link ModuleRevisionId}. */ - public T[] getRules(ModuleRevisionId mrid, Filter filter) { + public List getRules(ModuleRevisionId mrid, Filter filter) { Checks.checkNotNull(mrid, "mrid"); Checks.checkNotNull(filter, "filter"); Map moduleAttributes = mrid.getAttributes(); return getRules(moduleAttributes, filter); } - private T[] getRules(Map moduleAttributes, Filter filter) { - List matchers = matcher_lookup.get(moduleAttributes); - List matchingRules = new ArrayList(); + private List getRules(Map moduleAttributes, Filter filter) { + List matchers = matcherLookup.get(moduleAttributes); + List matchingRules = new ArrayList<>(); for (MapMatcher midm : matchers) { T rule = rules.get(midm); if (filter.accept(rule)) { matchingRules.add(rule); } } - return matchingRules.toArray((T[]) new Object[0]); + return matchingRules; } /** @@ -245,8 +245,7 @@ public Map getAllRules() { return Collections.unmodifiableMap(rules); } - @Override - public Object clone() { - return new ModuleRules(rules); + public ModuleRules clone() { + return new ModuleRules<>(rules); } } diff --git a/src/java/org/apache/ivy/core/module/status/StatusManager.java b/src/java/org/apache/ivy/core/module/status/StatusManager.java index 0e355d70d..ba57a0ea9 100644 --- a/src/java/org/apache/ivy/core/module/status/StatusManager.java +++ b/src/java/org/apache/ivy/core/module/status/StatusManager.java @@ -20,9 +20,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import java.util.Iterator; import java.util.List; -import java.util.ListIterator; import java.util.Map; import org.apache.ivy.core.IvyContext; @@ -42,7 +40,7 @@ public static StatusManager getCurrent() { return IvyContext.getContext().getSettings().getStatusManager(); } - private List status = new ArrayList(); + private final List statuses = new ArrayList<>(); private String defaultStatus; @@ -54,7 +52,7 @@ public static StatusManager getCurrent() { private String deliveryStatusListString; public StatusManager(Status[] status, String defaultStatus) { - this.status.addAll(Arrays.asList(status)); + this.statuses.addAll(Arrays.asList(status)); this.defaultStatus = defaultStatus; computeMaps(); @@ -64,7 +62,7 @@ public StatusManager() { } public void addStatus(Status status) { - this.status.add(status); + this.statuses.add(status); } public void setDefaultStatus(String defaultStatus) { @@ -72,22 +70,20 @@ public void setDefaultStatus(String defaultStatus) { } public List getStatuses() { - return status; + return statuses; } private void computeMaps() { - if (status.isEmpty()) { - throw new IllegalStateException("badly configured statuses: no status found"); + if (statuses.isEmpty()) { + throw new IllegalStateException("badly configured statuses: none found"); } - statusPriorityMap = new HashMap(); - for (ListIterator iter = status.listIterator(); iter.hasNext();) { - Status status = iter.next(); - statusPriorityMap.put(status.getName(), new Integer(iter.previousIndex())); + statusPriorityMap = new HashMap<>(); + for (Status status : statuses) { + statusPriorityMap.put(status.getName(), statuses.indexOf(status)); } - statusIntegrationMap = new HashMap(); - for (Iterator iter = status.iterator(); iter.hasNext();) { - Status status = iter.next(); - statusIntegrationMap.put(status.getName(), Boolean.valueOf(status.isIntegration())); + statusIntegrationMap = new HashMap<>(); + for (Status status : statuses) { + statusIntegrationMap.put(status.getName(), status.isIntegration()); } } @@ -102,19 +98,19 @@ public int getPriority(String status) { if (statusPriorityMap == null) { computeMaps(); } - Integer priority = (Integer) statusPriorityMap.get(status); + Integer priority = statusPriorityMap.get(status); if (priority == null) { Message.debug("unknown status " + status + ": assuming lowest priority"); return Integer.MAX_VALUE; } - return priority.intValue(); + return priority; } public boolean isIntegration(String status) { if (statusIntegrationMap == null) { computeMaps(); } - Boolean isIntegration = (Boolean) statusIntegrationMap.get(status); + Boolean isIntegration = statusIntegrationMap.get(status); if (isIntegration == null) { Message.debug("unknown status " + status + ": assuming integration"); return true; @@ -124,8 +120,8 @@ public boolean isIntegration(String status) { public String getDeliveryStatusListString() { if (deliveryStatusListString == null) { - StringBuffer ret = new StringBuffer(); - for (Status status : this.status) { + StringBuilder ret = new StringBuilder(); + for (Status status : statuses) { if (!status.isIntegration()) { ret.append(status.getName()).append(","); } @@ -140,10 +136,10 @@ public String getDeliveryStatusListString() { public String getDefaultStatus() { if (defaultStatus == null) { - if (status.isEmpty()) { - throw new IllegalStateException("badly configured statuses: no status found"); + if (statuses.isEmpty()) { + throw new IllegalStateException("badly configured statuses: none found"); } - defaultStatus = ((Status) status.get(status.size() - 1)).getName(); + defaultStatus = statuses.get(statuses.size() - 1).getName(); } return defaultStatus; } diff --git a/src/java/org/apache/ivy/core/pack/PackagingManager.java b/src/java/org/apache/ivy/core/pack/PackagingManager.java index 0271f8757..6d9a03e5d 100644 --- a/src/java/org/apache/ivy/core/pack/PackagingManager.java +++ b/src/java/org/apache/ivy/core/pack/PackagingManager.java @@ -55,7 +55,7 @@ public Artifact getUnpackedArtifact(Artifact artifact) { throw new IllegalStateException("Unsupported archive only packing type '" + packings[i] + "' in the streamed chain: " + packaging); } - ext = ((StreamPacking) packing).getUnpackedExtension(ext); + ext = packing.getUnpackedExtension(ext); } ArchivePacking packing = settings.getPackingRegistry().get(packings[0]); if (packing == null) { @@ -110,12 +110,11 @@ public Artifact unpackArtifact(Artifact artifact, File localFile, File archiveFi } } } - final DefaultArtifact unpacked = new DefaultArtifact(artifact.getModuleRevisionId(), + + return new DefaultArtifact(artifact.getModuleRevisionId(), artifact.getPublicationDate(), artifact.getName(), artifact.getType() + "_unpacked", ext); - return unpacked; - } } diff --git a/src/java/org/apache/ivy/core/pack/PackingRegistry.java b/src/java/org/apache/ivy/core/pack/PackingRegistry.java index 6688677fb..77684dcba 100644 --- a/src/java/org/apache/ivy/core/pack/PackingRegistry.java +++ b/src/java/org/apache/ivy/core/pack/PackingRegistry.java @@ -22,7 +22,7 @@ public class PackingRegistry { - private Map packings = new HashMap(); + private Map packings = new HashMap<>(); public PackingRegistry() { // register defaults diff --git a/src/java/org/apache/ivy/core/pack/ZipPacking.java b/src/java/org/apache/ivy/core/pack/ZipPacking.java index 35da6948f..76d06ade5 100644 --- a/src/java/org/apache/ivy/core/pack/ZipPacking.java +++ b/src/java/org/apache/ivy/core/pack/ZipPacking.java @@ -49,9 +49,7 @@ public String getUnpackedExtension(String ext) { @Override public void unpack(InputStream packed, File dest) throws IOException { - ZipInputStream zip = null; - try { - zip = new ZipInputStream(packed); + try (ZipInputStream zip = new ZipInputStream(packed)) { ZipEntry entry = null; while (((entry = zip.getNextEntry()) != null)) { File f = new File(dest, entry.getName()); @@ -71,14 +69,6 @@ public void unpack(InputStream packed, File dest) throws IOException { f.setLastModified(entry.getTime()); } - } finally { - if (zip != null) { - try { - zip.close(); - } catch (IOException e) { - // ignore - } - } } } diff --git a/src/java/org/apache/ivy/core/publish/PublishEngine.java b/src/java/org/apache/ivy/core/publish/PublishEngine.java index a43240cb1..9730957e7 100644 --- a/src/java/org/apache/ivy/core/publish/PublishEngine.java +++ b/src/java/org/apache/ivy/core/publish/PublishEngine.java @@ -118,7 +118,7 @@ public Collection publish(ModuleRevisionId mrid, tmp.deleteOnExit(); String[] confs = ConfigurationUtils.replaceWildcards(options.getConfs(), md); - Set confsToRemove = new HashSet(Arrays.asList(md + Set confsToRemove = new HashSet<>(Arrays.asList(md .getConfigurationsNames())); confsToRemove.removeAll(Arrays.asList(confs)); @@ -183,24 +183,24 @@ public Collection publish(ModuleRevisionId mrid, public Collection publish(ModuleDescriptor md, Collection srcArtifactPattern, DependencyResolver resolver, PublishOptions options) throws IOException { - Collection missing = new ArrayList(); - Set artifactsSet = new LinkedHashSet(); + Collection missing = new ArrayList<>(); + Set artifactsSet = new LinkedHashSet<>(); String[] confs = ConfigurationUtils.replaceWildcards(options.getConfs(), md); - for (int i = 0; i < confs.length; i++) { - Artifact[] artifacts = md.getArtifacts(confs[i]); + for (String conf : confs) { + Artifact[] artifacts = md.getArtifacts(conf); artifactsSet.addAll(Arrays.asList(artifacts)); } Artifact[] extraArtifacts = options.getExtraArtifacts(); if (extraArtifacts != null) { - for (int i = 0; i < extraArtifacts.length; i++) { - artifactsSet.add(new MDArtifact(md, extraArtifacts[i].getName(), extraArtifacts[i] - .getType(), extraArtifacts[i].getExt(), extraArtifacts[i].getUrl(), - extraArtifacts[i].getQualifiedExtraAttributes())); + for (Artifact extraArtifact : extraArtifacts) { + artifactsSet.add(new MDArtifact(md, extraArtifact.getName(), extraArtifact + .getType(), extraArtifact.getExt(), extraArtifact.getUrl(), + extraArtifact.getQualifiedExtraAttributes())); } } // now collects artifacts files - Map artifactsFiles = new LinkedHashMap(); + Map artifactsFiles = new LinkedHashMap<>(); for (Artifact artifact : artifactsSet) { for (String pattern : srcArtifactPattern) { File artifactFile = settings.resolveFile(IvyPatternHelper.substitute( @@ -211,7 +211,7 @@ public Collection publish(ModuleDescriptor md, Collection srcA } } if (!artifactsFiles.containsKey(artifact)) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("missing artifact ").append(artifact).append(":\n"); for (String pattern : srcArtifactPattern) { sb.append("\t").append(settings.resolveFile(IvyPatternHelper.substitute(pattern, artifact))).append(" file does not exist\n"); diff --git a/src/java/org/apache/ivy/core/report/ArtifactDownloadReport.java b/src/java/org/apache/ivy/core/report/ArtifactDownloadReport.java index 03c244151..6ca13ca66 100644 --- a/src/java/org/apache/ivy/core/report/ArtifactDownloadReport.java +++ b/src/java/org/apache/ivy/core/report/ArtifactDownloadReport.java @@ -182,14 +182,11 @@ public int hashCode() { } public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { + if (!(obj instanceof ArtifactDownloadReport)) { return false; } - if (getClass() != obj.getClass()) { - return false; + if (this == obj) { + return true; } ArtifactDownloadReport other = (ArtifactDownloadReport) obj; if (artifact == null) { diff --git a/src/java/org/apache/ivy/core/report/ConfigurationResolveReport.java b/src/java/org/apache/ivy/core/report/ConfigurationResolveReport.java index 47fa680e2..c8e28547a 100644 --- a/src/java/org/apache/ivy/core/report/ConfigurationResolveReport.java +++ b/src/java/org/apache/ivy/core/report/ConfigurationResolveReport.java @@ -56,13 +56,13 @@ public class ConfigurationResolveReport { private final ResolveOptions options; - private Map> dependencyReports = new LinkedHashMap>(); + private Map> dependencyReports = new LinkedHashMap<>(); - private Map dependencies = new LinkedHashMap(); + private Map dependencies = new LinkedHashMap<>(); private final ResolveEngine resolveEngine; - private Map> modulesIdsMap = new LinkedHashMap>(); + private Map> modulesIdsMap = new LinkedHashMap<>(); private List modulesIds; @@ -98,7 +98,7 @@ public void checkIfChanged() { parser.parse(previousReportFile); List previousDeps = Arrays.asList(parser .getDependencyRevisionIds()); - HashSet previousDepSet = new HashSet( + HashSet previousDepSet = new HashSet<>( previousDeps); hasChanged = !previousDepSet.equals(getModuleRevisionIds()); } catch (Exception e) { @@ -126,7 +126,7 @@ public boolean hasChanged() { * @return all non evicted and non error dependency mrids */ public Set getModuleRevisionIds() { - Set mrids = new LinkedHashSet(); + Set mrids = new LinkedHashSet<>(); for (IvyNode node : getDependencies()) { if (!node.isEvicted(getConfiguration()) && !node.hasProblem()) { mrids.add(node.getResolvedId()); @@ -148,7 +148,7 @@ public void updateDependency(ModuleRevisionId mrid, IvyNode node) { public void addDependency(IvyNode node, DownloadReport report) { dependencies.put(node.getId(), node); dependencies.put(node.getResolvedId(), node); - List adrs = new ArrayList(); + List adrs = new ArrayList<>(); Artifact[] artifacts = node.getArtifacts(conf); for (Artifact artifact : artifacts) { ArtifactDownloadReport artifactReport = report.getArtifactReport(artifact); @@ -174,7 +174,7 @@ public ModuleDescriptor getModuleDescriptor() { } public IvyNode[] getUnresolvedDependencies() { - List unresolved = new ArrayList(); + List unresolved = new ArrayList<>(); for (IvyNode node : getDependencies()) { if (node.hasProblem()) { unresolved.add(node); @@ -184,11 +184,11 @@ public IvyNode[] getUnresolvedDependencies() { } private Collection getDependencies() { - return new LinkedHashSet(dependencies.values()); + return new LinkedHashSet<>(dependencies.values()); } public IvyNode[] getEvictedNodes() { - List evicted = new ArrayList(); + List evicted = new ArrayList<>(); for (IvyNode node : getDependencies()) { if (node.isEvicted(conf)) { evicted.add(node); @@ -198,7 +198,7 @@ public IvyNode[] getEvictedNodes() { } private Set getEvictedMrids() { - Set evicted = new LinkedHashSet(); + Set evicted = new LinkedHashSet<>(); IvyNode[] evictedNodes = getEvictedNodes(); for (IvyNode node : evictedNodes) { evicted.add(node.getId()); @@ -207,7 +207,7 @@ private Set getEvictedMrids() { } public IvyNode[] getDownloadedNodes() { - List downloaded = new ArrayList(); + List downloaded = new ArrayList<>(); for (IvyNode node : getDependencies()) { if (node.isDownloaded() && node.getRealNode() == node) { downloaded.add(node); @@ -217,7 +217,7 @@ public IvyNode[] getDownloadedNodes() { } public IvyNode[] getSearchedNodes() { - List downloaded = new ArrayList(); + List downloaded = new ArrayList<>(); for (IvyNode node : getDependencies()) { if (node.isSearched() && node.getRealNode() == node) { downloaded.add(node); @@ -252,12 +252,12 @@ public List getModuleIds() { ModuleId mid = dependency.getResolvedId().getModuleId(); Collection deps = modulesIdsMap.get(mid); if (deps == null) { - deps = new LinkedHashSet(); + deps = new LinkedHashSet<>(); modulesIdsMap.put(mid, deps); } deps.add(dependency); } - modulesIds = new ArrayList(modulesIdsMap.keySet()); + modulesIds = new ArrayList<>(modulesIdsMap.keySet()); } return Collections.unmodifiableList(modulesIds); } @@ -305,7 +305,7 @@ public ArtifactDownloadReport[] getAllArtifactsReports() { */ public ArtifactDownloadReport[] getArtifactsReports(DownloadStatus downloadStatus, boolean withEvicted) { - Collection all = new LinkedHashSet(); + Collection all = new LinkedHashSet<>(); Collection evictedMrids = null; if (!withEvicted) { evictedMrids = getEvictedMrids(); @@ -353,9 +353,10 @@ public int getNodesNumber() { public static ArtifactDownloadReport[] filterOutMergedArtifacts( ArtifactDownloadReport[] allFailedReports) { - Collection adrs = new ArrayList( + Collection adrs = new ArrayList<>( Arrays.asList(allFailedReports)); - for (Iterator iterator = adrs.iterator(); iterator.hasNext();) { + Iterator iterator = adrs.iterator(); + while (iterator.hasNext()) { ArtifactDownloadReport adr = iterator.next(); if (adr.getArtifact().getExtraAttribute("ivy:merged") != null) { diff --git a/src/java/org/apache/ivy/core/report/DownloadReport.java b/src/java/org/apache/ivy/core/report/DownloadReport.java index f2dfcb644..267c7b138 100644 --- a/src/java/org/apache/ivy/core/report/DownloadReport.java +++ b/src/java/org/apache/ivy/core/report/DownloadReport.java @@ -19,7 +19,6 @@ import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -29,29 +28,27 @@ * */ public class DownloadReport { - private Map artifacts = new HashMap(); + private final Map artifacts = new HashMap<>(); public void addArtifactReport(ArtifactDownloadReport adr) { artifacts.put(adr.getArtifact(), adr); } public ArtifactDownloadReport[] getArtifactsReports() { - return (ArtifactDownloadReport[]) artifacts.values().toArray( - new ArtifactDownloadReport[artifacts.size()]); + return artifacts.values().toArray(new ArtifactDownloadReport[artifacts.size()]); } public ArtifactDownloadReport[] getArtifactsReports(DownloadStatus status) { - List ret = new ArrayList(artifacts.size()); - for (Iterator iter = artifacts.values().iterator(); iter.hasNext();) { - ArtifactDownloadReport adr = (ArtifactDownloadReport) iter.next(); + List ret = new ArrayList<>(artifacts.size()); + for (ArtifactDownloadReport adr : artifacts.values()) { if (adr.getDownloadStatus() == status) { ret.add(adr); } } - return (ArtifactDownloadReport[]) ret.toArray(new ArtifactDownloadReport[ret.size()]); + return ret.toArray(new ArtifactDownloadReport[ret.size()]); } public ArtifactDownloadReport getArtifactReport(Artifact artifact) { - return (ArtifactDownloadReport) artifacts.get(artifact); + return artifacts.get(artifact); } } diff --git a/src/java/org/apache/ivy/core/report/ResolveReport.java b/src/java/org/apache/ivy/core/report/ResolveReport.java index 01be74871..5bc7e5664 100644 --- a/src/java/org/apache/ivy/core/report/ResolveReport.java +++ b/src/java/org/apache/ivy/core/report/ResolveReport.java @@ -50,16 +50,16 @@ public class ResolveReport { private ModuleDescriptor md; - private Map confReports = new LinkedHashMap(); + private Map confReports = new LinkedHashMap<>(); - private List problemMessages = new ArrayList(); + private List problemMessages = new ArrayList<>(); /** * the list of all dependencies resolved, ordered from the more dependent to the less dependent */ - private List dependencies = new ArrayList(); + private List dependencies = new ArrayList<>(); - private List artifacts = new ArrayList(); + private List artifacts = new ArrayList<>(); private long resolveTime; @@ -101,8 +101,8 @@ public boolean hasError() { public void output(ReportOutputter[] outputters, ResolutionCacheManager cacheMgr, ResolveOptions options) throws IOException { - for (int i = 0; i < outputters.length; i++) { - outputters[i].output(this, cacheMgr, options); + for (ReportOutputter outputter : outputters) { + outputter.output(this, cacheMgr, options); } } @@ -111,7 +111,7 @@ public ModuleDescriptor getModuleDescriptor() { } public IvyNode[] getEvictedNodes() { - Collection all = new LinkedHashSet(); + Collection all = new LinkedHashSet<>(); for (ConfigurationResolveReport report : confReports.values()) { all.addAll(Arrays.asList(report.getEvictedNodes())); } @@ -119,7 +119,7 @@ public IvyNode[] getEvictedNodes() { } public IvyNode[] getUnresolvedDependencies() { - Collection all = new LinkedHashSet(); + Collection all = new LinkedHashSet<>(); for (ConfigurationResolveReport report : confReports.values()) { all.addAll(Arrays.asList(report.getUnresolvedDependencies())); } @@ -161,7 +161,7 @@ public ArtifactDownloadReport[] getAllArtifactsReports() { */ public ArtifactDownloadReport[] getArtifactsReports(DownloadStatus downloadStatus, boolean withEvicted) { - Collection all = new LinkedHashSet(); + Collection all = new LinkedHashSet<>(); for (ConfigurationResolveReport report : confReports.values()) { ArtifactDownloadReport[] reports = report.getArtifactsReports(downloadStatus, withEvicted); @@ -171,7 +171,7 @@ public ArtifactDownloadReport[] getArtifactsReports(DownloadStatus downloadStatu } public ArtifactDownloadReport[] getArtifactsReports(ModuleRevisionId mrid) { - Collection all = new LinkedHashSet(); + Collection all = new LinkedHashSet<>(); for (ConfigurationResolveReport report : confReports.values()) { all.addAll(Arrays.asList(report.getDownloadReports(mrid))); } @@ -207,20 +207,18 @@ public List getProblemMessages() { } public List getAllProblemMessages() { - List ret = new ArrayList(problemMessages); + List ret = new ArrayList<>(problemMessages); for (ConfigurationResolveReport r : confReports.values()) { - IvyNode[] unresolved = r.getUnresolvedDependencies(); - for (int i = 0; i < unresolved.length; i++) { - String errMsg = unresolved[i].getProblemMessage(); + for (IvyNode unresolved : r.getUnresolvedDependencies()) { + String errMsg = unresolved.getProblemMessage(); if (errMsg.length() > 0) { - ret.add("unresolved dependency: " + unresolved[i].getId() + ": " + errMsg); + ret.add("unresolved dependency: " + unresolved.getId() + ": " + errMsg); } else { - ret.add("unresolved dependency: " + unresolved[i].getId()); + ret.add("unresolved dependency: " + unresolved.getId()); } } - ArtifactDownloadReport[] adrs = r.getFailedArtifactsReports(); - for (int i = 0; i < adrs.length; i++) { - ret.add("download failed: " + adrs[i].getArtifact()); + for (ArtifactDownloadReport adr : r.getFailedArtifactsReports()) { + ret.add("download failed: " + adr.getArtifact()); } } return ret; @@ -229,16 +227,15 @@ public List getAllProblemMessages() { public void setDependencies(List dependencies, Filter artifactFilter) { this.dependencies = dependencies; // collect list of artifacts - artifacts = new ArrayList(); + artifacts = new ArrayList<>(); for (IvyNode dependency : dependencies) { if (!dependency.isCompletelyEvicted() && !dependency.hasProblem()) { artifacts.addAll(Arrays.asList(dependency.getSelectedArtifacts(artifactFilter))); } // update the configurations reports with the dependencies // these reports will be completed later with download information, if any - String[] dconfs = dependency.getRootModuleConfigurations(); - for (int j = 0; j < dconfs.length; j++) { - ConfigurationResolveReport configurationReport = getConfigurationReport(dconfs[j]); + for (String dconf : dependency.getRootModuleConfigurations()) { + ConfigurationResolveReport configurationReport = getConfigurationReport(dconf); if (configurationReport != null) { configurationReport.addDependency(dependency); } @@ -272,8 +269,8 @@ public List getArtifacts() { * @return a list of ModuleId */ public List getModuleIds() { - List ret = new ArrayList(); - List sortedDependencies = new ArrayList(dependencies); + List ret = new ArrayList<>(); + List sortedDependencies = new ArrayList<>(dependencies); for (IvyNode dependency : sortedDependencies) { ModuleId mid = dependency.getResolvedId().getModuleId(); if (!ret.contains(mid)) { @@ -329,11 +326,10 @@ public String getResolveId() { */ @SuppressWarnings("unused") private String[] getExtendingConfs(String extended) { - String[] allConfs = md.getConfigurationsNames(); - Set extendingConfs = new HashSet(); + Set extendingConfs = new HashSet<>(); extendingConfs.add(extended); - for (int i = 0; i < allConfs.length; i++) { - gatherExtendingConfs(extendingConfs, allConfs[i], extended); + for (String conf : md.getConfigurationsNames()) { + gatherExtendingConfs(extendingConfs, conf, extended); } return extendingConfs.toArray(new String[extendingConfs.size()]); } @@ -342,20 +338,20 @@ private boolean gatherExtendingConfs(Set extendingConfs, String conf, St if (extendingConfs.contains(conf)) { return true; } - String[] ext = md.getConfiguration(conf).getExtends(); - if (ext == null || ext.length == 0) { + String[] exts = md.getConfiguration(conf).getExtends(); + if (exts == null || exts.length == 0) { return false; } - for (int i = 0; i < ext.length; i++) { - if (extendingConfs.contains(ext[i])) { + for (String ext : exts) { + if (extendingConfs.contains(ext)) { extendingConfs.add(conf); return true; } - if (ext[i].equals(extended)) { + if (ext.equals(extended)) { extendingConfs.add(conf); return true; } - if (gatherExtendingConfs(extendingConfs, ext[i], extended)) { + if (gatherExtendingConfs(extendingConfs, ext, extended)) { extendingConfs.add(conf); return true; } diff --git a/src/java/org/apache/ivy/core/repository/RepositoryManagementEngine.java b/src/java/org/apache/ivy/core/repository/RepositoryManagementEngine.java index ae769cc20..c700b02e2 100644 --- a/src/java/org/apache/ivy/core/repository/RepositoryManagementEngine.java +++ b/src/java/org/apache/ivy/core/repository/RepositoryManagementEngine.java @@ -22,13 +22,14 @@ import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.TreeSet; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.DependencyDescriptor; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; +import org.apache.ivy.core.module.id.ModuleId; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.core.resolve.ResolveData; import org.apache.ivy.core.resolve.ResolveEngine; @@ -85,17 +86,17 @@ public class RepositoryManagementEngine { /** * ModuleDescriptors stored by ModuleRevisionId */ - private Map/* */revisions = new HashMap(); + private Map revisions = new HashMap<>(); /** * ModuleRevisionId for which loading was not possible, with corresponding error message. */ - private Map/* */errors = new HashMap(); + private Map errors = new HashMap<>(); /** - * List of ModuleRevisionId per ModuleId. + * List of ModuleDescriptor per ModuleId. */ - private Map/* > */modules = new HashMap(); + private Map> modules = new HashMap<>(); // ///////////////////////////////////////// // state loaded on #analyze() @@ -109,12 +110,12 @@ public class RepositoryManagementEngine { /** * Cache from requested module revision id to actual module revision id. */ - private Map/* */cache = new HashMap(); + private Map cache = new HashMap<>(); /** * list of dependers per ModuleRevisionId. */ - private Map/* > */dependers = new HashMap(); + private Map> dependers = new HashMap<>(); // ///////////////////////////////////////// // dependencies @@ -148,22 +149,19 @@ public void load() { Message.rawinfo("searching modules... "); ModuleRevisionId[] mrids = searchModules(); Message.info("loading repository metadata..."); - for (int i = 0; i < mrids.length; i++) { + for (ModuleRevisionId mrid : mrids) { try { - loadModuleRevision(mrids[i]); + loadModuleRevision(mrid); } catch (Exception e) { Message.debug(e); - errors.put(mrids[i], e.getMessage()); + errors.put(mrid, e.getMessage()); } } long endTime = System.currentTimeMillis(); - Message.info("\nrepository loaded: " - + modules.size() - + " modules; " - + revisions.size() - + " revisions; " - + (settings.dumpMemoryUsage() ? (MemoryUtil.getUsedMemory() - startingMemoryUse) - / KILO + "kB; " : "") + (endTime - startTime) / THOUSAND + "s"); + Message.info(String.format("\nrepository loaded: %d modules; %d revisions; %s%ss", + modules.size(), revisions.size(), settings.dumpMemoryUsage() + ? (MemoryUtil.getUsedMemory() - startingMemoryUse) / KILO + "kB; " : "", + (endTime - startTime) / THOUSAND)); loaded = true; } @@ -181,14 +179,11 @@ public void load() { public void analyze() { ensureLoaded(); Message.info("\nanalyzing dependencies..."); - for (Iterator iterator = revisions.values().iterator(); iterator.hasNext();) { - ModuleDescriptor md = (ModuleDescriptor) iterator.next(); - DependencyDescriptor[] dds = md.getDependencies(); - for (int i = 0; i < dds.length; i++) { - ModuleRevisionId dep = getDependency(dds[i]); + for (ModuleDescriptor md : revisions.values()) { + for (DependencyDescriptor dd : md.getDependencies()) { + ModuleRevisionId dep = getDependency(dd); if (dep == null) { - Message.warn("inconsistent repository: declared dependency not found: " - + dds[i]); + Message.warn("inconsistent repository: declared dependency not found: " + dd); } else { getDependers(dep).add(md.getModuleRevisionId()); } @@ -233,30 +228,27 @@ public int getModuleIdsNumber() { * if the repository has not been analyzed yet * @see #analyze() */ - public Collection getOrphans() { + public Collection getOrphans() { ensureAnalyzed(); - Collection orphans = new HashSet(revisions.keySet()); + Collection orphans = new HashSet<>(revisions.keySet()); orphans.removeAll(dependers.keySet()); return orphans; } private ModuleRevisionId[] searchModules() { - ModuleRevisionId[] mrids = searchEngine.listModules(ModuleRevisionId.newInstance( + return searchEngine.listModules(ModuleRevisionId.newInstance( PatternMatcher.ANY_EXPRESSION, PatternMatcher.ANY_EXPRESSION, PatternMatcher.ANY_EXPRESSION, PatternMatcher.ANY_EXPRESSION), RegexpPatternMatcher.INSTANCE); - return mrids; } private ModuleRevisionId getDependency(DependencyDescriptor dd) { ModuleRevisionId askedMrid = dd.getDependencyRevisionId(); VersionMatcher vmatcher = settings.getVersionMatcher(); if (vmatcher.isDynamic(askedMrid)) { - ModuleRevisionId mrid = (ModuleRevisionId) cache.get(askedMrid); + ModuleRevisionId mrid = cache.get(askedMrid); if (mrid == null) { - Collection revs = getAllRevisions(askedMrid); - for (Iterator iterator = revs.iterator(); iterator.hasNext();) { - ModuleDescriptor md = (ModuleDescriptor) iterator.next(); + for (ModuleDescriptor md : getAllRevisions(askedMrid)) { if (vmatcher.needModuleDescriptor(askedMrid, md.getResolvedModuleRevisionId())) { if (vmatcher.accept(askedMrid, md)) { mrid = md.getResolvedModuleRevisionId(); @@ -281,10 +273,10 @@ private ModuleRevisionId getDependency(DependencyDescriptor dd) { } } - private Collection getDependers(ModuleRevisionId id) { - Collection depders = (Collection) dependers.get(id); + private Collection getDependers(ModuleRevisionId id) { + List depders = dependers.get(id); if (depders == null) { - depders = new ArrayList(); + depders = new ArrayList<>(); dependers.put(id, depders); } return depders; @@ -302,13 +294,11 @@ private void loadModuleRevision(ModuleRevisionId mrid) throws Exception { Message.progress(); } - private Collection getAllRevisions(ModuleRevisionId id) { - Collection revisions = (Collection) modules.get(id.getModuleId()); + private Collection getAllRevisions(ModuleRevisionId id) { + Collection revisions = modules.get(id.getModuleId()); if (revisions == null) { - revisions = new TreeSet(new Comparator() { - public int compare(Object o1, Object o2) { - ModuleDescriptor md1 = (ModuleDescriptor) o1; - ModuleDescriptor md2 = (ModuleDescriptor) o2; + revisions = new TreeSet<>(new Comparator() { + public int compare(ModuleDescriptor md1, ModuleDescriptor md2) { // we use reverse order compared to latest revision, to have latest revision // first return settings.getDefaultLatestStrategy().sort(new ArtifactInfo[] {md1, md2}) diff --git a/src/java/org/apache/ivy/core/resolve/IvyNode.java b/src/java/org/apache/ivy/core/resolve/IvyNode.java index a26146fb2..47bc3e1fa 100644 --- a/src/java/org/apache/ivy/core/resolve/IvyNode.java +++ b/src/java/org/apache/ivy/core/resolve/IvyNode.java @@ -82,7 +82,7 @@ public class IvyNode implements Comparable { private ModuleRevisionId id; // set only when node has been built or updated from a DependencyDescriptor - private Map dds = new HashMap(); + private Map dds = new HashMap<>(); // Set when data has been loaded only, or when constructed from a module descriptor private ModuleDescriptor md; @@ -96,18 +96,18 @@ public class IvyNode implements Comparable { private boolean searched = false; - private Collection confsToFetch = new HashSet(); + private Collection confsToFetch = new HashSet<>(); - private Collection fetchedConfigurations = new HashSet(); + private Collection fetchedConfigurations = new HashSet<>(); - private Collection loadedRootModuleConfs = new HashSet(); + private Collection loadedRootModuleConfs = new HashSet<>(); // //////// USAGE DATA private IvyNodeUsage usage = new IvyNodeUsage(this); // usage information merged from evicted nodes this node is "replacing" - private Map mergedUsages = new LinkedHashMap(); + private Map mergedUsages = new LinkedHashMap<>(); public IvyNode(ResolveData data, IvyNode parent, DependencyDescriptor dd) { id = dd.getDependencyRevisionId(); @@ -310,9 +310,9 @@ public Collection getDependencies(String rootModuleConf, String[] confs confs = md.getPublicConfigurationsNames(); } } - Collection deps = new HashSet(); - for (int i = 0; i < confs.length; i++) { - deps.addAll(getDependencies(rootModuleConf, confs[i], requestedConf)); + Collection deps = new HashSet<>(); + for (String conf : confs) { + deps.addAll(getDependencies(rootModuleConf, conf, requestedConf)); } return deps; } @@ -336,10 +336,9 @@ public Collection getDependencies(String rootModuleConf, String conf, throw new IllegalStateException( "impossible to get dependencies when data has not been loaded"); } - DependencyDescriptor[] dds = md.getDependencies(); // it's important to respect order => LinkedHashMap - Map dependencies = new LinkedHashMap(); - for (DependencyDescriptor dependencyDescriptor : dds) { + Map dependencies = new LinkedHashMap<>(); + for (DependencyDescriptor dependencyDescriptor : md.getDependencies()) { DependencyDescriptor dd = data.mediate(dependencyDescriptor); String[] dependencyConfigurations = dd.getDependencyConfigurations(conf, requestedConf); if (dependencyConfigurations.length == 0) { @@ -423,7 +422,7 @@ Boolean doesExclude(ModuleDescriptor md, String rootModuleConf, String[] moduleC // a circular dependency, we cannot be conclusive here return null; } - return Boolean.valueOf(c.doesCallersExclude(rootModuleConf, artifact, callersStack)); + return c.doesCallersExclude(rootModuleConf, artifact, callersStack); } return Boolean.FALSE; } @@ -513,7 +512,7 @@ && isLoaded()) { // there are exclusions in the configuration List exclusions = Arrays.asList(conf.substring(2).split("\\!")); - List ret = new ArrayList(Arrays.asList(getDescriptor() + List ret = new ArrayList<>(Arrays.asList(getDescriptor() .getPublicConfigurationsNames())); ret.removeAll(exclusions); @@ -530,7 +529,7 @@ && isLoaded()) { * @return array of configuration names */ public String[] getRequiredConfigurations(IvyNode in, String inConf) { - Collection req = new LinkedHashSet(); + Collection req = new LinkedHashSet<>(); addAllIfNotNull(req, usage.getRequiredConfigurations(in, inConf)); for (IvyNodeUsage usage : mergedUsages.values()) { addAllIfNotNull(req, usage.getRequiredConfigurations(in, inConf)); @@ -550,7 +549,7 @@ private void addAllIfNotNull(Collection into, Collection col) { * @return array of configuration names */ public String[] getRequiredConfigurations() { - Collection required = new ArrayList(confsToFetch.size() + Collection required = new ArrayList<>(confsToFetch.size() + fetchedConfigurations.size()); required.addAll(fetchedConfigurations); required.addAll(confsToFetch); @@ -578,7 +577,7 @@ public Configuration getConfiguration(String conf) { * @return array of configuration names */ public String[] getConfigurations(String rootModuleConf) { - Set depConfs = new LinkedHashSet(); + Set depConfs = new LinkedHashSet<>(); addAllIfNotNull(depConfs, usage.getConfigurations(rootModuleConf)); for (IvyNodeUsage usage : mergedUsages.values()) { addAllIfNotNull(depConfs, usage.getConfigurations(rootModuleConf)); @@ -598,10 +597,9 @@ public void discardConf(String rootModuleConf, String conf) { // remove all given dependency configurations to the set + extended ones Configuration c = md.getConfiguration(conf); if (conf != null) { - String[] exts = c.getExtends(); - for (int i = 0; i < exts.length; i++) { - discardConf(rootModuleConf, exts[i]); // recursive remove of extended - // configurations + // recursive remove of extended configurations + for (String ext : c.getExtends()) { + discardConf(rootModuleConf, ext); } depConfs.remove(c.getName()); } else { @@ -643,7 +641,7 @@ public String[] getRootModuleConfigurations() { * @return {@link Set} of configuration names */ public Set getRootModuleConfigurationsSet() { - Set confs = new LinkedHashSet(); + Set confs = new LinkedHashSet<>(); addAllIfNotNull(confs, usage.getRootModuleConfigurations()); for (IvyNodeUsage usage : mergedUsages.values()) { addAllIfNotNull(confs, usage.getRootModuleConfigurations()); @@ -672,7 +670,7 @@ public String[] getRealConfs(String conf) { if (conf.charAt(0) == '*') { return resolveSpecialConfigurations(new String[] {conf}); } - if (conf.indexOf(',') != -1) { + if (conf.contains(",")) { String[] confs = conf.split(","); for (int i = 0; i < confs.length; i++) { confs[i] = confs[i].trim(); @@ -749,7 +747,7 @@ private void updateDataFrom(IvyNode node, String rootModuleConf, boolean real) { } private Collection getAllUsages() { - Collection usages = new ArrayList(); + Collection usages = new ArrayList<>(); usages.add(usage); usages.addAll(mergedUsages.values()); return usages; @@ -761,7 +759,7 @@ private Collection getAllUsages() { * @return array of {@link Artifact}s */ public Artifact[] getAllArtifacts() { - Set ret = new HashSet(); + Set ret = new HashSet<>(); for (String rootModuleConf : getRootModuleConfigurationsSet()) { ret.addAll(Arrays.asList(getArtifacts(rootModuleConf))); } @@ -776,7 +774,7 @@ public Artifact[] getAllArtifacts() { * @return array of {@link Artifact}s */ public Artifact[] getSelectedArtifacts(Filter artifactFilter) { - Collection ret = new HashSet(); + Collection ret = new HashSet<>(); for (String rootModuleConf : getRootModuleConfigurationsSet()) { if (!isEvicted(rootModuleConf) && !isBlacklisted(rootModuleConf)) { ret.addAll(Arrays.asList(getArtifacts(rootModuleConf))); @@ -807,7 +805,7 @@ public Artifact[] getArtifacts(String rootModuleConf) { + this); } - Set artifacts = new HashSet(); // the set we fill before returning + Set artifacts = new HashSet<>(); // the set we fill before returning // we check if we have dependencyArtifacts includes description for this rootModuleConf Set dependencyArtifacts = usage @@ -817,7 +815,7 @@ public Artifact[] getArtifacts(String rootModuleConf) { addArtifactsFromOwnUsage(artifacts, dependencyArtifacts); addArtifactsFromMergedUsage(rootModuleConf, artifacts); } else { - Set includes = new LinkedHashSet(); + Set includes = new LinkedHashSet<>(); addAllIfNotNull(includes, usage.getDependencyIncludesSet(rootModuleConf)); for (IvyNodeUsage usage : mergedUsages.values()) { addAllIfNotNull(includes, usage.getDependencyIncludesSet(rootModuleConf)); @@ -826,19 +824,17 @@ public Artifact[] getArtifacts(String rootModuleConf) { if ((dependencyArtifacts == null || dependencyArtifacts.isEmpty()) && (includes.isEmpty())) { // no artifacts / includes: we get all artifacts as defined by the descriptor - for (int i = 0; i < confs.length; i++) { - artifacts.addAll(Arrays.asList(md.getArtifacts(confs[i]))); + for (String conf : confs) { + artifacts.addAll(Arrays.asList(md.getArtifacts(conf))); } } else { - // we have to get only artifacts listed as "includes" - + // we have to get only artifacts listed as "includes"; // first we get all artifacts as defined by the module descriptor // and classify them by artifact id - Map allArtifacts = new HashMap(); - for (int i = 0; i < confs.length; i++) { - Artifact[] arts = md.getArtifacts(confs[i]); - for (int j = 0; j < arts.length; j++) { - allArtifacts.put(arts[j].getId().getArtifactId(), arts[j]); + Map allArtifacts = new HashMap<>(); + for (String conf : confs) { + for (Artifact art : md.getArtifacts(conf)) { + allArtifacts.put(art.getId().getArtifactId(), art); } } @@ -849,7 +845,8 @@ public Artifact[] getArtifacts(String rootModuleConf) { addArtifactsFromMergedUsage(rootModuleConf, artifacts); // and now we filter according to include rules - for (Iterator it = includes.iterator(); it.hasNext();) { + Iterator it = includes.iterator(); + while (it.hasNext()) { IncludeRule dad = it.next(); Collection arts = findArtifactsMatching(dad, allArtifacts); if (arts.isEmpty()) { @@ -866,8 +863,9 @@ public Artifact[] getArtifacts(String rootModuleConf) { } } - // now excludes artifacts that aren't accepted by any caller - for (Iterator iter = artifacts.iterator(); iter.hasNext();) { + // now exclude artifacts that aren't accepted by any caller + Iterator iter = artifacts.iterator(); + while (iter.hasNext()) { Artifact artifact = iter.next(); boolean excluded = callers.doesCallersExclude(rootModuleConf, artifact); if (excluded) { @@ -892,7 +890,7 @@ private void addArtifactsFromMergedUsage(String rootModuleConf, Set ar .getDependencyArtifactsSet(rootModuleConf); if (mergedDependencyArtifacts != null) { for (DependencyArtifactDescriptor dad : mergedDependencyArtifacts) { - Map extraAttributes = new HashMap( + Map extraAttributes = new HashMap<>( dad.getQualifiedExtraAttributes()); MDArtifact artifact = new MDArtifact(md, dad.getName(), dad.getType(), dad.getExt(), dad.getUrl(), extraAttributes); @@ -910,7 +908,7 @@ private void addArtifactsFromMergedUsage(String rootModuleConf, Set ar private static Collection findArtifactsMatching(IncludeRule rule, Map allArtifacts) { - Collection ret = new ArrayList(); + Collection ret = new ArrayList<>(); for (Entry entry : allArtifacts.entrySet()) { if (MatcherHelper.matches(rule.getMatcher(), rule.getId(), entry.getKey())) { ret.add(entry.getValue()); @@ -1243,7 +1241,7 @@ public void blacklist(IvyNodeBlacklist bdata) { Message.verbose("BLACKLISTING " + bdata); } - Stack callerStack = new Stack(); + Stack callerStack = new Stack<>(); callerStack.push(this); clearEvictionDataInAllCallers(bdata.getRootModuleConf(), callerStack); diff --git a/src/java/org/apache/ivy/core/resolve/IvyNodeCallers.java b/src/java/org/apache/ivy/core/resolve/IvyNodeCallers.java index f9c6d57db..558565bb4 100644 --- a/src/java/org/apache/ivy/core/resolve/IvyNodeCallers.java +++ b/src/java/org/apache/ivy/core/resolve/IvyNodeCallers.java @@ -39,7 +39,7 @@ public static class Caller { private ModuleRevisionId mrid; // callerConf -> dependencyConfs - private Map confs = new HashMap(); + private Map confs = new HashMap<>(); private DependencyDescriptor dd; @@ -61,8 +61,8 @@ public void addConfiguration(String callerConf, String[] dependencyConfs) { if (conf != null) { String[] confExtends = conf.getExtends(); if (confExtends != null) { - for (int i = 0; i < confExtends.length; i++) { - addConfiguration(confExtends[i], dependencyConfs); + for (String confExtend : confExtends) { + addConfiguration(confExtend, dependencyConfs); } } } @@ -71,7 +71,7 @@ public void addConfiguration(String callerConf, String[] dependencyConfs) { private void updateConfs(String callerConf, String[] dependencyConfs) { String[] prevDepConfs = confs.get(callerConf); if (prevDepConfs != null) { - Set newDepConfs = new HashSet(Arrays.asList(prevDepConfs)); + Set newDepConfs = new HashSet<>(Arrays.asList(prevDepConfs)); newDepConfs.addAll(Arrays.asList(dependencyConfs)); confs.put(callerConf, newDepConfs.toArray(new String[newDepConfs.size()])); } else { @@ -137,12 +137,12 @@ public boolean isRealCaller() { } // key in second map is used to easily get a caller by its mrid - private Map> callersByRootConf = new HashMap>(); + private Map> callersByRootConf = new HashMap<>(); // this map contains all the module ids calling this one (including transitively) as keys. // the mapped nodes (values) correspond to a direct caller from which the transitive caller // comes - private Map allCallers = new HashMap(); + private Map allCallers = new HashMap<>(); private IvyNode node; @@ -170,7 +170,7 @@ public void addCaller(String rootModuleConf, IvyNode callerNode, String callerCo } Map callers = callersByRootConf.get(rootModuleConf); if (callers == null) { - callers = new HashMap(); + callers = new HashMap<>(); callersByRootConf.put(rootModuleConf, callers); } Caller caller = callers.get(mrid); @@ -204,7 +204,7 @@ public Caller[] getCallers(String rootModuleConf) { } public Caller[] getAllCallers() { - Set all = new HashSet(); + Set all = new HashSet<>(); for (Map callers : callersByRootConf.values()) { all.addAll(callers.values()); } @@ -212,7 +212,7 @@ public Caller[] getAllCallers() { } public Caller[] getAllRealCallers() { - Set all = new HashSet(); + Set all = new HashSet<>(); for (Map callers : callersByRootConf.values()) { for (Caller c : callers.values()) { if (c.isRealCaller()) { @@ -232,7 +232,7 @@ void updateFrom(IvyNodeCallers callers, String rootModuleConf, boolean real) { if (nodecallers != null) { Map thiscallers = callersByRootConf.get(rootModuleConf); if (thiscallers == null) { - thiscallers = new HashMap(); + thiscallers = new HashMap<>(); callersByRootConf.put(rootModuleConf, thiscallers); } for (Caller caller : nodecallers.values()) { @@ -270,14 +270,14 @@ boolean doesCallersExclude(String rootModuleConf, Artifact artifact, return false; } boolean allInconclusive = true; - for (int i = 0; i < callers.length; i++) { - if (!callers[i].canExclude()) { + for (Caller caller : callers) { + if (!caller.canExclude()) { return false; } - ModuleDescriptor md = callers[i].getModuleDescriptor(); + ModuleDescriptor md = caller.getModuleDescriptor(); Boolean doesExclude = node.doesExclude(md, rootModuleConf, - callers[i].getCallerConfigurations(), callers[i].getDependencyDescriptor(), - artifact, callersStack); + caller.getCallerConfigurations(), caller.getDependencyDescriptor(), + artifact, callersStack); if (doesExclude != null) { if (!doesExclude) { return false; diff --git a/src/java/org/apache/ivy/core/resolve/IvyNodeEviction.java b/src/java/org/apache/ivy/core/resolve/IvyNodeEviction.java index 3524f21ff..abd135cf0 100644 --- a/src/java/org/apache/ivy/core/resolve/IvyNodeEviction.java +++ b/src/java/org/apache/ivy/core/resolve/IvyNodeEviction.java @@ -157,7 +157,9 @@ public final ModuleId getModuleId() { @Override public boolean equals(Object obj) { - return obj instanceof ModuleIdConf && getModuleId().equals(((ModuleIdConf) obj).getModuleId()) && getConf().equals(((ModuleIdConf) obj).getConf()); + return obj instanceof ModuleIdConf + && getModuleId().equals(((ModuleIdConf) obj).getModuleId()) + && getConf().equals(((ModuleIdConf) obj).getConf()); } @Override @@ -174,20 +176,20 @@ public int hashCode() { private IvyNode node; // map indicating for each dependency which node has been selected - private Map> selectedDeps = new HashMap>(); + private Map> selectedDeps = new HashMap<>(); // map indicating for each dependency which nodes are in pending conflict (conflict detected but // not yet resolved) - private Map> pendingConflicts = new HashMap>(); + private Map> pendingConflicts = new HashMap<>(); // map indicating for each dependency which node has been evicted - private Map> evictedDeps = new HashMap>(); + private Map> evictedDeps = new HashMap<>(); // map indicating for each dependency which revision has been evicted - private Map> evictedRevs = new HashMap>(); + private Map> evictedRevs = new HashMap<>(); // indicates if the node is evicted in each root module conf - private Map evicted = new HashMap(); + private Map evicted = new HashMap<>(); public IvyNodeEviction(IvyNode node) { if (node == null) { @@ -203,7 +205,7 @@ public IvyNodeEviction(IvyNode node) { */ public Set getResolvedNodes(ModuleId mid, String rootModuleConf) { Collection resolved = selectedDeps.get(new ModuleIdConf(mid, rootModuleConf)); - Set ret = new HashSet(); + Set ret = new HashSet<>(); if (resolved != null) { for (IvyNode node : resolved) { ret.add(node.getRealNode()); @@ -215,9 +217,9 @@ public Set getResolvedNodes(ModuleId mid, String rootModuleConf) { public Collection getResolvedRevisions(ModuleId mid, String rootModuleConf) { Collection resolved = selectedDeps.get(new ModuleIdConf(mid, rootModuleConf)); if (resolved == null) { - return new HashSet(); + return new HashSet<>(); } else { - Collection resolvedRevs = new HashSet(); + Collection resolvedRevs = new HashSet<>(); for (IvyNode node : resolved) { ModuleRevisionId resolvedId = node.getResolvedId(); resolvedRevs.add(node.getId()); @@ -237,12 +239,12 @@ public Collection getResolvedRevisions(ModuleId mid, String ro public void setResolvedNodes(ModuleId moduleId, String rootModuleConf, Collection resolved) { ModuleIdConf moduleIdConf = new ModuleIdConf(moduleId, rootModuleConf); - selectedDeps.put(moduleIdConf, new HashSet(resolved)); + selectedDeps.put(moduleIdConf, new HashSet<>(resolved)); } public Collection getEvictedNodes(ModuleId mid, String rootModuleConf) { Collection resolved = evictedDeps.get(new ModuleIdConf(mid, rootModuleConf)); - Set ret = new HashSet(); + Set ret = new HashSet<>(); if (resolved != null) { for (IvyNode node : resolved) { ret.add(node.getRealNode()); @@ -255,17 +257,17 @@ public Collection getEvictedRevisions(ModuleId mid, String roo Collection evicted = evictedRevs .get(new ModuleIdConf(mid, rootModuleConf)); if (evicted == null) { - return new HashSet(); + return new HashSet<>(); } else { - return new HashSet(evicted); + return new HashSet<>(evicted); } } public void setEvictedNodes(ModuleId moduleId, String rootModuleConf, Collection evicted) { ModuleIdConf moduleIdConf = new ModuleIdConf(moduleId, rootModuleConf); - evictedDeps.put(moduleIdConf, new HashSet(evicted)); - Collection evictedRevs = new HashSet(); + evictedDeps.put(moduleIdConf, new HashSet<>(evicted)); + Collection evictedRevs = new HashSet<>(); for (IvyNode node : evicted) { evictedRevs.add(node.getId()); evictedRevs.add(node.getResolvedId()); @@ -295,9 +297,8 @@ public boolean isCompletelyEvicted() { if (node.isRoot()) { return false; } - String[] rootModuleConfigurations = node.getRootModuleConfigurations(); - for (int i = 0; i < rootModuleConfigurations.length; i++) { - if (!isEvicted(rootModuleConfigurations[i])) { + for (String rootModuleConfiguration : node.getRootModuleConfigurations()) { + if (!isEvicted(rootModuleConfiguration)) { return false; } } @@ -306,7 +307,8 @@ public boolean isCompletelyEvicted() { private void cleanEvicted() { // check if it was evicted by a node that we are now the real node for - for (Iterator iter = evicted.keySet().iterator(); iter.hasNext();) { + Iterator iter = evicted.keySet().iterator(); + while (iter.hasNext()) { String rootModuleConf = iter.next(); EvictionData ed = evicted.get(rootModuleConf); Collection sel = ed.getSelected(); @@ -348,7 +350,7 @@ public Collection getAllEvictingNodes() { Collection selected = ed.getSelected(); if (selected != null) { if (allEvictingNodes == null) { - allEvictingNodes = new HashSet(); + allEvictingNodes = new HashSet<>(); } allEvictingNodes.addAll(selected); } @@ -362,7 +364,7 @@ public Collection getAllEvictingNodesDetails() { Collection selected = ed.getSelected(); if (selected != null) { if (ret == null) { - ret = new HashSet(); + ret = new HashSet<>(); } if (selected.size() == 1) { ret.add(selected.iterator().next() @@ -376,7 +378,7 @@ public Collection getAllEvictingNodesDetails() { } public Collection getAllEvictingConflictManagers() { - Collection ret = new HashSet(); + Collection ret = new HashSet<>(); for (EvictionData ed : evicted.values()) { ret.add(ed.getConflictManager()); } @@ -409,7 +411,7 @@ public EvictionData getEvictionDataInRoot(String rootModuleConf, IvyNode ancesto public Collection getPendingConflicts(String rootModuleConf, ModuleId mid) { Collection resolved = pendingConflicts.get(new ModuleIdConf(mid, rootModuleConf)); - Set ret = new HashSet(); + Set ret = new HashSet<>(); if (resolved != null) { for (IvyNode node : resolved) { ret.add(node.getRealNode()); @@ -421,7 +423,7 @@ public Collection getPendingConflicts(String rootModuleConf, ModuleId m public void setPendingConflicts(ModuleId moduleId, String rootModuleConf, Collection conflicts) { ModuleIdConf moduleIdConf = new ModuleIdConf(moduleId, rootModuleConf); - pendingConflicts.put(moduleIdConf, new HashSet(conflicts)); + pendingConflicts.put(moduleIdConf, new HashSet<>(conflicts)); } } diff --git a/src/java/org/apache/ivy/core/resolve/IvyNodeUsage.java b/src/java/org/apache/ivy/core/resolve/IvyNodeUsage.java index 0399f5229..53f857b91 100644 --- a/src/java/org/apache/ivy/core/resolve/IvyNodeUsage.java +++ b/src/java/org/apache/ivy/core/resolve/IvyNodeUsage.java @@ -123,14 +123,14 @@ public int hashCode() { // used to know which configurations of the dependency are required // for each root module configuration // rootConfName -> confNames - private Map> rootModuleConfs = new HashMap>(); + private Map> rootModuleConfs = new HashMap<>(); - private Map> requiredConfs = new HashMap>(); + private Map> requiredConfs = new HashMap<>(); - private Map> dependers = new HashMap>(); + private Map> dependers = new HashMap<>(); // rootModuleConf -> black list - private Map blacklisted = new HashMap(); + private Map blacklisted = new HashMap<>(); public IvyNodeUsage(IvyNode node) { this.node = node; @@ -141,7 +141,7 @@ protected Collection getRequiredConfigurations(IvyNode in, String inConf } protected void setRequiredConfs(IvyNode parent, String parentConf, Collection confs) { - requiredConfs.put(new NodeConf(parent, parentConf), new HashSet(confs)); + requiredConfs.put(new NodeConf(parent, parentConf), new HashSet<>(confs)); } /** @@ -157,7 +157,7 @@ protected Set getConfigurations(String rootModuleConf) { protected Set addAndGetConfigurations(String rootModuleConf) { Set depConfs = rootModuleConfs.get(rootModuleConf); if (depConfs == null) { - depConfs = new HashSet(); + depConfs = new HashSet<>(); rootModuleConfs.put(rootModuleConf, depConfs); } return depConfs; @@ -197,7 +197,7 @@ private void updateMapOfSetForKey(Map> from, Map> to, if (toupdate != null) { toupdate.addAll(set); } else { - to.put(key, new HashSet(set)); + to.put(key, new HashSet<>(set)); } } } @@ -205,7 +205,7 @@ private void updateMapOfSetForKey(Map> from, Map> to, private void addObjectsForConf(K rootModuleConf, V objectToAdd, Map> map) { Set set = map.get(rootModuleConf); if (set == null) { - set = new HashSet(); + set = new HashSet<>(); map.put(rootModuleConf, set); } set.add(objectToAdd); @@ -224,7 +224,7 @@ protected Set getDependencyArtifactsSet(String roo if (dependersInConf == null) { return null; } - Set dependencyArtifacts = new HashSet(); + Set dependencyArtifacts = new HashSet<>(); for (Depender depender : dependersInConf) { DependencyArtifactDescriptor[] dads = depender.dd .getDependencyArtifacts(depender.dependerConf); @@ -238,7 +238,7 @@ protected Set getDependencyIncludesSet(String rootModuleConf) { if (dependersInConf == null) { return null; } - Set dependencyIncludes = new HashSet(); + Set dependencyIncludes = new HashSet<>(); for (Depender depender : dependersInConf) { IncludeRule[] rules = depender.dd.getIncludeRules(depender.dependerConf); if (rules == null || rules.length == 0) { diff --git a/src/java/org/apache/ivy/core/resolve/ResolveData.java b/src/java/org/apache/ivy/core/resolve/ResolveData.java index 74221f052..920e97dcb 100644 --- a/src/java/org/apache/ivy/core/resolve/ResolveData.java +++ b/src/java/org/apache/ivy/core/resolve/ResolveData.java @@ -82,7 +82,7 @@ public IvyNode getNode(ModuleRevisionId mrid) { } public Collection getNodes() { - Collection nodes = new ArrayList(); + Collection nodes = new ArrayList<>(); for (VisitData vdata : visitData.values()) { nodes.add(vdata.getNode()); } @@ -142,19 +142,7 @@ private static boolean isSubMap(Map map1, Map map2) { } private static boolean isEqual(Object obj1, Object obj2) { - if (obj1 == obj2) { - return true; - } - - if (obj1 == null) { - return obj2 == null; - } - - if (obj2 == null) { - return obj1 == null; - } - - return obj1.equals(obj2); + return obj1 == obj2 || obj1 != null && obj2 != null && obj1.equals(obj2); } /** @@ -256,11 +244,10 @@ public ResolveEngine getEngine() { } void blacklist(IvyNode node) { - for (Iterator> iter = visitData.entrySet().iterator(); iter - .hasNext();) { + Iterator> iter = visitData.entrySet().iterator(); + while (iter.hasNext()) { Entry entry = iter.next(); - VisitData vdata = entry.getValue(); - if (vdata.getNode() == node && !node.getResolvedId().equals(entry.getKey())) { + if (entry.getValue().getNode() == node && !node.getResolvedId().equals(entry.getKey())) { // this visit data was associated with the blacklisted node, // we discard this association iter.remove(); @@ -271,22 +258,22 @@ void blacklist(IvyNode node) { public boolean isBlacklisted(String rootModuleConf, ModuleRevisionId mrid) { IvyNode node = getNode(mrid); - // if (node == null) { - // // search again, now ignore the extra attributes - // // TODO: maybe we should search the node that has at least the - // // same attributes as mrid - // for (Iterator it = visitData.entrySet().iterator(); it.hasNext();) { - // Map.Entry entry = (Entry) it.next(); - // ModuleRevisionId current = (ModuleRevisionId) entry.getKey(); - // if (current.getModuleId().equals(mrid.getModuleId()) - // && current.getRevision().equals(mrid.getRevision())) { - // VisitData data = (VisitData) entry.getValue(); - // node = data.getNode(); - // break; - // } - // } - // } - // + /* + if (node == null) { + // search again, now ignore the extra attributes + // TODO: maybe we should search the node that has at least the same attributes as mrid + for (Entry entry : visitData.entrySet()) { + ModuleRevisionId current = entry.getKey(); + if (current.getModuleId().equals(mrid.getModuleId()) + && current.getRevision().equals(mrid.getRevision())) { + VisitData data = entry.getValue(); + node = data.getNode(); + break; + } + } + } + */ + return node != null && node.isBlacklisted(rootModuleConf); } @@ -297,7 +284,7 @@ public DependencyDescriptor mediate(DependencyDescriptor dd) { VisitNode current = getCurrentVisitNode(); if (current != null) { // mediating dd through dependers stack - List dependers = new ArrayList(current.getPath()); + List dependers = new ArrayList<>(current.getPath()); // the returned path contains the currently visited node, we are only interested in // the dependers, so we remove the currently visited node from the end dependers.remove(dependers.size() - 1); diff --git a/src/java/org/apache/ivy/core/resolve/ResolveEngine.java b/src/java/org/apache/ivy/core/resolve/ResolveEngine.java index 425842470..3d538aee8 100644 --- a/src/java/org/apache/ivy/core/resolve/ResolveEngine.java +++ b/src/java/org/apache/ivy/core/resolve/ResolveEngine.java @@ -86,7 +86,7 @@ public class ResolveEngine { private SortEngine sortEngine; - private Set fetchedSet = new HashSet(); + private Set fetchedSet = new HashSet<>(); private DependencyResolver dictatorResolver; @@ -267,47 +267,47 @@ public ResolveReport resolve(ModuleDescriptor md, ResolveOptions options) .getResolvedModuleRevisionId()); Properties props = new Properties(); if (dependencies.length > 0) { - Map forcedRevisions = new HashMap(); - for (int i = 0; i < dependencies.length; i++) { - if (dependencies[i].getModuleRevision() != null - && dependencies[i].getModuleRevision().isForce()) { - forcedRevisions.put(dependencies[i].getModuleId(), - dependencies[i].getResolvedId()); + Map forcedRevisions = new HashMap<>(); + for (IvyNode dependency : dependencies) { + if (dependency.getModuleRevision() != null + && dependency.getModuleRevision().isForce()) { + forcedRevisions.put(dependency.getModuleId(), + dependency.getResolvedId()); } } IvyNode root = dependencies[0].getRoot(); - Map topLevelDeps = new HashMap(); - for (int i = 0; i < dependencies.length; i++) { - if (!dependencies[i].hasProblem()) { - DependencyDescriptor dd = dependencies[i].getDependencyDescriptor(root); + Map topLevelDeps = new HashMap<>(); + for (IvyNode dependency : dependencies) { + if (!dependency.hasProblem()) { + DependencyDescriptor dd = dependency.getDependencyDescriptor(root); if (dd != null) { - ModuleId orgMod = dependencies[i].getModuleId(); - topLevelDeps.put(orgMod, dependencies[i]); + ModuleId orgMod = dependency.getModuleId(); + topLevelDeps.put(orgMod, dependency); } } } - for (int i = 0; i < dependencies.length; i++) { - if (!dependencies[i].hasProblem() && !dependencies[i].isCompletelyEvicted()) { - DependencyDescriptor dd = dependencies[i].getDependencyDescriptor(root); + for (IvyNode dependency : dependencies) { + if (!dependency.hasProblem() && !dependency.isCompletelyEvicted()) { + DependencyDescriptor dd = dependency.getDependencyDescriptor(root); if (dd == null) { - ModuleId mid = dependencies[i].getModuleId(); + ModuleId mid = dependency.getModuleId(); IvyNode tlDep = topLevelDeps.get(mid); if (tlDep != null) { dd = tlDep.getDependencyDescriptor(root); } } if (dd != null) { - ModuleRevisionId depResolvedId = dependencies[i].getResolvedId(); - ModuleDescriptor depDescriptor = dependencies[i].getDescriptor(); + ModuleRevisionId depResolvedId = dependency.getResolvedId(); + ModuleDescriptor depDescriptor = dependency.getDescriptor(); ModuleRevisionId depRevisionId = dd.getDependencyRevisionId(); - ModuleRevisionId forcedRevisionId = forcedRevisions.get(dependencies[i] + ModuleRevisionId forcedRevisionId = forcedRevisions.get(dependency .getModuleId()); - if (dependencies[i].getModuleRevision() != null - && dependencies[i].getModuleRevision().isForce() + if (dependency.getModuleRevision() != null + && dependency.getModuleRevision().isForce() && !depResolvedId.equals(depRevisionId) && !settings.getVersionMatcher().isDynamic(depRevisionId)) { // if we were forced to this revision and we @@ -319,7 +319,7 @@ public ResolveReport resolve(ModuleDescriptor md, ResolveOptions options) if (depResolvedId == null) { throw new NullPointerException("getResolvedId() is null for " - + dependencies[i].toString()); + + dependency.toString()); } if (depRevisionId == null) { throw new NullPointerException("getDependencyRevisionId() " @@ -391,49 +391,45 @@ public void outputReport(ResolveReport report, ResolutionCacheManager cacheMgr, public void downloadArtifacts(ResolveReport report, Filter artifactFilter, DownloadOptions options) { long start = System.currentTimeMillis(); - IvyNode[] dependencies = report.getDependencies().toArray( - new IvyNode[report.getDependencies().size()]); eventManager.fireIvyEvent(new PrepareDownloadEvent(report.getArtifacts().toArray( new Artifact[report.getArtifacts().size()]))); long totalSize = 0; - for (int i = 0; i < dependencies.length; i++) { + for (IvyNode dependency : report.getDependencies()) { checkInterrupted(); // download artifacts required in all asked configurations - if (!dependencies[i].isCompletelyEvicted() && !dependencies[i].hasProblem() - && dependencies[i].getModuleRevision() != null) { - DependencyResolver resolver = dependencies[i].getModuleRevision() + if (!dependency.isCompletelyEvicted() && !dependency.hasProblem() + && dependency.getModuleRevision() != null) { + DependencyResolver resolver = dependency.getModuleRevision() .getArtifactResolver(); - Artifact[] selectedArtifacts = dependencies[i].getSelectedArtifacts(artifactFilter); + Artifact[] selectedArtifacts = dependency.getSelectedArtifacts(artifactFilter); DownloadReport dReport = resolver.download(selectedArtifacts, options); - ArtifactDownloadReport[] adrs = dReport.getArtifactsReports(); - for (int j = 0; j < adrs.length; j++) { - if (adrs[j].getDownloadStatus() == DownloadStatus.FAILED) { - if (adrs[j].getArtifact().getExtraAttribute("ivy:merged") != null) { - Message.warn("\tmerged artifact not found: " + adrs[j].getArtifact() + for (ArtifactDownloadReport adr : dReport.getArtifactsReports()) { + if (adr.getDownloadStatus() == DownloadStatus.FAILED) { + if (adr.getArtifact().getExtraAttribute("ivy:merged") != null) { + Message.warn("\tmerged artifact not found: " + adr.getArtifact() + ". It was required in " - + adrs[j].getArtifact().getExtraAttribute("ivy:merged")); + + adr.getArtifact().getExtraAttribute("ivy:merged")); } else { - Message.warn("\t" + adrs[j]); - resolver.reportFailure(adrs[j].getArtifact()); + Message.warn("\t" + adr); + resolver.reportFailure(adr.getArtifact()); } - } else if (adrs[j].getDownloadStatus() == DownloadStatus.SUCCESSFUL) { - totalSize += adrs[j].getSize(); + } else if (adr.getDownloadStatus() == DownloadStatus.SUCCESSFUL) { + totalSize += adr.getSize(); } } // update concerned reports - String[] dconfs = dependencies[i].getRootModuleConfigurations(); - for (int j = 0; j < dconfs.length; j++) { + for (String dconf : dependency.getRootModuleConfigurations()) { // the report itself is responsible to take into account only // artifacts required in its corresponding configuration // (as described by the Dependency object) - if (dependencies[i].isEvicted(dconfs[j]) - || dependencies[i].isBlacklisted(dconfs[j])) { - report.getConfigurationReport(dconfs[j]).addDependency(dependencies[i]); + if (dependency.isEvicted(dconf) + || dependency.isBlacklisted(dconf)) { + report.getConfigurationReport(dconf).addDependency(dependency); } else { - report.getConfigurationReport(dconfs[j]).addDependency(dependencies[i], - dReport); + report.getConfigurationReport(dconf).addDependency(dependency, + dReport); } } } @@ -554,15 +550,15 @@ public IvyNode[] getDependencies(ModuleDescriptor md, ResolveOptions options, throw new NullPointerException("module descriptor must not be null"); } String[] confs = options.getConfs(md); - Collection missingConfs = new ArrayList(); - for (int i = 0; i < confs.length; i++) { - if (confs[i] == null) { + Collection missingConfs = new ArrayList<>(); + for (String conf : confs) { + if (conf == null) { throw new NullPointerException("null conf not allowed: confs where: " + Arrays.asList(confs)); } - if (md.getConfiguration(confs[i]) == null) { - missingConfs.add(" '" + confs[i] + "' "); + if (md.getConfiguration(conf) == null) { + missingConfs.add(" '" + conf + "' "); } } if (!missingConfs.isEmpty()) { @@ -583,33 +579,33 @@ public IvyNode[] getDependencies(ModuleDescriptor md, ResolveOptions options, } IvyNode rootNode = new IvyNode(data, md); - for (int i = 0; i < confs.length; i++) { - Message.verbose("resolving dependencies for configuration '" + confs[i] + "'"); + for (String conf : confs) { + Message.verbose("resolving dependencies for configuration '" + conf + "'"); // for each configuration we clear the cache of what's been fetched fetchedSet.clear(); ConfigurationResolveReport confReport = null; if (report != null) { - confReport = report.getConfigurationReport(confs[i]); + confReport = report.getConfigurationReport(conf); if (confReport == null) { - confReport = new ConfigurationResolveReport(this, md, confs[i], reportDate, + confReport = new ConfigurationResolveReport(this, md, conf, reportDate, options); - report.addReport(confs[i], confReport); + report.addReport(conf, confReport); } } // we reuse the same resolve data with a new report for each conf data.setReport(confReport); // update the root module conf we are about to fetch - VisitNode root = new VisitNode(data, rootNode, null, confs[i], null); - root.setRequestedConf(confs[i]); - rootNode.updateConfsToFetch(Collections.singleton(confs[i])); + VisitNode root = new VisitNode(data, rootNode, null, conf, null); + root.setRequestedConf(conf); + rootNode.updateConfsToFetch(Collections.singleton(conf)); // go fetch ! boolean fetched = false; while (!fetched) { try { - fetchDependencies(root, confs[i], false); + fetchDependencies(root, conf, false); fetched = true; } catch (RestartResolveProcess restart) { Message.verbose("===================================================="); @@ -629,7 +625,7 @@ public IvyNode[] getDependencies(ModuleDescriptor md, ResolveOptions options, // prune and reverse sort fetched dependencies Collection nodes = data.getNodes(); // use a Set to avoid duplicates, linked to preserve order - Collection dependencies = new LinkedHashSet(nodes.size()); + Collection dependencies = new LinkedHashSet<>(nodes.size()); for (IvyNode node : nodes) { if (node != null && !node.isRoot() && !node.isCompletelyBlacklisted()) { dependencies.add(node); @@ -655,26 +651,26 @@ private void handleTransitiveEviction(ModuleDescriptor md, String[] confs, Resol // can traverse the list and check only the direct parent and not all the ancestors for (IvyNode node : sortedDependencies) { if (!node.isCompletelyEvicted()) { - for (int i = 0; i < confs.length; i++) { - IvyNodeCallers.Caller[] callers = node.getCallers(confs[i]); + for (String conf : confs) { + IvyNodeCallers.Caller[] callers = node.getCallers(conf); if (settings.debugConflictResolution()) { Message.debug("checking if " + node.getId() - + " is transitively evicted in " + confs[i]); + + " is transitively evicted in " + conf); } boolean allEvicted = callers.length > 0; - for (int j = 0; j < callers.length; j++) { - if (callers[j].getModuleRevisionId().equals(md.getModuleRevisionId())) { + for (IvyNodeCallers.Caller caller : callers) { + if (caller.getModuleRevisionId().equals(md.getModuleRevisionId())) { // the caller is the root module itself, it can't be evicted allEvicted = false; break; } else { - IvyNode callerNode = data.getNode(callers[j].getModuleRevisionId()); + IvyNode callerNode = data.getNode(caller.getModuleRevisionId()); if (callerNode == null) { Message.warn("ivy internal error: no node found for " - + callers[j].getModuleRevisionId() + ": looked in " + + caller.getModuleRevisionId() + ": looked in " + data.getNodeIds() + " and root module id was " + md.getModuleRevisionId()); - } else if (!callerNode.isEvicted(confs[i])) { + } else if (!callerNode.isEvicted(conf)) { allEvicted = false; break; } else { @@ -687,7 +683,7 @@ private void handleTransitiveEviction(ModuleDescriptor md, String[] confs, Resol } if (allEvicted) { Message.verbose("all callers are evicted for " + node + ": evicting too"); - node.markEvicted(confs[i], null, null, null); + node.markEvicted(conf, null, null, null); } else { if (settings.debugConflictResolution()) { Message.debug(node.getId() @@ -715,9 +711,8 @@ private void fetchDependencies(VisitNode node, String conf, boolean shouldBePubl data.setCurrentVisitNode(node); DependencyDescriptor dd = node.getDependencyDescriptor(); VersionMatcher versionMatcher = node.getNode().getData().getSettings().getVersionMatcher(); - if (dd != null - && !(node.getRoot() == node.getParent() && versionMatcher.isDynamic(dd - .getDependencyRevisionId()))) { + if (dd != null && !(node.getRoot() == node.getParent() + && versionMatcher.isDynamic(dd.getDependencyRevisionId()))) { /* * we don't resolve conflicts before loading data for direct dependencies on dynamic * revisions, so that direct dynamic revisions are always resolved, which is mandatory @@ -732,18 +727,16 @@ private void fetchDependencies(VisitNode node, String conf, boolean shouldBePubl // dependency to take the decision resolveConflict(node, conf); if (!node.isEvicted() && !node.isCircular()) { - String[] confs = node.getRealConfs(conf); - for (int i = 0; i < confs.length; i++) { - doFetchDependencies(node, confs[i]); + for (String rconf : node.getRealConfs(conf)) { + doFetchDependencies(node, rconf); } } } else if (!node.hasProblem()) { // the node has not been loaded but hasn't problem: it was already loaded // => we just have to update its dependencies data if (!node.isEvicted() && !node.isCircular()) { - String[] confs = node.getRealConfs(conf); - for (int i = 0; i < confs.length; i++) { - doFetchDependencies(node, confs[i]); + for (String rconf : node.getRealConfs(conf)) { + doFetchDependencies(node, rconf); } } } @@ -797,31 +790,28 @@ private void doFetchDependencies(VisitNode node, String conf) { if (extendedConfs.length > 0) { node.updateConfsToFetch(Arrays.asList(extendedConfs)); } - for (int i = 0; i < extendedConfs.length; i++) { - fetchDependencies(node, extendedConfs[i], false); + for (String extendedConf : extendedConfs) { + fetchDependencies(node, extendedConf, false); } // now we can actually resolve this configuration dependencies if (!isDependenciesFetched(node.getNode(), conf) && node.isTransitive()) { - Collection dependencies = node.getDependencies(conf); - for (VisitNode dep : dependencies) { + for (VisitNode dep : node.getDependencies(conf)) { dep.useRealNode(); // the node may have been resolved to another real one while // resolving other deps - String[] confs = dep.getRequiredConfigurations(node, conf); - for (int i = 0; i < confs.length; i++) { - fetchDependencies(dep, confs[i], true); + for (String rconf : dep.getRequiredConfigurations(node, conf)) { + fetchDependencies(dep, rconf, true); } if (!dep.isEvicted() && !dep.hasProblem()) { // if there are still confs to fetch (usually because they have // been updated when evicting another module), we fetch them now - confs = dep.getConfsToFetch(); - for (int i = 0; i < confs.length; i++) { + for (String fconf : dep.getConfsToFetch()) { // shouldBeFixed=false to because some of those dependencies might // be private when they were actually extending public conf. // Should we keep two list of confs to fetch (private&public)? // I don't think, visibility is already checked, and a change in the // configuration between version might anyway have worse problems. - fetchDependencies(dep, confs[i], false); + fetchDependencies(dep, fconf, false); } } } @@ -982,8 +972,8 @@ private boolean resolveConflict(VisitNode node, VisitNode ancestor, String conf, ancestor.getNode().setResolvedNodes(node.getModuleId(), node.getRootModuleConf(), resolved); - Collection evicted = new HashSet(ancestor.getNode().getEvictedNodes( - node.getModuleId(), node.getRootModuleConf())); + Collection evicted = new HashSet<>(ancestor.getNode().getEvictedNodes( + node.getModuleId(), node.getRootModuleConf())); evicted.removeAll(resolved); evicted.addAll(toevict); ancestor.getNode().setEvictedNodes(node.getModuleId(), node.getRootModuleConf(), @@ -1003,8 +993,8 @@ private boolean resolveConflict(VisitNode node, VisitNode ancestor, String conf, // it's time to update parent resolved and evicted with what was found - Collection evicted = new HashSet(ancestor.getNode().getEvictedNodes( - node.getModuleId(), node.getRootModuleConf())); + Collection evicted = new HashSet<>(ancestor.getNode().getEvictedNodes( + node.getModuleId(), node.getRootModuleConf())); toevict.removeAll(resolved); evicted.removeAll(resolved); evicted.addAll(toevict); @@ -1091,7 +1081,7 @@ private Collection resolveConflicts(VisitNode node, VisitNode ancestor, */ private Collection computeConflicts(VisitNode node, VisitNode ancestor, String conf, Collection toevict, Collection selectedNodes) { - Collection conflicts = new LinkedHashSet(); + Collection conflicts = new LinkedHashSet<>(); conflicts.add(node.getNode()); /* * We first try to remove all evicted nodes from the collection of selected nodes to update diff --git a/src/java/org/apache/ivy/core/resolve/ResolveOptions.java b/src/java/org/apache/ivy/core/resolve/ResolveOptions.java index b434c05ec..77c5ee15d 100644 --- a/src/java/org/apache/ivy/core/resolve/ResolveOptions.java +++ b/src/java/org/apache/ivy/core/resolve/ResolveOptions.java @@ -175,12 +175,7 @@ public ResolveOptions setResolveMode(String resolveMode) { * @see #getConfs(ModuleDescriptor) */ public boolean useSpecialConfs() { - for (int i = 0; confs != null && i < confs.length; i++) { - if (confs[0].startsWith("*")) { - return true; - } - } - return false; + return confs != null && confs[0].startsWith("*"); } /** diff --git a/src/java/org/apache/ivy/core/resolve/VisitData.java b/src/java/org/apache/ivy/core/resolve/VisitData.java index 3beb8770e..fa668582f 100644 --- a/src/java/org/apache/ivy/core/resolve/VisitData.java +++ b/src/java/org/apache/ivy/core/resolve/VisitData.java @@ -38,7 +38,7 @@ public class VisitData { * The associated visit nodes, per rootModuleConf Note that the value is a List, because a node * can be visited from several parents during the resolution process */ - private Map> visitNodes = new HashMap>(); + private Map> visitNodes = new HashMap<>(); public VisitData(IvyNode node) { this.node = node; @@ -52,7 +52,7 @@ public void addVisitNode(VisitNode node) { public List getVisitNodes(String rootModuleConf) { List visits = visitNodes.get(rootModuleConf); if (visits == null) { - visits = new ArrayList(); + visits = new ArrayList<>(); visitNodes.put(rootModuleConf, visits); } return visits; diff --git a/src/java/org/apache/ivy/core/resolve/VisitNode.java b/src/java/org/apache/ivy/core/resolve/VisitNode.java index b5171b967..39497f1fe 100644 --- a/src/java/org/apache/ivy/core/resolve/VisitNode.java +++ b/src/java/org/apache/ivy/core/resolve/VisitNode.java @@ -164,7 +164,7 @@ public Collection getPath() { private Collection computePath() { if (parent != null) { - Collection p = new LinkedHashSet(parent.getPath()); + Collection p = new LinkedHashSet<>(parent.getPath()); p.add(this); return p; } else { @@ -196,7 +196,7 @@ public String getRootModuleConf() { public static VisitNode getRoot(VisitNode parent) { VisitNode root = parent; - Collection path = new HashSet(); + Collection path = new HashSet<>(); path.add(root); while (root.getParent() != null && !root.getNode().isRoot()) { if (path.contains(root.getParent())) { @@ -303,7 +303,7 @@ public boolean loadData(String conf, boolean shouldBePublic) { public Collection getDependencies(String conf) { Collection deps = node.getDependencies(rootModuleConf, conf, requestedConf); - Collection ret = new ArrayList(deps.size()); + Collection ret = new ArrayList<>(deps.size()); for (IvyNode depNode : deps) { ret.add(traverseChild(conf, depNode)); } diff --git a/src/java/org/apache/ivy/core/retrieve/RetrieveEngine.java b/src/java/org/apache/ivy/core/retrieve/RetrieveEngine.java index 4822e8973..022d3a800 100644 --- a/src/java/org/apache/ivy/core/retrieve/RetrieveEngine.java +++ b/src/java/org/apache/ivy/core/retrieve/RetrieveEngine.java @@ -128,15 +128,15 @@ public RetrieveReport retrieve(ModuleRevisionId mrid, RetrieveOptions options) report.setRetrieveRoot(fileRetrieveRoot); File ivyRetrieveRoot = destIvyPattern == null ? null : settings .resolveFile(IvyPatternHelper.getTokenRoot(destIvyPattern)); - Collection targetArtifactsStructure = new HashSet(); + Collection targetArtifactsStructure = new HashSet<>(); // Set(File) set of all paths which should be present at then end of retrieve (useful // for sync) - Collection targetIvysStructure = new HashSet(); // same for ivy files + Collection targetIvysStructure = new HashSet<>(); // same for ivy files if (options.isMakeSymlinksInMass()) { // The HashMap is of "destToSrc" because src could go two places, but dest can only // come from one - destToSrcMap = new HashMap(); + destToSrcMap = new HashMap<>(); } // do retrieve @@ -217,15 +217,13 @@ public RetrieveReport retrieve(ModuleRevisionId mrid, RetrieveOptions options) Collection ignoreList = Arrays.asList(ignorableFilenames); Collection existingArtifacts = FileUtil.listAll(fileRetrieveRoot, ignoreList); - Collection existingIvys = ivyRetrieveRoot == null ? null : FileUtil.listAll( + Collection existingIvys = (ivyRetrieveRoot == null) ? null : FileUtil.listAll( ivyRetrieveRoot, ignoreList); if (fileRetrieveRoot.equals(ivyRetrieveRoot)) { - Collection target = targetArtifactsStructure; - target.addAll(targetIvysStructure); - Collection existing = existingArtifacts; - existing.addAll(existingIvys); - sync(target, existing); + targetArtifactsStructure.addAll(targetIvysStructure); + existingArtifacts.addAll(existingIvys); + sync(targetArtifactsStructure, existingArtifacts); } else { sync(targetArtifactsStructure, existingArtifacts); if (existingIvys != null) { @@ -269,9 +267,7 @@ private String[] getConfs(ModuleRevisionId mrid, RetrieveOptions options) throws } catch (IOException e) { throw e; } catch (Exception e) { - IOException ioex = new IOException(e.getMessage()); - ioex.initCause(e); - throw ioex; + throw new IOException(e.getMessage(), e); } } return confs; @@ -282,7 +278,7 @@ private ResolutionCacheManager getCache() { } private void sync(Collection target, Collection existing) { - Collection toRemove = new HashSet(); + Collection toRemove = new HashSet<>(); for (File file : existing) { toRemove.add(file.getAbsoluteFile()); } @@ -313,28 +309,25 @@ public Map> determineArtifactsToCopy(ModuleR // find what we must retrieve where // ArtifactDownloadReport source -> Set (String copyDestAbsolutePath) - final Map> artifactsToCopy = new HashMap>(); + final Map> artifactsToCopy = new HashMap<>(); // String copyDestAbsolutePath -> Set (ArtifactRevisionId source) - final Map> conflictsMap = new HashMap>(); + final Map> conflictsMap = new HashMap<>(); // String copyDestAbsolutePath -> Set (ArtifactDownloadReport source) - final Map> conflictsReportsMap = new HashMap>(); + final Map> conflictsReportsMap = new HashMap<>(); // String copyDestAbsolutePath -> Set (String conf) - final Map> conflictsConfMap = new HashMap>(); + final Map> conflictsConfMap = new HashMap<>(); XmlReportParser parser = new XmlReportParser(); - for (int i = 0; i < confs.length; i++) { - final String conf = confs[i]; - + for (final String conf : confs) { File report = cacheManager.getConfigurationResolveReportInCache(options.getResolveId(), conf); parser.parse(report); - Collection artifacts = new ArrayList( + Collection artifacts = new ArrayList<>( Arrays.asList(parser.getArtifactReports())); if (destIvyPattern != null) { - ModuleRevisionId[] mrids = parser.getRealDependencyRevisionIds(); - for (int j = 0; j < mrids.length; j++) { - artifacts.add(parser.getMetadataArtifactReport(mrids[j])); + for (ModuleRevisionId rmrid : parser.getRealDependencyRevisionIds()) { + artifacts.add(parser.getMetadataArtifactReport(rmrid)); } } final PackagingManager packagingManager = new PackagingManager(); @@ -377,7 +370,7 @@ public Map> determineArtifactsToCopy(ModuleR artifact.getQualifiedExtraAttributes()); Set dest = artifactsToCopy.get(adr); if (dest == null) { - dest = new HashSet(); + dest = new HashSet<>(); artifactsToCopy.put(adr, dest); } String copyDest = settings.resolveFile(destFileName).getAbsolutePath(); @@ -387,24 +380,24 @@ public Map> determineArtifactsToCopy(ModuleR destinations = options.getMapper().mapFileName(copyDest); } - for (int j = 0; j < destinations.length; j++) { - dest.add(destinations[j]); + for (String destination : destinations) { + dest.add(destination); - Set conflicts = conflictsMap.get(destinations[j]); + Set conflicts = conflictsMap.get(destination); Set conflictsReports = conflictsReportsMap - .get(destinations[j]); - Set conflictsConf = conflictsConfMap.get(destinations[j]); + .get(destination); + Set conflictsConf = conflictsConfMap.get(destination); if (conflicts == null) { - conflicts = new HashSet(); - conflictsMap.put(destinations[j], conflicts); + conflicts = new HashSet<>(); + conflictsMap.put(destination, conflicts); } if (conflictsReports == null) { - conflictsReports = new HashSet(); - conflictsReportsMap.put(destinations[j], conflictsReports); + conflictsReports = new HashSet<>(); + conflictsReportsMap.put(destination, conflictsReports); } if (conflictsConf == null) { - conflictsConf = new HashSet(); - conflictsConfMap.put(destinations[j], conflictsConf); + conflictsConf = new HashSet<>(); + conflictsConfMap.put(destination, conflictsConf); } if (conflicts.add(artifact.getId())) { conflictsReports.add(adr); @@ -420,7 +413,7 @@ public Map> determineArtifactsToCopy(ModuleR Set artifacts = entry.getValue(); Set conflictsConfs = conflictsConfMap.get(copyDest); if (artifacts.size() > 1) { - List artifactsList = new ArrayList( + List artifactsList = new ArrayList<>( conflictsReportsMap.get(copyDest)); // conflicts battle is resolved by a sort using a conflict resolving policy // comparator which consider as greater a winning artifact diff --git a/src/java/org/apache/ivy/core/retrieve/RetrieveOptions.java b/src/java/org/apache/ivy/core/retrieve/RetrieveOptions.java index 7f27d5684..6fa23994d 100644 --- a/src/java/org/apache/ivy/core/retrieve/RetrieveOptions.java +++ b/src/java/org/apache/ivy/core/retrieve/RetrieveOptions.java @@ -18,6 +18,7 @@ package org.apache.ivy.core.retrieve; import org.apache.ivy.core.LogOptions; +import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.util.filter.Filter; import org.apache.ivy.util.filter.FilterHelper; @@ -55,7 +56,7 @@ public class RetrieveOptions extends LogOptions { /** * The filter to apply before retrieving artifacts. */ - private Filter artifactFilter = FilterHelper.NO_FILTER; + private Filter artifactFilter = FilterHelper.NO_FILTER; /** * True if a synchronisation of the destination directory should be done, false if a simple copy @@ -117,11 +118,11 @@ public RetrieveOptions setDestArtifactPattern(String destArtifactPattern) { return this; } - public Filter getArtifactFilter() { + public Filter getArtifactFilter() { return artifactFilter; } - public RetrieveOptions setArtifactFilter(Filter artifactFilter) { + public RetrieveOptions setArtifactFilter(Filter artifactFilter) { this.artifactFilter = artifactFilter; return this; } diff --git a/src/java/org/apache/ivy/core/retrieve/RetrieveReport.java b/src/java/org/apache/ivy/core/retrieve/RetrieveReport.java index 6dcb9fd56..256678c80 100644 --- a/src/java/org/apache/ivy/core/retrieve/RetrieveReport.java +++ b/src/java/org/apache/ivy/core/retrieve/RetrieveReport.java @@ -28,11 +28,11 @@ public class RetrieveReport { - private Collection upToDateFiles = new HashSet(); + private Collection upToDateFiles = new HashSet<>(); - private Collection copiedFiles = new HashSet(); + private Collection copiedFiles = new HashSet<>(); - private Map downloadReport = new HashMap(); + private Map downloadReport = new HashMap<>(); private File retrieveRoot; @@ -74,7 +74,7 @@ public void addUpToDateFile(File file, ArtifactDownloadReport report) { * @return Collection<File> */ public Collection getCopiedFiles() { - return new ArrayList(copiedFiles); + return new ArrayList<>(copiedFiles); } /** @@ -84,7 +84,7 @@ public Collection getCopiedFiles() { * @return Collection<File> */ public Collection getUpToDateFiles() { - return new ArrayList(upToDateFiles); + return new ArrayList<>(upToDateFiles); } /** @@ -94,7 +94,7 @@ public Collection getUpToDateFiles() { * @return Collection<File> */ public Collection getRetrievedFiles() { - Collection result = new ArrayList(upToDateFiles.size() + copiedFiles.size()); + Collection result = new ArrayList<>(upToDateFiles.size() + copiedFiles.size()); result.addAll(upToDateFiles); result.addAll(copiedFiles); return result; diff --git a/src/java/org/apache/ivy/core/search/SearchEngine.java b/src/java/org/apache/ivy/core/search/SearchEngine.java index 3fde2637c..9a508cd2a 100644 --- a/src/java/org/apache/ivy/core/search/SearchEngine.java +++ b/src/java/org/apache/ivy/core/search/SearchEngine.java @@ -57,13 +57,13 @@ public SearchEngine(IvySettings settings) { * @return String[] */ public String[] listTokenValues(String token, Map otherTokenValues) { - Set entries = new LinkedHashSet(); + Set entries = new LinkedHashSet<>(); for (DependencyResolver resolver : settings.getResolvers()) { Map[] values = resolver.listTokenValues(new String[] {token}, otherTokenValues); - for (int i = 0; i < values.length; i++) { - entries.add(values[i].get(token)); + for (Map value : values) { + entries.add(value.get(token)); } } @@ -71,13 +71,13 @@ public String[] listTokenValues(String token, Map otherTokenValu } public OrganisationEntry[] listOrganisationEntries() { - Set entries = new HashSet(); + Set entries = new HashSet<>(); for (DependencyResolver resolver : settings.getResolvers()) { Map[] orgs = resolver.listTokenValues( new String[] {IvyPatternHelper.ORGANISATION_KEY}, new HashMap()); - for (int i = 0; i < orgs.length; i++) { - String org = orgs[i].get(IvyPatternHelper.ORGANISATION_KEY); + for (Map oe : orgs) { + String org = oe.get(IvyPatternHelper.ORGANISATION_KEY); entries.add(new OrganisationEntry(resolver, org)); } } @@ -86,13 +86,13 @@ public OrganisationEntry[] listOrganisationEntries() { } public String[] listOrganisations() { - Set entries = new HashSet(); + Set entries = new HashSet<>(); for (DependencyResolver resolver : settings.getResolvers()) { Map[] orgs = resolver.listTokenValues( new String[] {IvyPatternHelper.ORGANISATION_KEY}, new HashMap()); - for (int i = 0; i < orgs.length; i++) { - entries.add(orgs[i].get(IvyPatternHelper.ORGANISATION_KEY)); + for (Map org : orgs) { + entries.add(org.get(IvyPatternHelper.ORGANISATION_KEY)); } } @@ -100,16 +100,16 @@ public String[] listOrganisations() { } public ModuleEntry[] listModuleEntries(OrganisationEntry org) { - Set entries = new HashSet(); + Set entries = new HashSet<>(); - Map tokenValues = new HashMap(); + Map tokenValues = new HashMap<>(); tokenValues.put(IvyPatternHelper.ORGANISATION_KEY, org.getOrganisation()); for (DependencyResolver resolver : settings.getResolvers()) { Map[] modules = resolver.listTokenValues( new String[] {IvyPatternHelper.MODULE_KEY}, tokenValues); - for (int i = 0; i < modules.length; i++) { - String module = modules[i].get(IvyPatternHelper.MODULE_KEY); + for (Map me : modules) { + String module = me.get(IvyPatternHelper.MODULE_KEY); entries.add(new ModuleEntry(org, module)); } } @@ -118,16 +118,16 @@ public ModuleEntry[] listModuleEntries(OrganisationEntry org) { } public String[] listModules(String org) { - Set entries = new HashSet(); + Set entries = new HashSet<>(); - Map tokenValues = new HashMap(); + Map tokenValues = new HashMap<>(); tokenValues.put(IvyPatternHelper.ORGANISATION_KEY, org); for (DependencyResolver resolver : settings.getResolvers()) { Map[] modules = resolver.listTokenValues( new String[] {IvyPatternHelper.MODULE_KEY}, tokenValues); - for (int i = 0; i < modules.length; i++) { - entries.add(modules[i].get(IvyPatternHelper.MODULE_KEY)); + for (Map module : modules) { + entries.add(module.get(IvyPatternHelper.MODULE_KEY)); } } @@ -135,18 +135,17 @@ public String[] listModules(String org) { } public RevisionEntry[] listRevisionEntries(ModuleEntry module) { - Set entries = new HashSet(); + Set entries = new HashSet<>(); - Map tokenValues = new HashMap(); + Map tokenValues = new HashMap<>(); tokenValues.put(IvyPatternHelper.ORGANISATION_KEY, module.getOrganisation()); tokenValues.put(IvyPatternHelper.MODULE_KEY, module.getModule()); for (DependencyResolver resolver : settings.getResolvers()) { Map[] revisions = resolver.listTokenValues( new String[] {IvyPatternHelper.REVISION_KEY}, tokenValues); - for (int i = 0; i < revisions.length; i++) { - String revision = revisions[i].get(IvyPatternHelper.REVISION_KEY); - entries.add(new RevisionEntry(module, revision)); + for (Map revision : revisions) { + entries.add(new RevisionEntry(module, revision.get(IvyPatternHelper.REVISION_KEY))); } } @@ -154,17 +153,17 @@ public RevisionEntry[] listRevisionEntries(ModuleEntry module) { } public String[] listRevisions(String org, String module) { - Set entries = new HashSet(); + Set entries = new HashSet<>(); - Map tokenValues = new HashMap(); + Map tokenValues = new HashMap<>(); tokenValues.put(IvyPatternHelper.ORGANISATION_KEY, org); tokenValues.put(IvyPatternHelper.MODULE_KEY, module); for (DependencyResolver resolver : settings.getResolvers()) { Map[] revisions = resolver.listTokenValues( new String[] {IvyPatternHelper.REVISION_KEY}, tokenValues); - for (int i = 0; i < revisions.length; i++) { - entries.add(revisions[i].get(IvyPatternHelper.REVISION_KEY)); + for (Map revision : revisions) { + entries.add(revision.get(IvyPatternHelper.REVISION_KEY)); } } @@ -183,9 +182,9 @@ public String[] listRevisions(String org, String module) { * @return ModuleId[] */ public ModuleId[] listModules(ModuleId moduleCrit, PatternMatcher matcher) { - List ret = new ArrayList(); + List ret = new ArrayList<>(); - Map criteria = new HashMap(); + Map criteria = new HashMap<>(); addMatcher(matcher, moduleCrit.getOrganisation(), criteria, IvyPatternHelper.ORGANISATION_KEY); addMatcher(matcher, moduleCrit.getName(), criteria, IvyPatternHelper.MODULE_KEY); @@ -195,9 +194,9 @@ public ModuleId[] listModules(ModuleId moduleCrit, PatternMatcher matcher) { for (DependencyResolver resolver : settings.getResolvers()) { Map[] moduleIdAsMap = resolver.listTokenValues(tokensToList, criteria); - for (int i = 0; i < moduleIdAsMap.length; i++) { - String org = moduleIdAsMap[i].get(IvyPatternHelper.ORGANISATION_KEY); - String name = moduleIdAsMap[i].get(IvyPatternHelper.MODULE_KEY); + for (Map moduleId : moduleIdAsMap) { + String org = moduleId.get(IvyPatternHelper.ORGANISATION_KEY); + String name = moduleId.get(IvyPatternHelper.MODULE_KEY); ModuleId modId = ModuleId.newInstance(org, name); ret.add(NameSpaceHelper.transform(modId, resolver.getNamespace() .getToSystemTransformer())); @@ -219,9 +218,9 @@ public ModuleId[] listModules(ModuleId moduleCrit, PatternMatcher matcher) { * @return ModuleRevisionId[] */ public ModuleRevisionId[] listModules(ModuleRevisionId moduleCrit, PatternMatcher matcher) { - List ret = new ArrayList(); + List ret = new ArrayList<>(); - Map criteria = new HashMap(); + Map criteria = new HashMap<>(); for (Entry entry : moduleCrit.getAttributes().entrySet()) { addMatcher(matcher, entry.getValue(), criteria, entry.getKey()); } @@ -231,21 +230,20 @@ public ModuleRevisionId[] listModules(ModuleRevisionId moduleCrit, PatternMatche for (DependencyResolver resolver : settings.getResolvers()) { Map[] moduleIdAsMap = resolver.listTokenValues(tokensToList, criteria); - for (int i = 0; i < moduleIdAsMap.length; i++) { - String org = moduleIdAsMap[i].get(IvyPatternHelper.ORGANISATION_KEY); - String name = moduleIdAsMap[i].get(IvyPatternHelper.MODULE_KEY); - String branch = moduleIdAsMap[i].get(IvyPatternHelper.BRANCH_KEY); - String rev = moduleIdAsMap[i].get(IvyPatternHelper.REVISION_KEY); - - Map foundExtraAtts = new HashMap(); - Set qualAttributes = moduleCrit.getQualifiedExtraAttributes().keySet(); - for (String qualifiedKey : qualAttributes) { + for (Map moduleId : moduleIdAsMap) { + String org = moduleId.get(IvyPatternHelper.ORGANISATION_KEY); + String name = moduleId.get(IvyPatternHelper.MODULE_KEY); + String branch = moduleId.get(IvyPatternHelper.BRANCH_KEY); + String rev = moduleId.get(IvyPatternHelper.REVISION_KEY); + + Map foundExtraAtts = new HashMap<>(); + for (String qualifiedKey : moduleCrit.getQualifiedExtraAttributes().keySet()) { String value = null; int colonIndex = qualifiedKey.indexOf(':'); if (colonIndex == -1) { - value = moduleIdAsMap[i].get(qualifiedKey); + value = moduleId.get(qualifiedKey); } else { - value = moduleIdAsMap[i].get(qualifiedKey.substring(colonIndex + 1)); + value = moduleId.get(qualifiedKey.substring(colonIndex + 1)); } if (value != null) { @@ -278,7 +276,7 @@ public ModuleRevisionId[] listModules(ModuleRevisionId moduleCrit, PatternMatche */ public ModuleRevisionId[] listModules(DependencyResolver resolver, ModuleRevisionId moduleCrit, PatternMatcher matcher) { - Map criteria = new HashMap(); + Map criteria = new HashMap<>(); for (Entry entry : moduleCrit.getAttributes().entrySet()) { addMatcher(matcher, entry.getValue(), criteria, entry.getKey()); } @@ -287,23 +285,21 @@ public ModuleRevisionId[] listModules(DependencyResolver resolver, ModuleRevisio .toArray(new String[moduleCrit.getAttributes().size()]); Map[] moduleIdAsMap = resolver.listTokenValues(tokensToList, criteria); - Set result = new LinkedHashSet(); // we use a Set to - // remove duplicates - for (int i = 0; i < moduleIdAsMap.length; i++) { - String org = moduleIdAsMap[i].get(IvyPatternHelper.ORGANISATION_KEY); - String name = moduleIdAsMap[i].get(IvyPatternHelper.MODULE_KEY); - String branch = moduleIdAsMap[i].get(IvyPatternHelper.BRANCH_KEY); - String rev = moduleIdAsMap[i].get(IvyPatternHelper.REVISION_KEY); - - Map foundExtraAtts = new HashMap(); - Set qualExtraAttributes = moduleCrit.getQualifiedExtraAttributes().keySet(); - for (String qualifiedKey : qualExtraAttributes) { + Set result = new LinkedHashSet<>(); // we use a Set to remove duplicates + for (Map moduleId : moduleIdAsMap) { + String org = moduleId.get(IvyPatternHelper.ORGANISATION_KEY); + String name = moduleId.get(IvyPatternHelper.MODULE_KEY); + String branch = moduleId.get(IvyPatternHelper.BRANCH_KEY); + String rev = moduleId.get(IvyPatternHelper.REVISION_KEY); + + Map foundExtraAtts = new HashMap<>(); + for (String qualifiedKey : moduleCrit.getQualifiedExtraAttributes().keySet()) { String value = null; int colonIndex = qualifiedKey.indexOf(':'); if (colonIndex == -1) { - value = moduleIdAsMap[i].get(qualifiedKey); + value = moduleId.get(qualifiedKey); } else { - value = moduleIdAsMap[i].get(qualifiedKey.substring(colonIndex + 1)); + value = moduleId.get(qualifiedKey.substring(colonIndex + 1)); } if (value != null) { @@ -335,16 +331,16 @@ private void addMatcher(PatternMatcher patternMatcher, String expression, public Collection findModuleRevisionIds(DependencyResolver resolver, ModuleRevisionId pattern, PatternMatcher matcher) { - Collection mrids = new ArrayList(); + Collection mrids = new ArrayList<>(); String resolverName = resolver.getName(); Message.verbose("looking for modules matching " + pattern + " using " + matcher.getName()); Namespace fromNamespace = null; if (resolver instanceof AbstractResolver) { - fromNamespace = ((AbstractResolver) resolver).getNamespace(); + fromNamespace = resolver.getNamespace(); } - Collection modules = new ArrayList(); + Collection modules = new ArrayList<>(); OrganisationEntry[] orgs = resolver.listOrganisations(); if (orgs == null || orgs.length == 0) { @@ -358,13 +354,11 @@ public Collection findModuleRevisionIds(DependencyResolver res modules.addAll(Arrays.asList(resolver.listModules(new OrganisationEntry(resolver, org)))); } else { Matcher orgMatcher = matcher.getMatcher(pattern.getOrganisation()); - for (int i = 0; i < orgs.length; i++) { - String org = orgs[i].getOrganisation(); - String systemOrg = org; - if (fromNamespace != null) { - systemOrg = NameSpaceHelper.transformOrganisation(org, + for (OrganisationEntry oe : orgs) { + String org = oe.getOrganisation(); + String systemOrg = (fromNamespace == null) ? org + : NameSpaceHelper.transformOrganisation(org, fromNamespace.getToSystemTransformer()); - } if (orgMatcher.matches(systemOrg)) { modules.addAll(Arrays.asList(resolver.listModules(new OrganisationEntry( resolver, org)))); @@ -392,9 +386,7 @@ public Collection findModuleRevisionIds(DependencyResolver res + resolverName); boolean foundRevision = false; - for (int j = 0; j < rEntries.length; j++) { - RevisionEntry rEntry = rEntries[j]; - + for (RevisionEntry rEntry : rEntries) { ModuleRevisionId foundMrid = ModuleRevisionId.newInstance( mEntry.getOrganisation(), mEntry.getModule(), rEntry.getRevision()); ModuleRevisionId systemMrid = foundMrid; diff --git a/src/java/org/apache/ivy/core/settings/IvySettings.java b/src/java/org/apache/ivy/core/settings/IvySettings.java index 342079d97..adaa1886d 100644 --- a/src/java/org/apache/ivy/core/settings/IvySettings.java +++ b/src/java/org/apache/ivy/core/settings/IvySettings.java @@ -118,9 +118,9 @@ public class IvySettings implements SortEngineSettings, PublishEngineSettings, P ResolveEngineSettings, RetrieveEngineSettings, RepositoryManagementEngineSettings { private static final long INTERRUPT_TIMEOUT = 2000; - private Map> typeDefs = new HashMap>(); + private Map> typeDefs = new HashMap<>(); - private Map resolversMap = new HashMap(); + private Map resolversMap = new HashMap<>(); private DependencyResolver defaultResolver; @@ -134,29 +134,29 @@ public class IvySettings implements SortEngineSettings, PublishEngineSettings, P private boolean checkUpToDate = true; - private ModuleRules moduleSettings = new ModuleRules(); + private ModuleRules moduleSettings = new ModuleRules<>(); - private Map conflictsManager = new HashMap(); + private Map conflictsManager = new HashMap<>(); - private Map latestStrategies = new HashMap(); + private Map latestStrategies = new HashMap<>(); - private Map lockStrategies = new HashMap(); + private Map lockStrategies = new HashMap<>(); - private Map namespaces = new HashMap(); + private Map namespaces = new HashMap<>(); - private Map matchers = new HashMap(); + private Map matchers = new HashMap<>(); - private Map reportOutputters = new HashMap(); + private Map reportOutputters = new HashMap<>(); - private Map versionMatchers = new HashMap(); + private Map versionMatchers = new HashMap<>(); - private Map circularDependencyStrategies = new HashMap(); + private Map circularDependencyStrategies = new HashMap<>(); - private Map repositoryCacheManagers = new HashMap(); + private Map repositoryCacheManagers = new HashMap<>(); - private Map signatureGenerators = new HashMap(); + private Map signatureGenerators = new HashMap<>(); - private List triggers = new ArrayList(); + private List triggers = new ArrayList<>(); private IvyVariableContainer variableContainer = new IvyVariableContainerImpl(); @@ -174,7 +174,7 @@ public class IvySettings implements SortEngineSettings, PublishEngineSettings, P private ResolutionCacheManager resolutionCacheManager = null; - private List listingIgnore = new ArrayList(); + private List listingIgnore = new ArrayList<>(); private boolean repositoriesConfigured; @@ -184,7 +184,7 @@ public class IvySettings implements SortEngineSettings, PublishEngineSettings, P private File baseDir = new File(".").getAbsoluteFile(); - private List classpathURLs = new ArrayList(); + private List classpathURLs = new ArrayList<>(); private ClassLoader classloader; @@ -224,16 +224,14 @@ public IvySettings(IvyVariableContainer variableContainer) { String ivyTypeDefs = System.getProperty("ivy.typedef.files"); if (ivyTypeDefs != null) { - String[] files = ivyTypeDefs.split("\\,"); - for (int i = 0; i < files.length; i++) { + for (String file : ivyTypeDefs.split("\\,")) { try { - typeDefs( - new FileInputStream(Checks.checkAbsolute(files[i].trim(), + typeDefs(new FileInputStream(Checks.checkAbsolute(file.trim(), "ivy.typedef.files")), true); } catch (FileNotFoundException e) { - Message.warn("typedefs file not found: " + files[i].trim()); + Message.warn("typedefs file not found: " + file.trim()); } catch (IOException e) { - Message.warn("problem with typedef file: " + files[i].trim(), e); + Message.warn("problem with typedef file: " + file.trim(), e); } } } else { @@ -390,10 +388,8 @@ public synchronized void load(File settingsFile) throws ParseException, IOExcept try { new XmlSettingsParser(this).parse(settingsFile.toURI().toURL()); } catch (MalformedURLException e) { - IllegalArgumentException iae = new IllegalArgumentException( - "given file cannot be transformed to url: " + settingsFile); - iae.initCause(e); - throw iae; + throw new IllegalArgumentException( + "given file cannot be transformed to url: " + settingsFile, e); } setVariable("ivy.default.ivy.user.dir", getDefaultIvyUserDir().getAbsolutePath(), false); Message.verbose("settings loaded (" + (System.currentTimeMillis() - start) + "ms)"); @@ -484,10 +480,8 @@ public synchronized void setSettingsVariables(File settingsFile) { setVariable("ivy.settings.dir.url", new File(settingsFile.getAbsolutePath()) .getParentFile().toURI().toURL().toExternalForm()); } catch (MalformedURLException e) { - IllegalArgumentException iae = new IllegalArgumentException( - "given file cannot be transformed to url: " + settingsFile); - iae.initCause(e); - throw iae; + throw new IllegalArgumentException( + "given file cannot be transformed to url: " + settingsFile, e); } } @@ -633,7 +627,7 @@ public synchronized String substitute(String str) { * substituted by their value */ public synchronized Map substitute(Map strings) { - Map substituted = new LinkedHashMap(); + Map substituted = new LinkedHashMap<>(); for (Entry entry : strings.entrySet()) { substituted.put(entry.getKey(), substitute(entry.getValue())); } diff --git a/src/java/org/apache/ivy/core/settings/XmlSettingsParser.java b/src/java/org/apache/ivy/core/settings/XmlSettingsParser.java index 81d0f9a60..f245b49a3 100644 --- a/src/java/org/apache/ivy/core/settings/XmlSettingsParser.java +++ b/src/java/org/apache/ivy/core/settings/XmlSettingsParser.java @@ -29,7 +29,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -64,13 +63,13 @@ public class XmlSettingsParser extends DefaultHandler { * propagated to the wrapped instance. */ private static final class IvyVariableContainerWrapper implements IvyVariableContainer { - private static final Collection SETTINGS_VARIABLES = Arrays.asList(new String[] { - "ivy.settings.dir", "ivy.settings.url", "ivy.settings.file", "ivy.conf.dir", - "ivy.conf.url", "ivy.conf.file"}); + private static final Collection SETTINGS_VARIABLES = Arrays.asList( + "ivy.settings.dir", "ivy.settings.url", "ivy.settings.file", "ivy.conf.dir", + "ivy.conf.url", "ivy.conf.file"); private final IvyVariableContainer variables; - private Map localVariables = new HashMap(); + private Map localVariables = new HashMap<>(); private IvyVariableContainerWrapper(IvyVariableContainer variables) { this.variables = variables; @@ -92,7 +91,7 @@ public void setEnvironmentPrefix(String prefix) { public String getVariable(String name) { if (localVariables.containsKey(name)) { - return (String) localVariables.get(name); + return localVariables.get(name); } return variables.getVariable(name); } @@ -104,10 +103,9 @@ public Object clone() { private Configurator configurator; - private List configuratorTags = Arrays.asList(new String[] {"resolvers", "namespaces", - "parsers", "latest-strategies", "conflict-managers", "outputters", "version-matchers", - "statuses", "circular-dependency-strategies", "triggers", "lock-strategies", "caches", - "signers"}); + private List configuratorTags = Arrays.asList("resolvers", "namespaces", "parsers", + "latest-strategies", "conflict-managers", "outputters", "version-matchers", "statuses", + "circular-dependency-strategies", "triggers", "lock-strategies", "caches", "signers"); private IvySettings ivy; @@ -141,10 +139,9 @@ public File resolveFile(String path, String filename) { } }); // put every type definition from ivy to configurator - Map typeDefs = ivy.getTypeDefs(); - for (Iterator iter = typeDefs.keySet().iterator(); iter.hasNext();) { - String name = (String) iter.next(); - configurator.typeDef(name, (Class) typeDefs.get(name)); + Map> typeDefs = ivy.getTypeDefs(); + for (String name : typeDefs.keySet()) { + configurator.typeDef(name, typeDefs.get(name)); } doParse(settings); @@ -186,7 +183,7 @@ private void parse(Configurator configurator, URL configuration) throws IOExcept public void startElement(String uri, String localName, String qName, Attributes att) throws SAXException { // we first copy attributes in a Map to be able to modify them - Map attributes = new HashMap(); + Map attributes = new HashMap<>(); for (int i = 0; i < att.getLength(); i++) { attributes.put(att.getQName(i), ivy.substitute(att.getValue(i))); } @@ -227,41 +224,35 @@ public void startElement(String uri, String localName, String qName, Attributes credentialsStarted(attributes); } } catch (ParseException ex) { - SAXException sax = new SAXException("problem in config file: " + ex.getMessage(), ex); - sax.initCause(ex); - throw sax; + throw new SAXException("problem in config file: " + ex.getMessage(), ex); } catch (IOException ex) { - SAXException sax = new SAXException("io problem while parsing config file: " - + ex.getMessage(), ex); - sax.initCause(ex); - throw sax; + throw new SAXException("io problem while parsing config file: " + ex.getMessage(), ex); } } - private void credentialsStarted(Map attributes) { - String realm = (String) attributes.remove("realm"); - String host = (String) attributes.remove("host"); - String userName = (String) attributes.remove("username"); - String passwd = (String) attributes.remove("passwd"); + private void credentialsStarted(Map attributes) { + String realm = attributes.remove("realm"); + String host = attributes.remove("host"); + String userName = attributes.remove("username"); + String passwd = attributes.remove("passwd"); CredentialsStore.INSTANCE.addCredentials(realm, host, userName, passwd); } - private void moduleStarted(Map attributes) { + private void moduleStarted(Map attributes) { attributes.put(IvyPatternHelper.MODULE_KEY, attributes.remove("name")); - String resolver = (String) attributes.remove("resolver"); - String branch = (String) attributes.remove("branch"); - String cm = (String) attributes.remove("conflict-manager"); - String resolveMode = (String) attributes.remove("resolveMode"); - String matcher = (String) attributes.remove("matcher"); - matcher = matcher == null ? PatternMatcher.EXACT_OR_REGEXP : matcher; + String resolver = attributes.remove("resolver"); + String branch = attributes.remove("branch"); + String cm = attributes.remove("conflict-manager"); + String resolveMode = attributes.remove("resolveMode"); + String matcher = attributes.remove("matcher"); + matcher = (matcher == null) ? PatternMatcher.EXACT_OR_REGEXP : matcher; ivy.addModuleConfiguration(attributes, ivy.getMatcher(matcher), resolver, branch, cm, resolveMode); } - private void macrodefStarted(String qName, Map attributes) { + private void macrodefStarted(String qName, Map attributes) { currentConfiguratorTag = qName; - Configurator.MacroDef macrodef = configurator - .startMacroDef((String) attributes.get("name")); + Configurator.MacroDef macrodef = configurator.startMacroDef(attributes.get("name")); macrodef.addAttribute("name", null); } @@ -270,10 +261,10 @@ private void anyConfiguratorStarted(String qName) { configurator.setRoot(ivy); } - private void statusesStarted(String qName, Map attributes) { + private void statusesStarted(String qName, Map attributes) { currentConfiguratorTag = qName; StatusManager m = new StatusManager(); - String defaultStatus = (String) attributes.get("default"); + String defaultStatus = attributes.get("default"); if (defaultStatus != null) { m.setDefaultStatus(defaultStatus); } @@ -281,91 +272,91 @@ private void statusesStarted(String qName, Map attributes) { configurator.setRoot(m); } - private void versionMatchersStarted(String qName, Map attributes) { + private void versionMatchersStarted(String qName, Map attributes) { anyConfiguratorStarted(qName); if ("true".equals(attributes.get("usedefaults"))) { ivy.configureDefaultVersionMatcher(); } } - private void cachesStarted(String qName, Map attributes) { + private void cachesStarted(String qName, Map attributes) { anyConfiguratorStarted(qName); - defaultLock = (String) attributes.get("lockStrategy"); - defaultCacheManager = (String) attributes.get("default"); + defaultLock = attributes.get("lockStrategy"); + defaultCacheManager = attributes.get("default"); - String cache = (String) attributes.get("defaultCacheDir"); + String cache = attributes.get("defaultCacheDir"); if (cache != null) { ivy.setDefaultCache(Checks.checkAbsolute(cache, "defaultCacheDir")); } - String up2d = (String) attributes.get("checkUpToDate"); + String up2d = attributes.get("checkUpToDate"); if (up2d != null) { Message.deprecated("'checkUpToDate' is deprecated, " + "use the 'overwriteMode' on the 'ivy:retrieve' task instead (" + settings + ")"); ivy.setCheckUpToDate(Boolean.valueOf(up2d)); } - String resolutionDir = (String) attributes.get("resolutionCacheDir"); + String resolutionDir = attributes.get("resolutionCacheDir"); if (resolutionDir != null) { ivy.setDefaultResolutionCacheBasedir(resolutionDir); } - String useOrigin = (String) attributes.get("useOrigin"); + String useOrigin = attributes.get("useOrigin"); if (useOrigin != null) { ivy.setDefaultUseOrigin(Boolean.valueOf(useOrigin)); } - String cacheIvyPattern = (String) attributes.get("ivyPattern"); + String cacheIvyPattern = attributes.get("ivyPattern"); if (cacheIvyPattern != null) { ivy.setDefaultCacheIvyPattern(cacheIvyPattern); } - String cacheArtPattern = (String) attributes.get("artifactPattern"); + String cacheArtPattern = attributes.get("artifactPattern"); if (cacheArtPattern != null) { ivy.setDefaultCacheArtifactPattern(cacheArtPattern); } - String repositoryDir = (String) attributes.get("repositoryCacheDir"); + String repositoryDir = attributes.get("repositoryCacheDir"); if (repositoryDir != null) { ivy.setDefaultRepositoryCacheBasedir(repositoryDir); } } - private void settingsStarted(String qName, Map attributes) { + private void settingsStarted(String qName, Map attributes) { if ("conf".equals(qName) && !deprecatedMessagePrinted) { Message.deprecated("'conf' is deprecated, use 'settings' instead (" + settings + ")"); } - String cache = (String) attributes.get("defaultCache"); + String cache = attributes.get("defaultCache"); if (cache != null) { Message.deprecated("'defaultCache' is deprecated, " + "use 'caches[@defaultCacheDir]' instead (" + settings + ")"); ivy.setDefaultCache(Checks.checkAbsolute(cache, "defaultCache")); } - String defaultBranch = (String) attributes.get("defaultBranch"); + String defaultBranch = attributes.get("defaultBranch"); if (defaultBranch != null) { ivy.setDefaultBranch(defaultBranch); } - String defaultResolveMode = (String) attributes.get("defaultResolveMode"); + String defaultResolveMode = attributes.get("defaultResolveMode"); if (defaultResolveMode != null) { ivy.setDefaultResolveMode(defaultResolveMode); } - String validate = (String) attributes.get("validate"); + String validate = attributes.get("validate"); if (validate != null) { ivy.setValidate(Boolean.valueOf(validate)); } - String up2d = (String) attributes.get("checkUpToDate"); + String up2d = attributes.get("checkUpToDate"); if (up2d != null) { Message.deprecated("'checkUpToDate' is deprecated, " + "use the 'overwriteMode' on the 'ivy:retrieve' task instead (" + settings + ")"); ivy.setCheckUpToDate(Boolean.valueOf(up2d)); } - String useRemoteConfig = (String) attributes.get("useRemoteConfig"); + String useRemoteConfig = attributes.get("useRemoteConfig"); if (useRemoteConfig != null) { ivy.setUseRemoteConfig(Boolean.valueOf(useRemoteConfig)); } - String cacheIvyPattern = (String) attributes.get("cacheIvyPattern"); + String cacheIvyPattern = attributes.get("cacheIvyPattern"); if (cacheIvyPattern != null) { Message.deprecated("'cacheIvyPattern' is deprecated, use 'caches[@ivyPattern]' instead" + " (" + settings + ")"); ivy.setDefaultCacheIvyPattern(cacheIvyPattern); } - String cacheArtPattern = (String) attributes.get("cacheArtifactPattern"); + String cacheArtPattern = attributes.get("cacheArtifactPattern"); if (cacheArtPattern != null) { Message.deprecated("'cacheArtifactPattern' is deprecated, " + "use 'caches[@artifactPattern]' instead (" + settings + ")"); @@ -373,31 +364,31 @@ private void settingsStarted(String qName, Map attributes) { } // we do not set following defaults here since no instances has been registered yet - defaultResolver = (String) attributes.get("defaultResolver"); - defaultCM = (String) attributes.get("defaultConflictManager"); - defaultLatest = (String) attributes.get("defaultLatestStrategy"); - defaultCircular = (String) attributes.get("circularDependencyStrategy"); + defaultResolver = attributes.get("defaultResolver"); + defaultCM = attributes.get("defaultConflictManager"); + defaultLatest = attributes.get("defaultLatestStrategy"); + defaultCircular = attributes.get("circularDependencyStrategy"); - String requestMethod = (String) attributes.get("httpRequestMethod"); + String requestMethod = attributes.get("httpRequestMethod"); if ("head".equalsIgnoreCase(requestMethod)) { URLHandlerRegistry.getHttp().setRequestMethod(URLHandler.REQUEST_METHOD_HEAD); } else if ("get".equalsIgnoreCase(requestMethod)) { URLHandlerRegistry.getHttp().setRequestMethod(URLHandler.REQUEST_METHOD_GET); } else if ((requestMethod != null) && (requestMethod.trim().length() > 0)) { - throw new IllegalArgumentException("Invalid httpRequestMethod specified, must be " - + "one of {'HEAD', 'GET'}"); + throw new IllegalArgumentException( + "Invalid httpRequestMethod specified, must be one of {'HEAD', 'GET'}"); } } - private void includeStarted(Map attributes) throws IOException, ParseException { + private void includeStarted(Map attributes) throws IOException, ParseException { final IvyVariableContainer variables = ivy.getVariableContainer(); ivy.setVariableContainer(new IvyVariableContainerWrapper(variables)); final boolean optionalInclude = "true".equals(attributes.get("optional")); try { - String propFilePath = (String) attributes.get("file"); + String propFilePath = attributes.get("file"); URL settingsURL = null; if (propFilePath == null) { - propFilePath = (String) attributes.get("url"); + propFilePath = attributes.get("url"); if (propFilePath == null) { throw new IllegalArgumentException( "bad include tag: specify file or url to include"); @@ -495,11 +486,11 @@ private URL urlFromFileAttribute(String filePath) throws IOException { } } - private void propertiesStarted(Map attributes) throws IOException { - String propFilePath = (String) attributes.get("file"); - String environmentPrefix = (String) attributes.get("environment"); + private void propertiesStarted(Map attributes) throws IOException { + String propFilePath = attributes.get("file"); + String environmentPrefix = attributes.get("environment"); if (propFilePath != null) { - String overrideStr = (String) attributes.get("override"); + String overrideStr = attributes.get("override"); boolean override = (overrideStr == null) || Boolean.valueOf(overrideStr); Message.verbose("loading properties: " + propFilePath); try { @@ -516,12 +507,12 @@ private void propertiesStarted(Map attributes) throws IOException { } } - private void propertyStarted(Map attributes) { - String name = (String) attributes.get("name"); - String value = (String) attributes.get("value"); - String override = (String) attributes.get("override"); - String isSetVar = (String) attributes.get("ifset"); - String unlessSetVar = (String) attributes.get("unlessset"); + private void propertyStarted(Map attributes) { + String name = attributes.get("name"); + String value = attributes.get("value"); + String override = attributes.get("override"); + String isSetVar = attributes.get("ifset"); + String unlessSetVar = attributes.get("unlessset"); if (name == null) { throw new IllegalArgumentException("missing attribute name on property tag"); } @@ -532,18 +523,18 @@ private void propertyStarted(Map attributes) { unlessSetVar); } - private void typedefStarted(Map attributes) { - String name = (String) attributes.get("name"); - String className = (String) attributes.get("classname"); - Class clazz = ivy.typeDef(name, className); + private void typedefStarted(Map attributes) { + String name = attributes.get("name"); + String className = attributes.get("classname"); + Class clazz = ivy.typeDef(name, className); configurator.typeDef(name, clazz); } - private void classpathStarted(Map attributes) throws IOException { - String urlStr = (String) attributes.get("url"); + private void classpathStarted(Map attributes) throws IOException { + String urlStr = attributes.get("url"); URL url = null; if (urlStr == null) { - String file = (String) attributes.get("file"); + String file = attributes.get("file"); if (file == null) { throw new IllegalArgumentException( "either url or file should be given for classpath element"); @@ -556,12 +547,12 @@ private void classpathStarted(Map attributes) throws IOException { ivy.addClasspathURL(url); } - private void inConfiguratorStarted(String qName, Map attributes) { + private void inConfiguratorStarted(String qName, Map attributes) { if ("macrodef".equals(currentConfiguratorTag) && configurator.getTypeDef(qName) != null) { - String name = (String) attributes.get("name"); + String name = attributes.get("name"); if (name == null) { attributes.put("name", "@{name}"); - } else if (name.indexOf("@{name}") != -1) { + } else if (name.contains("@{name}")) { attributes.put("name", name); } else { attributes.put("name", "@{name}-" + name); @@ -572,7 +563,7 @@ private void inConfiguratorStarted(String qName, Map attributes) { throw new IllegalArgumentException("ref attribute should be the only one ! found " + attributes.size() + " in " + qName); } - String name = (String) attributes.get("ref"); + String name = attributes.get("ref"); Object child = null; if ("resolvers".equals(currentConfiguratorTag) || "resolver".equals(qName)) { child = ivy.getResolver(name); @@ -599,9 +590,8 @@ private void inConfiguratorStarted(String qName, Map attributes) { configurator.addChild(qName, child); } else { configurator.startCreateChild(qName); - for (Iterator iter = attributes.keySet().iterator(); iter.hasNext();) { - String attName = (String) iter.next(); - configurator.setAttribute(attName, (String) attributes.get(attName)); + for (String attName : attributes.keySet()) { + configurator.setAttribute(attName, attributes.get(attName)); } } } diff --git a/src/java/org/apache/ivy/core/sort/CollectionOfModulesToSort.java b/src/java/org/apache/ivy/core/sort/CollectionOfModulesToSort.java index 93e228baa..91e62492e 100644 --- a/src/java/org/apache/ivy/core/sort/CollectionOfModulesToSort.java +++ b/src/java/org/apache/ivy/core/sort/CollectionOfModulesToSort.java @@ -59,8 +59,8 @@ public CollectionOfModulesToSort(Collection modulesToSort, VersionMatcher matcher, NonMatchingVersionReporter nonMatchingVersionReporter) { this.versionMatcher = matcher; this.nonMatchingVersionReporter = nonMatchingVersionReporter; - this.modulesByModuleId = new HashMap>(); - moduleDescriptors = new ArrayList(modulesToSort.size()); + this.modulesByModuleId = new HashMap<>(); + moduleDescriptors = new ArrayList<>(modulesToSort.size()); for (ModuleDescriptor md : modulesToSort) { ModuleInSort mdInSort = new ModuleInSort(md); moduleDescriptors.add(mdInSort); @@ -70,7 +70,7 @@ public CollectionOfModulesToSort(Collection modulesToSort, private void addToModulesByModuleId(ModuleDescriptor md, ModuleInSort mdInSort) { ModuleId mdId = md.getModuleRevisionId().getModuleId(); - List mdInSortAsList = new LinkedList(); + List mdInSortAsList = new LinkedList<>(); mdInSortAsList.add(mdInSort); Collection previousList = modulesByModuleId.put(mdId, mdInSortAsList); if (previousList != null) { diff --git a/src/java/org/apache/ivy/core/sort/ModuleDescriptorSorter.java b/src/java/org/apache/ivy/core/sort/ModuleDescriptorSorter.java index 330f30205..be8582078 100644 --- a/src/java/org/apache/ivy/core/sort/ModuleDescriptorSorter.java +++ b/src/java/org/apache/ivy/core/sort/ModuleDescriptorSorter.java @@ -42,7 +42,7 @@ public class ModuleDescriptorSorter { private final CollectionOfModulesToSort moduleDescriptors; - private final List sorted = new LinkedList(); + private final List sorted = new LinkedList<>(); private final CircularDependencyStrategy circularDepStrategy; @@ -93,8 +93,8 @@ private void sortModuleDescriptorsHelp(ModuleInSort current, ModuleInSort caller Message.debug("Sort dependencies of : " + current.toString() + " / Number of dependencies = " + descriptors.length); current.setCaller(caller); - for (int i = 0; i < descriptors.length; i++) { - ModuleInSort child = moduleDescriptors.getModuleDescriptorDependency(descriptors[i]); + for (DependencyDescriptor descriptor : descriptors) { + ModuleInSort child = moduleDescriptors.getModuleDescriptorDependency(descriptor); if (child != null) { sortModuleDescriptorsHelp(child, current); } diff --git a/src/java/org/apache/ivy/core/sort/ModuleInSort.java b/src/java/org/apache/ivy/core/sort/ModuleInSort.java index 6e30b254b..2ac1a2060 100644 --- a/src/java/org/apache/ivy/core/sort/ModuleInSort.java +++ b/src/java/org/apache/ivy/core/sort/ModuleInSort.java @@ -53,7 +53,7 @@ class ModuleInSort { private boolean isSorted = false; - private List loopElements = new LinkedList(); + private List loopElements = new LinkedList<>(); private boolean isLoopIntermediateElement = false; @@ -113,12 +113,14 @@ public void endOfCall() { */ public boolean checkLoop(ModuleInSort futurCaller, CircularDependencyStrategy depStrategy) { if (caller != null) { - LinkedList elemOfLoop = new LinkedList(); + LinkedList elemOfLoop = new LinkedList<>(); elemOfLoop.add(this.module.getModuleRevisionId()); - for (ModuleInSort stackEl = futurCaller; stackEl != this; stackEl = stackEl.caller) { + ModuleInSort stackEl = futurCaller; + while (stackEl != this) { elemOfLoop.add(stackEl.module.getModuleRevisionId()); stackEl.isLoopIntermediateElement = true; loopElements.add(stackEl); + stackEl = stackEl.caller; } elemOfLoop.add(this.module.getModuleRevisionId()); ModuleRevisionId[] mrids = elemOfLoop.toArray(new ModuleRevisionId[elemOfLoop.size()]); @@ -166,7 +168,7 @@ public DependencyDescriptor[] getDependencies() { } /** Log a warning saying that a loop is detected */ - public static void logLoopWarning(List loopElement) { + public static void logLoopWarning(List loopElement) { Message.warn("circular dependency detected during sort: " + CircularDependencyHelper.formatMessageFromDescriptors(loopElement)); } diff --git a/src/java/org/apache/ivy/core/sort/SortEngine.java b/src/java/org/apache/ivy/core/sort/SortEngine.java index d4ddbbc20..4aa547fb8 100644 --- a/src/java/org/apache/ivy/core/sort/SortEngine.java +++ b/src/java/org/apache/ivy/core/sort/SortEngine.java @@ -63,15 +63,15 @@ public List sortNodes(Collection nodes, SortOptions options) { * corresponding dependency */ - Map> dependenciesMap = new LinkedHashMap>(); - List nulls = new ArrayList(); + Map> dependenciesMap = new LinkedHashMap<>(); + List nulls = new ArrayList<>(); for (IvyNode node : nodes) { if (node.getDescriptor() == null) { nulls.add(node); } else { List n = dependenciesMap.get(node.getDescriptor()); if (n == null) { - n = new ArrayList(); + n = new ArrayList<>(); dependenciesMap.put(node.getDescriptor(), n); } n.add(node); @@ -79,11 +79,10 @@ public List sortNodes(Collection nodes, SortOptions options) { } List list = sortModuleDescriptors(dependenciesMap.keySet(), options); final double adjustFactor = 1.3; - List ret = new ArrayList( + List ret = new ArrayList<>( (int) (list.size() * adjustFactor + nulls.size())); // attempt to adjust the size to avoid too much list resizing - for (int i = 0; i < list.size(); i++) { - ModuleDescriptor md = list.get(i); + for (ModuleDescriptor md : list) { List n = dependenciesMap.get(md); ret.addAll(n); } diff --git a/src/java/org/apache/ivy/osgi/core/ManifestHeaderValue.java b/src/java/org/apache/ivy/osgi/core/ManifestHeaderValue.java index 08af4c612..5bff0e0a7 100644 --- a/src/java/org/apache/ivy/osgi/core/ManifestHeaderValue.java +++ b/src/java/org/apache/ivy/osgi/core/ManifestHeaderValue.java @@ -143,7 +143,7 @@ class ManifestHeaderParser { /** * Do the parsing * - * @throws ParseException + * @throws ParseException if something goes wrong */ void parse() throws ParseException { do { diff --git a/src/java/org/apache/ivy/osgi/core/ManifestParser.java b/src/java/org/apache/ivy/osgi/core/ManifestParser.java index 4806f33dc..5ccf3d7e2 100644 --- a/src/java/org/apache/ivy/osgi/core/ManifestParser.java +++ b/src/java/org/apache/ivy/osgi/core/ManifestParser.java @@ -257,7 +257,7 @@ private static VersionRange versionRangeOf(String v) throws ParseException { return new VersionRange(v); } - private static Version versionOf(String v) throws ParseException { + private static Version versionOf(String v) { if (v == null) { return null; } diff --git a/src/java/org/apache/ivy/osgi/filter/OSGiFilterParser.java b/src/java/org/apache/ivy/osgi/filter/OSGiFilterParser.java index 522175260..0123bcbe6 100644 --- a/src/java/org/apache/ivy/osgi/filter/OSGiFilterParser.java +++ b/src/java/org/apache/ivy/osgi/filter/OSGiFilterParser.java @@ -65,7 +65,7 @@ static class Parser { * * @return OSGiFilter * - * @throws ParseException + * @throws ParseException if something goes wrong */ OSGiFilter parse() throws ParseException { return parseFilter(); diff --git a/src/java/org/apache/ivy/osgi/obr/xml/RequirementAdapter.java b/src/java/org/apache/ivy/osgi/obr/xml/RequirementAdapter.java index 0c20f1f2b..f453cf2ba 100644 --- a/src/java/org/apache/ivy/osgi/obr/xml/RequirementAdapter.java +++ b/src/java/org/apache/ivy/osgi/obr/xml/RequirementAdapter.java @@ -50,7 +50,7 @@ public static void adapt(BundleInfo info, Requirement requirement) adapter.adapt(info, requirement.isOptional()); } - private void extractFilter(OSGiFilter filter) throws UnsupportedFilterException, ParseException { + private void extractFilter(OSGiFilter filter) throws UnsupportedFilterException { if (filter instanceof AndFilter) { AndFilter andFilter = (AndFilter) filter; for (OSGiFilter subFilter : andFilter.getSubFilters()) { @@ -93,7 +93,7 @@ private VersionRange getVersionRange() { } private void parseCompareFilter(CompareFilter compareFilter, boolean not) - throws UnsupportedFilterException, ParseException { + throws UnsupportedFilterException { String att = compareFilter.getLeftValue(); if (BundleInfo.PACKAGE_TYPE.equals(att) || BundleInfo.BUNDLE_TYPE.equals(att) || BundleInfo.EXECUTION_ENVIRONMENT_TYPE.equals(att) || "symbolicname".equals(att) diff --git a/src/java/org/apache/ivy/osgi/repo/AbstractOSGiResolver.java b/src/java/org/apache/ivy/osgi/repo/AbstractOSGiResolver.java index 02589b5ad..08e762c68 100644 --- a/src/java/org/apache/ivy/osgi/repo/AbstractOSGiResolver.java +++ b/src/java/org/apache/ivy/osgi/repo/AbstractOSGiResolver.java @@ -27,7 +27,6 @@ import java.util.Date; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -389,11 +388,12 @@ private void filterCapabilityValues(Set capabilityValues, capabilityValues.addAll(moduleByCapabilityValue.keySet()); } else { for (Entry> entry : moduleByCapabilityValue.entrySet()) { - Iterator itModules = entry.getValue().iterator(); boolean moduleMatchRev = false; - while (!moduleMatchRev && itModules.hasNext()) { - ModuleDescriptor md = itModules.next(); + for (ModuleDescriptor md : entry.getValue()) { moduleMatchRev = rev.equals(md.getRevision()); + if (moduleMatchRev) { + break; + } } if (moduleMatchRev) { // at least one module matched, the capability value is ok to add @@ -403,6 +403,7 @@ private void filterCapabilityValues(Set capabilityValues, } } + @SuppressWarnings("unchecked") @Override public Map[] listTokenValues(String[] tokens, Map criteria) { Set tokenSet = new HashSet<>(Arrays.asList(tokens)); diff --git a/src/java/org/apache/ivy/osgi/repo/EditableRepoDescriptor.java b/src/java/org/apache/ivy/osgi/repo/EditableRepoDescriptor.java index 7889a1e57..8890a9038 100644 --- a/src/java/org/apache/ivy/osgi/repo/EditableRepoDescriptor.java +++ b/src/java/org/apache/ivy/osgi/repo/EditableRepoDescriptor.java @@ -150,14 +150,11 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { + if (!(obj instanceof EditableRepoDescriptor)) { return false; } - if (getClass() != obj.getClass()) { - return false; + if (this == obj) { + return true; } EditableRepoDescriptor other = (EditableRepoDescriptor) obj; if (modules == null) { diff --git a/src/java/org/apache/ivy/osgi/repo/ModuleDescriptorWrapper.java b/src/java/org/apache/ivy/osgi/repo/ModuleDescriptorWrapper.java index 7efcb0307..c6e42ab58 100644 --- a/src/java/org/apache/ivy/osgi/repo/ModuleDescriptorWrapper.java +++ b/src/java/org/apache/ivy/osgi/repo/ModuleDescriptorWrapper.java @@ -85,7 +85,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - return !(obj == null || !(obj instanceof ModuleDescriptorWrapper)) + return obj instanceof ModuleDescriptorWrapper && bundleInfo.equals(((ModuleDescriptorWrapper) obj).bundleInfo); } diff --git a/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java b/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java index c63b4374a..dd0c227c0 100644 --- a/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java +++ b/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java @@ -222,7 +222,7 @@ private boolean readJarOrXml(URI repoUri, String baseName, XMLInputParser reader return true; } - private UpdateSite loadSite(URI repoUri) throws IOException, ParseException, SAXException { + private UpdateSite loadSite(URI repoUri) throws IOException, SAXException { URI siteUri = normalizeSiteUri(repoUri, null); URL u = siteUri.resolve("site.xml").toURL(); @@ -262,7 +262,7 @@ private URI normalizeSiteUri(URI uri, URI defaultValue) { } private UpdateSiteDescriptor loadFromDigest(UpdateSite site) throws IOException, - ParseException, SAXException { + SAXException { URI digestBaseUri = site.getDigestUri(); if (digestBaseUri == null) { digestBaseUri = site.getUri(); @@ -287,8 +287,7 @@ private UpdateSiteDescriptor loadFromDigest(UpdateSite site) throws IOException, } } - private UpdateSiteDescriptor loadFromSite(UpdateSite site) throws IOException, ParseException, - SAXException { + private UpdateSiteDescriptor loadFromSite(UpdateSite site) throws IOException, SAXException { UpdateSiteDescriptor repoDescriptor = new UpdateSiteDescriptor(site.getUri(), ExecutionEnvironmentProfileProvider.getInstance()); diff --git a/src/java/org/apache/ivy/osgi/util/ParseUtil.java b/src/java/org/apache/ivy/osgi/util/ParseUtil.java index 62a0a1c5b..783990650 100644 --- a/src/java/org/apache/ivy/osgi/util/ParseUtil.java +++ b/src/java/org/apache/ivy/osgi/util/ParseUtil.java @@ -50,9 +50,7 @@ public static String[] parseDelimitedString(String value, String delim) { int expecting = (CHAR | DELIMITER | STARTQUOTE); - for (int i = 0; i < value.length(); i++) { - final char c = value.charAt(i); - + for (final char c : value.toCharArray()) { final boolean isDelimiter = (delim.indexOf(c) >= 0); final boolean isQuote = (c == '"'); diff --git a/src/java/org/apache/ivy/osgi/util/VersionRange.java b/src/java/org/apache/ivy/osgi/util/VersionRange.java index 4d97562b3..5b75f3a77 100644 --- a/src/java/org/apache/ivy/osgi/util/VersionRange.java +++ b/src/java/org/apache/ivy/osgi/util/VersionRange.java @@ -79,7 +79,7 @@ class VersionRangeParser { /** * Do the parsing * - * @throws ParseException + * @throws ParseException if something goes wrong */ void parse() throws ParseException { boolean range = parseStart(); @@ -306,7 +306,7 @@ public boolean isClosedRange() { return startVersion.equals(endVersion); } - public boolean contains(String versionStr) throws ParseException { + public boolean contains(String versionStr) { return contains(new Version(versionStr)); } diff --git a/src/java/org/apache/ivy/plugins/conflict/LatestCompatibleConflictManager.java b/src/java/org/apache/ivy/plugins/conflict/LatestCompatibleConflictManager.java index 73f4951aa..f0676d69b 100644 --- a/src/java/org/apache/ivy/plugins/conflict/LatestCompatibleConflictManager.java +++ b/src/java/org/apache/ivy/plugins/conflict/LatestCompatibleConflictManager.java @@ -191,13 +191,13 @@ private void blackListIncompatibleCallerAndRestartResolveIfPossible(IvySettings settings.getVersionMatcher(), parent, selected, evicted, callerStack); if (toBlacklist != null) { final StringBuilder blacklisted = new StringBuilder(); - for (Iterator iterator = toBlacklist.iterator(); iterator.hasNext();) { - IvyNodeBlacklist blacklist = iterator.next(); - blacklist.getBlacklistedNode().blacklist(blacklist); - blacklisted.append(blacklist.getBlacklistedNode()); - if (iterator.hasNext()) { + for (IvyNodeBlacklist blacklist : toBlacklist) { + if (blacklisted.length() > 0) { blacklisted.append(" "); } + IvyNode blacklistedNode = blacklist.getBlacklistedNode(); + blacklistedNode.blacklist(blacklist); + blacklisted.append(blacklistedNode); } String rootModuleConf = parent.getData().getReport().getConfiguration(); diff --git a/src/java/org/apache/ivy/plugins/latest/AbstractLatestStrategy.java b/src/java/org/apache/ivy/plugins/latest/AbstractLatestStrategy.java index dbd24dc36..0812b56bb 100644 --- a/src/java/org/apache/ivy/plugins/latest/AbstractLatestStrategy.java +++ b/src/java/org/apache/ivy/plugins/latest/AbstractLatestStrategy.java @@ -42,7 +42,8 @@ public ArtifactInfo findLatest(ArtifactInfo[] infos, Date date) { // the latest revision comes last, use a ListIterator to iterate the // sorted list in the reverse direction. - for (ListIterator iter = l.listIterator(l.size()); iter.hasPrevious();) { + ListIterator iter = l.listIterator(l.size()); + while (iter.hasPrevious()) { ArtifactInfo info = iter.previous(); if (date == null || info.getLastModified() < date.getTime()) { return info; diff --git a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java index cc640a86f..9cea4430f 100644 --- a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java +++ b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java @@ -167,9 +167,9 @@ public void toIvyFile(InputStream is, Resource res, File destFile, ModuleDescrip .setPubdate(md.getResolvedPublicationDate()).setUpdateBranch(false) .setNamespace(ns)); } catch (SAXException e) { - ParseException ex = new ParseException("exception occurred while parsing " + res, 0); - ex.initCause(e); - throw ex; + ParseException pe = new ParseException("exception occurred while parsing " + res, 0); + pe.initCause(e); + throw pe; } finally { if (is != null) { is.close(); @@ -381,10 +381,8 @@ && isOtherNamespace(qName)) { if (ex instanceof SAXException) { throw (SAXException) ex; } - SAXException sax = new SAXException("Problem occurred while parsing ivy file: " + throw new SAXException("Problem occurred while parsing ivy file: " + ex.getMessage(), ex); - sax.initCause(ex); - throw sax; } } diff --git a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorUpdater.java b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorUpdater.java index c3ea1dd03..7d09011ed 100644 --- a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorUpdater.java +++ b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorUpdater.java @@ -412,11 +412,13 @@ private void startExtends(Attributes attributes) { // replace inline revision with resolved parent revision ModuleDescriptor merged = options.getMergedDescriptor(); if (merged != null) { - ExtendsDescriptor[] parents = merged.getInheritedDescriptors(); - for (int j = 0; value == null && j < parents.length; ++j) { - ModuleRevisionId resolvedId = parents[j].getResolvedParentRevisionId(); + for (ExtendsDescriptor parent : merged.getInheritedDescriptors()) { + ModuleRevisionId resolvedId = parent.getResolvedParentRevisionId(); if (parentId.equals(resolvedId.getModuleId())) { value = resolvedId.getRevision(); + if (value != null) { + break; + } } } } @@ -441,10 +443,9 @@ private void startElementInConfigurationsConf(String qName, Attributes attribute buffers.peek().setPrint(true); String extend = substitute(settings, attributes.getValue("extends")); if (extend != null) { - for (StringTokenizer tok = new StringTokenizer(extend, ", "); tok - .hasMoreTokens();) { - String current = tok.nextToken(); - if (confs.contains(current)) { + StringTokenizer tok = new StringTokenizer(extend, ", "); + while (tok.hasMoreTokens()) { + if (confs.contains(tok.nextToken())) { throw new IllegalArgumentException( "Cannot exclude a configuration which is extended."); } @@ -618,7 +619,7 @@ private void includeStarted(Attributes attributes) throws SAXException { settings.substitute(attributes.getValue("url"))); } else { // TODO : settings can be null, but I don't why. - // Check if the next code is correct in that case + // Check if the following code is correct in that case String fileName = attributes.getValue("file"); if (fileName == null) { String urlStr = attributes.getValue("url"); @@ -655,10 +656,9 @@ public void startElement(String uri, String localName, String qName, } String extend = substitute(settings, attributes.getValue("extends")); if (extend != null) { - for (StringTokenizer tok = new StringTokenizer(extend, ", "); tok - .hasMoreTokens();) { - String current = tok.nextToken(); - if (confs.contains(current)) { + StringTokenizer tok = new StringTokenizer(extend, ", "); + while (tok.hasMoreTokens()) { + if (confs.contains(tok.nextToken())) { throw new IllegalArgumentException("Cannot exclude a " + "configuration which is extended."); } @@ -806,13 +806,12 @@ private String substitute(ParserSettings ivy, String value) { return XMLHelper.escape(result); } - private String removeConfigurationsFromMapping(String mapping, List confsToRemove) { + private String removeConfigurationsFromMapping(String mapping, List confsToRemove) { StringBuilder newMapping = new StringBuilder(); String mappingSep = ""; - for (StringTokenizer tokenizer = new StringTokenizer(mapping, ";"); tokenizer - .hasMoreTokens();) { - String current = tokenizer.nextToken(); - String[] ops = current.split("->"); + StringTokenizer tokenizer = new StringTokenizer(mapping, ";"); + while (tokenizer.hasMoreTokens()) { + String[] ops = tokenizer.nextToken().split("->"); List confsToWrite = new ArrayList<>(); for (String lh : ops[0].split(",")) { if (!confs.contains(lh.trim())) { @@ -821,37 +820,31 @@ private String removeConfigurationsFromMapping(String mapping, List confsToRemov } if (!confsToWrite.isEmpty()) { newMapping.append(mappingSep); - String sep = ""; for (String confToWrite : confsToWrite) { - newMapping.append(sep); - newMapping.append(confToWrite); + newMapping.append(sep).append(confToWrite); sep = ","; } if (ops.length == 2) { - newMapping.append("->"); - newMapping.append(ops[1]); + newMapping.append("->").append(ops[1]); } mappingSep = ";"; } } - return newMapping.toString(); } - private String removeConfigurationsFromList(String list, List confsToRemove) { + private String removeConfigurationsFromList(String list, List confsToRemove) { StringBuilder newList = new StringBuilder(); String listSep = ""; - for (StringTokenizer tokenizer = new StringTokenizer(list, ","); tokenizer - .hasMoreTokens();) { + StringTokenizer tokenizer = new StringTokenizer(list, ","); + while (tokenizer.hasMoreTokens()) { String current = tokenizer.nextToken(); if (!confsToRemove.contains(current.trim())) { - newList.append(listSep); - newList.append(current); + newList.append(listSep).append(current); listSep = ","; } } - return newList.toString(); } @@ -966,15 +959,12 @@ private void writeInheritedItems(ModuleDescriptor merged, InheritableItem[] item for (Map.Entry> entry : inheritedItems .entrySet()) { - ModuleRevisionId parent = entry.getKey(); - List list = entry.getValue(); - if (justOpen != null) { out.println(">"); justOpen = null; // helps endElement() decide how to write close tags } - writeInheritanceComment(itemName, parent); - for (InheritableItem item : list) { + writeInheritanceComment(itemName, entry.getKey()); + for (InheritableItem item : entry.getValue()) { out.print(getIndent()); printer.print(merged, item, out); } @@ -1091,8 +1081,8 @@ private void flushMergedElementsBefore(String moduleElement) { && !(mergedConfigurations && mergedDependencies)) { // calculate the position of the element in ivy-module - int position = moduleElement == null ? MODULE_ELEMENTS.size() : MODULE_ELEMENTS - .indexOf(moduleElement); + int position = (moduleElement == null) ? MODULE_ELEMENTS.size() + : MODULE_ELEMENTS.indexOf(moduleElement); ModuleDescriptor merged = options.getMergedDescriptor(); diff --git a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java index db8c4695a..2f984645b 100644 --- a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java +++ b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java @@ -109,24 +109,24 @@ private static void printDependencies(ModuleDescriptor md, PrintWriter out) { protected static void printDependency(ModuleDescriptor md, DependencyDescriptor dep, PrintWriter out) { - out.print(""); - for (int k = 0; k < depConfs.length; k++) { - out.print(XMLHelper.escape(depConfs[k])); - if (k + 1 < depConfs.length) { - out.print(","); - } - } - if (j + 1 < modConfs.length) { - out.print(";"); + StringBuilder sb = new StringBuilder(); + for (String modConf : dep.getModuleConfigurations()) { + if (sb.length() > 0) { + sb.append(";"); } + sb.append(XMLHelper.escape(modConf)).append( + listToPrefixedString(dep.getDependencyConfigurations(modConf), "->")); } - out.print("\""); + out.print(" conf=\"" + sb + "\""); printExtraAttributes(dep, out, " "); @@ -215,28 +208,17 @@ private static void printAllExcludes(ModuleDescriptor md, PrintWriter out) { ExcludeRule[] excludes = md.getAllExcludeRules(); if (excludes.length > 0) { for (ExcludeRule exclude : excludes) { - out.print("\t\t"); } } @@ -246,28 +228,17 @@ private static void printDependencyExcludeRules(ModuleDescriptor md, PrintWriter ExcludeRule[] excludes) { if (excludes.length > 0) { for (ExcludeRule exclude : excludes) { - out.print("\t\t\t"); } } @@ -277,23 +248,15 @@ private static void printDependencyIncludeRules(ModuleDescriptor md, PrintWriter IncludeRule[] includes) { if (includes.length > 0) { for (IncludeRule include : includes) { - out.print("\t\t\t"); } } @@ -303,20 +266,13 @@ private static void printDependencyArtefacts(ModuleDescriptor md, PrintWriter ou DependencyArtifactDescriptor[] depArtifacts) { if (depArtifacts.length > 0) { for (DependencyArtifactDescriptor depArtifact : depArtifacts) { - out.print("\t\t\t"); @@ -324,6 +280,20 @@ private static void printDependencyArtefacts(ModuleDescriptor md, PrintWriter ou } } + private static String listToPrefixedString(String[] confs, String prefix) { + StringBuilder sb = new StringBuilder(prefix); + for (String conf : confs) { + if (sb.length() > prefix.length()) { + sb.append(","); + } + sb.append(XMLHelper.escape(conf)); + } + if (prefix.endsWith("\"")) { + sb.append("\""); + } + return sb.toString(); + } + /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. @@ -367,11 +337,11 @@ private static void printPublications(ModuleDescriptor md, PrintWriter out) { out.println("\t"); Artifact[] artifacts = md.getAllArtifacts(); for (Artifact artifact : artifacts) { - out.print("\t\t"); } @@ -399,14 +369,7 @@ protected static void printConfiguration(Configuration conf, PrintWriter out) { } String[] exts = conf.getExtends(); if (exts.length > 0) { - out.print(" extends=\""); - for (int j = 0; j < exts.length; j++) { - out.print(XMLHelper.escape(exts[j])); - if (j + 1 < exts.length) { - out.print(","); - } - } - out.print("\""); + out.print(listToPrefixedString(exts, " extends=\"")); } if (!conf.isTransitive()) { out.print(" transitive=\"false\""); @@ -451,9 +414,10 @@ private static void printInfoTag(ModuleDescriptor md, PrintWriter out) { ExtendsDescriptor[] parents = md.getInheritedDescriptors(); for (ExtendsDescriptor parent : parents) { ModuleRevisionId mrid = parent.getParentRevisionId(); - out.print("\t\t entry : extraInfo.getAttributes().entrySet()) { - out.print(" "); - out.print(entry.getKey()); - out.print("="); - out.print("\""); - out.print(entry.getValue()); - out.print("\""); + out.print(String.format(" %s=\"%s\"", entry.getKey(), entry.getValue())); } boolean requireClosingTag = false; if (extraInfo.getContent() != null && extraInfo.getContent().trim().length() > 0) { @@ -536,19 +495,15 @@ private static void printExtraInfoElement(PrintWriter out, ExtraInfoHolder extra } } - @SuppressWarnings("deprecation") private static boolean requireInnerInfoElement(ModuleDescriptor md) { - return md.getExtraInfo().size() > 0 || md.getExtraInfos().size() > 0 - || md.getHomePage() != null + return md.getExtraInfos().size() > 0 || md.getHomePage() != null || (md.getDescription() != null && md.getDescription().trim().length() > 0) || md.getLicenses().length > 0 || md.getInheritedDescriptors().length > 0; } private static String getConfs(ModuleDescriptor md, Artifact artifact) { StringBuilder ret = new StringBuilder(); - - String[] confs = md.getConfigurationsNames(); - for (String conf : confs) { + for (String conf : md.getConfigurationsNames()) { if (Arrays.asList(md.getArtifacts(conf)).contains(artifact)) { ret.append(conf).append(","); } diff --git a/src/java/org/apache/ivy/plugins/repository/sftp/SFTPRepository.java b/src/java/org/apache/ivy/plugins/repository/sftp/SFTPRepository.java index 1aeda9420..e1d013c21 100644 --- a/src/java/org/apache/ivy/plugins/repository/sftp/SFTPRepository.java +++ b/src/java/org/apache/ivy/plugins/repository/sftp/SFTPRepository.java @@ -88,17 +88,11 @@ public Resource getResource(String source) { @SuppressWarnings("unchecked") public Resource resolveResource(String path) { try { - ChannelSftp c = getSftpChannel(path); - - // ls() returns a Vector of LsEntry - Collection r = c.ls(getPath(path)); - + List r = getSftpChannel(path).ls(getPath(path)); if (r != null) { - for (LsEntry entry : r) { - SftpATTRS attrs = entry.getAttrs(); - return new BasicResource(path, true, attrs.getSize(), + SftpATTRS attrs = r.get(0).getAttrs(); + return new BasicResource(path, true, attrs.getSize(), attrs.getMTime() * MILLIS_PER_SECOND, false); - } } } catch (Exception e) { Message.debug("Error while resolving resource " + path, e); @@ -148,7 +142,7 @@ public void put(File source, String destination, boolean overwrite) throws IOExc } } - private void mkdirs(String directory, ChannelSftp c) throws IOException, SftpException { + private void mkdirs(String directory, ChannelSftp c) throws SftpException { try { SftpATTRS att = c.stat(directory); if (att != null) { diff --git a/src/java/org/apache/ivy/plugins/repository/ssh/Scp.java b/src/java/org/apache/ivy/plugins/repository/ssh/Scp.java index 8e5a5e1e1..0723e2534 100644 --- a/src/java/org/apache/ivy/plugins/repository/ssh/Scp.java +++ b/src/java/org/apache/ivy/plugins/repository/ssh/Scp.java @@ -491,8 +491,8 @@ public void put(String localFile, String remoteTargetDir, String remoteTargetNam throw new IllegalArgumentException("Invalid mode."); } - for (int i = 0; i < mode.length(); i++) { - if (!Character.isDigit(mode.charAt(i))) { + for (char c : mode.toCharArray()) { + if (!Character.isDigit(c)) { throw new IllegalArgumentException("Invalid mode."); } } @@ -500,10 +500,10 @@ public void put(String localFile, String remoteTargetDir, String remoteTargetNam String cmd = "scp -t "; if (mode != null) { - cmd = cmd + "-p "; + cmd += "-p "; } if (remoteTargetDir != null && remoteTargetDir.length() > 0) { - cmd = cmd + "-d " + remoteTargetDir; + cmd += "-d " + remoteTargetDir; } try { @@ -549,9 +549,9 @@ public void get(String remoteFile, String localTarget) throws IOException, Remot * @throws RemoteScpException * in case of problems on the target system (connection ok) */ + @SuppressWarnings("unused") public void get(String remoteFile, OutputStream localTarget) throws IOException, RemoteScpException { - @SuppressWarnings("unused") ChannelExec channel = null; if ((remoteFile == null) || (localTarget == null)) { diff --git a/src/java/org/apache/ivy/plugins/repository/ssh/SshCache.java b/src/java/org/apache/ivy/plugins/repository/ssh/SshCache.java index f0563807a..1240db4a9 100644 --- a/src/java/org/apache/ivy/plugins/repository/ssh/SshCache.java +++ b/src/java/org/apache/ivy/plugins/repository/ssh/SshCache.java @@ -263,9 +263,8 @@ public void clearSession(Session session) { * @param session * to connect to * @return channelSftp or null if not successful (channel not existent or dead) - * @throws IOException if something goes wrong */ - public ChannelSftp getChannelSftp(Session session) throws IOException { + public ChannelSftp getChannelSftp(Session session) { ChannelSftp channel = null; Entry entry = getCacheEntry(session); if (entry != null) { diff --git a/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpRepository.java b/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpRepository.java index 861fe3c21..463facce1 100644 --- a/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpRepository.java +++ b/src/java/org/apache/ivy/plugins/repository/vsftp/VsftpRepository.java @@ -221,7 +221,7 @@ public List list(String parent) throws IOException { initIvy(); try { if (!parent.endsWith("/")) { - parent = parent + "/"; + parent += "/"; } String response = sendCommand("ls -l " + parent, true, true); if (response.startsWith("ls")) { @@ -229,12 +229,12 @@ public List list(String parent) throws IOException { } String[] lines = response.split("\n"); List ret = new ArrayList<>(lines.length); - for (int i = 0; i < lines.length; i++) { - while (lines[i].endsWith("\r") || lines[i].endsWith("\n")) { - lines[i] = lines[i].substring(0, lines[i].length() - 1); + for (String line : lines) { + while (line.endsWith("\r") || line.endsWith("\n")) { + line = line.substring(0, line.length() - 1); } - if (lines[i].trim().length() != 0) { - ret.add(parent + lines[i].substring(lines[i].lastIndexOf(' ') + 1)); + if (line.trim().length() != 0) { + ret.add(parent + line.substring(line.lastIndexOf(' ') + 1)); } } return ret; @@ -383,12 +383,13 @@ public void run() { try { int c; boolean getPrompt = false; - // the reading is done in a for loop making five attempts to read the stream + // the reading is done in a loop making five attempts to read the stream // if we do not reach the next prompt - for (int attempts = 0; !getPrompt && attempts < MAX_READ_PROMPT_ATTEMPT; attempts++) { + int attempt = 0; + while (!getPrompt && attempt < MAX_READ_PROMPT_ATTEMPT) { while ((c = in.read()) != -1) { - attempts = 0; // we manage to read something, reset numer of - // attempts + // we managed to read something, reset number of attempts + attempt = 0; response.append((char) c); if (response.length() >= PROMPT.length() && response.substring(response.length() - PROMPT.length(), @@ -405,6 +406,7 @@ public void run() { break; } } + attempt++; } if (getPrompt) { // wait enough for error stream to be fully read @@ -457,12 +459,14 @@ public void run() { } else if (!done[0]) { if (reader != null && reader.isAlive()) { reader.interrupt(); - for (int i = 0; i < MAX_READER_ALIVE_ATTEMPT && reader.isAlive(); i++) { + int attempt = 0; + while (attempt < MAX_READER_ALIVE_ATTEMPT && reader.isAlive()) { try { Thread.sleep(READER_ALIVE_SLEEP_TIME); } catch (InterruptedException e) { break; } + attempt++; } if (reader.isAlive()) { reader.stop(); // no way to interrupt it non abruptly diff --git a/src/java/org/apache/ivy/plugins/resolver/AbstractPatternsBasedResolver.java b/src/java/org/apache/ivy/plugins/resolver/AbstractPatternsBasedResolver.java index 5a3765b3e..6872f3052 100644 --- a/src/java/org/apache/ivy/plugins/resolver/AbstractPatternsBasedResolver.java +++ b/src/java/org/apache/ivy/plugins/resolver/AbstractPatternsBasedResolver.java @@ -24,7 +24,6 @@ import java.util.Date; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -92,16 +91,17 @@ protected ResolvedResource findResourceUsingPatterns(ModuleRevisionId moduleRevi List resolvedResources = new ArrayList<>(); Set foundRevisions = new HashSet<>(); boolean dynamic = getSettings().getVersionMatcher().isDynamic(moduleRevision); - boolean stop = false; - for (Iterator iter = patternList.iterator(); iter.hasNext() && !stop;) { - String pattern = iter.next(); + for (String pattern : patternList) { ResolvedResource rres = findResourceUsingPattern(moduleRevision, pattern, artifact, rmdparser, date); if ((rres != null) && !foundRevisions.contains(rres.getRevision())) { // only add the first found ResolvedResource for each revision foundRevisions.add(rres.getRevision()); resolvedResources.add(rres); - stop = !dynamic; // stop iterating if we are not searching a dynamic revision + if (!dynamic) { + // stop iterating if we are not searching a dynamic revision + break; + } } } @@ -158,6 +158,7 @@ protected Collection findArtifactNames(Map tokenValues, return names; } + @SuppressWarnings("unchecked") @Override public Map[] listTokenValues(String[] tokens, Map criteria) { Set> result = new LinkedHashSet<>(); diff --git a/src/java/org/apache/ivy/plugins/resolver/AbstractResolver.java b/src/java/org/apache/ivy/plugins/resolver/AbstractResolver.java index 1d66f450f..59148de51 100644 --- a/src/java/org/apache/ivy/plugins/resolver/AbstractResolver.java +++ b/src/java/org/apache/ivy/plugins/resolver/AbstractResolver.java @@ -174,6 +174,7 @@ public String[] listTokenValues(String token, Map otherTokenValu return new String[0]; } + @SuppressWarnings("unchecked") public Map[] listTokenValues(String[] tokens, Map criteria) { return new Map[0]; } diff --git a/src/java/org/apache/ivy/plugins/resolver/BasicResolver.java b/src/java/org/apache/ivy/plugins/resolver/BasicResolver.java index b45db0922..780cc05bb 100644 --- a/src/java/org/apache/ivy/plugins/resolver/BasicResolver.java +++ b/src/java/org/apache/ivy/plugins/resolver/BasicResolver.java @@ -95,7 +95,6 @@ public abstract class BasicResolver extends AbstractResolver { * converted in a message (either error or verbose) and returning null *

*/ - @SuppressWarnings("serial") private static class UnresolvedDependencyException extends RuntimeException { private static final long serialVersionUID = 1L; @@ -660,8 +659,8 @@ public ResolvedResource findResource(ResolvedResource[] rress, ResourceMDParser List foundBlacklisted = new ArrayList<>(); IvyContext context = IvyContext.getContext(); - for (ListIterator iter = sorted.listIterator(sorted.size()); iter - .hasPrevious();) { + ListIterator iter = sorted.listIterator(sorted.size()); + while (iter.hasPrevious()) { ResolvedResource rres = (ResolvedResource) iter.previous(); // we start by filtering based on information already available, // even though we don't even know if the resource actually exist. @@ -780,7 +779,7 @@ protected void logArtifactAttempt(Artifact art, String attempt) { } protected void logAttempt(String attempt) { - Artifact currentArtifact = (Artifact) IvyContext.getContext().get(getName() + ".artifact"); + Artifact currentArtifact = IvyContext.getContext().get(getName() + ".artifact"); if (currentArtifact != null) { logArtifactAttempt(currentArtifact, attempt); } else { @@ -795,10 +794,9 @@ public void reportFailure() { Message.warn(" " + m); } for (Map.Entry> entry : artattempts.entrySet()) { - Artifact art = entry.getKey(); List attempts = entry.getValue(); if (attempts != null) { - Message.warn(" -- artifact " + art + ":"); + Message.warn(" -- artifact " + entry.getKey() + ":"); for (String m : attempts) { Message.warn(" " + m); } diff --git a/src/java/org/apache/ivy/plugins/resolver/ChainResolver.java b/src/java/org/apache/ivy/plugins/resolver/ChainResolver.java index 18ce35224..5581f41d2 100644 --- a/src/java/org/apache/ivy/plugins/resolver/ChainResolver.java +++ b/src/java/org/apache/ivy/plugins/resolver/ChainResolver.java @@ -180,6 +180,7 @@ public ResolvedResource findIvyFileRef(DependencyDescriptor dd, ResolveData data return null; } + @SuppressWarnings("unchecked") @Override public Map[] listTokenValues(String[] tokens, Map criteria) { Set> result = new HashSet<>(); diff --git a/src/java/org/apache/ivy/plugins/resolver/FileSystemResolver.java b/src/java/org/apache/ivy/plugins/resolver/FileSystemResolver.java index f217693c9..c2bb7c990 100644 --- a/src/java/org/apache/ivy/plugins/resolver/FileSystemResolver.java +++ b/src/java/org/apache/ivy/plugins/resolver/FileSystemResolver.java @@ -155,18 +155,17 @@ public void commitPublishTransaction() throws IOException { Message.info("\tpublish committed: moved " + transactionTempDir + " \n\t\tto " + transactionDestDir); } catch (IOException ex) { - IOException commitEx; + String message; try { getFileRepository().delete(transactionTempDir); - commitEx = new IOException("publish transaction commit error for " - + transactionDestDir + ": rolled back"); + message = "publish transaction commit error for " + + transactionDestDir + ": rolled back"; } catch (IOException deleteEx) { - commitEx = new IOException("publish transaction commit error for " - + transactionDestDir + ": rollback impossible either, " - + "please remove " + transactionTempDir + " manually"); + message = "publish transaction commit error for " + + transactionDestDir + ": rollback impossible either, " + + "please remove " + transactionTempDir + " manually"; } - commitEx.initCause(ex); - throw commitEx; + throw new IOException(message, ex); } finally { closeTransaction(); } @@ -203,9 +202,9 @@ public void beginPublishTransaction(ModuleRevisionId module, boolean overwrite) protected Collection filterNames(Collection values) { if (supportTransaction()) { values = super.filterNames(values); - for (Iterator iterator = values.iterator(); iterator.hasNext();) { - String v = iterator.next(); - if (v.endsWith(TRANSACTION_DESTINATION_SUFFIX)) { + Iterator iterator = values.iterator(); + while (iterator.hasNext()) { + if (iterator.next().endsWith(TRANSACTION_DESTINATION_SUFFIX)) { iterator.remove(); } } diff --git a/src/java/org/apache/ivy/plugins/resolver/VsftpResolver.java b/src/java/org/apache/ivy/plugins/resolver/VsftpResolver.java index 07a81da71..0ccbacfdb 100644 --- a/src/java/org/apache/ivy/plugins/resolver/VsftpResolver.java +++ b/src/java/org/apache/ivy/plugins/resolver/VsftpResolver.java @@ -20,7 +20,7 @@ import org.apache.ivy.plugins.repository.vsftp.VsftpRepository; /** - * This resolver uses SecureCRT vsft to access an sftp server. It supports listing and publishing. + * This resolver uses SecureCRT vsftp to access an sftp server. It supports listing and publishing. * The server host should absolutely be set using setHost, so does the username. */ public class VsftpResolver extends RepositoryResolver { diff --git a/src/java/org/apache/ivy/plugins/signer/bouncycastle/OpenPGPSignatureGenerator.java b/src/java/org/apache/ivy/plugins/signer/bouncycastle/OpenPGPSignatureGenerator.java index 33b880bad..d800d0e79 100644 --- a/src/java/org/apache/ivy/plugins/signer/bouncycastle/OpenPGPSignatureGenerator.java +++ b/src/java/org/apache/ivy/plugins/signer/bouncycastle/OpenPGPSignatureGenerator.java @@ -149,11 +149,12 @@ private PGPSecretKey readSecretKey(InputStream in) throws IOException, PGPExcept new BcKeyFingerprintCalculator()); PGPSecretKey key = null; - for (Iterator it = pgpSec.getKeyRings(); key == null && it.hasNext();) { + Iterator it = pgpSec.getKeyRings(); + while (key == null && it.hasNext()) { PGPSecretKeyRing kRing = it.next(); - for (Iterator it2 = kRing.getSecretKeys(); key == null - && it2.hasNext();) { + Iterator it2 = kRing.getSecretKeys(); + while (key == null && it2.hasNext()) { PGPSecretKey k = it2.next(); if ((keyId == null) && k.isSigningKey()) { key = k; diff --git a/src/java/org/apache/ivy/plugins/trigger/AbstractTrigger.java b/src/java/org/apache/ivy/plugins/trigger/AbstractTrigger.java index c5888671a..5aae2dd8a 100644 --- a/src/java/org/apache/ivy/plugins/trigger/AbstractTrigger.java +++ b/src/java/org/apache/ivy/plugins/trigger/AbstractTrigger.java @@ -33,7 +33,7 @@ * @since 1.4 */ public abstract class AbstractTrigger implements Trigger { - private Filter filter; + private Filter filter; private String event; @@ -41,14 +41,14 @@ public abstract class AbstractTrigger implements Trigger { private String matcher = PatternMatcher.EXACT; - public Filter getEventFilter() { + public Filter getEventFilter() { if (filter == null) { filter = createFilter(); } return filter; } - private Filter createFilter() { + private Filter createFilter() { return new IvyEventFilter(getEvent(), getFilter(), getPatternMatcher()); } diff --git a/src/java/org/apache/ivy/plugins/trigger/Trigger.java b/src/java/org/apache/ivy/plugins/trigger/Trigger.java index b8987e974..ea4ee5a0e 100644 --- a/src/java/org/apache/ivy/plugins/trigger/Trigger.java +++ b/src/java/org/apache/ivy/plugins/trigger/Trigger.java @@ -17,9 +17,10 @@ */ package org.apache.ivy.plugins.trigger; +import org.apache.ivy.core.event.IvyEvent; import org.apache.ivy.core.event.IvyListener; import org.apache.ivy.util.filter.Filter; public interface Trigger extends IvyListener { - Filter getEventFilter(); + Filter getEventFilter(); } diff --git a/src/java/org/apache/ivy/plugins/version/ChainVersionMatcher.java b/src/java/org/apache/ivy/plugins/version/ChainVersionMatcher.java index 5ab5d716b..412e8835e 100644 --- a/src/java/org/apache/ivy/plugins/version/ChainVersionMatcher.java +++ b/src/java/org/apache/ivy/plugins/version/ChainVersionMatcher.java @@ -117,7 +117,8 @@ public int compare(ModuleRevisionId askedMrid, ModuleRevisionId foundMrid, public boolean accept(ModuleRevisionId askedMrid, ModuleRevisionId foundMrid) { Checks.checkNotNull(askedMrid, "askedMrid"); Checks.checkNotNull(foundMrid, "foundMrid"); - for (Iterator iter = matchers.iterator(); iter.hasNext();) { + Iterator iter = matchers.iterator(); + while (iter.hasNext()) { VersionMatcher matcher = iter.next(); if (!iter.hasNext() || matcher.isDynamic(askedMrid)) { return matcher.accept(askedMrid, foundMrid); @@ -129,7 +130,8 @@ public boolean accept(ModuleRevisionId askedMrid, ModuleRevisionId foundMrid) { public boolean needModuleDescriptor(ModuleRevisionId askedMrid, ModuleRevisionId foundMrid) { Checks.checkNotNull(askedMrid, "askedMrid"); Checks.checkNotNull(foundMrid, "foundMrid"); - for (Iterator iter = matchers.iterator(); iter.hasNext();) { + Iterator iter = matchers.iterator(); + while (iter.hasNext()) { VersionMatcher matcher = iter.next(); if (!iter.hasNext() || matcher.isDynamic(askedMrid)) { return matcher.needModuleDescriptor(askedMrid, foundMrid); @@ -141,7 +143,8 @@ public boolean needModuleDescriptor(ModuleRevisionId askedMrid, ModuleRevisionId public boolean accept(ModuleRevisionId askedMrid, ModuleDescriptor foundMD) { Checks.checkNotNull(askedMrid, "askedMrid"); Checks.checkNotNull(foundMD, "foundMD"); - for (Iterator iter = matchers.iterator(); iter.hasNext();) { + Iterator iter = matchers.iterator(); + while (iter.hasNext()) { VersionMatcher matcher = iter.next(); if (!iter.hasNext() || matcher.isDynamic(askedMrid)) { return matcher.accept(askedMrid, foundMD); diff --git a/src/java/org/apache/ivy/tools/analyser/JarJarDependencyAnalyser.java b/src/java/org/apache/ivy/tools/analyser/JarJarDependencyAnalyser.java index ecb0cbdd4..2acf2b462 100644 --- a/src/java/org/apache/ivy/tools/analyser/JarJarDependencyAnalyser.java +++ b/src/java/org/apache/ivy/tools/analyser/JarJarDependencyAnalyser.java @@ -39,22 +39,20 @@ public JarJarDependencyAnalyser(File jarjarjarLocation) { } public ModuleDescriptor[] analyze(JarModule[] modules) { - StringBuilder jarjarCmd = new StringBuilder("java -jar \"").append( jarjarjarLocation.getAbsolutePath()).append("\" --find --level=jar "); Map jarModulesMap = new HashMap<>(); Map mds = new HashMap<>(); - for (int i = 0; i < modules.length; i++) { - jarModulesMap.put(modules[i].getJar().getAbsolutePath(), modules[i]); + for (JarModule jarModule : modules) { + jarModulesMap.put(jarModule.getJar().getAbsolutePath(), jarModule); DefaultModuleDescriptor md = DefaultModuleDescriptor.newBasicInstance( - modules[i].getMrid(), new Date(modules[i].getJar().lastModified())); - mds.put(modules[i].getMrid(), md); - jarjarCmd.append("\"").append(modules[i].getJar().getAbsolutePath()).append("\""); - if (i + 1 < modules.length) { - jarjarCmd.append(File.pathSeparator); - } + jarModule.getMrid(), new Date(jarModule.getJar().lastModified())); + mds.put(jarModule.getMrid(), md); + jarjarCmd.append("\"").append(jarModule.getJar().getAbsolutePath()).append("\""); + jarjarCmd.append(File.pathSeparator); } + jarjarCmd.setLength(jarjarCmd.length() - 1); Message.verbose("jarjar command: " + jarjarCmd); diff --git a/src/java/org/apache/ivy/util/Configurator.java b/src/java/org/apache/ivy/util/Configurator.java index 893ed505b..28fe662aa 100644 --- a/src/java/org/apache/ivy/util/Configurator.java +++ b/src/java/org/apache/ivy/util/Configurator.java @@ -202,7 +202,7 @@ public Attribute getAttribute(String attributeName) { public Object play(Configurator conf, Map attValues, Map> macroRecords) { for (Attribute att : attributes.values()) { - String val = attValues.get(att.getName()); + String val = attValues.get(att.getName()); if (val == null) { if (att.getDefault() == null) { throw new IllegalArgumentException("attribute " + att.getName() @@ -393,11 +393,11 @@ public Method getAddConfiguredMethod(String name) { return addConfiguredMethods.get(name); } - public Method getAddMethod(Class type) { + public Method getAddMethod(Class type) { return getTypeMatchingMethod(type, typeAddMethods); } - public Method getAddConfiguredMethod(Class type) { + public Method getAddConfiguredMethod(Class type) { return getTypeMatchingMethod(type, typeAddConfiguredMethods); } @@ -432,13 +432,13 @@ public String getObjectName() { // stack in which the top is current configured object descriptor private Stack objectStack = new Stack<>(); - private static final List TRUE_VALUES = Arrays.asList("true", "yes", "on"); + private static final List TRUE_VALUES = Arrays.asList("true", "yes", "on"); public void typeDef(String name, String className) throws ClassNotFoundException { typeDef(name, Class.forName(className)); } - public void typeDef(String name, Class clazz) { + public void typeDef(String name, Class clazz) { typedefs.put(name, clazz); } @@ -458,6 +458,7 @@ private void setCurrent(Object object, String name) { objectStack.push(new ObjectDescriptor(object, name)); } + @SuppressWarnings("rawtypes") public Object startCreateChild(String name) { if (objectStack.isEmpty()) { throw new IllegalStateException("set root before creating child"); @@ -488,7 +489,7 @@ public Object startCreateChild(String name) { setCurrent(macro, name); return macro; } - Class childClass = typedefs.get(name); + Class childClass = typedefs.get(name); Method addChild = null; try { if (childClass != null) { @@ -547,7 +548,9 @@ public void addChild(String name, Object child) { } } - private Object addChild(ObjectDescriptor parentOD, Class childClass, String name, Object child) + @SuppressWarnings("rawtypes") + private Object addChild(ObjectDescriptor parentOD, Class childClass, String name, + Object child) throws InstantiationException, IllegalAccessException, InvocationTargetException { Object parent = parentOD.getObject(); if (parent instanceof MacroRecord) { @@ -589,6 +592,7 @@ public boolean isTopLevelMacroRecord() { return (od.getObject() instanceof MacroDef); } + @SuppressWarnings("unchecked") public void setAttribute(String attributeName, String value) { if (objectStack.isEmpty()) { throw new IllegalStateException("set root before setting attribute"); @@ -726,7 +730,7 @@ public void addConfiguredMacrodef(MacroDef macrodef) { macrodefs.put(macrodef.getName(), macrodef); } - public Class getTypeDef(String name) { + public Class getTypeDef(String name) { return typedefs.get(name); } diff --git a/src/java/org/apache/ivy/util/Credentials.java b/src/java/org/apache/ivy/util/Credentials.java index 719e7afc8..6e70d6341 100644 --- a/src/java/org/apache/ivy/util/Credentials.java +++ b/src/java/org/apache/ivy/util/Credentials.java @@ -82,16 +82,8 @@ private String getPasswdAsStars() { } public boolean equals(Object o) { - if (o == null) { - return false; - } - - if (o instanceof Credentials) { - Credentials c = (Credentials) o; - return getKey().equals(c.getKey()); - } + return o instanceof Credentials && getKey().equals(((Credentials) o).getKey()); - return false; } public int hashCode() { diff --git a/src/java/org/apache/ivy/util/MemoryUtil.java b/src/java/org/apache/ivy/util/MemoryUtil.java index db425f103..dc8073089 100644 --- a/src/java/org/apache/ivy/util/MemoryUtil.java +++ b/src/java/org/apache/ivy/util/MemoryUtil.java @@ -35,7 +35,7 @@ private MemoryUtil() { * the class to evaluate. * @return the estimated size of instance, in bytes. */ - public static long sizeOf(Class clazz) { + public static long sizeOf(Class clazz) { long size = 0; Object[] objects = new Object[SAMPLING_SIZE]; try { diff --git a/src/java/org/apache/ivy/util/MessageLoggerHelper.java b/src/java/org/apache/ivy/util/MessageLoggerHelper.java index beb4ad0a7..093efe1b1 100644 --- a/src/java/org/apache/ivy/util/MessageLoggerHelper.java +++ b/src/java/org/apache/ivy/util/MessageLoggerHelper.java @@ -21,7 +21,7 @@ public final class MessageLoggerHelper { public static void sumupProblems(MessageLogger logger) { - List myProblems = logger.getProblems(); + List myProblems = logger.getProblems(); if (myProblems.size() > 0) { List myWarns = logger.getWarns(); List myErrors = logger.getErrors(); diff --git a/src/java/org/apache/ivy/util/StringUtils.java b/src/java/org/apache/ivy/util/StringUtils.java index 26ade1566..6e4931a0c 100644 --- a/src/java/org/apache/ivy/util/StringUtils.java +++ b/src/java/org/apache/ivy/util/StringUtils.java @@ -142,8 +142,7 @@ public static final String encrypt(String str) { return null; } StringBuilder buf = new StringBuilder(); - for (int i = 0; i < str.length(); i++) { - char c = str.charAt(i); + for (char c : str.toCharArray()) { if (c >= SHIFTS.length) { throw new IllegalArgumentException( "encrypt method can only be used with simple characters. '" + c @@ -166,8 +165,8 @@ public static final String decrypt(String str) { return null; } StringBuilder buf = new StringBuilder(); - for (int i = 0; i < str.length(); i++) { - buf.append(decrypt(str.charAt(i))); + for (char c : str.toCharArray()) { + buf.append(decrypt(c)); } return buf.toString(); } diff --git a/src/java/org/apache/ivy/util/filter/AndFilter.java b/src/java/org/apache/ivy/util/filter/AndFilter.java index f7474692d..bfa945fd6 100644 --- a/src/java/org/apache/ivy/util/filter/AndFilter.java +++ b/src/java/org/apache/ivy/util/filter/AndFilter.java @@ -17,25 +17,25 @@ */ package org.apache.ivy.util.filter; -public class AndFilter implements Filter { - private Filter op1; +public class AndFilter implements Filter { + private Filter op1; - private Filter op2; + private Filter op2; - public AndFilter(Filter op1, Filter op2) { + public AndFilter(Filter op1, Filter op2) { this.op1 = op1; this.op2 = op2; } - public Filter getOp1() { + public Filter getOp1() { return op1; } - public Filter getOp2() { + public Filter getOp2() { return op2; } - public boolean accept(Object o) { + public boolean accept(T o) { return op1.accept(o) && op2.accept(o); } } diff --git a/src/java/org/apache/ivy/util/filter/FilterHelper.java b/src/java/org/apache/ivy/util/filter/FilterHelper.java index 04e8011da..7664c09fd 100644 --- a/src/java/org/apache/ivy/util/filter/FilterHelper.java +++ b/src/java/org/apache/ivy/util/filter/FilterHelper.java @@ -73,9 +73,9 @@ public static Collection filter(Collection col, Filter filter) { return col; } Collection ret = new ArrayList<>(col); - for (Iterator iter = ret.iterator(); iter.hasNext();) { - T element = iter.next(); - if (!filter.accept(element)) { + Iterator iter = ret.iterator(); + while (iter.hasNext()) { + if (!filter.accept(iter.next())) { iter.remove(); } } diff --git a/src/java/org/apache/ivy/util/filter/NoFilter.java b/src/java/org/apache/ivy/util/filter/NoFilter.java index cdaf88d19..c89aab5f7 100644 --- a/src/java/org/apache/ivy/util/filter/NoFilter.java +++ b/src/java/org/apache/ivy/util/filter/NoFilter.java @@ -17,18 +17,20 @@ */ package org.apache.ivy.util.filter; -public final class NoFilter implements Filter { +public final class NoFilter implements Filter { + @SuppressWarnings("rawtypes") public static final Filter INSTANCE = new NoFilter(); + @SuppressWarnings("unchecked") public static Filter instance() { - return INSTANCE; + return (Filter) INSTANCE; } private NoFilter() { } - public boolean accept(Object o) { + public boolean accept(T o) { return true; } diff --git a/src/java/org/apache/ivy/util/filter/NotFilter.java b/src/java/org/apache/ivy/util/filter/NotFilter.java index 7d5500463..3401d60c0 100644 --- a/src/java/org/apache/ivy/util/filter/NotFilter.java +++ b/src/java/org/apache/ivy/util/filter/NotFilter.java @@ -17,18 +17,18 @@ */ package org.apache.ivy.util.filter; -public class NotFilter implements Filter { - private Filter op; +public class NotFilter implements Filter { + private Filter op; - public NotFilter(Filter op) { + public NotFilter(Filter op) { this.op = op; } - public Filter getOp() { + public Filter getOp() { return op; } - public boolean accept(Object o) { + public boolean accept(T o) { return !op.accept(o); } } diff --git a/src/java/org/apache/ivy/util/filter/OrFilter.java b/src/java/org/apache/ivy/util/filter/OrFilter.java index 46f157112..d372b024d 100644 --- a/src/java/org/apache/ivy/util/filter/OrFilter.java +++ b/src/java/org/apache/ivy/util/filter/OrFilter.java @@ -17,25 +17,25 @@ */ package org.apache.ivy.util.filter; -public class OrFilter implements Filter { - private Filter op1; +public class OrFilter implements Filter { + private Filter op1; - private Filter op2; + private Filter op2; - public OrFilter(Filter op1, Filter op2) { + public OrFilter(Filter op1, Filter op2) { this.op1 = op1; this.op2 = op2; } - public Filter getOp1() { + public Filter getOp1() { return op1; } - public Filter getOp2() { + public Filter getOp2() { return op2; } - public boolean accept(Object o) { + public boolean accept(T o) { return op1.accept(o) || op2.accept(o); } } diff --git a/src/java/org/apache/ivy/util/url/HttpClientHandler.java b/src/java/org/apache/ivy/util/url/HttpClientHandler.java index f0a0c967e..2c25026c8 100644 --- a/src/java/org/apache/ivy/util/url/HttpClientHandler.java +++ b/src/java/org/apache/ivy/util/url/HttpClientHandler.java @@ -177,7 +177,7 @@ public URLInfo getURLInfo(URL url, int timeout) { return UNAVAILABLE; } - private boolean checkStatusCode(URL url, HttpMethodBase method) throws IOException { + private boolean checkStatusCode(URL url, HttpMethodBase method) { int status = method.getStatusCode(); if (status == HttpStatus.SC_OK) { return true; diff --git a/src/java/org/apache/ivy/util/url/URLHandlerRegistry.java b/src/java/org/apache/ivy/util/url/URLHandlerRegistry.java index 6baa75837..8cf62de17 100644 --- a/src/java/org/apache/ivy/util/url/URLHandlerRegistry.java +++ b/src/java/org/apache/ivy/util/url/URLHandlerRegistry.java @@ -50,7 +50,7 @@ public static URLHandler getHttp() { // http-client-3.x is available Class.forName("org.apache.commons.httpclient.params.HttpClientParams"); - Class handler = Class.forName("org.apache.ivy.util.url.HttpClientHandler"); + Class handler = Class.forName("org.apache.ivy.util.url.HttpClientHandler"); Message.verbose("jakarta commons httpclient detected: using it for http downloading"); return (URLHandler) handler.newInstance(); } catch (ClassNotFoundException e) { diff --git a/test/java/org/apache/ivy/ant/IvyConfigureTest.java b/test/java/org/apache/ivy/ant/IvyConfigureTest.java index 8568f625d..4dc66def3 100644 --- a/test/java/org/apache/ivy/ant/IvyConfigureTest.java +++ b/test/java/org/apache/ivy/ant/IvyConfigureTest.java @@ -56,7 +56,6 @@ public void setUp() { configure.setProject(project); } - @SuppressWarnings("deprecation") private Ivy getIvyInstance() { IvyTask task = new IvyTask() { public void doExecute() throws BuildException { @@ -65,7 +64,7 @@ public void doExecute() throws BuildException { task.setProject(project); task.init(); - Reference ref = new Reference(configure.getSettingsId()); + Reference ref = new Reference(task.getProject(), configure.getSettingsId()); // ref.setProject(project); task.setSettingsRef(ref); return task.getIvyInstance(); diff --git a/test/java/org/apache/ivy/ant/IvyDeliverTest.java b/test/java/org/apache/ivy/ant/IvyDeliverTest.java index 0e94d4d69..5bcc689e6 100644 --- a/test/java/org/apache/ivy/ant/IvyDeliverTest.java +++ b/test/java/org/apache/ivy/ant/IvyDeliverTest.java @@ -135,10 +135,9 @@ public void testMergeParent() throws IOException, ParseException { try (BufferedReader merged = new BufferedReader(new FileReader(delivered)); BufferedReader expected = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("ivy-extends-merged.xml")))) { - for (String mergeLine = merged.readLine(), expectedLine = expected.readLine(); - mergeLine != null && expectedLine != null; - mergeLine = merged.readLine(), expectedLine = expected.readLine()) { - + String mergeLine = merged.readLine(); + String expectedLine = expected.readLine(); + while (mergeLine != null && expectedLine != null) { mergeLine = mergeLine.trim(); expectedLine = expectedLine.trim(); @@ -148,6 +147,8 @@ public void testMergeParent() throws IOException, ParseException { } ++lineNo; + mergeLine = merged.readLine(); + expectedLine = expected.readLine(); } } } diff --git a/test/java/org/apache/ivy/ant/IvyPublishTest.java b/test/java/org/apache/ivy/ant/IvyPublishTest.java index 077df587a..e20c0ad3b 100644 --- a/test/java/org/apache/ivy/ant/IvyPublishTest.java +++ b/test/java/org/apache/ivy/ant/IvyPublishTest.java @@ -138,9 +138,9 @@ private void checkPublishedFile(File published, String expectedFilename) throws try (BufferedReader expected = new BufferedReader(new InputStreamReader(getClass() .getResourceAsStream(expectedFilename)))) { int lineNo = 1; - for (String mergeLine = merged.readLine(), expectedLine = expected.readLine(); mergeLine != null - && expectedLine != null; mergeLine = merged.readLine(), expectedLine = expected - .readLine()) { + String mergeLine = merged.readLine(); + String expectedLine = expected.readLine(); + while (mergeLine != null && expectedLine != null) { // strip timestamps for the comparison if (mergeLine.contains(" files = asList(resources); assertEquals(1, files.size()); assertEquals(getArchiveFileInCache("org1", "mod1.2", "2.0", "mod1.2", "jar", "jar"), files.get(0)); @@ -97,7 +97,7 @@ public void testMultiple() throws Exception { dependency.setName("mod2.3"); dependency.setRev("0.7"); - List files = asList(resources); + List files = asList(resources); assertEquals(5, files.size()); assertTrue(files.contains(getArchiveFileInCache("org1", "mod1.2", "2.0", "mod1.2", "jar", "jar"))); @@ -124,7 +124,7 @@ public void testMultipleWithConf() throws Exception { dependency.setRev("0.10"); dependency.setConf("A"); - List files = asList(resources); + List files = asList(resources); assertEquals(3, files.size()); assertTrue(files.contains(getArchiveFileInCache("org1", "mod1.2", "2.0", "mod1.2", "jar", "jar"))); @@ -147,7 +147,7 @@ public void testMultipleWithConf2() throws Exception { dependency.setRev("0.10"); dependency.setConf("B"); - List files = asList(resources); + List files = asList(resources); assertEquals(4, files.size()); assertTrue(files.contains(getArchiveFileInCache("org1", "mod1.2", "2.0", "mod1.2", "jar", "jar"))); @@ -176,7 +176,7 @@ public void testExclude() throws Exception { exclude.setOrg("org1"); exclude.setModule("mod1.1"); - List files = asList(resources); + List files = asList(resources); assertEquals(3, files.size()); assertTrue(files.contains(getArchiveFileInCache("org1", "mod1.2", "2.0", "mod1.2", "jar", "jar"))); @@ -227,7 +227,7 @@ public void testDependencyInclude() throws Exception { IvyDependencyInclude include = dependency.createInclude(); include.setName("art22-1"); - List files = asList(resources); + List files = asList(resources); assertEquals(2, files.size()); assertTrue(files.contains(getArchiveFileInCache("org1", "mod1.2", "2.0", "mod1.2", "jar", "jar"))); diff --git a/test/java/org/apache/ivy/ant/IvyTaskTest.java b/test/java/org/apache/ivy/ant/IvyTaskTest.java index ab23d3ef4..cfa9a05ef 100644 --- a/test/java/org/apache/ivy/ant/IvyTaskTest.java +++ b/test/java/org/apache/ivy/ant/IvyTaskTest.java @@ -65,7 +65,6 @@ public void doExecute() throws BuildException { assertEquals("myvalue", settings.getVariables().getVariable("myproperty")); } - @SuppressWarnings("deprecation") @Test public void testReferencedSettings() throws MalformedURLException { Project p = TestHelper.newProject(); @@ -82,7 +81,7 @@ public void doExecute() throws BuildException { } }; task.setProject(p); - task.setSettingsRef(new Reference("mySettings")); + task.setSettingsRef(new Reference(task.getProject(), "mySettings")); Ivy ivy = task.getIvyInstance(); assertNotNull(ivy); IvySettings settings = ivy.getSettings(); diff --git a/test/java/org/apache/ivy/core/module/descriptor/IvyMakePomTest.java b/test/java/org/apache/ivy/core/module/descriptor/IvyMakePomTest.java index b3724794d..04c06e4cf 100644 --- a/test/java/org/apache/ivy/core/module/descriptor/IvyMakePomTest.java +++ b/test/java/org/apache/ivy/core/module/descriptor/IvyMakePomTest.java @@ -17,6 +17,17 @@ package org.apache.ivy.core.module.descriptor; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.xpath.XPathConstants; + import org.apache.ivy.TestHelper; import org.apache.ivy.ant.IvyMakePom; import org.apache.ivy.util.TestXmlHelper; @@ -28,16 +39,6 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import javax.xml.xpath.XPathConstants; -import java.io.File; -import java.util.HashSet; -import java.util.Set; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - /** * Tests {@link IvyMakePom} */ @@ -106,6 +107,7 @@ private static final class PomDependency { private final String version; private final String scope; private final String classifier; + @SuppressWarnings("unused") private final boolean optional; private PomDependency(final String groupId, final String artifactId, final String version, @@ -123,7 +125,6 @@ private PomDependency(final String groupId, final String artifactId, final Strin this.optional = optional; } - static PomDependency parse(final Node dependencyNode) { if (dependencyNode == null) { return null; diff --git a/test/java/org/apache/ivy/core/module/id/ModuleRevisionIdTest.java b/test/java/org/apache/ivy/core/module/id/ModuleRevisionIdTest.java index ca257c5d1..7d0b8b33b 100644 --- a/test/java/org/apache/ivy/core/module/id/ModuleRevisionIdTest.java +++ b/test/java/org/apache/ivy/core/module/id/ModuleRevisionIdTest.java @@ -78,18 +78,18 @@ public void testEncodeDecodeToString() { testEncodeDecodeToString(ModuleRevisionId.newInstance("org", "name", "revision")); testEncodeDecodeToString(ModuleRevisionId.newInstance("org", "name", "")); testEncodeDecodeToString(ModuleRevisionId.newInstance("org.apache", "name-post", "1.0")); - testEncodeDecodeToString(ModuleRevisionId.newInstance("org/apache", "pre/name", - "1.0-dev8/2")); - Map extraAttributes = new HashMap(); + testEncodeDecodeToString( + ModuleRevisionId.newInstance("org/apache", "pre/name", "1.0-dev8/2")); + Map extraAttributes = new HashMap<>(); extraAttributes.put("extra", "extravalue"); extraAttributes.put("att/name", "att/value"); extraAttributes.put("att.name", "att.value"); extraAttributes.put("att rules; - private Object[] rule; + private String[] rule; @Before public void setUp() { - rules = new ModuleRules(); - rule = new Object[10]; + rules = new ModuleRules(); + rule = new String[10]; for (int i = 0; i < rule.length; i++) { rule[i] = "RULE_" + i; } @@ -76,9 +76,9 @@ public void testGetRuleWithFilter() throws Exception { // test helpers - private Filter acceptNone() { - return new Filter() { - public boolean accept(Object o) { + private Filter acceptNone() { + return new Filter() { + public boolean accept(String o) { return false; } @@ -88,11 +88,11 @@ public String toString() { }; } - private Filter acceptSecond() { - return new Filter() { + private Filter acceptSecond() { + return new Filter() { private int cpt; - public boolean accept(Object o) { + public boolean accept(String o) { return ++cpt == 2; } @@ -102,8 +102,8 @@ public String toString() { }; } - private Filter acceptAll() { - return NoFilter.INSTANCE; + private Filter acceptAll() { + return NoFilter.instance(); } private void assertRule(Object rule, String mrid) { @@ -111,13 +111,13 @@ private void assertRule(Object rule, String mrid) { assertEquals("unexcepted rule for " + mrid, rule, ruleFound); } - private void assertRule(Object rule, String mrid, Filter filter) { - Object ruleFound = rules.getRule(ModuleRevisionId.parse(mrid), filter); + private void assertRule(String rule, String mrid, Filter filter) { + String ruleFound = rules.getRule(ModuleRevisionId.parse(mrid), filter); assertEquals("unexcepted rule for " + mrid + " filtered by " + filter, rule, ruleFound); } - private void assertModuleIdRule(Object rule, String mid, Filter filter) { - Object ruleFound = rules.getRule(ModuleId.parse(mid), filter); + private void assertModuleIdRule(Object rule, String mid, Filter filter) { + String ruleFound = rules.getRule(ModuleId.parse(mid), filter); assertEquals("unexcepted rule for " + mid + " filtered by " + filter, rule, ruleFound); } @@ -126,7 +126,7 @@ private MridMatcherBuilder mapMatcher() { } public class MridMatcherBuilder { - private Map attributes = new HashMap(); + private Map attributes = new HashMap<>(); private PatternMatcher matcher = ExactPatternMatcher.INSTANCE; diff --git a/test/java/org/apache/ivy/core/retrieve/RetrieveTest.java b/test/java/org/apache/ivy/core/retrieve/RetrieveTest.java index 12b92bec9..f51c06ec5 100644 --- a/test/java/org/apache/ivy/core/retrieve/RetrieveTest.java +++ b/test/java/org/apache/ivy/core/retrieve/RetrieveTest.java @@ -17,6 +17,12 @@ */ package org.apache.ivy.core.retrieve; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.File; import java.io.IOException; import java.net.URL; @@ -24,6 +30,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.ivy.Ivy; import org.apache.ivy.TestHelper; @@ -36,6 +43,7 @@ import org.apache.ivy.core.event.retrieve.StartRetrieveEvent; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleRevisionId; +import org.apache.ivy.core.report.ArtifactDownloadReport; import org.apache.ivy.core.report.ResolveReport; import org.apache.ivy.core.resolve.ResolveOptions; import org.apache.ivy.util.DefaultMessageLogger; @@ -47,8 +55,6 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; - public class RetrieveTest { private Ivy ivy; @@ -295,8 +301,9 @@ public void testRetrieveReport() throws Exception { ModuleRevisionId mrid = md.getModuleRevisionId(); RetrieveOptions options = getRetrieveOptions(); options.setConfs(new String[] {"A"}); - Map artifactsToCopy = ivy.getRetrieveEngine().determineArtifactsToCopy(mrid, - "build/test/retrieve/[module]/[conf]/[artifact]-[revision].[ext]", options); + Map> artifactsToCopy = ivy.getRetrieveEngine() + .determineArtifactsToCopy(mrid, + "build/test/retrieve/[module]/[conf]/[artifact]-[revision].[ext]", options); assertEquals(2, artifactsToCopy.size()); options.setConfs(new String[] {"B"}); diff --git a/test/java/org/apache/ivy/core/settings/XmlSettingsParserTest.java b/test/java/org/apache/ivy/core/settings/XmlSettingsParserTest.java index e3db04241..83fc9cc97 100644 --- a/test/java/org/apache/ivy/core/settings/XmlSettingsParserTest.java +++ b/test/java/org/apache/ivy/core/settings/XmlSettingsParserTest.java @@ -91,7 +91,7 @@ public void test() throws Exception { assertEquals("libraries", defaultResolver.getName()); assertTrue(defaultResolver instanceof FileSystemResolver); FileSystemResolver fsres = (FileSystemResolver) defaultResolver; - List ivyPatterns = fsres.getIvyPatterns(); + List ivyPatterns = fsres.getIvyPatterns(); assertNotNull(ivyPatterns); assertEquals(1, ivyPatterns.size()); assertLocationEquals("lib/[organisation]/[module]/ivys/ivy-[revision].xml", @@ -105,7 +105,7 @@ public void test() throws Exception { assertNotNull(internal); assertTrue(internal instanceof ChainResolver); ChainResolver chain = (ChainResolver) internal; - List subresolvers = chain.getResolvers(); + List subresolvers = chain.getResolvers(); assertNotNull(subresolvers); assertEquals(2, subresolvers.size()); FileSystemResolver fsInt1 = (FileSystemResolver) subresolvers.get(0); @@ -145,7 +145,7 @@ public void testTypedef() throws Exception { assertNotNull(internal); assertTrue(internal instanceof ChainResolver); ChainResolver chain = (ChainResolver) internal; - List subresolvers = chain.getResolvers(); + List subresolvers = chain.getResolvers(); assertNotNull(subresolvers); assertEquals(2, subresolvers.size()); @@ -318,13 +318,13 @@ public void testRef() throws Exception { assertNotNull(internal); assertTrue(internal instanceof ChainResolver); ChainResolver chain = (ChainResolver) internal; - List subresolvers = chain.getResolvers(); + List subresolvers = chain.getResolvers(); assertNotNull(subresolvers); assertEquals(2, subresolvers.size()); FileSystemResolver fsInt1 = (FileSystemResolver) subresolvers.get(0); assertEquals("fs", fsInt1.getName()); - List ivyPatterns = fsInt1.getIvyPatterns(); + List ivyPatterns = fsInt1.getIvyPatterns(); assertNotNull(ivyPatterns); assertEquals(1, ivyPatterns.size()); assertLocationEquals("sharedrep/[organisation]/[module]/ivys/ivy-[revision].xml", @@ -357,13 +357,13 @@ public void testMacro() throws Exception { assertNotNull(def); assertTrue(def instanceof ChainResolver); ChainResolver chain = (ChainResolver) def; - List subresolvers = chain.getResolvers(); + List subresolvers = chain.getResolvers(); assertNotNull(subresolvers); assertEquals(2, subresolvers.size()); FileSystemResolver fsInt1 = (FileSystemResolver) subresolvers.get(0); assertEquals("default-fs1", fsInt1.getName()); - List ivyPatterns = fsInt1.getIvyPatterns(); + List ivyPatterns = fsInt1.getIvyPatterns(); assertNotNull(ivyPatterns); assertEquals(1, ivyPatterns.size()); assertLocationEquals( @@ -413,7 +413,7 @@ public void testMacroAndRef() throws Exception { assertNotNull(mychain); assertTrue(mychain instanceof ChainResolver); ChainResolver chain = (ChainResolver) mychain; - List subresolvers = chain.getResolvers(); + List subresolvers = chain.getResolvers(); assertNotNull(subresolvers); assertEquals(1, subresolvers.size()); shared = (DependencyResolver) subresolvers.get(0); @@ -437,7 +437,7 @@ public void testMacroAndRef2() throws Exception { assertTrue(testResolver instanceof IBiblioResolver); ChainResolver chain = (ChainResolver) macrores; - List subresolvers = chain.getResolvers(); + List subresolvers = chain.getResolvers(); assertNotNull(subresolvers); assertEquals(1, subresolvers.size()); assertEquals(testResolver, subresolvers.get(0)); @@ -466,13 +466,13 @@ public void testInclude() throws Exception { assertNotNull(def); assertTrue(def instanceof ChainResolver); ChainResolver chain = (ChainResolver) def; - List subresolvers = chain.getResolvers(); + List subresolvers = chain.getResolvers(); assertNotNull(subresolvers); assertEquals(2, subresolvers.size()); FileSystemResolver fsInt1 = (FileSystemResolver) subresolvers.get(0); assertEquals("default-fs1", fsInt1.getName()); - List ivyPatterns = fsInt1.getIvyPatterns(); + List ivyPatterns = fsInt1.getIvyPatterns(); assertNotNull(ivyPatterns); assertEquals(1, ivyPatterns.size()); assertLocationEquals( @@ -523,7 +523,7 @@ public void testIncludeMissingFile() throws Exception { .getResource("ivysettings-include-missing-file.xml")); } - @Test + @Test public void testIncludeSpecialCharInName() throws Exception { IvySettings settings = new IvySettings(); XmlSettingsParser parser = new XmlSettingsParser(settings); @@ -533,13 +533,13 @@ public void testIncludeSpecialCharInName() throws Exception { assertNotNull(def); assertTrue(def instanceof ChainResolver); ChainResolver chain = (ChainResolver) def; - List subresolvers = chain.getResolvers(); + List subresolvers = chain.getResolvers(); assertNotNull(subresolvers); assertEquals(2, subresolvers.size()); FileSystemResolver fsInt1 = (FileSystemResolver) subresolvers.get(0); assertEquals("default-fs1", fsInt1.getName()); - List ivyPatterns = fsInt1.getIvyPatterns(); + List ivyPatterns = fsInt1.getIvyPatterns(); assertNotNull(ivyPatterns); assertEquals(1, ivyPatterns.size()); assertLocationEquals( diff --git a/test/java/org/apache/ivy/osgi/core/OsgiLatestStrategyTest.java b/test/java/org/apache/ivy/osgi/core/OsgiLatestStrategyTest.java index c0f0a8e31..e385f5d1c 100644 --- a/test/java/org/apache/ivy/osgi/core/OsgiLatestStrategyTest.java +++ b/test/java/org/apache/ivy/osgi/core/OsgiLatestStrategyTest.java @@ -17,6 +17,9 @@ */ package org.apache.ivy.osgi.core; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -26,9 +29,6 @@ import org.apache.ivy.plugins.latest.ArtifactInfo; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - public class OsgiLatestStrategyTest { @Test @@ -53,7 +53,7 @@ public void testSort() { ArtifactInfo[] shuffledRevs = shuffled.toArray(new ArtifactInfo[revs.length]); OsgiLatestStrategy latestRevisionStrategy = new OsgiLatestStrategy(); - List sorted = latestRevisionStrategy.sort(shuffledRevs); + List sorted = latestRevisionStrategy.sort(shuffledRevs); assertEquals(Arrays.asList(revs), sorted); } diff --git a/test/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoaderTest.java b/test/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoaderTest.java index 6f2403e5d..c41c80adc 100644 --- a/test/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoaderTest.java +++ b/test/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoaderTest.java @@ -34,12 +34,10 @@ import org.apache.ivy.osgi.repo.RepoDescriptor; import org.apache.ivy.util.CacheCleaner; import org.apache.ivy.util.CollectionUtils; - import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; - import org.xml.sax.SAXException; public class UpdateSiteLoaderTest { @@ -68,9 +66,9 @@ public void testIvyDE() throws IOException, ParseException, SAXException, URISyn RepoDescriptor site = loader.load(new URI( "http://www.apache.org/dist/ant/ivyde/updatesite/")); assertTrue(site.getModules().hasNext()); - for (Iterator it = site.getModules(); it.hasNext();) { - ModuleDescriptor md = ((ModuleDescriptorWrapper) it.next()).getModuleDescriptor(); - String name = md.getModuleRevisionId().getName(); + Iterator it = site.getModules(); + while (it.hasNext()) { + String name = it.next().getModuleDescriptor().getModuleRevisionId().getName(); assertTrue(name, name.startsWith("org.apache.ivy")); } } diff --git a/test/java/org/apache/ivy/plugins/conflict/LatestConflictManagerTest.java b/test/java/org/apache/ivy/plugins/conflict/LatestConflictManagerTest.java index 3a9e1130f..fb69b5f87 100644 --- a/test/java/org/apache/ivy/plugins/conflict/LatestConflictManagerTest.java +++ b/test/java/org/apache/ivy/plugins/conflict/LatestConflictManagerTest.java @@ -17,6 +17,9 @@ */ package org.apache.ivy.plugins.conflict; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import java.io.File; import java.util.Iterator; import java.util.List; @@ -32,9 +35,6 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - public class LatestConflictManagerTest { private Ivy ivy; @@ -60,8 +60,8 @@ public void testIvy388() throws Exception { ResolveReport report = ivy.resolve( LatestConflictManagerTest.class.getResource("ivy-388.xml"), getResolveOptions()); - List deps = report.getDependencies(); - Iterator dependencies = deps.iterator(); + List deps = report.getDependencies(); + Iterator dependencies = deps.iterator(); String[] confs = report.getConfigurations(); while (dependencies.hasNext()) { IvyNode node = (IvyNode) dependencies.next(); diff --git a/test/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParserTest.java b/test/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParserTest.java index 44c77e809..0252ca2cd 100644 --- a/test/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParserTest.java +++ b/test/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParserTest.java @@ -318,7 +318,7 @@ public void testDependenciesWithClassifier() throws Exception { assertEquals(1, dds.length); assertEquals(ModuleRevisionId.newInstance("commons-logging", "commons-logging", "1.0.4"), dds[0].getDependencyRevisionId()); - Map extraAtt = Collections.singletonMap("classifier", "asl"); + Map extraAtt = Collections.singletonMap("classifier", "asl"); assertEquals(1, dds[0].getAllDependencyArtifacts().length); assertEquals(extraAtt, dds[0].getAllDependencyArtifacts()[0].getExtraAttributes()); @@ -508,8 +508,8 @@ public void testOptional() throws Exception { assertEquals(3, dds.length); assertEquals(ModuleRevisionId.newInstance("commons-logging", "commons-logging", "1.0.4"), dds[0].getDependencyRevisionId()); - assertEquals(new HashSet(Arrays.asList(new String[] {"optional"})), - new HashSet(Arrays.asList(dds[0].getModuleConfigurations()))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"optional"})), + new HashSet<>(Arrays.asList(dds[0].getModuleConfigurations()))); // I don't know what it should be. Ivy has no notion of optional dependencies // assertEquals(new HashSet(Arrays.asList(new String[] {"compile(*)", "runtime(*)", // "master(*)"})), new HashSet(Arrays.asList(dds[0] @@ -517,21 +517,21 @@ public void testOptional() throws Exception { assertEquals(ModuleRevisionId.newInstance("cglib", "cglib", "2.0.2"), dds[1].getDependencyRevisionId()); - assertEquals(new HashSet(Arrays.asList(new String[] {"compile", "runtime"})), new HashSet( - Arrays.asList(dds[1].getModuleConfigurations()))); - assertEquals(new HashSet(Arrays.asList(new String[] {"master(*)", "compile(*)"})), - new HashSet(Arrays.asList(dds[1].getDependencyConfigurations("compile")))); - assertEquals(new HashSet(Arrays.asList(new String[] {"runtime(*)"})), - new HashSet(Arrays.asList(dds[1].getDependencyConfigurations("runtime")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"compile", "runtime"})), + new HashSet<>(Arrays.asList(dds[1].getModuleConfigurations()))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"master(*)", "compile(*)"})), + new HashSet<>(Arrays.asList(dds[1].getDependencyConfigurations("compile")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"runtime(*)"})), + new HashSet<>(Arrays.asList(dds[1].getDependencyConfigurations("runtime")))); assertEquals(ModuleRevisionId.newInstance("cglib", "cglib-extra", "2.0.2"), dds[2].getDependencyRevisionId()); - assertEquals(new HashSet(Arrays.asList(new String[] {"compile", "runtime"})), new HashSet( - Arrays.asList(dds[2].getModuleConfigurations()))); - assertEquals(new HashSet(Arrays.asList(new String[] {"master(*)", "compile(*)"})), - new HashSet(Arrays.asList(dds[2].getDependencyConfigurations("compile")))); - assertEquals(new HashSet(Arrays.asList(new String[] {"runtime(*)"})), - new HashSet(Arrays.asList(dds[2].getDependencyConfigurations("runtime")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"compile", "runtime"})), + new HashSet<>(Arrays.asList(dds[2].getModuleConfigurations()))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"master(*)", "compile(*)"})), + new HashSet<>(Arrays.asList(dds[2].getDependencyConfigurations("compile")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"runtime(*)"})), + new HashSet<>(Arrays.asList(dds[2].getDependencyConfigurations("runtime")))); } @Test @@ -548,29 +548,29 @@ public void testDependenciesWithScope() throws Exception { assertEquals(3, dds.length); assertEquals(ModuleRevisionId.newInstance("odmg", "odmg", "3.0"), dds[0].getDependencyRevisionId()); - assertEquals(new HashSet(Arrays.asList(new String[] {"runtime"})), - new HashSet(Arrays.asList(dds[0].getModuleConfigurations()))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"runtime"})), + new HashSet<>(Arrays.asList(dds[0].getModuleConfigurations()))); assertEquals( - new HashSet(Arrays.asList(new String[] {"compile(*)", "runtime(*)", "master(*)"})), - new HashSet(Arrays.asList(dds[0].getDependencyConfigurations("runtime")))); + new HashSet<>(Arrays.asList(new String[] {"compile(*)", "runtime(*)", "master(*)"})), + new HashSet<>(Arrays.asList(dds[0].getDependencyConfigurations("runtime")))); assertEquals(ModuleRevisionId.newInstance("commons-logging", "commons-logging", "1.0.4"), dds[1].getDependencyRevisionId()); - assertEquals(new HashSet(Arrays.asList(new String[] {"compile", "runtime"})), new HashSet( - Arrays.asList(dds[1].getModuleConfigurations()))); - assertEquals(new HashSet(Arrays.asList(new String[] {"master(*)", "compile(*)"})), - new HashSet(Arrays.asList(dds[1].getDependencyConfigurations("compile")))); - assertEquals(new HashSet(Arrays.asList(new String[] {"runtime(*)"})), - new HashSet(Arrays.asList(dds[1].getDependencyConfigurations("runtime")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"compile", "runtime"})), + new HashSet<>(Arrays.asList(dds[1].getModuleConfigurations()))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"master(*)", "compile(*)"})), + new HashSet<>(Arrays.asList(dds[1].getDependencyConfigurations("compile")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"runtime(*)"})), + new HashSet<>(Arrays.asList(dds[1].getDependencyConfigurations("runtime")))); assertEquals(ModuleRevisionId.newInstance("cglib", "cglib", "2.0.2"), dds[2].getDependencyRevisionId()); - assertEquals(new HashSet(Arrays.asList(new String[] {"compile", "runtime"})), new HashSet( - Arrays.asList(dds[2].getModuleConfigurations()))); - assertEquals(new HashSet(Arrays.asList(new String[] {"master(*)", "compile(*)"})), - new HashSet(Arrays.asList(dds[2].getDependencyConfigurations("compile")))); - assertEquals(new HashSet(Arrays.asList(new String[] {"runtime(*)"})), - new HashSet(Arrays.asList(dds[2].getDependencyConfigurations("runtime")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"compile", "runtime"})), + new HashSet<>(Arrays.asList(dds[2].getModuleConfigurations()))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"master(*)", "compile(*)"})), + new HashSet<>(Arrays.asList(dds[2].getDependencyConfigurations("compile")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"runtime(*)"})), + new HashSet<>(Arrays.asList(dds[2].getDependencyConfigurations("runtime")))); } @Test @@ -587,47 +587,51 @@ public void testExclusion() throws Exception { assertEquals(4, dds.length); assertEquals(ModuleRevisionId.newInstance("commons-logging", "commons-logging", "1.0.4"), dds[0].getDependencyRevisionId()); - assertEquals(new HashSet(Arrays.asList(new String[] {"compile", "runtime"})), new HashSet( - Arrays.asList(dds[0].getModuleConfigurations()))); - assertEquals(new HashSet(Arrays.asList(new String[] {"master(*)", "compile(*)"})), - new HashSet(Arrays.asList(dds[0].getDependencyConfigurations("compile")))); - assertEquals(new HashSet(Arrays.asList(new String[] {"runtime(*)"})), - new HashSet(Arrays.asList(dds[0].getDependencyConfigurations("runtime")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"compile", "runtime"})), + new HashSet<>(Arrays.asList(dds[0].getModuleConfigurations()))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"master(*)", "compile(*)"})), + new HashSet<>(Arrays.asList(dds[0].getDependencyConfigurations("compile")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"runtime(*)"})), + new HashSet<>(Arrays.asList(dds[0].getDependencyConfigurations("runtime")))); assertEquals(0, dds[0].getAllExcludeRules().length); assertEquals(ModuleRevisionId.newInstance("dom4j", "dom4j", "1.6"), dds[1].getDependencyRevisionId()); - assertEquals(new HashSet(Arrays.asList(new String[] {"compile", "runtime"})), new HashSet( - Arrays.asList(dds[1].getModuleConfigurations()))); - assertEquals(new HashSet(Arrays.asList(new String[] {"master(*)", "compile(*)"})), - new HashSet(Arrays.asList(dds[1].getDependencyConfigurations("compile")))); - assertEquals(new HashSet(Arrays.asList(new String[] {"runtime(*)"})), - new HashSet(Arrays.asList(dds[1].getDependencyConfigurations("runtime")))); - assertDependencyModulesExcludes(dds[1], new String[] {"compile"}, new String[] { - "jaxme-api", "jaxen"}); - assertDependencyModulesExcludes(dds[1], new String[] {"runtime"}, new String[] { - "jaxme-api", "jaxen"}); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"compile", "runtime"})), + new HashSet<>(Arrays.asList(dds[1].getModuleConfigurations()))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"master(*)", "compile(*)"})), + new HashSet<>(Arrays.asList(dds[1].getDependencyConfigurations("compile")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"runtime(*)"})), + new HashSet<>(Arrays.asList(dds[1].getDependencyConfigurations("runtime")))); + assertDependencyModulesExcludes(dds[1], new String[] {"compile"}, + new String[] {"jaxme-api", "jaxen"}); + assertDependencyModulesExcludes(dds[1], new String[] {"runtime"}, + new String[] {"jaxme-api", "jaxen"}); assertEquals(ModuleRevisionId.newInstance("cglib", "cglib", "2.0.2"), dds[2].getDependencyRevisionId()); - assertEquals(new HashSet(Arrays.asList(new String[] {"compile", "runtime"})), new HashSet( - Arrays.asList(dds[2].getModuleConfigurations()))); - assertEquals(new HashSet(Arrays.asList(new String[] {"master(*)", "compile(*)"})), - new HashSet(Arrays.asList(dds[2].getDependencyConfigurations("compile")))); - assertEquals(new HashSet(Arrays.asList(new String[] {"runtime(*)"})), - new HashSet(Arrays.asList(dds[2].getDependencyConfigurations("runtime")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"compile", "runtime"})), + new HashSet<>(Arrays.asList(dds[2].getModuleConfigurations()))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"master(*)", "compile(*)"})), + new HashSet<>(Arrays.asList(dds[2].getDependencyConfigurations("compile")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"runtime(*)"})), + new HashSet<>(Arrays.asList(dds[2].getDependencyConfigurations("runtime")))); assertEquals(0, dds[2].getAllExcludeRules().length); // test for IVY-1531 (where the pom.xml can have a exclusion for groupid=* and artifactid=*, implying transitive=false, in ivy land) final DependencyDescriptor excludeAllTransitiveDepsDescriptor = dds[3]; - assertEquals(ModuleRevisionId.newInstance("org.owasp.esapi", "esapi", "2.1.0"), excludeAllTransitiveDepsDescriptor.getDependencyRevisionId()); - assertEquals(new HashSet(Arrays.asList(new String[] {"compile", "runtime"})), new HashSet(Arrays.asList(excludeAllTransitiveDepsDescriptor.getModuleConfigurations()))); - assertEquals(new HashSet(Arrays.asList(new String[] {"master(*)", "compile(*)"})), - new HashSet(Arrays.asList(excludeAllTransitiveDepsDescriptor.getDependencyConfigurations("compile")))); - assertEquals(new HashSet(Arrays.asList(new String[] {"runtime(*)"})), - new HashSet(Arrays.asList(excludeAllTransitiveDepsDescriptor.getDependencyConfigurations("runtime")))); - assertEquals("No exclusion elements were expected to be present for " + excludeAllTransitiveDepsDescriptor, 0, excludeAllTransitiveDepsDescriptor.getAllExcludeRules().length); - assertFalse("Dependency " + excludeAllTransitiveDepsDescriptor + " was expected to have transitive=false", excludeAllTransitiveDepsDescriptor.isTransitive()); + assertEquals(ModuleRevisionId.newInstance("org.owasp.esapi", "esapi", "2.1.0"), + excludeAllTransitiveDepsDescriptor.getDependencyRevisionId()); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"compile", "runtime"})), + new HashSet<>(Arrays.asList(excludeAllTransitiveDepsDescriptor.getModuleConfigurations()))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"master(*)", "compile(*)"})), + new HashSet<>(Arrays.asList(excludeAllTransitiveDepsDescriptor.getDependencyConfigurations("compile")))); + assertEquals(new HashSet<>(Arrays.asList(new String[] {"runtime(*)"})), + new HashSet<>(Arrays.asList(excludeAllTransitiveDepsDescriptor.getDependencyConfigurations("runtime")))); + assertEquals("No exclusion elements were expected to be present for " + excludeAllTransitiveDepsDescriptor, + 0, excludeAllTransitiveDepsDescriptor.getAllExcludeRules().length); + assertFalse("Dependency " + excludeAllTransitiveDepsDescriptor + " was expected to have transitive=false", + excludeAllTransitiveDepsDescriptor.isTransitive()); } @Test diff --git a/test/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParserTest.java b/test/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParserTest.java index 8a5514902..229172254 100644 --- a/test/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParserTest.java +++ b/test/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParserTest.java @@ -210,7 +210,6 @@ public void testBadVersion() throws IOException, ParseException { getClass().getResource("test-bad-version.xml"), true); } - @SuppressWarnings("deprecation") @Test public void testFull() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor(settings, @@ -234,8 +233,11 @@ public void testFull() throws Exception { + "and myconf4 is not too bad too.", md.getDescription().replaceAll("\r\n", "\n") .replace('\r', '\n')); - assertEquals(1, md.getExtraInfo().size()); - assertEquals("56576", md.getExtraInfo().get("e:someExtra")); + assertEquals(1, md.getExtraInfos().size()); + ExtraInfoHolder someExtraElement = md.getExtraInfos().get(0); + assertEquals("e:someExtra", someExtraElement.getName()); + assertEquals("56576", someExtraElement.getContent()); + assertEquals(0, someExtraElement.getAttributes().size()); Configuration[] confs = md.getConfigurations(); assertNotNull(confs); @@ -505,24 +507,24 @@ public void testFull() throws Exception { Arrays.asList(rules[1].getConfigurations())); } - @SuppressWarnings("deprecation") @Test public void testFullNoValidation() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor(settings, getClass().getResource("test.xml"), false); assertNotNull(md); - assertEquals(1, md.getExtraInfo().size()); - assertEquals("56576", md.getExtraInfo().get("e:someExtra")); + assertEquals(1, md.getExtraInfos().size()); + ExtraInfoHolder someExtraElement = md.getExtraInfos().get(0); + assertEquals("e:someExtra", someExtraElement.getName()); + assertEquals("56576", someExtraElement.getContent()); + assertEquals(0, someExtraElement.getAttributes().size()); + assertEquals(0, someExtraElement.getNestedExtraInfoHolder().size()); } - @SuppressWarnings("deprecation") @Test public void testExtraInfos() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor(settings, getClass().getResource("test-extrainfo.xml"), true); assertNotNull(md); - assertEquals(2, md.getExtraInfo().size()); - assertEquals("56576", md.getExtraInfo().get("e:someExtra")); assertEquals(2, md.getExtraInfos().size()); ExtraInfoHolder firstExtraInfoElement = md.getExtraInfos().get(0); assertEquals("e:someExtra", firstExtraInfoElement.getName()); @@ -538,14 +540,11 @@ public void testExtraInfos() throws Exception { assertEquals(0, secondExtraInfoElement.getNestedExtraInfoHolder().size()); } - @SuppressWarnings("deprecation") @Test public void testExtraInfosNested() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor(settings, getClass().getResource("test-extrainfo-nested.xml"), true); assertNotNull(md); - assertEquals(4, md.getExtraInfo().size()); - assertEquals("56576", md.getExtraInfo().get("e:someExtra")); assertEquals(2, md.getExtraInfos().size()); ExtraInfoHolder someExtraElement = md.getExtraInfos().get(0); assertEquals("e:someExtra", someExtraElement.getName()); diff --git a/test/java/org/apache/ivy/plugins/parser/xml/XmlModuleUpdaterTest.java b/test/java/org/apache/ivy/plugins/parser/xml/XmlModuleUpdaterTest.java index 5e687b986..ad3de6a83 100644 --- a/test/java/org/apache/ivy/plugins/parser/xml/XmlModuleUpdaterTest.java +++ b/test/java/org/apache/ivy/plugins/parser/xml/XmlModuleUpdaterTest.java @@ -67,14 +67,14 @@ public void testUpdate() throws Exception { XmlModuleDescriptorUpdater.LINE_SEPARATOR = "\n"; File dest = new File("build/updated-test.xml"); dest.deleteOnExit(); - Map resolvedRevisions = new HashMap(); + Map resolvedRevisions = new HashMap<>(); resolvedRevisions.put( ModuleRevisionId.newInstance("yourorg", "yourmodule2", "branch1", "2+"), "2.5"); resolvedRevisions.put( ModuleRevisionId.newInstance("yourorg", "yourmodule6", "trunk", "latest.integration"), "6.3"); - Map resolvedBranches = new HashMap(); + Map resolvedBranches = new HashMap<>(); resolvedBranches.put(ModuleRevisionId.newInstance("yourorg", "yourmodule3", "3.1"), "branch1"); resolvedBranches.put( @@ -126,14 +126,14 @@ public void testVariableReplacement() throws Exception { XmlModuleDescriptorUpdater.LINE_SEPARATOR = "\n"; File dest = new File("build/updated-test2.xml"); dest.deleteOnExit(); - Map resolvedRevisions = new HashMap(); + Map resolvedRevisions = new HashMap<>(); resolvedRevisions.put( ModuleRevisionId.newInstance("yourorg", "yourmodule2", "branch1", "2+"), "2.5"); resolvedRevisions.put( ModuleRevisionId.newInstance("yourorg", "yourmodule6", "trunk", "latest.integration"), "6.3"); - Map resolvedBranches = new HashMap(); + Map resolvedBranches = new HashMap<>(); resolvedBranches.put(ModuleRevisionId.newInstance("yourorg", "yourmodule3", "3.1"), "branch1"); resolvedBranches.put( @@ -366,11 +366,13 @@ public void testMergedUpdateWithExtendsAndExcludes() throws Exception { } private UpdateOptions getUpdateOptions(String status, String revision) { - return getUpdateOptions(new IvySettings(), new HashMap(), status, revision, new Date()); + return getUpdateOptions(new IvySettings(), new HashMap(), status, + revision, new Date()); } - private UpdateOptions getUpdateOptions(IvySettings settings, Map resolvedRevisions, - String status, String revision, Date pubdate) { + private UpdateOptions getUpdateOptions(IvySettings settings, + Map resolvedRevisions, String status, String revision, + Date pubdate) { return new UpdateOptions().setSettings(settings).setResolvedRevisions(resolvedRevisions) .setStatus(status).setRevision(revision).setPubdate(pubdate); } diff --git a/test/java/org/apache/ivy/plugins/resolver/ChainResolverTest.java b/test/java/org/apache/ivy/plugins/resolver/ChainResolverTest.java index 27e9415eb..db1185650 100644 --- a/test/java/org/apache/ivy/plugins/resolver/ChainResolverTest.java +++ b/test/java/org/apache/ivy/plugins/resolver/ChainResolverTest.java @@ -17,6 +17,10 @@ */ package org.apache.ivy.plugins.resolver; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.util.Arrays; import java.util.Collections; import java.util.Date; @@ -48,10 +52,6 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - /** * Tests ChainResolver */ @@ -89,7 +89,7 @@ public void testOrderFromConf() throws Exception { } private void assertResolversSizeAndNames(ChainResolver chain, int size) { - List resolvers = chain.getResolvers(); + List resolvers = chain.getResolvers(); assertEquals(size, resolvers.size()); for (int i = 0; i < resolvers.size(); i++) { DependencyResolver r = (DependencyResolver) resolvers.get(i); @@ -214,13 +214,13 @@ public void testWithDefault() throws Exception { MockResolver.buildMockResolver(settings, "2", true, ModuleRevisionId.newInstance("org", "mod", "4"), new GregorianCalendar(2005, 1, 22).getTime(), true), - // latest -> but default + // latest -> but default MockResolver.buildMockResolver(settings, "3", false, null), MockResolver.buildMockResolver(settings, "4", false, null), MockResolver.buildMockResolver(settings, "5", true, ModuleRevisionId.newInstance("org", "mod", "4"), new GregorianCalendar(2005, 1, 22).getTime()), - // latest -> should be the one kept + // latest -> should be the one kept MockResolver.buildMockResolver(settings, "6", false, null), MockResolver.buildMockResolver(settings, "7", false, null)}; for (MockResolver resolver : resolvers) { @@ -298,12 +298,12 @@ public void testFixedWithDefault() throws Exception { MockResolver.buildMockResolver(settings, "2", true, ModuleRevisionId.newInstance("org", "mod", "4"), new GregorianCalendar(2005, 1, 22).getTime(), true), - // default + // default MockResolver.buildMockResolver(settings, "3", false, null), MockResolver.buildMockResolver(settings, "4", true, ModuleRevisionId.newInstance("org", "mod", "4"), new GregorianCalendar(2005, 1, 22).getTime()), - // not default -> should be the one kept + // not default -> should be the one kept MockResolver.buildMockResolver(settings, "5", false, null)}; for (MockResolver resolver : resolvers) { chain.add(resolver); diff --git a/test/java/org/apache/ivy/plugins/resolver/IBiblioResolverTest.java b/test/java/org/apache/ivy/plugins/resolver/IBiblioResolverTest.java index 743ff0251..edf77a62b 100644 --- a/test/java/org/apache/ivy/plugins/resolver/IBiblioResolverTest.java +++ b/test/java/org/apache/ivy/plugins/resolver/IBiblioResolverTest.java @@ -17,6 +17,12 @@ */ package org.apache.ivy.plugins.resolver; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -51,8 +57,6 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; - /** * */ @@ -87,7 +91,7 @@ public void testDefaults() { _settings.setVariable("ivy.ibiblio.default.artifact.pattern", "[module]/jars/[artifact]-[revision].jar"); resolver.setSettings(_settings); - List l = resolver.getArtifactPatterns(); + List l = resolver.getArtifactPatterns(); assertNotNull(l); assertEquals(1, l.size()); assertEquals("http://www.ibiblio.org/mymaven/[module]/jars/[artifact]-[revision].jar", @@ -104,7 +108,7 @@ public void testInitFromConf() throws Exception { _settings.load(IBiblioResolverTest.class.getResource("ibiblioresolverconf.xml")); IBiblioResolver resolver = (IBiblioResolver) _settings.getResolver("ibiblioA"); assertNotNull(resolver); - List l = resolver.getArtifactPatterns(); + List l = resolver.getArtifactPatterns(); assertNotNull(l); assertEquals(1, l.size()); assertEquals("http://www.ibiblio.org/mymaven/[module]/[artifact]-[revision].jar", l.get(0)); @@ -114,8 +118,7 @@ public void testInitFromConf() throws Exception { l = resolver.getArtifactPatterns(); assertNotNull(l); assertEquals(1, l.size()); - assertEquals( - "http://www.ibiblio.org/mymaven/[organisation]/jars/[artifact]-[revision].jar", + assertEquals("http://www.ibiblio.org/mymaven/[organisation]/jars/[artifact]-[revision].jar", l.get(0)); resolver = (IBiblioResolver) _settings.getResolver("ibiblioC"); @@ -203,6 +206,7 @@ public void testIBiblio() throws Exception { assertEquals(DownloadStatus.NO, ar.getDownloadStatus()); } + @SuppressWarnings({"rawtypes", "unchecked"}) @Test public void testMaven2Listing() throws Exception { IBiblioResolver resolver = new IBiblioResolver(); diff --git a/test/java/org/apache/ivy/plugins/resolver/IvyRepResolverTest.java b/test/java/org/apache/ivy/plugins/resolver/IvyRepResolverTest.java index aba3930e2..44c34633b 100644 --- a/test/java/org/apache/ivy/plugins/resolver/IvyRepResolverTest.java +++ b/test/java/org/apache/ivy/plugins/resolver/IvyRepResolverTest.java @@ -17,6 +17,9 @@ */ package org.apache.ivy.plugins.resolver; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import java.io.File; import java.util.List; @@ -41,8 +44,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.junit.Assert.*; - /** * */ @@ -76,16 +77,15 @@ public void testDefaults() { _settings.setVariable("ivy.ivyrep.default.ivy.root", "http://www.jayasoft.fr/myivyrep/"); _settings.setVariable("ivy.ivyrep.default.ivy.pattern", "[organisation]/[module]/ivy-[revision].[ext]"); - _settings - .setVariable("ivy.ivyrep.default.artifact.root", "http://www.ibiblio.org/mymaven/"); + _settings.setVariable("ivy.ivyrep.default.artifact.root", + "http://www.ibiblio.org/mymaven/"); _settings.setVariable("ivy.ivyrep.default.artifact.pattern", "[module]/jars/[artifact]-[revision].jar"); resolver.setSettings(_settings); - List l = resolver.getIvyPatterns(); + List l = resolver.getIvyPatterns(); assertNotNull(l); assertEquals(1, l.size()); - assertEquals( - "http://www.jayasoft.fr/myivyrep/[organisation]/[module]/ivy-[revision].[ext]", + assertEquals("http://www.jayasoft.fr/myivyrep/[organisation]/[module]/ivy-[revision].[ext]", l.get(0)); l = resolver.getArtifactPatterns(); assertNotNull(l); diff --git a/test/java/org/apache/ivy/util/IvyPatternHelperTest.java b/test/java/org/apache/ivy/util/IvyPatternHelperTest.java index 45939538c..3efbde676 100644 --- a/test/java/org/apache/ivy/util/IvyPatternHelperTest.java +++ b/test/java/org/apache/ivy/util/IvyPatternHelperTest.java @@ -36,7 +36,7 @@ public void testSubstitute() { @Test(expected = Exception.class) public void testCyclicSubstitute() { String pattern = "${var}"; - Map variables = new HashMap(); + Map variables = new HashMap<>(); variables.put("var", "${othervar}"); variables.put("othervar", "${var}"); @@ -45,7 +45,7 @@ public void testCyclicSubstitute() { @Test public void testOptionalSubstitute() { - Map tokens = new HashMap(); + Map tokens = new HashMap<>(); tokens.put("token", ""); tokens.put("othertoken", "myval"); assertEquals("test-myval", diff --git a/test/java/org/apache/ivy/util/url/ArtifactoryListingTest.java b/test/java/org/apache/ivy/util/url/ArtifactoryListingTest.java index 5cee76c0d..dec8746b3 100644 --- a/test/java/org/apache/ivy/util/url/ArtifactoryListingTest.java +++ b/test/java/org/apache/ivy/util/url/ArtifactoryListingTest.java @@ -17,13 +17,13 @@ */ package org.apache.ivy.util.url; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.net.URL; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.Test; public class ArtifactoryListingTest { // remote.test @@ -32,7 +32,7 @@ public class ArtifactoryListingTest { public void testWicketListing() throws Exception { ApacheURLLister lister = new ApacheURLLister(); - List content = lister.listAll(new URL( + List content = lister.listAll(new URL( "http://repo.jfrog.org/artifactory/libs-releases-local/org/apache/wicket/wicket/")); assertNotNull(content); assertEquals(5, content.size()); From 544c04eed61730f2b672a10cde360d6d76cdaace Mon Sep 17 00:00:00 2001 From: twogee Date: Sun, 9 Jul 2017 12:01:05 +0200 Subject: [PATCH 2/6] Checkstyle --- .checkstyle | 1 + src/java/org/apache/ivy/Main.java | 2 +- .../apache/ivy/ant/IvyPostResolveTask.java | 5 +-- .../cache/DefaultResolutionCacheManager.java | 2 +- .../apache/ivy/core/resolve/IvyNodeUsage.java | 10 +++--- .../ivy/core/retrieve/RetrieveEngine.java | 4 +-- .../ivy/osgi/util/VersionComparator.java | 2 +- .../conflict/LatestConflictManager.java | 2 +- .../ivy/plugins/lock/DeleteOnExitHook.java | 3 +- .../ivy/plugins/parser/m2/PomReader.java | 2 +- .../parser/xml/XmlModuleDescriptorParser.java | 2 +- .../ssh/AbstractSshBasedRepository.java | 8 ++--- .../plugins/repository/ssh/SshRepository.java | 2 +- .../plugins/repository/vfs/VfsRepository.java | 2 +- .../plugins/repository/vfs/VfsResource.java | 2 +- src/java/org/apache/ivy/util/FileUtil.java | 4 +-- .../ivy/plugins/resolver/CustomResolver.java | 2 +- test/java/org/apache/ivy/TestHelper.java | 36 ++++++++++--------- .../apache/ivy/ant/AntCallTriggerTest.java | 4 +-- .../apache/ivy/ant/IvyCacheFilesetTest.java | 12 ++++--- .../org/apache/ivy/ant/IvyConfigureTest.java | 8 ++--- .../ivy/ant/testutil/AntTestListener.java | 18 ++++++++++ .../ModuleDescriptorMemoryCacheTest.java | 13 ++++--- .../ivy/core/publish/PublishEventsTest.java | 17 +++++++-- .../core/settings/XmlSettingsParserTest.java | 8 ++--- .../conflict/LatestConflictManagerTest.java | 2 +- .../m2/PomModuleDescriptorParserTest.java | 4 +-- .../plugins/resolver/ChainResolverTest.java | 2 +- .../plugins/resolver/IvyRepResolverTest.java | 2 +- .../org/apache/ivy/util/CacheCleaner.java | 5 ++- .../org/apache/ivy/util/ConfiguratorTest.java | 10 +++--- .../org/apache/ivy/util/TestXmlHelper.java | 9 ++--- 32 files changed, 122 insertions(+), 83 deletions(-) diff --git a/.checkstyle b/.checkstyle index 59fdb69f5..c6310ea58 100644 --- a/.checkstyle +++ b/.checkstyle @@ -25,5 +25,6 @@ + diff --git a/src/java/org/apache/ivy/Main.java b/src/java/org/apache/ivy/Main.java index ad8c4a6f7..99690c1f4 100644 --- a/src/java/org/apache/ivy/Main.java +++ b/src/java/org/apache/ivy/Main.java @@ -507,7 +507,7 @@ private static void invoke(Ivy ivy, File cache, ModuleDescriptor md, String[] co // Add option cp (extra classpath) urls if (fileList != null && fileList.size() > 0) { - for (File file: fileList) { + for (File file : fileList) { try { urls.add(file.toURI().toURL()); } catch (MalformedURLException e) { diff --git a/src/java/org/apache/ivy/ant/IvyPostResolveTask.java b/src/java/org/apache/ivy/ant/IvyPostResolveTask.java index e78858580..36d2d2d51 100644 --- a/src/java/org/apache/ivy/ant/IvyPostResolveTask.java +++ b/src/java/org/apache/ivy/ant/IvyPostResolveTask.java @@ -20,6 +20,7 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; +import java.util.Set; import org.apache.ivy.Ivy; import org.apache.ivy.core.cache.ResolutionCacheManager; @@ -266,7 +267,7 @@ private String[] getConfsToResolve(ModuleDescriptor reference, String conf, Stri confs = splitConfs(conf); } - HashSet rconfsSet = new HashSet<>(); + Set rconfsSet = new HashSet<>(); // for each resolved configuration, check if the report still exists ResolutionCacheManager cache = getSettings().getResolutionCacheManager(); @@ -282,7 +283,7 @@ private String[] getConfsToResolve(ModuleDescriptor reference, String conf, Stri } } - HashSet confsSet = new HashSet<>(Arrays.asList(confs)); + Set confsSet = new HashSet<>(Arrays.asList(confs)); Message.debug("resolved configurations: " + rconfsSet); Message.debug("asked configurations: " + confsSet); confsSet.removeAll(rconfsSet); diff --git a/src/java/org/apache/ivy/core/cache/DefaultResolutionCacheManager.java b/src/java/org/apache/ivy/core/cache/DefaultResolutionCacheManager.java index e143df26a..2d08c44b7 100644 --- a/src/java/org/apache/ivy/core/cache/DefaultResolutionCacheManager.java +++ b/src/java/org/apache/ivy/core/cache/DefaultResolutionCacheManager.java @@ -136,7 +136,7 @@ public File[] getConfigurationResolveReportsInCache(final String resolveId) { final String suffix = ".xml"; return getResolutionCacheRoot().listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { - return (name.startsWith(prefix) && name.endsWith(suffix)); + return name.startsWith(prefix) && name.endsWith(suffix); } }); } diff --git a/src/java/org/apache/ivy/core/resolve/IvyNodeUsage.java b/src/java/org/apache/ivy/core/resolve/IvyNodeUsage.java index 53f857b91..99bdf74e6 100644 --- a/src/java/org/apache/ivy/core/resolve/IvyNodeUsage.java +++ b/src/java/org/apache/ivy/core/resolve/IvyNodeUsage.java @@ -146,7 +146,7 @@ protected void setRequiredConfs(IvyNode parent, String parentConf, Collection * A blacklisted node should be considered as if it doesn't even exist on the repository. *

- * + * * @param rootModuleConf * the root module conf for which we'd like to know if the node is blacklisted - * + * * @return true if this node is blacklisted int he given root module conf, false otherwise * @see #blacklist(IvyNodeBlacklist) */ @@ -278,7 +278,7 @@ protected boolean isBlacklisted(String rootModuleConf) { /** * Returns the blacklist data of this node in the given root module conf, or null * if this node is not blacklisted in this root module conf. - * + * * @param rootModuleConf * the root module configuration to consider * @return the blacklist data if any @@ -294,7 +294,7 @@ protected IvyNode getNode() { /** * Indicates if at least one depender has a transitive dependency descriptor for the given root * module conf. - * + * * @param rootModuleConf * the root module conf to consider * @return true if at least one depender has a transitive dependency descriptor for diff --git a/src/java/org/apache/ivy/core/retrieve/RetrieveEngine.java b/src/java/org/apache/ivy/core/retrieve/RetrieveEngine.java index 022d3a800..9fcf80ac1 100644 --- a/src/java/org/apache/ivy/core/retrieve/RetrieveEngine.java +++ b/src/java/org/apache/ivy/core/retrieve/RetrieveEngine.java @@ -349,8 +349,8 @@ public Map> determineArtifactsToCopy(ModuleR unpackedArtifact = packagingManager.getUnpackedArtifact(artifact); } if (unpackedArtifact == null) { - throw new RuntimeException("Could not determine unpacked artifact for " + artifact + - " while determining artifacts to copy for module " + mrid); + throw new RuntimeException("Could not determine unpacked artifact for " + artifact + + " while determining artifacts to copy for module " + mrid); } ext = unpackedArtifact.getExt(); } diff --git a/src/java/org/apache/ivy/osgi/util/VersionComparator.java b/src/java/org/apache/ivy/osgi/util/VersionComparator.java index 8872431bc..c3559b09f 100644 --- a/src/java/org/apache/ivy/osgi/util/VersionComparator.java +++ b/src/java/org/apache/ivy/osgi/util/VersionComparator.java @@ -33,7 +33,7 @@ private VersionComparator(boolean reverse) { public int compare(Version objA, Version objB) { final int val = objA.compareTo(objB); - return (reverse ? -val : val); + return reverse ? -val : val; } } diff --git a/src/java/org/apache/ivy/plugins/conflict/LatestConflictManager.java b/src/java/org/apache/ivy/plugins/conflict/LatestConflictManager.java index 2237acffb..143d92af7 100644 --- a/src/java/org/apache/ivy/plugins/conflict/LatestConflictManager.java +++ b/src/java/org/apache/ivy/plugins/conflict/LatestConflictManager.java @@ -101,7 +101,7 @@ public Collection resolveConflicts(IvyNode parent, Collection } } - ArrayList unevicted = new ArrayList<>(); + List unevicted = new ArrayList<>(); for (IvyNode node : conflicts) { if (!node.isCompletelyEvicted()) { unevicted.add(node); diff --git a/src/java/org/apache/ivy/plugins/lock/DeleteOnExitHook.java b/src/java/org/apache/ivy/plugins/lock/DeleteOnExitHook.java index c77d536a3..5f6c18a7b 100644 --- a/src/java/org/apache/ivy/plugins/lock/DeleteOnExitHook.java +++ b/src/java/org/apache/ivy/plugins/lock/DeleteOnExitHook.java @@ -20,6 +20,7 @@ import java.io.File; import java.util.Iterator; import java.util.LinkedHashSet; +import java.util.Set; final class DeleteOnExitHook { @@ -31,7 +32,7 @@ public void run() { }); } - private static final LinkedHashSet files = new LinkedHashSet<>(); + private static final Set files = new LinkedHashSet<>(); private DeleteOnExitHook() { } diff --git a/src/java/org/apache/ivy/plugins/parser/m2/PomReader.java b/src/java/org/apache/ivy/plugins/parser/m2/PomReader.java index 91f721b9e..3d6fbb313 100644 --- a/src/java/org/apache/ivy/plugins/parser/m2/PomReader.java +++ b/src/java/org/apache/ivy/plugins/parser/m2/PomReader.java @@ -401,7 +401,7 @@ public List getExcludedModules() { if (exclusionsElement == null) { return Collections.emptyList(); } - LinkedList exclusions = new LinkedList<>(); + List exclusions = new LinkedList<>(); NodeList children = exclusionsElement.getChildNodes(); for (int i = 0, sz = children.getLength(); i < sz; i++) { Node node = children.item(i); diff --git a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java index 9cea4430f..4911c99ce 100644 --- a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java +++ b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java @@ -572,7 +572,7 @@ private static String mergeValue(String inherited, String override) { private static Map mergeValues(Map inherited, Map overrides) { - LinkedHashMap dup = new LinkedHashMap<>(inherited.size() + Map dup = new LinkedHashMap<>(inherited.size() + overrides.size()); dup.putAll(inherited); dup.putAll(overrides); diff --git a/src/java/org/apache/ivy/plugins/repository/ssh/AbstractSshBasedRepository.java b/src/java/org/apache/ivy/plugins/repository/ssh/AbstractSshBasedRepository.java index d96d0c214..3411bd6ed 100644 --- a/src/java/org/apache/ivy/plugins/repository/ssh/AbstractSshBasedRepository.java +++ b/src/java/org/apache/ivy/plugins/repository/ssh/AbstractSshBasedRepository.java @@ -23,16 +23,17 @@ import java.net.URISyntaxException; import java.util.HashMap; import java.util.Locale; +import java.util.Map; import org.apache.ivy.plugins.repository.AbstractRepository; import org.apache.ivy.util.Credentials; import org.apache.ivy.util.CredentialsUtil; import org.apache.ivy.util.Message; +import com.jcraft.jsch.ConfigRepository; import com.jcraft.jsch.ConfigRepository.Config; -import com.jcraft.jsch.Session; import com.jcraft.jsch.OpenSSHConfig; -import com.jcraft.jsch.ConfigRepository; +import com.jcraft.jsch.Session; public abstract class AbstractSshBasedRepository extends AbstractRepository { @@ -61,7 +62,7 @@ public AbstractSshBasedRepository() { /** * hashmap of user/hosts with credentials. key is hostname, value is Credentials **/ - private static final HashMap credentialsCache = new HashMap<>(); + private static final Map credentialsCache = new HashMap<>(); private static final int MAX_CREDENTIALS_CACHE_SIZE = 100; @@ -113,7 +114,6 @@ protected Session getSession(String pathOrUri) throws IOException { } } - if (host == null) { throw new IllegalArgumentException( "missing host information. host should be provided either " diff --git a/src/java/org/apache/ivy/plugins/repository/ssh/SshRepository.java b/src/java/org/apache/ivy/plugins/repository/ssh/SshRepository.java index 49399310a..46b380c16 100644 --- a/src/java/org/apache/ivy/plugins/repository/ssh/SshRepository.java +++ b/src/java/org/apache/ivy/plugins/repository/ssh/SshRepository.java @@ -160,7 +160,7 @@ private void readSessionOutput(ChannelExec channel, StringBuffer strStdout, */ public List list(String parent) throws IOException { Message.debug("SShRepository:list called: " + parent); - ArrayList result = new ArrayList<>(); + List result = new ArrayList<>(); Session session = null; ChannelExec channel = null; session = getSession(parent); diff --git a/src/java/org/apache/ivy/plugins/repository/vfs/VfsRepository.java b/src/java/org/apache/ivy/plugins/repository/vfs/VfsRepository.java index b22025055..4706cb6ca 100644 --- a/src/java/org/apache/ivy/plugins/repository/vfs/VfsRepository.java +++ b/src/java/org/apache/ivy/plugins/repository/vfs/VfsRepository.java @@ -164,7 +164,7 @@ public void get(String srcVfsURI, File destination) throws IOException { * @see "Supported File Systems in the jakarta-commons-vfs documentation" */ public List list(String vfsURI) throws IOException { - ArrayList list = new ArrayList<>(); + List list = new ArrayList<>(); Message.debug("list called for URI" + vfsURI); FileObject resourceImpl = getVFSManager().resolveFile(vfsURI); Message.debug("resourceImpl=" + resourceImpl.toString()); diff --git a/src/java/org/apache/ivy/plugins/repository/vfs/VfsResource.java b/src/java/org/apache/ivy/plugins/repository/vfs/VfsResource.java index 3250e96fe..bf2234627 100644 --- a/src/java/org/apache/ivy/plugins/repository/vfs/VfsResource.java +++ b/src/java/org/apache/ivy/plugins/repository/vfs/VfsResource.java @@ -86,7 +86,7 @@ private void init() { */ public List getChildren() { init(); - ArrayList list = new ArrayList<>(); + List list = new ArrayList<>(); try { if ((resourceImpl != null) && resourceImpl.exists() && (resourceImpl.getType() == FileType.FOLDER)) { diff --git a/src/java/org/apache/ivy/util/FileUtil.java b/src/java/org/apache/ivy/util/FileUtil.java index d78afee8e..56ada7e6a 100644 --- a/src/java/org/apache/ivy/util/FileUtil.java +++ b/src/java/org/apache/ivy/util/FileUtil.java @@ -749,8 +749,8 @@ private DissectedPath(final String root, final String remainingPath) { @Override public String toString() { - return "Dissected Path [root=" + root + ", remainingPath=" + - remainingPath + "]"; + return "Dissected Path [root=" + root + ", remainingPath=" + + remainingPath + "]"; } } } diff --git a/test/custom-classpath/org/apache/ivy/plugins/resolver/CustomResolver.java b/test/custom-classpath/org/apache/ivy/plugins/resolver/CustomResolver.java index cb6b772b6..082c73502 100644 --- a/test/custom-classpath/org/apache/ivy/plugins/resolver/CustomResolver.java +++ b/test/custom-classpath/org/apache/ivy/plugins/resolver/CustomResolver.java @@ -20,7 +20,7 @@ /** * This custom resolver is only used to test custom classpath, and has absolutely * no interest in itself - * + * */ public class CustomResolver extends IBiblioResolver { diff --git a/test/java/org/apache/ivy/TestHelper.java b/test/java/org/apache/ivy/TestHelper.java index ac8b66980..e20144b50 100644 --- a/test/java/org/apache/ivy/TestHelper.java +++ b/test/java/org/apache/ivy/TestHelper.java @@ -17,6 +17,8 @@ */ package org.apache.ivy; +import static org.junit.Assert.assertEquals; + import java.io.File; import java.io.IOException; import java.lang.reflect.Field; @@ -49,8 +51,6 @@ import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Delete; -import static org.junit.Assert.assertEquals; - public class TestHelper { public static DefaultArtifact newArtifact(String organisation, String module, String revision, @@ -120,7 +120,7 @@ public static Collection parseMrids(String mrids) { /** * Returns an array of {@link ModuleRevisionId} corresponding to the given comma separated list * of their text representation. - * + * * @param mrids * the text representation of the {@link ModuleRevisionId} * @return an array of {@link ModuleRevisionId} @@ -134,25 +134,25 @@ public static ModuleRevisionId[] parseMridsToArray(String mrids) { * Parses a string representation of a module descriptor in micro ivy format. *

* Examples: - * + * *

      * #A;1
      * 
- * + * *
- * + * *
      * #A;2-> #B;[1.0,1.5]
      * 
- * + * *
- * + * *
      * #A;3-> { #B;[1.0,1.5] #C;[2.0,2.5] }
      * 
- * + * *

- * + * * @param microIvy * the micro ivy description of the module descriptor * @return the parsed module descriptor @@ -197,7 +197,7 @@ public static ModuleDescriptor parseMicroIvyDescriptor(String microIvy) { /** * Parses a collection of module descriptors in the micro ivy format, separated by double semi * columns. - * + * * @param microIvy * the text representation of the collection of module descriptors * @return the collection of module descriptors parsed @@ -212,7 +212,7 @@ public static Collection parseMicroIvyDescriptors(String micro /** * Fills a repository with a set of module, using empty files for published artifacts. - * + * * @param resolver * the resolver to use to publish the modules * @param mds @@ -256,6 +256,8 @@ public static void fillRepository(DependencyResolver resolver, Collection * When finished you should call {@link #cleanTestRepository()} *

+ * + * @return FileSystemResolver */ public static FileSystemResolver newTestRepository() { FileSystemResolver testRepository = new FileSystemResolver(); @@ -270,7 +272,7 @@ public static FileSystemResolver newTestRepository() { /** * Cleans up the test repository. - * + * * @see #newTestRepository() */ public static void cleanTestRepository() { @@ -279,7 +281,7 @@ public static void cleanTestRepository() { /** * Cleans up the test repository and cache. - * + * * @see #newTestRepository() */ public static void cleanTest() { @@ -290,7 +292,7 @@ public static void cleanTest() { /** * Init a test resolver as default, useful combined with * {@link #fillRepository(DependencyResolver, Collection)}. - * + * * @param settings * the settings to initialize * @return test settings @@ -304,7 +306,7 @@ public static IvySettings loadTestSettings(IvySettings settings) { /** * Create basic resolve data using the given settings - * + * * @param settings * the settings to use to create the resolve data * @return basic resolve data useful for testing @@ -316,7 +318,7 @@ public static ResolveData newResolveData(IvySettings settings) { /** * Create basic resolve options using the given settings - * + * * @param settings * the settings to use to create the resolve options * @return the basic resolve options, useful for testing diff --git a/test/java/org/apache/ivy/ant/AntCallTriggerTest.java b/test/java/org/apache/ivy/ant/AntCallTriggerTest.java index 138336652..1892ac3de 100644 --- a/test/java/org/apache/ivy/ant/AntCallTriggerTest.java +++ b/test/java/org/apache/ivy/ant/AntCallTriggerTest.java @@ -26,7 +26,6 @@ import java.util.Vector; import org.apache.ivy.util.FileUtil; - import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildLogger; import org.apache.tools.ant.DefaultLogger; @@ -37,7 +36,6 @@ import org.apache.tools.ant.ProjectHelper; import org.apache.tools.ant.input.DefaultInputHandler; import org.apache.tools.ant.input.InputHandler; - import org.junit.After; import org.junit.Test; @@ -163,6 +161,8 @@ private void runBuild(File buildFile, Vector targets, int messageLevel) * * @param project * The project to add listeners to. Must not be null. + * @param level + * log level */ protected void addBuildListeners(Project project, int level) { diff --git a/test/java/org/apache/ivy/ant/IvyCacheFilesetTest.java b/test/java/org/apache/ivy/ant/IvyCacheFilesetTest.java index b02c78c01..cc52a66ec 100644 --- a/test/java/org/apache/ivy/ant/IvyCacheFilesetTest.java +++ b/test/java/org/apache/ivy/ant/IvyCacheFilesetTest.java @@ -17,27 +17,29 @@ */ package org.apache.ivy.ant; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.File; import java.util.Arrays; import java.util.List; import org.apache.ivy.TestHelper; import org.apache.ivy.core.report.ArtifactDownloadReport; - import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Delete; import org.apache.tools.ant.types.FileSet; - import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.junit.Assert.*; - public class IvyCacheFilesetTest { private IvyCacheFileset fileset; @@ -263,7 +265,7 @@ public void requireCommonBaseDirCommon() { ); assertNotNull(fileset.requireCommonBaseDir(reports)); } - + private ArtifactDownloadReport artifactDownloadReport(File localFile) { ArtifactDownloadReport report = new ArtifactDownloadReport(null); report.setLocalFile(localFile); diff --git a/test/java/org/apache/ivy/ant/IvyConfigureTest.java b/test/java/org/apache/ivy/ant/IvyConfigureTest.java index 4dc66def3..11fdd6949 100644 --- a/test/java/org/apache/ivy/ant/IvyConfigureTest.java +++ b/test/java/org/apache/ivy/ant/IvyConfigureTest.java @@ -17,6 +17,10 @@ */ package org.apache.ivy.ant; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.io.File; import java.util.List; @@ -27,18 +31,14 @@ import org.apache.ivy.plugins.resolver.DependencyResolver; import org.apache.ivy.plugins.resolver.IBiblioResolver; import org.apache.ivy.plugins.resolver.IvyRepResolver; - import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.Reference; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.junit.Assert.*; - public class IvyConfigureTest { private IvyConfigure configure; diff --git a/test/java/org/apache/ivy/ant/testutil/AntTestListener.java b/test/java/org/apache/ivy/ant/testutil/AntTestListener.java index ef89fa6b7..73866d2b0 100644 --- a/test/java/org/apache/ivy/ant/testutil/AntTestListener.java +++ b/test/java/org/apache/ivy/ant/testutil/AntTestListener.java @@ -30,6 +30,9 @@ public class AntTestListener implements BuildListener { /** * Constructs a test listener which will ignore log events above the given level. + * + * @param logLevel + * ditto */ public AntTestListener(int logLevel) { this.logLevel = logLevel; @@ -37,6 +40,9 @@ public AntTestListener(int logLevel) { /** * Fired before any targets are started. + * + * @param event + * BuildEvent */ public void buildStarted(BuildEvent event) { } @@ -45,6 +51,8 @@ public void buildStarted(BuildEvent event) { * Fired after the last target has finished. This event will still be thrown if an error * occurred during the build. * + * @param event + * BuildEvent * @see BuildEvent#getException() */ public void buildFinished(BuildEvent event) { @@ -53,6 +61,8 @@ public void buildFinished(BuildEvent event) { /** * Fired when a target is started. * + * @param event + * BuildEvent * @see BuildEvent#getTarget() */ public void targetStarted(BuildEvent event) { @@ -63,6 +73,8 @@ public void targetStarted(BuildEvent event) { * Fired when a target has finished. This event will still be thrown if an error occurred during * the build. * + * @param event + * BuildEvent * @see BuildEvent#getException() */ public void targetFinished(BuildEvent event) { @@ -72,6 +84,8 @@ public void targetFinished(BuildEvent event) { /** * Fired when a task is started. * + * @param event + * BuildEvent * @see BuildEvent#getTask() */ public void taskStarted(BuildEvent event) { @@ -82,6 +96,8 @@ public void taskStarted(BuildEvent event) { * Fired when a task has finished. This event will still be throw if an error occurred during * the build. * + * @param event + * BuildEvent * @see BuildEvent#getException() */ public void taskFinished(BuildEvent event) { @@ -91,6 +107,8 @@ public void taskFinished(BuildEvent event) { /** * Fired whenever a message is logged. * + * @param event + * BuildEvent * @see BuildEvent#getMessage() * @see BuildEvent#getPriority() */ diff --git a/test/java/org/apache/ivy/core/cache/ModuleDescriptorMemoryCacheTest.java b/test/java/org/apache/ivy/core/cache/ModuleDescriptorMemoryCacheTest.java index 9052307b2..d28a4a166 100644 --- a/test/java/org/apache/ivy/core/cache/ModuleDescriptorMemoryCacheTest.java +++ b/test/java/org/apache/ivy/core/cache/ModuleDescriptorMemoryCacheTest.java @@ -17,6 +17,9 @@ */ package org.apache.ivy.core.cache; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import java.io.File; import java.io.IOException; import java.text.ParseException; @@ -28,10 +31,6 @@ import org.apache.ivy.plugins.parser.ParserSettings; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - - public class ModuleDescriptorMemoryCacheTest { ModuleDescriptorMemoryCache cache = new ModuleDescriptorMemoryCache(2); @@ -99,8 +98,8 @@ public void testSizeIsLimited() throws ParseException, IOException { ModuleDescriptorProviderMock providerMock3 = new ModuleDescriptorProviderMock(md3); cache.get(url1, ivySettings, false, providerMock); cache.get(url2, ivySettings, false, providerMock2); - cache.get(url3, ivySettings, false, providerMock3);// adding 1 - cache.get(url1, ivySettings, false, providerMock1b);// and one has been removed + cache.get(url3, ivySettings, false, providerMock3); // adding 1 + cache.get(url1, ivySettings, false, providerMock1b); // and one has been removed providerMock1b.assertCalled(); } @@ -114,7 +113,7 @@ public void testLastRecentlyUsedIsFlushedWhenSizeExceed() throws ParseException, cache.get(url2, ivySettings, false, providerMock2); cache.get(url1, ivySettings, false, null); cache.get(url3, ivySettings, false, providerMock3); - cache.get(url1, ivySettings, false, null);// and one has been removed + cache.get(url1, ivySettings, false, null); // and one has been removed cache.get(url2, ivySettings, false, providerMock2b); providerMock2b.assertCalled(); } diff --git a/test/java/org/apache/ivy/core/publish/PublishEventsTest.java b/test/java/org/apache/ivy/core/publish/PublishEventsTest.java index 71b5ed296..cdc5d9182 100644 --- a/test/java/org/apache/ivy/core/publish/PublishEventsTest.java +++ b/test/java/org/apache/ivy/core/publish/PublishEventsTest.java @@ -17,6 +17,13 @@ */ package org.apache.ivy.core.publish; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.File; import java.io.IOException; import java.util.Arrays; @@ -37,13 +44,10 @@ import org.apache.ivy.plugins.parser.xml.XmlModuleDescriptorParser; import org.apache.ivy.plugins.resolver.MockResolver; import org.apache.ivy.plugins.trigger.AbstractTrigger; - import org.junit.After; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; - public class PublishEventsTest { // maps ArtifactRevisionId to PublishTestCase instance. @@ -270,6 +274,13 @@ public void testPublishWithException() { /** * Assert that two Artifact instances refer to the same artifact and contain the same metadata. + * + * @param message + * String + * @param expected + * Artifact + * @param actual + * Artifact */ public static void assertSameArtifact(String message, Artifact expected, Artifact actual) { assertEquals(message + ": name", expected.getName(), actual.getName()); diff --git a/test/java/org/apache/ivy/core/settings/XmlSettingsParserTest.java b/test/java/org/apache/ivy/core/settings/XmlSettingsParserTest.java index 83fc9cc97..2cf7a4fb7 100644 --- a/test/java/org/apache/ivy/core/settings/XmlSettingsParserTest.java +++ b/test/java/org/apache/ivy/core/settings/XmlSettingsParserTest.java @@ -113,7 +113,7 @@ public void test() throws Exception { assertEquals(1, fsInt1.getIvyPatterns().size()); assertLocationEquals("sharedrep/[organisation]/[module]/ivys/ivy-[revision].xml", fsInt1 .getIvyPatterns().get(0)); - assertEquals("int2", ((DependencyResolver) subresolvers.get(1)).getName()); + assertEquals("int2", subresolvers.get(1).getName()); strategy = fsInt1.getLatestStrategy(); assertNotNull(strategy); @@ -149,8 +149,8 @@ public void testTypedef() throws Exception { assertNotNull(subresolvers); assertEquals(2, subresolvers.size()); - assertEquals("mock1", ((DependencyResolver) subresolvers.get(0)).getName()); - assertEquals("mock2", ((DependencyResolver) subresolvers.get(1)).getName()); + assertEquals("mock1", subresolvers.get(0).getName()); + assertEquals("mock2", subresolvers.get(1).getName()); assertTrue(subresolvers.get(0) instanceof MockResolver); assertTrue(subresolvers.get(1) instanceof MockResolver); } @@ -416,7 +416,7 @@ public void testMacroAndRef() throws Exception { List subresolvers = chain.getResolvers(); assertNotNull(subresolvers); assertEquals(1, subresolvers.size()); - shared = (DependencyResolver) subresolvers.get(0); + shared = subresolvers.get(0); assertEquals("shared", shared.getName()); assertTrue(shared instanceof FileSystemResolver); } diff --git a/test/java/org/apache/ivy/plugins/conflict/LatestConflictManagerTest.java b/test/java/org/apache/ivy/plugins/conflict/LatestConflictManagerTest.java index fb69b5f87..932446150 100644 --- a/test/java/org/apache/ivy/plugins/conflict/LatestConflictManagerTest.java +++ b/test/java/org/apache/ivy/plugins/conflict/LatestConflictManagerTest.java @@ -64,7 +64,7 @@ public void testIvy388() throws Exception { Iterator dependencies = deps.iterator(); String[] confs = report.getConfigurations(); while (dependencies.hasNext()) { - IvyNode node = (IvyNode) dependencies.next(); + IvyNode node = dependencies.next(); for (String conf : confs) { if (!node.isEvicted(conf)) { boolean flag1 = report.getConfigurationReport(conf).getDependency( diff --git a/test/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParserTest.java b/test/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParserTest.java index 0252ca2cd..3ed867b9a 100644 --- a/test/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParserTest.java +++ b/test/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParserTest.java @@ -868,8 +868,8 @@ public ResolvedModuleRevision getDependency(DependencyDescriptor dd, ResolveData // 2 are inherited from parent. Only the first one is important for this test assertEquals(ModuleRevisionId.newInstance("org.apache", "test-version-other", "5.76"), - dds[0].getDependencyRevisionId());// present in the pom using a property defined in the - // parent + dds[0].getDependencyRevisionId()); + // present in the pom using a property defined in the parent } @Test diff --git a/test/java/org/apache/ivy/plugins/resolver/ChainResolverTest.java b/test/java/org/apache/ivy/plugins/resolver/ChainResolverTest.java index db1185650..c04894c21 100644 --- a/test/java/org/apache/ivy/plugins/resolver/ChainResolverTest.java +++ b/test/java/org/apache/ivy/plugins/resolver/ChainResolverTest.java @@ -92,7 +92,7 @@ private void assertResolversSizeAndNames(ChainResolver chain, int size) { List resolvers = chain.getResolvers(); assertEquals(size, resolvers.size()); for (int i = 0; i < resolvers.size(); i++) { - DependencyResolver r = (DependencyResolver) resolvers.get(i); + DependencyResolver r = resolvers.get(i); assertEquals(String.valueOf(i + 1), r.getName()); } } diff --git a/test/java/org/apache/ivy/plugins/resolver/IvyRepResolverTest.java b/test/java/org/apache/ivy/plugins/resolver/IvyRepResolverTest.java index 44c34633b..6091f5eb9 100644 --- a/test/java/org/apache/ivy/plugins/resolver/IvyRepResolverTest.java +++ b/test/java/org/apache/ivy/plugins/resolver/IvyRepResolverTest.java @@ -45,7 +45,7 @@ import org.junit.rules.ExpectedException; /** - * + * */ public class IvyRepResolverTest extends AbstractDependencyResolverTest { private IvySettings _settings; diff --git a/test/java/org/apache/ivy/util/CacheCleaner.java b/test/java/org/apache/ivy/util/CacheCleaner.java index 00e4acc9f..6c7c91699 100644 --- a/test/java/org/apache/ivy/util/CacheCleaner.java +++ b/test/java/org/apache/ivy/util/CacheCleaner.java @@ -24,7 +24,10 @@ public class CacheCleaner { /** * Delete the directory and all it contains. Previously, we used the ant delete task, but it * occasionally failed (access denied) on my machine for unknown reason. - **/ + * + * @param toDelete + * File + */ public static void deleteDir(File toDelete) { FileUtil.forceDelete(toDelete); } diff --git a/test/java/org/apache/ivy/util/ConfiguratorTest.java b/test/java/org/apache/ivy/util/ConfiguratorTest.java index 9a2af55d3..532998574 100644 --- a/test/java/org/apache/ivy/util/ConfiguratorTest.java +++ b/test/java/org/apache/ivy/util/ConfiguratorTest.java @@ -17,16 +17,16 @@ */ package org.apache.ivy.util; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; /** * @@ -109,7 +109,7 @@ public void setClazz(Class clazz) { } } - public static abstract class Housing { + public abstract static class Housing { private final List _rooms = new ArrayList<>(); private boolean _isEmpty; diff --git a/test/java/org/apache/ivy/util/TestXmlHelper.java b/test/java/org/apache/ivy/util/TestXmlHelper.java index e0c191e3b..cea9e0bc0 100644 --- a/test/java/org/apache/ivy/util/TestXmlHelper.java +++ b/test/java/org/apache/ivy/util/TestXmlHelper.java @@ -17,14 +17,15 @@ package org.apache.ivy.util; -import org.w3c.dom.Document; +import java.io.File; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; -import java.io.File; + +import org.w3c.dom.Document; /** * An utility class to help with XML file parsing and XML content handling @@ -38,7 +39,7 @@ public class TestXmlHelper { * @param xmlFile The XML file to parse * @param xPathExpression The XPath expression to evaluate * @param returnType The expected return type of the {@link XPathExpression#evaluate(Object, QName) evaluation} - * @return + * @return The result * @throws Exception */ public static Object evaluateXPathExpr(final File xmlFile, final XPathExpression xPathExpression, final QName returnType) @@ -65,7 +66,7 @@ public static Object evaluateXPathExpr(final File xmlFile, final XPathExpression * @param xmlFile The XML file to parse * @param xpathExpression The XPath expression to evaluate * @param returnType The expected return type of the {@link XPathExpression#evaluate(Object, QName) evaluation} - * @return + * @return The result * @throws Exception */ public static Object evaluateXPathExpr(final File xmlFile, final String xpathExpression, final QName returnType) throws Exception { From 3aa259c3be8d146c32cb5aafa4c7909374d4cdda Mon Sep 17 00:00:00 2001 From: twogee Date: Mon, 10 Jul 2017 18:48:36 +0200 Subject: [PATCH 3/6] Code cleanup --- .../apache/ivy/osgi/p2/P2ArtifactParser.java | 2 +- .../apache/ivy/osgi/p2/P2CompositeParser.java | 3 +-- .../apache/ivy/osgi/p2/P2MetadataParser.java | 2 +- .../apache/ivy/osgi/p2/XMLInputParser.java | 3 +-- .../osgi/repo/AbstractFSManifestIterable.java | 18 ++++----------- .../osgi/repo/RepositoryManifestIterable.java | 4 ++-- .../ivy/osgi/updatesite/UpdateSiteLoader.java | 2 +- .../circular/CircularDependencyHelper.java | 23 ++++++------------- .../ivy/plugins/report/XmlReportWriter.java | 6 ++--- .../analyser/JarJarDependencyAnalyser.java | 5 +++- .../org/apache/ivy/util/Configurator.java | 4 ++-- .../ivy/core/module/id/ModuleRulesTest.java | 6 ++--- 12 files changed, 30 insertions(+), 48 deletions(-) diff --git a/src/java/org/apache/ivy/osgi/p2/P2ArtifactParser.java b/src/java/org/apache/ivy/osgi/p2/P2ArtifactParser.java index c0279896d..281895c0b 100644 --- a/src/java/org/apache/ivy/osgi/p2/P2ArtifactParser.java +++ b/src/java/org/apache/ivy/osgi/p2/P2ArtifactParser.java @@ -52,7 +52,7 @@ public P2ArtifactParser(P2Descriptor p2Descriptor, String repoUrl) { this.repoUrl = repoUrl; } - public void parse(InputStream in) throws ParseException, IOException, SAXException { + public void parse(InputStream in) throws IOException, SAXException { RepositoryHandler handler = new RepositoryHandler(p2Descriptor, repoUrl); try { XMLHelper.parse(in, null, handler, null); diff --git a/src/java/org/apache/ivy/osgi/p2/P2CompositeParser.java b/src/java/org/apache/ivy/osgi/p2/P2CompositeParser.java index 3819d6c5d..062e2b8a2 100644 --- a/src/java/org/apache/ivy/osgi/p2/P2CompositeParser.java +++ b/src/java/org/apache/ivy/osgi/p2/P2CompositeParser.java @@ -19,7 +19,6 @@ import java.io.IOException; import java.io.InputStream; -import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; @@ -41,7 +40,7 @@ public Set getChildLocations() { return childLocations; } - public void parse(InputStream in) throws ParseException, IOException, SAXException { + public void parse(InputStream in) throws IOException, SAXException { RepositoryHandler handler = new RepositoryHandler(); try { XMLHelper.parse(in, null, handler, null); diff --git a/src/java/org/apache/ivy/osgi/p2/P2MetadataParser.java b/src/java/org/apache/ivy/osgi/p2/P2MetadataParser.java index eedb4aa4b..fe3d971ea 100644 --- a/src/java/org/apache/ivy/osgi/p2/P2MetadataParser.java +++ b/src/java/org/apache/ivy/osgi/p2/P2MetadataParser.java @@ -56,7 +56,7 @@ public void setLogLevel(int logLevel) { this.logLevel = logLevel; } - public void parse(InputStream in) throws ParseException, IOException, SAXException { + public void parse(InputStream in) throws IOException, SAXException { RepositoryHandler handler = new RepositoryHandler(p2Descriptor); try { XMLHelper.parse(in, null, handler, null); diff --git a/src/java/org/apache/ivy/osgi/p2/XMLInputParser.java b/src/java/org/apache/ivy/osgi/p2/XMLInputParser.java index 617072635..f3faff8c9 100644 --- a/src/java/org/apache/ivy/osgi/p2/XMLInputParser.java +++ b/src/java/org/apache/ivy/osgi/p2/XMLInputParser.java @@ -19,12 +19,11 @@ import java.io.IOException; import java.io.InputStream; -import java.text.ParseException; import org.xml.sax.SAXException; public interface XMLInputParser { - void parse(InputStream in) throws ParseException, IOException, SAXException; + void parse(InputStream in) throws IOException, SAXException; } diff --git a/src/java/org/apache/ivy/osgi/repo/AbstractFSManifestIterable.java b/src/java/org/apache/ivy/osgi/repo/AbstractFSManifestIterable.java index cf1d511e1..7ffcaea62 100644 --- a/src/java/org/apache/ivy/osgi/repo/AbstractFSManifestIterable.java +++ b/src/java/org/apache/ivy/osgi/repo/AbstractFSManifestIterable.java @@ -44,9 +44,9 @@ public Iterator iterator() { return new FSManifestIterator(); } - protected abstract List listBundleFiles(T dir) throws IOException; + protected abstract List listBundleFiles(T dir); - protected abstract List listDirs(T dir) throws IOException; + protected abstract List listDirs(T dir); protected abstract InputStream getInputStream(T f) throws IOException; @@ -86,12 +86,7 @@ public boolean hasNext() { // so get the next one if (dirs.peek().hasNext()) { currentDir = dirs.peek().next(); - try { - bundleCandidates = listBundleFiles(currentDir).iterator(); - } catch (IOException e) { - Message.warn("Unlistable dir: " + currentDir, e); - currentDir = null; - } + bundleCandidates = listBundleFiles(currentDir).iterator(); } else if (dirs.size() <= 1) { // no next directory, but we are at the root: finished return false; @@ -127,12 +122,7 @@ public boolean hasNext() { } else { // no more candidate on the current directory // so lookup in the children directories - try { - dirs.add(listDirs(currentDir).iterator()); - } catch (IOException e) { - Message.warn("Unlistable dir: " + currentDir + " (" + e + ")"); - dirs.add(Collections. emptyList().iterator()); - } + dirs.add(listDirs(currentDir).iterator()); currentDir = null; } } diff --git a/src/java/org/apache/ivy/osgi/repo/RepositoryManifestIterable.java b/src/java/org/apache/ivy/osgi/repo/RepositoryManifestIterable.java index 88ac784b2..95d1332d5 100644 --- a/src/java/org/apache/ivy/osgi/repo/RepositoryManifestIterable.java +++ b/src/java/org/apache/ivy/osgi/repo/RepositoryManifestIterable.java @@ -59,11 +59,11 @@ protected InputStream getInputStream(String f) throws IOException { return repo.getResource(f).openStream(); } - protected List listBundleFiles(String dir) throws IOException { + protected List listBundleFiles(String dir) { return asList(ResolverHelper.listAll(repo, dir)); } - protected List listDirs(String dir) throws IOException { + protected List listDirs(String dir) { return asList(ResolverHelper.listAll(repo, dir)); } diff --git a/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java b/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java index dd0c227c0..62ac6b681 100644 --- a/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java +++ b/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java @@ -173,7 +173,7 @@ private boolean readCompositeArtifact(URI repoUri, String name, P2Descriptor p2D } private boolean readJarOrXml(URI repoUri, String baseName, XMLInputParser reader) - throws IOException, ParseException, SAXException { + throws IOException, SAXException { InputStream readIn = null; // the input stream from which the xml should be read URL contentUrl = repoUri.resolve(baseName + ".jar").toURL(); diff --git a/src/java/org/apache/ivy/plugins/circular/CircularDependencyHelper.java b/src/java/org/apache/ivy/plugins/circular/CircularDependencyHelper.java index 0c99d98de..634ab92b7 100644 --- a/src/java/org/apache/ivy/plugins/circular/CircularDependencyHelper.java +++ b/src/java/org/apache/ivy/plugins/circular/CircularDependencyHelper.java @@ -17,7 +17,9 @@ */ package org.apache.ivy.plugins.circular; +import java.util.Arrays; import java.util.HashSet; +import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -28,7 +30,6 @@ public final class CircularDependencyHelper { /** CircularDependencyHelper is not designed to be an instance */ private CircularDependencyHelper() { - } /** @@ -56,7 +57,7 @@ public static String formatMessage(final ModuleRevisionId[] mrids) { } public static String formatMessage(final ModuleDescriptor[] descriptors) { - return formatMessage(toMrids(descriptors)); + return formatMessageFromDescriptors(Arrays.asList(descriptors)); } /** @@ -65,21 +66,11 @@ public static String formatMessage(final ModuleDescriptor[] descriptors) { * @return String */ public static String formatMessageFromDescriptors(List loopElements) { - ModuleRevisionId[] mrids = new ModuleRevisionId[loopElements.size()]; - int pos = 0; - for (ModuleDescriptor descriptor: loopElements) { - mrids[pos] = descriptor.getModuleRevisionId(); - pos++; - } - return formatMessage(mrids); - } - - public static ModuleRevisionId[] toMrids(ModuleDescriptor[] descriptors) { - ModuleRevisionId[] mrids = new ModuleRevisionId[descriptors.length]; - for (int i = 0; i < descriptors.length; i++) { - mrids[i] = descriptors[i].getModuleRevisionId(); + List mrids = new LinkedList<>(); + for (ModuleDescriptor descriptor : loopElements) { + mrids.add(descriptor.getModuleRevisionId()); } - return mrids; + return formatMessage(mrids.toArray(new ModuleRevisionId[mrids.size()])); } } diff --git a/src/java/org/apache/ivy/plugins/report/XmlReportWriter.java b/src/java/org/apache/ivy/plugins/report/XmlReportWriter.java index 9f33c01b1..deaeec7d9 100644 --- a/src/java/org/apache/ivy/plugins/report/XmlReportWriter.java +++ b/src/java/org/apache/ivy/plugins/report/XmlReportWriter.java @@ -92,7 +92,7 @@ public void output(ConfigurationResolveReport report, String[] confs, OutputStre out.println("\t\t"); for (IvyNode dep : report.getNodes(mid)) { - ouputRevision(report, out, dependencies, dep); + outputRevision(report, out, dependencies, dep); } out.println("\t\t"); } @@ -101,8 +101,8 @@ public void output(ConfigurationResolveReport report, String[] confs, OutputStre out.flush(); } - private void ouputRevision(ConfigurationResolveReport report, PrintWriter out, - List dependencies, IvyNode dep) { + private void outputRevision(ConfigurationResolveReport report, PrintWriter out, + List dependencies, IvyNode dep) { Map extraAttributes; ModuleDescriptor md = null; if (dep.getModuleRevision() != null) { diff --git a/src/java/org/apache/ivy/tools/analyser/JarJarDependencyAnalyser.java b/src/java/org/apache/ivy/tools/analyser/JarJarDependencyAnalyser.java index 2acf2b462..6ba246669 100644 --- a/src/java/org/apache/ivy/tools/analyser/JarJarDependencyAnalyser.java +++ b/src/java/org/apache/ivy/tools/analyser/JarJarDependencyAnalyser.java @@ -52,7 +52,10 @@ public ModuleDescriptor[] analyze(JarModule[] modules) { jarjarCmd.append("\"").append(jarModule.getJar().getAbsolutePath()).append("\""); jarjarCmd.append(File.pathSeparator); } - jarjarCmd.setLength(jarjarCmd.length() - 1); + + if (modules.length > 0) { + jarjarCmd.setLength(jarjarCmd.length() - 1); + } Message.verbose("jarjar command: " + jarjarCmd); diff --git a/src/java/org/apache/ivy/util/Configurator.java b/src/java/org/apache/ivy/util/Configurator.java index 28fe662aa..deac6c819 100644 --- a/src/java/org/apache/ivy/util/Configurator.java +++ b/src/java/org/apache/ivy/util/Configurator.java @@ -513,7 +513,7 @@ public Object startCreateChild(String name) { if (addChild != null) { childClass = addChild.getParameterTypes()[0]; if (Map.class == childClass) { - child = new HashMap(); + child = new HashMap<>(); } else { child = childClass.newInstance(); } @@ -572,7 +572,7 @@ private Object addChild(ObjectDescriptor parentOD, Class childClass, String n if (addChild != null) { if (child == null) { if (Map.class == childClass) { - child = new HashMap(); + child = new HashMap<>(); } else { child = childClass.newInstance(); } diff --git a/test/java/org/apache/ivy/core/module/id/ModuleRulesTest.java b/test/java/org/apache/ivy/core/module/id/ModuleRulesTest.java index 9738daccb..68be4d3d6 100644 --- a/test/java/org/apache/ivy/core/module/id/ModuleRulesTest.java +++ b/test/java/org/apache/ivy/core/module/id/ModuleRulesTest.java @@ -106,8 +106,8 @@ private Filter acceptAll() { return NoFilter.instance(); } - private void assertRule(Object rule, String mrid) { - Object ruleFound = rules.getRule(ModuleRevisionId.parse(mrid)); + private void assertRule(String rule, String mrid) { + String ruleFound = rules.getRule(ModuleRevisionId.parse(mrid)); assertEquals("unexcepted rule for " + mrid, rule, ruleFound); } @@ -116,7 +116,7 @@ private void assertRule(String rule, String mrid, Filter filter) { assertEquals("unexcepted rule for " + mrid + " filtered by " + filter, rule, ruleFound); } - private void assertModuleIdRule(Object rule, String mid, Filter filter) { + private void assertModuleIdRule(String rule, String mid, Filter filter) { String ruleFound = rules.getRule(ModuleId.parse(mid), filter); assertEquals("unexcepted rule for " + mid + " filtered by " + filter, rule, ruleFound); } From dea44c1e76f81896861961f5d4eb8cca6f178291 Mon Sep 17 00:00:00 2001 From: twogee Date: Fri, 14 Jul 2017 16:57:08 +0200 Subject: [PATCH 4/6] Revert potentially incompatible removal of superfluous checked exceptions --- .../apache/ivy/osgi/p2/P2ArtifactParser.java | 2 +- .../apache/ivy/osgi/p2/P2CompositeParser.java | 3 ++- .../apache/ivy/osgi/p2/P2MetadataParser.java | 2 +- .../org/apache/ivy/osgi/p2/XMLInputParser.java | 3 ++- .../osgi/repo/AbstractFSManifestIterable.java | 18 ++++++++++++++---- .../ivy/osgi/repo/FSManifestIterable.java | 5 +++-- .../osgi/repo/RepositoryManifestIterable.java | 4 ++-- .../ivy/osgi/updatesite/UpdateSiteLoader.java | 2 +- .../ivy/plugins/repository/ssh/SshCache.java | 2 +- 9 files changed, 27 insertions(+), 14 deletions(-) diff --git a/src/java/org/apache/ivy/osgi/p2/P2ArtifactParser.java b/src/java/org/apache/ivy/osgi/p2/P2ArtifactParser.java index 281895c0b..9e037f34a 100644 --- a/src/java/org/apache/ivy/osgi/p2/P2ArtifactParser.java +++ b/src/java/org/apache/ivy/osgi/p2/P2ArtifactParser.java @@ -52,7 +52,7 @@ public P2ArtifactParser(P2Descriptor p2Descriptor, String repoUrl) { this.repoUrl = repoUrl; } - public void parse(InputStream in) throws IOException, SAXException { + public void parse(InputStream in) throws IOException, ParseException, SAXException { RepositoryHandler handler = new RepositoryHandler(p2Descriptor, repoUrl); try { XMLHelper.parse(in, null, handler, null); diff --git a/src/java/org/apache/ivy/osgi/p2/P2CompositeParser.java b/src/java/org/apache/ivy/osgi/p2/P2CompositeParser.java index 062e2b8a2..dfac018e0 100644 --- a/src/java/org/apache/ivy/osgi/p2/P2CompositeParser.java +++ b/src/java/org/apache/ivy/osgi/p2/P2CompositeParser.java @@ -19,6 +19,7 @@ import java.io.IOException; import java.io.InputStream; +import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; @@ -40,7 +41,7 @@ public Set getChildLocations() { return childLocations; } - public void parse(InputStream in) throws IOException, SAXException { + public void parse(InputStream in) throws IOException, ParseException, SAXException { RepositoryHandler handler = new RepositoryHandler(); try { XMLHelper.parse(in, null, handler, null); diff --git a/src/java/org/apache/ivy/osgi/p2/P2MetadataParser.java b/src/java/org/apache/ivy/osgi/p2/P2MetadataParser.java index fe3d971ea..44b7a2a6c 100644 --- a/src/java/org/apache/ivy/osgi/p2/P2MetadataParser.java +++ b/src/java/org/apache/ivy/osgi/p2/P2MetadataParser.java @@ -56,7 +56,7 @@ public void setLogLevel(int logLevel) { this.logLevel = logLevel; } - public void parse(InputStream in) throws IOException, SAXException { + public void parse(InputStream in) throws IOException, ParseException, SAXException { RepositoryHandler handler = new RepositoryHandler(p2Descriptor); try { XMLHelper.parse(in, null, handler, null); diff --git a/src/java/org/apache/ivy/osgi/p2/XMLInputParser.java b/src/java/org/apache/ivy/osgi/p2/XMLInputParser.java index f3faff8c9..dfe16df3c 100644 --- a/src/java/org/apache/ivy/osgi/p2/XMLInputParser.java +++ b/src/java/org/apache/ivy/osgi/p2/XMLInputParser.java @@ -19,11 +19,12 @@ import java.io.IOException; import java.io.InputStream; +import java.text.ParseException; import org.xml.sax.SAXException; public interface XMLInputParser { - void parse(InputStream in) throws IOException, SAXException; + void parse(InputStream in) throws IOException, ParseException, SAXException; } diff --git a/src/java/org/apache/ivy/osgi/repo/AbstractFSManifestIterable.java b/src/java/org/apache/ivy/osgi/repo/AbstractFSManifestIterable.java index 7ffcaea62..cf1d511e1 100644 --- a/src/java/org/apache/ivy/osgi/repo/AbstractFSManifestIterable.java +++ b/src/java/org/apache/ivy/osgi/repo/AbstractFSManifestIterable.java @@ -44,9 +44,9 @@ public Iterator iterator() { return new FSManifestIterator(); } - protected abstract List listBundleFiles(T dir); + protected abstract List listBundleFiles(T dir) throws IOException; - protected abstract List listDirs(T dir); + protected abstract List listDirs(T dir) throws IOException; protected abstract InputStream getInputStream(T f) throws IOException; @@ -86,7 +86,12 @@ public boolean hasNext() { // so get the next one if (dirs.peek().hasNext()) { currentDir = dirs.peek().next(); - bundleCandidates = listBundleFiles(currentDir).iterator(); + try { + bundleCandidates = listBundleFiles(currentDir).iterator(); + } catch (IOException e) { + Message.warn("Unlistable dir: " + currentDir, e); + currentDir = null; + } } else if (dirs.size() <= 1) { // no next directory, but we are at the root: finished return false; @@ -122,7 +127,12 @@ public boolean hasNext() { } else { // no more candidate on the current directory // so lookup in the children directories - dirs.add(listDirs(currentDir).iterator()); + try { + dirs.add(listDirs(currentDir).iterator()); + } catch (IOException e) { + Message.warn("Unlistable dir: " + currentDir + " (" + e + ")"); + dirs.add(Collections. emptyList().iterator()); + } currentDir = null; } } diff --git a/src/java/org/apache/ivy/osgi/repo/FSManifestIterable.java b/src/java/org/apache/ivy/osgi/repo/FSManifestIterable.java index f2cb305fd..7c024c722 100644 --- a/src/java/org/apache/ivy/osgi/repo/FSManifestIterable.java +++ b/src/java/org/apache/ivy/osgi/repo/FSManifestIterable.java @@ -22,6 +22,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FilenameFilter; +import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; @@ -108,7 +109,7 @@ protected InputStream getInputStream(File f) throws FileNotFoundException { return new FileInputStream(f); } - protected List listBundleFiles(File dir) { + protected List listBundleFiles(File dir) throws IOException { return Arrays.asList(dir.listFiles(new FileFilter() { public boolean accept(File f) { return f.isFile() && bundleFilter.accept(f.getParentFile(), f.getName()); @@ -116,7 +117,7 @@ public boolean accept(File f) { })); } - protected List listDirs(File dir) { + protected List listDirs(File dir) throws IOException { return Arrays.asList(dir.listFiles(new FileFilter() { public boolean accept(File f) { return f.isDirectory() && (dirFilter == null || dirFilter.accept(f.getParentFile(), f.getName())); diff --git a/src/java/org/apache/ivy/osgi/repo/RepositoryManifestIterable.java b/src/java/org/apache/ivy/osgi/repo/RepositoryManifestIterable.java index 95d1332d5..88ac784b2 100644 --- a/src/java/org/apache/ivy/osgi/repo/RepositoryManifestIterable.java +++ b/src/java/org/apache/ivy/osgi/repo/RepositoryManifestIterable.java @@ -59,11 +59,11 @@ protected InputStream getInputStream(String f) throws IOException { return repo.getResource(f).openStream(); } - protected List listBundleFiles(String dir) { + protected List listBundleFiles(String dir) throws IOException { return asList(ResolverHelper.listAll(repo, dir)); } - protected List listDirs(String dir) { + protected List listDirs(String dir) throws IOException { return asList(ResolverHelper.listAll(repo, dir)); } diff --git a/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java b/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java index 62ac6b681..dd0c227c0 100644 --- a/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java +++ b/src/java/org/apache/ivy/osgi/updatesite/UpdateSiteLoader.java @@ -173,7 +173,7 @@ private boolean readCompositeArtifact(URI repoUri, String name, P2Descriptor p2D } private boolean readJarOrXml(URI repoUri, String baseName, XMLInputParser reader) - throws IOException, SAXException { + throws IOException, ParseException, SAXException { InputStream readIn = null; // the input stream from which the xml should be read URL contentUrl = repoUri.resolve(baseName + ".jar").toURL(); diff --git a/src/java/org/apache/ivy/plugins/repository/ssh/SshCache.java b/src/java/org/apache/ivy/plugins/repository/ssh/SshCache.java index 1240db4a9..04ac8b5fc 100644 --- a/src/java/org/apache/ivy/plugins/repository/ssh/SshCache.java +++ b/src/java/org/apache/ivy/plugins/repository/ssh/SshCache.java @@ -264,7 +264,7 @@ public void clearSession(Session session) { * to connect to * @return channelSftp or null if not successful (channel not existent or dead) */ - public ChannelSftp getChannelSftp(Session session) { + public ChannelSftp getChannelSftp(Session session) throws IOException { ChannelSftp channel = null; Entry entry = getCacheEntry(session); if (entry != null) { From 52b99a74d5770485d95d087aac8a97f8ad6c6795 Mon Sep 17 00:00:00 2001 From: twogee Date: Sat, 15 Jul 2017 18:58:39 +0200 Subject: [PATCH 5/6] Uniform import rules for inner classes; get rid of some suppressed warnings --- .../org/apache/ivy/ant/AntBuildTrigger.java | 3 +- .../org/apache/ivy/ant/AntCallTrigger.java | 3 +- src/java/org/apache/ivy/ant/IvyInfo.java | 10 +-- src/java/org/apache/ivy/ant/IvyReport.java | 10 +-- .../apache/ivy/ant/IvyRepositoryReport.java | 17 ++--- src/java/org/apache/ivy/ant/IvyRetrieve.java | 4 +- src/java/org/apache/ivy/ant/IvyVar.java | 4 +- src/java/org/apache/ivy/core/IvyContext.java | 14 ++-- .../org/apache/ivy/core/IvyPatternHelper.java | 5 +- .../cache/DefaultRepositoryCacheManager.java | 3 +- .../ivy/core/cache/ParserSettingsMonitor.java | 5 +- .../descriptor/DefaultModuleDescriptor.java | 4 +- .../ivy/core/module/id/ModuleRevisionId.java | 5 +- .../ivy/core/publish/PublishEngine.java | 4 +- .../report/ConfigurationResolveReport.java | 6 +- .../org/apache/ivy/core/resolve/IvyNode.java | 9 +-- .../ivy/core/resolve/ResolveEngine.java | 7 +- .../apache/ivy/core/settings/IvySettings.java | 5 +- .../ivy/osgi/core/BundleInfoAdapter.java | 11 +-- .../ivy/osgi/core/ManifestHeaderElement.java | 24 +++---- .../ivy/osgi/core/ManifestHeaderValue.java | 14 ++-- .../apache/ivy/osgi/core/ManifestParser.java | 2 +- .../apache/ivy/osgi/obr/xml/OBRXMLParser.java | 8 +-- .../apache/ivy/osgi/obr/xml/OBRXMLWriter.java | 68 ++++++++++--------- .../ivy/osgi/repo/AbstractOSGiResolver.java | 3 +- .../parser/m2/PomModuleDescriptorBuilder.java | 50 +++++++------- .../parser/m2/PomModuleDescriptorParser.java | 45 +++++------- .../ivy/plugins/parser/m2/PomReader.java | 3 +- .../parser/xml/XmlModuleDescriptorParser.java | 8 ++- .../xml/XmlModuleDescriptorUpdater.java | 8 +-- .../parser/xml/XmlModuleDescriptorWriter.java | 6 +- .../ivy/plugins/report/XmlReportWriter.java | 61 ++++++++--------- .../ivy/plugins/repository/ssh/Scp.java | 25 +++---- .../AbstractPatternsBasedResolver.java | 3 +- .../ivy/plugins/resolver/BasicResolver.java | 5 +- .../ivy/plugins/resolver/IBiblioResolver.java | 2 +- .../resolver/packager/PackagerCacheEntry.java | 3 +- .../resolver/packager/PackagerResolver.java | 5 +- .../apache/ivy/util/ConfigurationUtils.java | 14 ++-- .../org/apache/ivy/util/Configurator.java | 2 - src/java/org/apache/ivy/util/FileUtil.java | 10 +-- .../ivy/util/cli/CommandLineParser.java | 6 +- .../apache/ivy/osgi/obr/OBRResolverTest.java | 14 ++-- .../m2/PomModuleDescriptorParserTest.java | 3 +- .../xml/XmlModuleDescriptorParserTest.java | 64 ++++++++--------- .../xml/XmlModuleDescriptorWriterTest.java | 6 +- 46 files changed, 282 insertions(+), 309 deletions(-) diff --git a/src/java/org/apache/ivy/ant/AntBuildTrigger.java b/src/java/org/apache/ivy/ant/AntBuildTrigger.java index 735fe2332..11ba6f2c2 100644 --- a/src/java/org/apache/ivy/ant/AntBuildTrigger.java +++ b/src/java/org/apache/ivy/ant/AntBuildTrigger.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Map; +import java.util.Map.Entry; import org.apache.ivy.core.IvyContext; import org.apache.ivy.core.IvyPatternHelper; @@ -91,7 +92,7 @@ public void progress(IvyEvent event) { ant.setTarget(target); } Map atts = event.getAttributes(); - for (Map.Entry entry : atts.entrySet()) { + for (Entry entry : atts.entrySet()) { if (entry.getValue() != null) { Property p = ant.createProperty(); p.setName(prefix == null ? entry.getKey() : prefix + entry.getKey()); diff --git a/src/java/org/apache/ivy/ant/AntCallTrigger.java b/src/java/org/apache/ivy/ant/AntCallTrigger.java index 9544e39b6..8d2b4440a 100644 --- a/src/java/org/apache/ivy/ant/AntCallTrigger.java +++ b/src/java/org/apache/ivy/ant/AntCallTrigger.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Map; +import java.util.Map.Entry; import org.apache.ivy.core.IvyContext; import org.apache.ivy.core.IvyPatternHelper; @@ -76,7 +77,7 @@ public void progress(IvyEvent event) { String target = IvyPatternHelper.substituteTokens(getTarget(), attributes); call.setTarget(target); - for (Map.Entry entry : attributes.entrySet()) { + for (Entry entry : attributes.entrySet()) { Property p = call.createParam(); p.setName(prefix == null ? entry.getKey() : prefix + entry.getKey()); p.setValue(entry.getValue() == null ? "" : entry.getValue()); diff --git a/src/java/org/apache/ivy/ant/IvyInfo.java b/src/java/org/apache/ivy/ant/IvyInfo.java index df5c880e2..8a181ac71 100644 --- a/src/java/org/apache/ivy/ant/IvyInfo.java +++ b/src/java/org/apache/ivy/ant/IvyInfo.java @@ -24,11 +24,11 @@ import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import org.apache.ivy.Ivy; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.Configuration; -import org.apache.ivy.core.module.descriptor.Configuration.Visibility; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleId; import org.apache.ivy.core.module.id.ModuleRevisionId; @@ -38,6 +38,8 @@ import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; +import static org.apache.ivy.core.module.descriptor.Configuration.Visibility.PUBLIC; + /** * Parses information about an ivy file and make them available in ant. */ @@ -162,7 +164,7 @@ private void setProperties(ModuleDescriptor md, ModuleRevisionId mrid) { } Map extra = mrid.getExtraAttributes(); - for (Map.Entry entry : extra.entrySet()) { + for (Entry entry : extra.entrySet()) { getProject().setProperty(property + ".extra." + entry.getKey(), entry.getValue()); } @@ -174,7 +176,7 @@ private void setProperties(ModuleDescriptor md, ModuleRevisionId mrid) { List publicConfigsList = new ArrayList<>(); for (Configuration config : md.getConfigurations()) { String name = config.getName(); - if (Visibility.PUBLIC.equals(config.getVisibility())) { + if (PUBLIC.equals(config.getVisibility())) { publicConfigsList.add(name); } @@ -196,7 +198,7 @@ private void setProperties(ModuleDescriptor md, ModuleRevisionId mrid) { mergeConfs(artifact.getConfigurations())); Map artiExtra = artifact.getExtraAttributes(); - for (Map.Entry entry : artiExtra.entrySet()) { + for (Entry entry : artiExtra.entrySet()) { getProject().setProperty(property + ".artifact." + id + ".extra." + entry.getKey(), entry.getValue()); } diff --git a/src/java/org/apache/ivy/ant/IvyReport.java b/src/java/org/apache/ivy/ant/IvyReport.java index b4d411268..de202ce61 100644 --- a/src/java/org/apache/ivy/ant/IvyReport.java +++ b/src/java/org/apache/ivy/ant/IvyReport.java @@ -49,7 +49,7 @@ import org.apache.ivy.util.FileUtil; import org.apache.ivy.util.Message; import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.taskdefs.XSLTProcess; +import org.apache.tools.ant.taskdefs.XSLTProcess.Param; import org.apache.tools.ant.util.JAXPUtils; /** @@ -78,7 +78,7 @@ public class IvyReport extends IvyTask { private String xslext = "html"; - private final List params = new ArrayList<>(); + private final List params = new ArrayList<>(); private String resolveId; @@ -321,7 +321,7 @@ private void genStyled(String[] confs, File style, String ext) throws IOExceptio transformer.setParameter("extension", xslext); // add the provided XSLT parameters - for (XSLTProcess.Param param : params) { + for (Param param : params) { transformer.setParameter(param.getName(), param.getExpression()); } @@ -414,8 +414,8 @@ public void setXslext(String xslext) { this.xslext = xslext; } - public XSLTProcess.Param createParam() { - XSLTProcess.Param result = new XSLTProcess.Param(); + public Param createParam() { + Param result = new Param(); params.add(result); return result; } diff --git a/src/java/org/apache/ivy/ant/IvyRepositoryReport.java b/src/java/org/apache/ivy/ant/IvyRepositoryReport.java index 6ce744528..ba25213fc 100644 --- a/src/java/org/apache/ivy/ant/IvyRepositoryReport.java +++ b/src/java/org/apache/ivy/ant/IvyRepositoryReport.java @@ -38,6 +38,7 @@ import org.apache.ivy.util.FileUtil; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.XSLTProcess; +import org.apache.tools.ant.taskdefs.XSLTProcess.Param; /** * Generates a report of dependencies of a set of modules in the repository. The set of modules is @@ -70,7 +71,7 @@ public class IvyRepositoryReport extends IvyTask { private String xslext = "html"; - private final List params = new ArrayList<>(); + private final List params = new ArrayList<>(); public void doExecute() throws BuildException { Ivy ivy = getIvyInstance(); @@ -142,15 +143,15 @@ private void genreport(ResolutionCacheManager cache, String organisation, String xslt.setStyle(xslFile); - XSLTProcess.Param xslExt = xslt.createParam(); + Param xslExt = xslt.createParam(); xslExt.setName("extension"); xslExt.setExpression(xslext); // add the provided XSLT parameters - for (XSLTProcess.Param param : params) { - XSLTProcess.Param realParam = xslt.createParam(); - realParam.setName(param.getName()); - realParam.setExpression(param.getExpression()); + for (Param parm : params) { + Param realParam = xslt.createParam(); + realParam.setName(parm.getName()); + realParam.setExpression(parm.getExpression()); } xslt.execute(); @@ -251,8 +252,8 @@ public void setXslext(String xslext) { this.xslext = xslext; } - public XSLTProcess.Param createParam() { - XSLTProcess.Param result = new XSLTProcess.Param(); + public Param createParam() { + Param result = new Param(); params.add(result); return result; } diff --git a/src/java/org/apache/ivy/ant/IvyRetrieve.java b/src/java/org/apache/ivy/ant/IvyRetrieve.java index f90403a27..d6946eb44 100644 --- a/src/java/org/apache/ivy/ant/IvyRetrieve.java +++ b/src/java/org/apache/ivy/ant/IvyRetrieve.java @@ -30,7 +30,7 @@ import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Mapper; import org.apache.tools.ant.types.Path; -import org.apache.tools.ant.types.PatternSet; +import org.apache.tools.ant.types.PatternSet.NameEntry; import org.apache.tools.ant.util.FileNameMapper; /** @@ -128,7 +128,7 @@ public void doExecute() throws BuildException { fileset.setDir(report.getRetrieveRoot()); for (File file : report.getRetrievedFiles()) { - PatternSet.NameEntry ne = fileset.createInclude(); + NameEntry ne = fileset.createInclude(); ne.setName(getPath(report.getRetrieveRoot(), file)); } } diff --git a/src/java/org/apache/ivy/ant/IvyVar.java b/src/java/org/apache/ivy/ant/IvyVar.java index dd1738fc1..7fafe57e3 100644 --- a/src/java/org/apache/ivy/ant/IvyVar.java +++ b/src/java/org/apache/ivy/ant/IvyVar.java @@ -21,7 +21,7 @@ import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; -import java.util.Map; +import java.util.Map.Entry; import java.util.Properties; import org.apache.ivy.Ivy; @@ -110,7 +110,7 @@ public void doExecute() throws BuildException { } } } - for (Map.Entry entry : props.entrySet()) { + for (Entry entry : props.entrySet()) { settings.setVariable(getVarName((String) entry.getKey()), (String) entry.getValue()); } } diff --git a/src/java/org/apache/ivy/core/IvyContext.java b/src/java/org/apache/ivy/core/IvyContext.java index b26d69e18..aa902fe86 100644 --- a/src/java/org/apache/ivy/core/IvyContext.java +++ b/src/java/org/apache/ivy/core/IvyContext.java @@ -246,10 +246,10 @@ public Object peek(String key) { return null; } if (o instanceof List) { - if (((List) o).size() == 0) { + if (((List) o).size() == 0) { return null; } - return ((List) o).get(0); + return ((List) o).get(0); } else { throw new RuntimeException("Cannot top from non List object " + o); } @@ -272,10 +272,10 @@ public Object pop(String key) { return null; } if (o instanceof List) { - if (((List) o).size() == 0) { + if (((List) o).size() == 0) { return null; } - return ((List) o).remove(0); + return ((List) o).remove(0); } else { throw new RuntimeException("Cannot pop from non List object " + o); } @@ -301,14 +301,14 @@ public boolean pop(String key, Object expectedValue) { return false; } if (o instanceof List) { - if (((List) o).size() == 0) { + if (((List) o).size() == 0) { return false; } - Object top = ((List) o).get(0); + Object top = ((List) o).get(0); if (!top.equals(expectedValue)) { return false; } - ((List) o).remove(0); + ((List) o).remove(0); return true; } else { throw new RuntimeException("Cannot pop from non List object " + o); diff --git a/src/java/org/apache/ivy/core/IvyPatternHelper.java b/src/java/org/apache/ivy/core/IvyPatternHelper.java index 70bebcde9..83b65a759 100644 --- a/src/java/org/apache/ivy/core/IvyPatternHelper.java +++ b/src/java/org/apache/ivy/core/IvyPatternHelper.java @@ -21,6 +21,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -128,7 +129,7 @@ public static String substitute(String pattern, String org, String module, Strin ArtifactOrigin origin, Map extraModuleAttributes, Map extraArtifactAttributes) { Map tokens = new HashMap<>(); if (extraModuleAttributes != null) { - for (Map.Entry entry : extraModuleAttributes.entrySet()) { + for (Entry entry : extraModuleAttributes.entrySet()) { String token = entry.getKey(); if (token.indexOf(':') > 0) { token = token.substring(token.indexOf(':') + 1); @@ -137,7 +138,7 @@ public static String substitute(String pattern, String org, String module, Strin } } if (extraArtifactAttributes != null) { - for (Map.Entry entry : extraArtifactAttributes.entrySet()) { + for (Entry entry : extraArtifactAttributes.entrySet()) { String token = entry.getKey(); if (token.indexOf(':') > 0) { token = token.substring(token.indexOf(':') + 1); diff --git a/src/java/org/apache/ivy/core/cache/DefaultRepositoryCacheManager.java b/src/java/org/apache/ivy/core/cache/DefaultRepositoryCacheManager.java index c0d2eb595..3302e02f1 100644 --- a/src/java/org/apache/ivy/core/cache/DefaultRepositoryCacheManager.java +++ b/src/java/org/apache/ivy/core/cache/DefaultRepositoryCacheManager.java @@ -32,6 +32,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; @@ -550,7 +551,7 @@ public ArtifactOrigin getSavedArtifactOrigin(Artifact artifact) { // origin. We must parse the key as we do not know for sure what the original // artifact is named. String ownLocationKey = getLocationKey(artifact); - for (Map.Entry entry : cdf.entrySet()) { + for (Entry entry : cdf.entrySet()) { if (entry.getValue().equals(location) && !ownLocationKey.equals(entry.getKey())) { // found a match, key is diff --git a/src/java/org/apache/ivy/core/cache/ParserSettingsMonitor.java b/src/java/org/apache/ivy/core/cache/ParserSettingsMonitor.java index f38357893..8f5b2efca 100644 --- a/src/java/org/apache/ivy/core/cache/ParserSettingsMonitor.java +++ b/src/java/org/apache/ivy/core/cache/ParserSettingsMonitor.java @@ -21,6 +21,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Map.Entry; import org.apache.ivy.core.RelativeUrlResolver; import org.apache.ivy.core.module.id.ModuleId; @@ -77,7 +78,7 @@ public void endMonitoring() { * Only the info that was actually used is compared. */ public boolean hasChanged(ParserSettings newSettings) { - for (Map.Entry entry : substitutes.entrySet()) { + for (Entry entry : substitutes.entrySet()) { String key = entry.getKey(); if (!entry.getValue().equals(newSettings.substitute(key))) { Message.debug("settings variable has changed for : " + key); @@ -131,7 +132,7 @@ public Namespace getContextNamespace() { public Map substitute(Map strings) { Map substituted = new LinkedHashMap<>(); - for (Map.Entry entry : strings.entrySet()) { + for (Entry entry : strings.entrySet()) { substituted.put(entry.getKey(), substitute(entry.getValue())); } return substituted; diff --git a/src/java/org/apache/ivy/core/module/descriptor/DefaultModuleDescriptor.java b/src/java/org/apache/ivy/core/module/descriptor/DefaultModuleDescriptor.java index 2d2b97b18..b4adfc0ef 100644 --- a/src/java/org/apache/ivy/core/module/descriptor/DefaultModuleDescriptor.java +++ b/src/java/org/apache/ivy/core/module/descriptor/DefaultModuleDescriptor.java @@ -53,6 +53,8 @@ import org.apache.ivy.plugins.version.VersionMatcher; import org.apache.ivy.util.Message; +import static org.apache.ivy.core.module.descriptor.Configuration.Visibility.PUBLIC; + /** * */ @@ -415,7 +417,7 @@ public String[] getConfigurationsNames() { public String[] getPublicConfigurationsNames() { List ret = new ArrayList<>(); for (Configuration conf : configurations.values()) { - if (conf.getVisibility() == Configuration.Visibility.PUBLIC) { + if (PUBLIC.equals(conf.getVisibility())) { ret.add(conf.getName()); } } diff --git a/src/java/org/apache/ivy/core/module/id/ModuleRevisionId.java b/src/java/org/apache/ivy/core/module/id/ModuleRevisionId.java index 957915926..e38ab523f 100644 --- a/src/java/org/apache/ivy/core/module/id/ModuleRevisionId.java +++ b/src/java/org/apache/ivy/core/module/id/ModuleRevisionId.java @@ -265,10 +265,9 @@ public String encodeToString() { attributes.putAll(getQualifiedExtraAttributes()); for (Entry att : attributes.entrySet()) { - String attName = att.getKey(); String value = att.getValue(); - value = value == null ? NULL_ENCODE : value; - buf.append(ENCODE_PREFIX).append(attName).append(ENCODE_SEPARATOR) + value = (value == null) ? NULL_ENCODE : value; + buf.append(ENCODE_PREFIX).append(att.getKey()).append(ENCODE_SEPARATOR) .append(ENCODE_PREFIX).append(value).append(ENCODE_SEPARATOR); } return buf.toString(); diff --git a/src/java/org/apache/ivy/core/publish/PublishEngine.java b/src/java/org/apache/ivy/core/publish/PublishEngine.java index 9730957e7..50aa6c38a 100644 --- a/src/java/org/apache/ivy/core/publish/PublishEngine.java +++ b/src/java/org/apache/ivy/core/publish/PublishEngine.java @@ -254,9 +254,7 @@ public Collection publish(ModuleDescriptor md, Collection srcA resolver.beginPublishTransaction(md.getModuleRevisionId(), options.isOverwrite()); // for each declared published artifact in this descriptor, do: for (Entry entry : artifactsFiles.entrySet()) { - Artifact artifact = entry.getKey(); - File artifactFile = entry.getValue(); - publish(artifact, artifactFile, resolver, options.isOverwrite()); + publish(entry.getKey(), entry.getValue(), resolver, options.isOverwrite()); } resolver.commitPublishTransaction(); successfullyPublished = true; diff --git a/src/java/org/apache/ivy/core/report/ConfigurationResolveReport.java b/src/java/org/apache/ivy/core/report/ConfigurationResolveReport.java index c8e28547a..1f2e01c4d 100644 --- a/src/java/org/apache/ivy/core/report/ConfigurationResolveReport.java +++ b/src/java/org/apache/ivy/core/report/ConfigurationResolveReport.java @@ -96,10 +96,8 @@ public void checkIfChanged() { try { XmlReportParser parser = new XmlReportParser(); parser.parse(previousReportFile); - List previousDeps = Arrays.asList(parser - .getDependencyRevisionIds()); - HashSet previousDepSet = new HashSet<>( - previousDeps); + Set previousDepSet = new HashSet<>( + Arrays.asList(parser.getDependencyRevisionIds())); hasChanged = !previousDepSet.equals(getModuleRevisionIds()); } catch (Exception e) { Message.warn("Error while parsing configuration resolve report " diff --git a/src/java/org/apache/ivy/core/resolve/IvyNode.java b/src/java/org/apache/ivy/core/resolve/IvyNode.java index 47bc3e1fa..a10ca0093 100644 --- a/src/java/org/apache/ivy/core/resolve/IvyNode.java +++ b/src/java/org/apache/ivy/core/resolve/IvyNode.java @@ -61,6 +61,9 @@ import org.apache.ivy.util.filter.Filter; import org.apache.ivy.util.filter.FilterHelper; +import static org.apache.ivy.core.module.descriptor.Configuration.Visibility.PRIVATE; +import static org.apache.ivy.core.module.descriptor.Configuration.Visibility.PUBLIC; + public class IvyNode implements Comparable { private static final Pattern FALLBACK_CONF_PATTERN = Pattern.compile("(.+)\\((.*)\\)"); @@ -461,8 +464,7 @@ private boolean handleConfiguration(boolean loaded, String rootModuleConf, IvyNo } return false; } - if (shouldBePublic && !isRoot() - && c.getVisibility() != Configuration.Visibility.PUBLIC) { + if (shouldBePublic && !isRoot() && !PUBLIC.equals(c.getVisibility())) { confsToFetch.remove(conf); if (isConfRequiredByMergedUsageOnly(rootModuleConf, conf)) { Message.verbose("configuration required by evicted revision is not visible in " @@ -660,8 +662,7 @@ public String[] getRealConfs(String conf) { String defaultConf = getDefaultConf(conf); conf = getMainConf(conf); if ((md.getConfiguration(conf) == null) - || Configuration.Visibility.PRIVATE.equals(md.getConfiguration(conf) - .getVisibility())) { + || PRIVATE.equals(md.getConfiguration(conf).getVisibility())) { if ("".equals(defaultConf)) { return new String[0]; } diff --git a/src/java/org/apache/ivy/core/resolve/ResolveEngine.java b/src/java/org/apache/ivy/core/resolve/ResolveEngine.java index 3d538aee8..7af15f965 100644 --- a/src/java/org/apache/ivy/core/resolve/ResolveEngine.java +++ b/src/java/org/apache/ivy/core/resolve/ResolveEngine.java @@ -57,6 +57,7 @@ import org.apache.ivy.core.report.DownloadReport; import org.apache.ivy.core.report.DownloadStatus; import org.apache.ivy.core.report.ResolveReport; +import org.apache.ivy.core.resolve.IvyNodeCallers.Caller; import org.apache.ivy.core.resolve.IvyNodeEviction.EvictionData; import org.apache.ivy.core.settings.IvySettings; import org.apache.ivy.core.sort.SortEngine; @@ -652,13 +653,13 @@ private void handleTransitiveEviction(ModuleDescriptor md, String[] confs, Resol for (IvyNode node : sortedDependencies) { if (!node.isCompletelyEvicted()) { for (String conf : confs) { - IvyNodeCallers.Caller[] callers = node.getCallers(conf); + Caller[] callers = node.getCallers(conf); + boolean allEvicted = callers.length > 0; if (settings.debugConflictResolution()) { Message.debug("checking if " + node.getId() + " is transitively evicted in " + conf); } - boolean allEvicted = callers.length > 0; - for (IvyNodeCallers.Caller caller : callers) { + for (Caller caller : callers) { if (caller.getModuleRevisionId().equals(md.getModuleRevisionId())) { // the caller is the root module itself, it can't be evicted allEvicted = false; diff --git a/src/java/org/apache/ivy/core/settings/IvySettings.java b/src/java/org/apache/ivy/core/settings/IvySettings.java index adaa1886d..989c19940 100644 --- a/src/java/org/apache/ivy/core/settings/IvySettings.java +++ b/src/java/org/apache/ivy/core/settings/IvySettings.java @@ -596,11 +596,10 @@ public synchronized void addAllVariables(Map variables) { } public synchronized void addAllVariables(Map variables, boolean overwrite) { - for (Map.Entry entry : variables.entrySet()) { - String key = entry.getKey().toString(); + for (Entry entry : variables.entrySet()) { Object val = entry.getValue(); if (val == null || val instanceof String) { - setVariable(key, (String) val, overwrite); + setVariable(entry.getKey().toString(), (String) val, overwrite); } } } diff --git a/src/java/org/apache/ivy/osgi/core/BundleInfoAdapter.java b/src/java/org/apache/ivy/osgi/core/BundleInfoAdapter.java index 79c2ad978..57b52f1ee 100644 --- a/src/java/org/apache/ivy/osgi/core/BundleInfoAdapter.java +++ b/src/java/org/apache/ivy/osgi/core/BundleInfoAdapter.java @@ -34,7 +34,6 @@ import org.apache.ivy.Ivy; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.Configuration; -import org.apache.ivy.core.module.descriptor.Configuration.Visibility; import org.apache.ivy.core.module.descriptor.DefaultArtifact; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.DefaultExcludeRule; @@ -49,6 +48,8 @@ import org.apache.ivy.plugins.matcher.PatternMatcher; import org.apache.ivy.plugins.parser.ModuleDescriptorParser; +import static org.apache.ivy.core.module.descriptor.Configuration.Visibility.PUBLIC; + public class BundleInfoAdapter { public static final String CONF_NAME_DEFAULT = "default"; @@ -58,13 +59,13 @@ public class BundleInfoAdapter { public static final String CONF_NAME_OPTIONAL = "optional"; public static final Configuration CONF_OPTIONAL = new Configuration(CONF_NAME_OPTIONAL, - Visibility.PUBLIC, "Optional dependencies", new String[] {CONF_NAME_DEFAULT}, true, + PUBLIC, "Optional dependencies", new String[] {CONF_NAME_DEFAULT}, true, null); public static final String CONF_NAME_TRANSITIVE_OPTIONAL = "transitive-optional"; public static final Configuration CONF_TRANSITIVE_OPTIONAL = new Configuration( - CONF_NAME_TRANSITIVE_OPTIONAL, Visibility.PUBLIC, "Optional dependencies", + CONF_NAME_TRANSITIVE_OPTIONAL, PUBLIC, "Optional dependencies", new String[] {CONF_NAME_OPTIONAL}, true, null); public static final String CONF_USE_PREFIX = "use_"; @@ -113,7 +114,7 @@ public static DefaultModuleDescriptor toModuleDescriptor(ModuleDescriptorParser } confDependencies[i] = CONF_NAME_DEFAULT; md.addConfiguration(new Configuration(CONF_USE_PREFIX + exportPackage.getName(), - Visibility.PUBLIC, "Exported package " + exportPackage.getName(), + PUBLIC, "Exported package " + exportPackage.getName(), confDependencies, true, null)); } @@ -329,7 +330,7 @@ private static void requirementAsDependency(DefaultModuleDescriptor md, BundleIn if (BundleInfo.PACKAGE_TYPE.equals(type)) { // declare the configuration for the package conf = CONF_USE_PREFIX + name; - md.addConfiguration(new Configuration(CONF_USE_PREFIX + name, Visibility.PUBLIC, + md.addConfiguration(new Configuration(CONF_USE_PREFIX + name, PUBLIC, "Exported package " + name, new String[] {CONF_NAME_DEFAULT}, true, null)); dd.addDependencyConfiguration(conf, conf); } diff --git a/src/java/org/apache/ivy/osgi/core/ManifestHeaderElement.java b/src/java/org/apache/ivy/osgi/core/ManifestHeaderElement.java index 96f884f55..efca83f30 100644 --- a/src/java/org/apache/ivy/osgi/core/ManifestHeaderElement.java +++ b/src/java/org/apache/ivy/osgi/core/ManifestHeaderElement.java @@ -19,7 +19,6 @@ import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -88,26 +87,19 @@ public boolean equals(Object obj) { } public String toString() { - String string = ""; - Iterator itValues = values.iterator(); - while (itValues.hasNext()) { - string = string.concat(itValues.next()); - if (itValues.hasNext()) { - string = string.concat(";"); + StringBuilder sb = new StringBuilder(); + for (String value : values) { + if (sb.length() > 0) { + sb.append(";"); } + sb.append(value); } for (Entry directive : directives.entrySet()) { - string = string.concat(";"); - string = string.concat(directive.getKey()); - string = string.concat(":="); - string = string.concat(directive.getValue()); + sb.append(";").append(directive.getKey()).append(":=").append(directive.getValue()); } for (Entry attribute : attributes.entrySet()) { - string = string.concat(";"); - string = string.concat(attribute.getKey()); - string = string.concat("="); - string = string.concat(attribute.getValue()); + sb.append(";").append(attribute.getKey()).append("=").append(attribute.getValue()); } - return string; + return sb.toString(); } } diff --git a/src/java/org/apache/ivy/osgi/core/ManifestHeaderValue.java b/src/java/org/apache/ivy/osgi/core/ManifestHeaderValue.java index 5bff0e0a7..843d3e1f2 100644 --- a/src/java/org/apache/ivy/osgi/core/ManifestHeaderValue.java +++ b/src/java/org/apache/ivy/osgi/core/ManifestHeaderValue.java @@ -21,7 +21,6 @@ import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; -import java.util.Iterator; import java.util.List; /** @@ -394,15 +393,14 @@ public boolean equals(Object obj) { } public String toString() { - String string = ""; - Iterator it = elements.iterator(); - while (it.hasNext()) { - string = string.concat(it.next().toString()); - if (it.hasNext()) { - string = string.concat(","); + StringBuilder sb = new StringBuilder(); + for (ManifestHeaderElement element : elements) { + if (sb.length() > 0) { + sb.append(","); } + sb.append(element.toString()); } - return string; + return sb.toString(); } public static void writeParseException(PrintStream out, String source, ParseException e) { diff --git a/src/java/org/apache/ivy/osgi/core/ManifestParser.java b/src/java/org/apache/ivy/osgi/core/ManifestParser.java index 5ccf3d7e2..7dc61ea24 100644 --- a/src/java/org/apache/ivy/osgi/core/ManifestParser.java +++ b/src/java/org/apache/ivy/osgi/core/ManifestParser.java @@ -75,9 +75,9 @@ public class ManifestParser { public static BundleInfo parseJarManifest(InputStream jarStream) throws IOException, ParseException { - @SuppressWarnings("resource") JarInputStream jis = new JarInputStream(jarStream); Manifest manifest = jis.getManifest(); + jis.close(); if (manifest == null) { return null; } diff --git a/src/java/org/apache/ivy/osgi/obr/xml/OBRXMLParser.java b/src/java/org/apache/ivy/osgi/obr/xml/OBRXMLParser.java index 1bff1083c..a25b05ddb 100644 --- a/src/java/org/apache/ivy/osgi/obr/xml/OBRXMLParser.java +++ b/src/java/org/apache/ivy/osgi/obr/xml/OBRXMLParser.java @@ -321,7 +321,7 @@ static class CapabilityPropertyHandler extends DelegatingHandler { static final String CAPABILITY_PROPERTY = "p"; - static final String NAME = "n"; + static final String CAPABILITY_NAME = "n"; static final String VALUE = "v"; @@ -339,7 +339,7 @@ public CapabilityPropertyHandler() { @Override protected void handleAttributes(Attributes atts) throws SAXException { - name = getRequiredAttribute(atts, NAME); + name = getRequiredAttribute(atts, CAPABILITY_NAME); value = getRequiredAttribute(atts, VALUE); type = atts.getValue(TYPE); } @@ -347,7 +347,7 @@ protected void handleAttributes(Attributes atts) throws SAXException { static class AbstractRequirementHandler extends DelegatingHandler { - static final String NAME = "name"; + static final String REQUIREMENT_NAME = "name"; static final String OPTIONAL = "optional"; @@ -365,7 +365,7 @@ public AbstractRequirementHandler(String name) { @Override protected void handleAttributes(Attributes atts) throws SAXException { - String name = getRequiredAttribute(atts, NAME); + String name = getRequiredAttribute(atts, REQUIREMENT_NAME); String filterText = atts.getValue(FILTER); filter = null; diff --git a/src/java/org/apache/ivy/osgi/obr/xml/OBRXMLWriter.java b/src/java/org/apache/ivy/osgi/obr/xml/OBRXMLWriter.java index 1518d7da1..f9445a10d 100644 --- a/src/java/org/apache/ivy/osgi/obr/xml/OBRXMLWriter.java +++ b/src/java/org/apache/ivy/osgi/obr/xml/OBRXMLWriter.java @@ -35,12 +35,6 @@ import org.apache.ivy.osgi.core.BundleRequirement; import org.apache.ivy.osgi.core.ExportPackage; import org.apache.ivy.osgi.core.ManifestParser; -import org.apache.ivy.osgi.obr.xml.OBRXMLParser.CapabilityHandler; -import org.apache.ivy.osgi.obr.xml.OBRXMLParser.CapabilityPropertyHandler; -import org.apache.ivy.osgi.obr.xml.OBRXMLParser.RepositoryHandler; -import org.apache.ivy.osgi.obr.xml.OBRXMLParser.RequireHandler; -import org.apache.ivy.osgi.obr.xml.OBRXMLParser.ResourceHandler; -import org.apache.ivy.osgi.obr.xml.OBRXMLParser.ResourceSourceHandler; import org.apache.ivy.osgi.repo.ManifestAndLocation; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.osgi.util.VersionRange; @@ -49,6 +43,17 @@ import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; +import static org.apache.ivy.osgi.obr.xml.OBRXMLParser.AbstractRequirementHandler.FILTER; +import static org.apache.ivy.osgi.obr.xml.OBRXMLParser.AbstractRequirementHandler.OPTIONAL; +import static org.apache.ivy.osgi.obr.xml.OBRXMLParser.AbstractRequirementHandler.REQUIREMENT_NAME; +import static org.apache.ivy.osgi.obr.xml.OBRXMLParser.CapabilityHandler.CAPABILITY; +import static org.apache.ivy.osgi.obr.xml.OBRXMLParser.CapabilityHandler.NAME; +import static org.apache.ivy.osgi.obr.xml.OBRXMLParser.CapabilityPropertyHandler.*; +import static org.apache.ivy.osgi.obr.xml.OBRXMLParser.RepositoryHandler.REPOSITORY; +import static org.apache.ivy.osgi.obr.xml.OBRXMLParser.RequireHandler.REQUIRE; +import static org.apache.ivy.osgi.obr.xml.OBRXMLParser.ResourceHandler.*; +import static org.apache.ivy.osgi.obr.xml.OBRXMLParser.ResourceSourceHandler.SOURCE; + public class OBRXMLWriter { public static ContentHandler newHandler(OutputStream out, String encoding, boolean indent) @@ -68,7 +73,7 @@ public static void writeManifests(Iterable manifestAndLocat int level = quiet ? Message.MSG_DEBUG : Message.MSG_WARN; handler.startDocument(); AttributesImpl atts = new AttributesImpl(); - handler.startElement("", RepositoryHandler.REPOSITORY, RepositoryHandler.REPOSITORY, atts); + handler.startElement("", REPOSITORY, REPOSITORY, atts); int nbOk = 0; int nbRejected = 0; for (ManifestAndLocation manifestAndLocation : manifestAndLocations) { @@ -93,7 +98,7 @@ public static void writeManifests(Iterable manifestAndLocat } saxBundleInfo(bundleInfo, handler); } - handler.endElement("", RepositoryHandler.REPOSITORY, RepositoryHandler.REPOSITORY); + handler.endElement("", REPOSITORY, REPOSITORY); handler.endDocument(); Message.info(nbOk + " bundle" + (nbOk > 1 ? "s" : "") + " added, " + nbRejected + " bundle" + (nbRejected > 1 ? "s" : "") + " rejected."); @@ -103,32 +108,31 @@ public static void writeBundles(Iterable bundleInfos, ContentHandler throws SAXException { handler.startDocument(); AttributesImpl atts = new AttributesImpl(); - handler.startElement("", RepositoryHandler.REPOSITORY, RepositoryHandler.REPOSITORY, atts); + handler.startElement("", REPOSITORY, REPOSITORY, atts); for (BundleInfo bundleInfo : bundleInfos) { saxBundleInfo(bundleInfo, handler); } - handler.endElement("", RepositoryHandler.REPOSITORY, RepositoryHandler.REPOSITORY); + handler.endElement("", REPOSITORY, REPOSITORY); handler.endDocument(); } private static void saxBundleInfo(BundleInfo bundleInfo, ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); - addAttr(atts, ResourceHandler.SYMBOLIC_NAME, bundleInfo.getSymbolicName()); - addAttr(atts, ResourceHandler.VERSION, bundleInfo.getRawVersion()); + addAttr(atts, SYMBOLIC_NAME, bundleInfo.getSymbolicName()); + addAttr(atts, VERSION, bundleInfo.getRawVersion()); for (BundleArtifact artifact : bundleInfo.getArtifacts()) { if (!artifact.isSource()) { - addAttr(atts, ResourceHandler.URI, bundleInfo.getArtifacts().get(0).getUri() - .toString()); + addAttr(atts, URI, bundleInfo.getArtifacts().get(0).getUri().toString()); break; } } - handler.startElement("", ResourceHandler.RESOURCE, ResourceHandler.RESOURCE, atts); + handler.startElement("", RESOURCE, RESOURCE, atts); for (BundleArtifact artifact : bundleInfo.getArtifacts()) { if (artifact.isSource()) { - startElement(handler, ResourceSourceHandler.SOURCE); + startElement(handler, SOURCE); characters(handler, artifact.getUri().toString()); - endElement(handler, ResourceSourceHandler.SOURCE); + endElement(handler, SOURCE); break; } } @@ -138,7 +142,7 @@ private static void saxBundleInfo(BundleInfo bundleInfo, ContentHandler handler) for (BundleRequirement requirement : bundleInfo.getRequirements()) { saxRequirement(requirement, handler); } - handler.endElement("", ResourceHandler.RESOURCE, ResourceHandler.RESOURCE); + handler.endElement("", RESOURCE, RESOURCE); handler.characters("\n".toCharArray(), 0, 1); } @@ -146,8 +150,8 @@ private static void saxCapability(BundleCapability capability, ContentHandler ha throws SAXException { AttributesImpl atts = new AttributesImpl(); String type = capability.getType(); - addAttr(atts, CapabilityHandler.NAME, type); - handler.startElement("", CapabilityHandler.CAPABILITY, CapabilityHandler.CAPABILITY, atts); + addAttr(atts, NAME, type); + handler.startElement("", CAPABILITY, CAPABILITY, atts); switch (type) { case BundleInfo.BUNDLE_TYPE: // nothing to do, already handled with the resource tag @@ -183,7 +187,7 @@ private static void saxCapability(BundleCapability capability, ContentHandler ha // oups break; } - handler.endElement("", CapabilityHandler.CAPABILITY, CapabilityHandler.CAPABILITY); + handler.endElement("", CAPABILITY, CAPABILITY); handler.characters("\n".toCharArray(), 0, 1); } @@ -195,28 +199,26 @@ private static void saxCapabilityProperty(String n, String v, ContentHandler han private static void saxCapabilityProperty(String n, String t, String v, ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); - addAttr(atts, CapabilityPropertyHandler.NAME, n); + addAttr(atts, CAPABILITY_NAME, n); if (t != null) { - addAttr(atts, CapabilityPropertyHandler.TYPE, t); + addAttr(atts, TYPE, t); } - addAttr(atts, CapabilityPropertyHandler.VALUE, v); - handler.startElement("", CapabilityPropertyHandler.CAPABILITY_PROPERTY, - CapabilityPropertyHandler.CAPABILITY_PROPERTY, atts); - handler.endElement("", CapabilityPropertyHandler.CAPABILITY_PROPERTY, - CapabilityPropertyHandler.CAPABILITY_PROPERTY); + addAttr(atts, VALUE, v); + handler.startElement("", CAPABILITY_PROPERTY, CAPABILITY_PROPERTY, atts); + handler.endElement("", CAPABILITY_PROPERTY, CAPABILITY_PROPERTY); handler.characters("\n".toCharArray(), 0, 1); } private static void saxRequirement(BundleRequirement requirement, ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); - addAttr(atts, RequireHandler.NAME, requirement.getType()); + addAttr(atts, REQUIREMENT_NAME, requirement.getType()); if ("optional".equals(requirement.getResolution())) { - addAttr(atts, RequireHandler.OPTIONAL, Boolean.TRUE.toString()); + addAttr(atts, OPTIONAL, Boolean.TRUE.toString()); } - addAttr(atts, RequireHandler.FILTER, buildFilter(requirement)); - handler.startElement("", RequireHandler.REQUIRE, RequireHandler.REQUIRE, atts); - handler.endElement("", RequireHandler.REQUIRE, RequireHandler.REQUIRE); + addAttr(atts, FILTER, buildFilter(requirement)); + handler.startElement("", REQUIRE, REQUIRE, atts); + handler.endElement("", REQUIRE, REQUIRE); handler.characters("\n".toCharArray(), 0, 1); } diff --git a/src/java/org/apache/ivy/osgi/repo/AbstractOSGiResolver.java b/src/java/org/apache/ivy/osgi/repo/AbstractOSGiResolver.java index 08e762c68..e39e526c4 100644 --- a/src/java/org/apache/ivy/osgi/repo/AbstractOSGiResolver.java +++ b/src/java/org/apache/ivy/osgi/repo/AbstractOSGiResolver.java @@ -415,13 +415,12 @@ private Set> listTokenValues(Set tokens, Map criteria) { Map stringCriteria = new HashMap<>(); for (Entry entry : criteria.entrySet()) { - String key = entry.getKey(); Object value = entry.getValue(); if (!(value instanceof String)) { // no support for matcher for now return Collections.emptySet(); } - stringCriteria.put(key, (String) value); + stringCriteria.put(entry.getKey(), (String) value); } if (tokens.isEmpty()) { diff --git a/src/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorBuilder.java b/src/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorBuilder.java index e1d15dc34..366f4de58 100644 --- a/src/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorBuilder.java +++ b/src/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorBuilder.java @@ -27,12 +27,12 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import org.apache.ivy.Ivy; import org.apache.ivy.core.cache.ArtifactOrigin; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.Configuration; -import org.apache.ivy.core.module.descriptor.Configuration.Visibility; import org.apache.ivy.core.module.descriptor.DefaultArtifact; import org.apache.ivy.core.module.descriptor.DefaultDependencyArtifactDescriptor; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; @@ -56,6 +56,8 @@ import org.apache.ivy.plugins.resolver.DependencyResolver; import org.apache.ivy.util.Message; +import static org.apache.ivy.core.module.descriptor.Configuration.Visibility.PUBLIC; + /** * Build a module descriptor. This class handle the complexity of the structure of an ivy * ModuleDescriptor and isolate the PomModuleDescriptorParser from it. @@ -65,47 +67,41 @@ public class PomModuleDescriptorBuilder { private static final int DEPENDENCY_MANAGEMENT_KEY_PARTS_COUNT = 4; public static final Configuration[] MAVEN2_CONFIGURATIONS = new Configuration[] { - new Configuration("default", Visibility.PUBLIC, + new Configuration("default", PUBLIC, "runtime dependencies and master artifact can be used with this conf", new String[] {"runtime", "master"}, true, null), - new Configuration("master", Visibility.PUBLIC, + new Configuration("master", PUBLIC, "contains only the artifact published by this module itself, " + "with no transitive dependencies", new String[0], true, null), - new Configuration("compile", Visibility.PUBLIC, + new Configuration("compile", PUBLIC, "this is the default scope, used if none is specified. " + "Compile dependencies are available in all classpaths.", new String[0], true, null), - new Configuration( - "provided", - Visibility.PUBLIC, + new Configuration("provided", PUBLIC, "this is much like compile, but indicates you expect the JDK or a container " + "to provide it. " + "It is only available on the compilation classpath, and is not transitive.", new String[0], true, null), - new Configuration("runtime", Visibility.PUBLIC, + new Configuration("runtime", PUBLIC, "this scope indicates that the dependency is not required for compilation, " + "but is for execution. It is in the runtime and test classpaths, " + "but not the compile classpath.", new String[] {"compile"}, true, null), - new Configuration( - "test", - Visibility.PUBLIC, + new Configuration("test", PUBLIC, "this scope indicates that the dependency is not required for normal use of " + "the application, and is only available for the test compilation and " + "execution phases.", new String[] {"runtime"}, true, null), - new Configuration( - "system", - Visibility.PUBLIC, + new Configuration("system", PUBLIC, "this scope is similar to provided except that you have to provide the JAR " + "which contains it explicitly. The artifact is always available and is not " + "looked up in a repository.", new String[0], true, null), - new Configuration("sources", Visibility.PUBLIC, + new Configuration("sources", PUBLIC, "this configuration contains the source artifact of this module, if any.", new String[0], true, null), - new Configuration("javadoc", Visibility.PUBLIC, + new Configuration("javadoc", PUBLIC, "this configuration contains the javadoc artifact of this module, if any.", new String[0], true, null), - new Configuration("optional", Visibility.PUBLIC, "contains all optional dependencies", + new Configuration("optional", PUBLIC, "contains all optional dependencies", new String[0], true, null)}; static final Map MAVEN2_CONF_MAPPING = new HashMap<>(); @@ -400,7 +396,7 @@ public void addDependencyMgt(PomDependencyMgt dep) { exclusionPrefix + index, excludedModule.getOrganisation() + EXTRA_INFO_DELIMITER + excludedModule.getName()); - index += 1; + index++; } } // dependency management info is also used for version mediation of transitive dependencies @@ -424,7 +420,7 @@ public void addPlugin(PomDependencyMgt plugin) { if (pluginExtraInfo == null) { pluginExtraInfo = pluginValue; } else { - pluginExtraInfo = pluginExtraInfo + "|" + pluginValue; + pluginExtraInfo += "|" + pluginValue; } extraInfoByTagName.setContent(pluginExtraInfo); } @@ -551,7 +547,7 @@ private static List getDependencyMgtExclusions(ModuleDescriptor descri public static Map getDependencyManagementMap(ModuleDescriptor md) { Map ret = new LinkedHashMap<>(); if (md instanceof PomModuleDescriptor) { - for (Map.Entry e : ((PomModuleDescriptor) md) + for (Entry e : ((PomModuleDescriptor) md) .getDependencyManagementMap().entrySet()) { PomDependencyMgt dependencyMgt = e.getValue(); ret.put(e.getKey(), dependencyMgt.getVersion()); @@ -559,7 +555,7 @@ public static Map getDependencyManagementMap(ModuleDescriptor } else { for (ExtraInfoHolder extraInfoHolder : md.getExtraInfos()) { String key = extraInfoHolder.getName(); - if ((key).startsWith(DEPENDENCY_MANAGEMENT)) { + if (key.startsWith(DEPENDENCY_MANAGEMENT)) { String[] parts = key.split(EXTRA_INFO_DELIMITER); if (parts.length != DEPENDENCY_MANAGEMENT_KEY_PARTS_COUNT) { Message.warn("what seem to be a dependency management extra info " @@ -610,7 +606,7 @@ public static List getDependencyManagements(ModuleDescriptor m @Deprecated public void addExtraInfos(Map extraAttributes) { - for (Map.Entry entry : extraAttributes.entrySet()) { + for (Entry entry : extraAttributes.entrySet()) { addExtraInfo(entry.getKey(), entry.getValue()); } } @@ -643,10 +639,10 @@ public void addExtraInfos(List extraInfosHolder) { @Deprecated public static Map extractPomProperties(Map extraInfo) { Map r = new HashMap<>(); - for (Map.Entry extraInfoEntry : extraInfo.entrySet()) { + for (Entry extraInfoEntry : extraInfo.entrySet()) { if (extraInfoEntry.getKey().startsWith(PROPERTIES)) { - String prop = extraInfoEntry.getKey().substring( - PROPERTIES.length() + EXTRA_INFO_DELIMITER.length()); + String prop = extraInfoEntry.getKey().substring(PROPERTIES.length() + + EXTRA_INFO_DELIMITER.length()); r.put(prop, extraInfoEntry.getValue()); } } @@ -656,8 +652,8 @@ public static Map extractPomProperties(Map extra public static Map extractPomProperties(List extraInfos) { Map r = new HashMap<>(); for (ExtraInfoHolder extraInfoHolder : extraInfos) { - if ((extraInfoHolder.getName()).startsWith(PROPERTIES)) { - String prop = (extraInfoHolder.getName()).substring(PROPERTIES.length() + if (extraInfoHolder.getName().startsWith(PROPERTIES)) { + String prop = extraInfoHolder.getName().substring(PROPERTIES.length() + EXTRA_INFO_DELIMITER.length()); r.put(prop, extraInfoHolder.getContent()); } diff --git a/src/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParser.java b/src/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParser.java index ced6e55ab..bc60c6a48 100644 --- a/src/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParser.java +++ b/src/java/org/apache/ivy/plugins/parser/m2/PomModuleDescriptorParser.java @@ -23,14 +23,11 @@ import java.net.URL; import java.text.ParseException; import java.util.Date; -import java.util.List; -import java.util.Map; +import java.util.Map.Entry; -import org.apache.ivy.core.IvyContext; import org.apache.ivy.core.cache.ArtifactOrigin; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.Configuration; -import org.apache.ivy.core.module.descriptor.Configuration.Visibility; import org.apache.ivy.core.module.descriptor.DefaultArtifact; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.DependencyDescriptor; @@ -41,10 +38,8 @@ import org.apache.ivy.core.resolve.ResolveEngine; import org.apache.ivy.core.resolve.ResolveOptions; import org.apache.ivy.core.resolve.ResolvedModuleRevision; -import org.apache.ivy.plugins.namespace.NameSpaceHelper; import org.apache.ivy.plugins.parser.ModuleDescriptorParser; import org.apache.ivy.plugins.parser.ParserSettings; -import org.apache.ivy.plugins.parser.m2.PomModuleDescriptorBuilder.PomDependencyDescriptor; import org.apache.ivy.plugins.parser.m2.PomReader.PomDependencyData; import org.apache.ivy.plugins.parser.m2.PomReader.PomDependencyMgtElement; import org.apache.ivy.plugins.parser.m2.PomReader.PomPluginElement; @@ -56,6 +51,11 @@ import org.apache.ivy.util.Message; import org.xml.sax.SAXException; +import static org.apache.ivy.core.IvyContext.getContext; +import static org.apache.ivy.core.module.descriptor.Configuration.Visibility.PUBLIC; +import static org.apache.ivy.plugins.namespace.NameSpaceHelper.toSystem; +import static org.apache.ivy.plugins.parser.m2.PomModuleDescriptorBuilder.*; + /** * A parser for Maven 2 POM. *

@@ -125,8 +125,7 @@ public ModuleDescriptor parseDescriptor(ParserSettings ivySettings, URL descript domReader.setProperty("project.parent.version", domReader.getParentVersion()); domReader.setProperty("project.parent.groupId", domReader.getParentGroupId()); - Map pomProperties = domReader.getPomProperties(); - for (Map.Entry prop : pomProperties.entrySet()) { + for (Entry prop : domReader.getPomProperties().entrySet()) { domReader.setProperty(prop.getKey(), prop.getValue()); mdBuilder.addProperty(prop.getKey(), prop.getValue()); } @@ -145,9 +144,8 @@ public ModuleDescriptor parseDescriptor(ParserSettings ivySettings, URL descript } parentDescr = parentModule.getDescriptor(); if (parentDescr != null) { - Map parentPomProps = PomModuleDescriptorBuilder - .extractPomProperties(parentDescr.getExtraInfos()); - for (Map.Entry prop : parentPomProps.entrySet()) { + for (Entry prop : + extractPomProperties(parentDescr.getExtraInfos()).entrySet()) { domReader.setProperty(prop.getKey(), prop.getValue()); } } @@ -187,8 +185,7 @@ public ModuleDescriptor parseDescriptor(ParserSettings ivySettings, URL descript + " has been relocated", 0); } - for (DependencyDescriptor dd : relocatedModule.getDescriptor() - .getDependencies()) { + for (DependencyDescriptor dd : relocatedModule.getDescriptor().getDependencies()) { mdBuilder.addDependency(dd); } } else { @@ -199,9 +196,8 @@ public ModuleDescriptor parseDescriptor(ParserSettings ivySettings, URL descript DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor( mdBuilder.getModuleDescriptor(), relocation, true, false, true); /* Map all public dependencies */ - Configuration[] m2Confs = PomModuleDescriptorBuilder.MAVEN2_CONFIGURATIONS; - for (Configuration m2Conf : m2Confs) { - if (Visibility.PUBLIC.equals(m2Conf.getVisibility())) { + for (Configuration m2Conf : MAVEN2_CONFIGURATIONS) { + if (PUBLIC.equals(m2Conf.getVisibility())) { dd.addDependencyConfiguration(m2Conf.getName(), m2Conf.getName()); } } @@ -222,9 +218,7 @@ public ModuleDescriptor parseDescriptor(ParserSettings ivySettings, URL descript mdBuilder.addExtraInfos(parentDescr.getExtraInfos()); // add dependency management info from parent - List depMgt = PomModuleDescriptorBuilder - .getDependencyManagements(parentDescr); - for (PomDependencyMgt dep : depMgt) { + for (PomDependencyMgt dep : getDependencyManagements(parentDescr)) { if (dep instanceof PomDependencyMgtElement) { dep = domReader.new PomDependencyMgtElement( (PomDependencyMgtElement) dep); @@ -233,8 +227,7 @@ public ModuleDescriptor parseDescriptor(ParserSettings ivySettings, URL descript } // add plugins from parent - for (PomDependencyMgt pomDependencyMgt : PomModuleDescriptorBuilder - .getPlugins(parentDescr)) { + for (PomDependencyMgt pomDependencyMgt : getPlugins(parentDescr)) { mdBuilder.addPlugin(pomDependencyMgt); } } @@ -303,9 +296,7 @@ private void addTo(PomModuleDescriptorBuilder mdBuilder, PomDependencyMgt dep, ModuleDescriptor importDescr = importModule.getDescriptor(); // add dependency management info from imported module - List depMgt = PomModuleDescriptorBuilder - .getDependencyManagements(importDescr); - for (PomDependencyMgt importedDepMgt : depMgt) { + for (PomDependencyMgt importedDepMgt : getDependencyManagements(importDescr)) { mdBuilder.addDependencyMgt(new DefaultPomDependencyMgt(importedDepMgt.getGroupId(), importedDepMgt.getArtifactId(), importedDepMgt.getVersion(), importedDepMgt.getScope(), importedDepMgt.getExcludedModules())); @@ -387,9 +378,9 @@ private void addSourcesAndJavadocArtifactsIfPresent(PomModuleDescriptorBuilder m private ResolvedModuleRevision parseOtherPom(ParserSettings ivySettings, ModuleRevisionId parentModRevID) throws ParseException { DependencyDescriptor dd = new DefaultDependencyDescriptor(parentModRevID, true); - ResolveData data = IvyContext.getContext().getResolveData(); + ResolveData data = getContext().getResolveData(); if (data == null) { - ResolveEngine engine = IvyContext.getContext().getIvy().getResolveEngine(); + ResolveEngine engine = getContext().getIvy().getResolveEngine(); ResolveOptions options = new ResolveOptions(); options.setDownload(false); data = new ResolveData(engine, options); @@ -400,7 +391,7 @@ private ResolvedModuleRevision parseOtherPom(ParserSettings ivySettings, // TODO: Throw exception here? return null; } else { - dd = NameSpaceHelper.toSystem(dd, ivySettings.getContextNamespace()); + dd = toSystem(dd, ivySettings.getContextNamespace()); return resolver.getDependency(dd, data); } } diff --git a/src/java/org/apache/ivy/plugins/parser/m2/PomReader.java b/src/java/org/apache/ivy/plugins/parser/m2/PomReader.java index 3d6fbb313..dfe43d067 100644 --- a/src/java/org/apache/ivy/plugins/parser/m2/PomReader.java +++ b/src/java/org/apache/ivy/plugins/parser/m2/PomReader.java @@ -30,6 +30,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Properties; import org.apache.ivy.core.IvyPatternHelper; @@ -150,7 +151,7 @@ public InputSource resolveEntity(String publicId, String systemId) // Both environment and system properties take precedence over properties set in // pom.xml. So we pre-populate our properties with the environment and system properties // here - for (final Map.Entry envEntry : System.getenv().entrySet()) { + for (final Entry envEntry : System.getenv().entrySet()) { // Maven let's users use "env." prefix for environment variables this.setProperty("env." + envEntry.getKey(), envEntry.getValue()); } diff --git a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java index 4911c99ce..2828499ff 100644 --- a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java +++ b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorParser.java @@ -82,6 +82,8 @@ import org.xml.sax.Attributes; import org.xml.sax.SAXException; +import static org.apache.ivy.core.module.descriptor.Configuration.Visibility.getVisibility; + /** * Parses an xml ivy file and output a ModuleDescriptor. For dependency and performance reasons, it * uses only the SAX API, which makes the parsing code harder to understand. @@ -839,9 +841,9 @@ protected void confStarted(Attributes attributes) { || Boolean.valueOf(attributes.getValue("transitive")); String deprecated = attributes.getValue("deprecated"); Configuration configuration = new Configuration(conf, - Configuration.Visibility.getVisibility((visibility == null) ? "public" - : visibility), settings.substitute(attributes.getValue("description")), - (ext == null) ? null : ext.split(","), transitive, deprecated); + getVisibility((visibility == null) ? "public" : visibility), + settings.substitute(attributes.getValue("description")), + (ext == null) ? null : ext.split(","), transitive, deprecated); ExtendableItemHelper.fillExtraAttributes(settings, configuration, attributes, new String[] {"name", "visibility", "extends", "transitive", "description", "deprecated"}); diff --git a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorUpdater.java b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorUpdater.java index 7d09011ed..9f0e9925b 100644 --- a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorUpdater.java +++ b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorUpdater.java @@ -35,6 +35,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Stack; import java.util.StringTokenizer; @@ -251,7 +252,7 @@ public UpdaterHandler(URL relativePathCtx, PrintWriter out, final UpdateOptions private StringBuffer currentIndent = new StringBuffer(); - private ArrayList indentLevels = new ArrayList<>(); // ArrayList + private List indentLevels = new ArrayList<>(); // ArrayList // true if an ivy-module/info/description element has been found in the published descriptor private boolean hasDescription = false; @@ -777,7 +778,7 @@ private void infoStarted(Attributes attributes) { write(" namespace=\"" + namespace + "\""); } - for (Map.Entry extra : extraAttributes.entrySet()) { + for (Entry extra : extraAttributes.entrySet()) { write(" " + extra.getKey() + "=\"" + extra.getValue() + "\""); } } @@ -957,8 +958,7 @@ private void writeInheritedItems(ModuleDescriptor merged, InheritableItem[] item justOpen = null; } - for (Map.Entry> entry : inheritedItems - .entrySet()) { + for (Entry> entry : inheritedItems.entrySet()) { if (justOpen != null) { out.println(">"); justOpen = null; // helps endElement() decide how to write close tags diff --git a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java index 2f984645b..b37ae7337 100644 --- a/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java +++ b/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java @@ -74,7 +74,7 @@ public static void write(ModuleDescriptor md, String licenseHeader, File output) } StringBuilder xmlNamespace = new StringBuilder(); Map namespaces = md.getExtraAttributesNamespaces(); - for (Map.Entry ns : namespaces.entrySet()) { + for (Entry ns : namespaces.entrySet()) { xmlNamespace.append(" xmlns:").append(ns.getKey()).append("=\"") .append(ns.getValue()).append("\""); } @@ -178,7 +178,7 @@ private static void printAllMediators(ModuleDescriptor md, PrintWriter out) { Map mediators = md .getAllDependencyDescriptorMediators().getAllRules(); - for (Map.Entry mediatorRule : mediators.entrySet()) { + for (Entry mediatorRule : mediators.entrySet()) { MapMatcher matcher = mediatorRule.getKey(); DependencyDescriptorMediator mediator = mediatorRule.getValue(); @@ -326,7 +326,7 @@ private static void printExtraAttributes(Map extra, PrintWriter } String delim = prefix; - for (Map.Entry entry : extra.entrySet()) { + for (Entry entry : extra.entrySet()) { out.print(String.format("%s%s=\"%s\"", delim, entry.getKey(), XMLHelper.escape(entry.getValue()))); delim = " "; diff --git a/src/java/org/apache/ivy/plugins/report/XmlReportWriter.java b/src/java/org/apache/ivy/plugins/report/XmlReportWriter.java index deaeec7d9..f5edfc2ac 100644 --- a/src/java/org/apache/ivy/plugins/report/XmlReportWriter.java +++ b/src/java/org/apache/ivy/plugins/report/XmlReportWriter.java @@ -27,8 +27,10 @@ import java.util.Date; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import org.apache.ivy.core.cache.ArtifactOrigin; +import org.apache.ivy.core.module.descriptor.DependencyDescriptor; import org.apache.ivy.core.module.descriptor.License; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleId; @@ -49,6 +51,7 @@ public class XmlReportWriter { static final String REPORT_ENCODING = "UTF-8"; + private static final String SEPARATOR = " "; public void output(ConfigurationResolveReport report, OutputStream stream) { output(report, new String[] {report.getConfiguration()}, stream); @@ -74,11 +77,7 @@ public void output(ConfigurationResolveReport report, String[] confs, OutputStre if (mrid.getBranch() != null) { out.println("\t\tbranch=\"" + XMLHelper.escape(mrid.getBranch()) + "\""); } - Map extraAttributes = mrid.getExtraAttributes(); - for (Map.Entry entry : extraAttributes.entrySet()) { - out.println("\t\textra-" + entry.getKey() + "=\"" - + XMLHelper.escape(entry.getValue()) + "\""); - } + out.println(extraToString(mrid.getExtraAttributes(), "\t\t")); out.println("\t\tconf=\"" + XMLHelper.escape(report.getConfiguration()) + "\""); out.println("\t\tconfs=\"" + XMLHelper.escape(StringUtils.join(confs, ", ")) + "\""); out.println("\t\tdate=\"" + DateUtil.format(report.getDate()) + "\"/>"); @@ -142,10 +141,7 @@ private void outputRevision(ConfigurationResolveReport report, PrintWriter out, } extraAttributes = (md != null) ? md.getExtraAttributes() : dep.getResolvedId() .getExtraAttributes(); - for (Map.Entry entry : extraAttributes.entrySet()) { - details.append(" extra-").append(entry.getKey()).append("=\"") - .append(XMLHelper.escape(entry.getValue())).append("\""); - } + details.append(extraToString(extraAttributes, SEPARATOR)); out.println(String.format("\t\t\t", XMLHelper.escape(dep.getResolvedId().getRevision()), (dep.getResolvedId().getBranch() == null) ? "" : " branch=\"" @@ -158,14 +154,9 @@ private void outputRevision(ConfigurationResolveReport report, PrintWriter out, if (md != null) { License[] licenses = md.getLicenses(); for (License license : licenses) { - String lurl; - if (license.getUrl() != null) { - lurl = " url=\"" + XMLHelper.escape(license.getUrl()) + "\""; - } else { - lurl = ""; - } - out.println("\t\t\t\t"); + out.println(String.format("\t\t\t\t", + XMLHelper.escape(license.getName()), + license.getUrl() == null ? "" : " url=\"" + XMLHelper.escape(license.getUrl()) + "\"")); } } outputMetadataArtifact(out, dep); @@ -175,6 +166,18 @@ private void outputRevision(ConfigurationResolveReport report, PrintWriter out, out.println("\t\t\t"); } + private String extraToString(Map extraAttributes, String prefix) { + StringBuilder sb = new StringBuilder(); + for (Entry entry : extraAttributes.entrySet()) { + if (sb.length() > 0 && !SEPARATOR.equals(prefix)) { + sb.append(System.lineSeparator()); + } + sb.append(prefix).append("extra-").append(entry.getKey()).append("=\"") + .append(XMLHelper.escape(entry.getValue())).append("\""); + } + return sb.toString(); + } + private void outputEvictionInformation(ConfigurationResolveReport report, PrintWriter out, IvyNode dep) { if (dep.isEvicted(report.getConfiguration())) { @@ -219,24 +222,17 @@ private void outputMetadataArtifact(PrintWriter out, IvyNode dep) { } private void outputCallers(ConfigurationResolveReport report, PrintWriter out, IvyNode dep) { - Caller[] callers = dep.getCallers(report.getConfiguration()); - for (Caller caller : callers) { - StringBuilder callerDetails = new StringBuilder(); - Map callerExtraAttributes = caller.getDependencyDescriptor() - .getExtraAttributes(); - for (Map.Entry entry : callerExtraAttributes.entrySet()) { - callerDetails.append(" extra-").append(entry.getKey()).append("=\"") - .append(XMLHelper.escape(entry.getValue())).append("\""); - } - + for (Caller caller : dep.getCallers(report.getConfiguration())) { + final DependencyDescriptor dependencyDescriptor = caller.getDependencyDescriptor(); out.println(String.format("\t\t\t\t", XMLHelper.escape(caller.getModuleRevisionId().getOrganisation()), XMLHelper.escape(caller.getModuleRevisionId().getName()), XMLHelper.escape(toString(caller.getCallerConfigurations())), XMLHelper.escape(caller.getAskedDependencyId(dep.getData()).getRevision()), - XMLHelper.escape(caller.getDependencyDescriptor().getDependencyRevisionId().getRevision()), - XMLHelper.escape(caller.getDependencyDescriptor().getDynamicConstraintDependencyRevisionId().getRevision()), - XMLHelper.escape(caller.getModuleRevisionId().getRevision()), callerDetails)); + XMLHelper.escape(dependencyDescriptor.getDependencyRevisionId().getRevision()), + XMLHelper.escape(dependencyDescriptor.getDynamicConstraintDependencyRevisionId().getRevision()), + XMLHelper.escape(caller.getModuleRevisionId().getRevision()), + extraToString(dependencyDescriptor.getExtraAttributes(), SEPARATOR))); } } @@ -246,10 +242,7 @@ private void outputArtifacts(ConfigurationResolveReport report, PrintWriter out, out.print("\t\t\t\t\t entry : adr.getArtifact().getExtraAttributes().entrySet()) { - out.print(" extra-" + entry.getKey() + "=\"" - + XMLHelper.escape(entry.getValue()) + "\""); - } + out.print(extraToString(adr.getArtifact().getExtraAttributes(), SEPARATOR)); out.print(" status=\"" + XMLHelper.escape(adr.getDownloadStatus().toString()) + "\""); out.print(" details=\"" + XMLHelper.escape(adr.getDownloadDetails()) + "\""); out.print(" size=\"" + adr.getSize() + "\""); diff --git a/src/java/org/apache/ivy/plugins/repository/ssh/Scp.java b/src/java/org/apache/ivy/plugins/repository/ssh/Scp.java index 0723e2534..640e630e5 100644 --- a/src/java/org/apache/ivy/plugins/repository/ssh/Scp.java +++ b/src/java/org/apache/ivy/plugins/repository/ssh/Scp.java @@ -275,15 +275,8 @@ private void parseTLine(String line, FileInfo fileInfo) throws RemoteScpExceptio fileInfo.setLastModified(modtime); } - @SuppressWarnings("resource") private void sendFile(Channel channel, String localFile, String remoteName, String mode) throws IOException, RemoteScpException { - byte[] buffer = new byte[BUFFER_SIZE]; - - OutputStream os = new BufferedOutputStream(channel.getOutputStream(), - SEND_FILE_BUFFER_LENGTH); - InputStream is = new BufferedInputStream(channel.getInputStream(), SEND_BYTES_BUFFER_LENGTH); - try { if (channel.isConnected()) { channel.start(); @@ -294,6 +287,13 @@ private void sendFile(Channel channel, String localFile, String remoteName, Stri throw new IOException("Channel connection problems", jsche); } + byte[] buffer = new byte[BUFFER_SIZE]; + + OutputStream os = new BufferedOutputStream(channel.getOutputStream(), + SEND_FILE_BUFFER_LENGTH); + InputStream is = new BufferedInputStream(channel.getInputStream(), + SEND_BYTES_BUFFER_LENGTH); + readResponse(is); File f = new File(localFile); @@ -310,11 +310,7 @@ private void sendFile(Channel channel, String localFile, String remoteName, Stri readResponse(is); - FileInputStream fis = null; - - try { - fis = new FileInputStream(f); - + try (FileInputStream fis = new FileInputStream(f)) { while (remain > 0) { int trans; if (remain > buffer.length) { @@ -332,11 +328,6 @@ private void sendFile(Channel channel, String localFile, String remoteName, Stri } fis.close(); - } catch (IOException e) { - if (fis != null) { - fis.close(); - } - throw (e); } os.write(0); diff --git a/src/java/org/apache/ivy/plugins/resolver/AbstractPatternsBasedResolver.java b/src/java/org/apache/ivy/plugins/resolver/AbstractPatternsBasedResolver.java index 6872f3052..7b26e6ecc 100644 --- a/src/java/org/apache/ivy/plugins/resolver/AbstractPatternsBasedResolver.java +++ b/src/java/org/apache/ivy/plugins/resolver/AbstractPatternsBasedResolver.java @@ -202,10 +202,9 @@ private Set> resolveTokenValues(String[] tokens, String patt Map tokenValues = new HashMap<>(); for (Entry entry : criteria.entrySet()) { - String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof String) { - tokenValues.put(key, (String) value); + tokenValues.put(entry.getKey(), (String) value); } } diff --git a/src/java/org/apache/ivy/plugins/resolver/BasicResolver.java b/src/java/org/apache/ivy/plugins/resolver/BasicResolver.java index 780cc05bb..cbc792c9a 100644 --- a/src/java/org/apache/ivy/plugins/resolver/BasicResolver.java +++ b/src/java/org/apache/ivy/plugins/resolver/BasicResolver.java @@ -34,6 +34,7 @@ import java.util.List; import java.util.ListIterator; import java.util.Map; +import java.util.Map.Entry; import org.apache.ivy.core.IvyContext; import org.apache.ivy.core.IvyPatternHelper; @@ -618,7 +619,7 @@ private void checkDescriptorConsistency(ModuleRevisionId mrid, ModuleDescriptor errors.append("bad status: '").append(md.getStatus()).append("'; "); ok = false; } - for (Map.Entry extra : mrid.getExtraAttributes().entrySet()) { + for (Entry extra : mrid.getExtraAttributes().entrySet()) { if (extra.getValue() != null && !extra.getValue().equals(md.getExtraAttribute(extra.getKey()))) { String errorMsg = "bad " + extra.getKey() + " found in " + ivyRef.getResource() @@ -793,7 +794,7 @@ public void reportFailure() { for (String m : ivyattempts) { Message.warn(" " + m); } - for (Map.Entry> entry : artattempts.entrySet()) { + for (Entry> entry : artattempts.entrySet()) { List attempts = entry.getValue(); if (attempts != null) { Message.warn(" -- artifact " + entry.getKey() + ":"); diff --git a/src/java/org/apache/ivy/plugins/resolver/IBiblioResolver.java b/src/java/org/apache/ivy/plugins/resolver/IBiblioResolver.java index 184a28ada..3cb930c3a 100644 --- a/src/java/org/apache/ivy/plugins/resolver/IBiblioResolver.java +++ b/src/java/org/apache/ivy/plugins/resolver/IBiblioResolver.java @@ -189,7 +189,7 @@ public void endElement(String uri, String localName, String qName) // we have found a timestamp, so this is a snapshot unique version String rev = mrid.getRevision(); rev = rev.substring(0, rev.length() - "SNAPSHOT".length()); - rev = rev + timestamp.toString() + "-" + buildNumer.toString(); + rev += timestamp.toString() + "-" + buildNumer.toString(); return rev; } diff --git a/src/java/org/apache/ivy/plugins/resolver/packager/PackagerCacheEntry.java b/src/java/org/apache/ivy/plugins/resolver/packager/PackagerCacheEntry.java index f183e95f0..b637f9e8a 100644 --- a/src/java/org/apache/ivy/plugins/resolver/packager/PackagerCacheEntry.java +++ b/src/java/org/apache/ivy/plugins/resolver/packager/PackagerCacheEntry.java @@ -21,6 +21,7 @@ import java.io.IOException; import java.io.InputStream; import java.util.Map; +import java.util.Map.Entry; import org.apache.ivy.core.IvyPatternHelper; import org.apache.ivy.core.module.descriptor.Artifact; @@ -155,7 +156,7 @@ public synchronized void build(Resource packagerResource, Map pr project.setUserProperty("ivy.packager.restricted", "" + this.restricted); project.setUserProperty("ivy.packager.quiet", String.valueOf(quiet)); if (properties != null) { - for (Map.Entry entry : properties.entrySet()) { + for (Entry entry : properties.entrySet()) { project.setUserProperty(entry.getKey(), entry.getValue()); } } diff --git a/src/java/org/apache/ivy/plugins/resolver/packager/PackagerResolver.java b/src/java/org/apache/ivy/plugins/resolver/packager/PackagerResolver.java index 7142c0dee..4d012bcf6 100644 --- a/src/java/org/apache/ivy/plugins/resolver/packager/PackagerResolver.java +++ b/src/java/org/apache/ivy/plugins/resolver/packager/PackagerResolver.java @@ -23,6 +23,7 @@ import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import org.apache.ivy.core.module.descriptor.Artifact; @@ -49,7 +50,7 @@ public class PackagerResolver extends URLResolver { private static final String PACKAGER_ARTIFACT_EXT = "xml"; - private final HashMap packagerCache = new HashMap<>(); + private final Map packagerCache = new HashMap<>(); private File buildRoot; @@ -141,7 +142,7 @@ public void setResourceURL(String resourceURL) { * @param pattern String */ public void setPackagerPattern(String pattern) { - ArrayList list = new ArrayList<>(); + List list = new ArrayList<>(); list.add(pattern); setArtifactPatterns(list); } diff --git a/src/java/org/apache/ivy/util/ConfigurationUtils.java b/src/java/org/apache/ivy/util/ConfigurationUtils.java index 4bbb17c45..deaf9a680 100644 --- a/src/java/org/apache/ivy/util/ConfigurationUtils.java +++ b/src/java/org/apache/ivy/util/ConfigurationUtils.java @@ -22,9 +22,11 @@ import java.util.Set; import org.apache.ivy.core.module.descriptor.Configuration; -import org.apache.ivy.core.module.descriptor.Configuration.Visibility; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; +import static org.apache.ivy.core.module.descriptor.Configuration.Visibility.PRIVATE; +import static org.apache.ivy.core.module.descriptor.Configuration.Visibility.PUBLIC; + /** * Class containing several utility methods for working with configurations. */ @@ -66,16 +68,14 @@ public static String[] replaceWildcards(String[] confs, ModuleDescriptor md) { if ("*".equals(conf)) { result.addAll(Arrays.asList(md.getConfigurationsNames())); } else if ("*(public)".equals(conf)) { - Configuration[] all = md.getConfigurations(); - for (Configuration cf : all) { - if (cf.getVisibility().equals(Visibility.PUBLIC)) { + for (Configuration cf : md.getConfigurations()) { + if (PUBLIC.equals(cf.getVisibility())) { result.add(cf.getName()); } } } else if ("*(private)".equals(conf)) { - Configuration[] all = md.getConfigurations(); - for (Configuration cf : all) { - if (cf.getVisibility().equals(Visibility.PRIVATE)) { + for (Configuration cf : md.getConfigurations()) { + if (PRIVATE.equals(cf.getVisibility())) { result.add(cf.getName()); } } diff --git a/src/java/org/apache/ivy/util/Configurator.java b/src/java/org/apache/ivy/util/Configurator.java index deac6c819..80b45e90f 100644 --- a/src/java/org/apache/ivy/util/Configurator.java +++ b/src/java/org/apache/ivy/util/Configurator.java @@ -458,7 +458,6 @@ private void setCurrent(Object object, String name) { objectStack.push(new ObjectDescriptor(object, name)); } - @SuppressWarnings("rawtypes") public Object startCreateChild(String name) { if (objectStack.isEmpty()) { throw new IllegalStateException("set root before creating child"); @@ -548,7 +547,6 @@ public void addChild(String name, Object child) { } } - @SuppressWarnings("rawtypes") private Object addChild(ObjectDescriptor parentOD, Class childClass, String name, Object child) throws InstantiationException, IllegalAccessException, InvocationTargetException { diff --git a/src/java/org/apache/ivy/util/FileUtil.java b/src/java/org/apache/ivy/util/FileUtil.java index 56ada7e6a..408b1de54 100644 --- a/src/java/org/apache/ivy/util/FileUtil.java +++ b/src/java/org/apache/ivy/util/FileUtil.java @@ -17,6 +17,8 @@ */ package org.apache.ivy.util; +import org.apache.ivy.util.url.URLHandlerRegistry; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -40,12 +42,11 @@ import java.util.StringTokenizer; import java.util.jar.JarOutputStream; import java.util.jar.Pack200; -import java.util.jar.Pack200.Unpacker; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import java.util.zip.ZipInputStream; -import org.apache.ivy.util.url.URLHandlerRegistry; +import static java.util.jar.Pack200.newUnpacker; /** * Utility class used to deal with file related operations, like copy, full reading, symlink, ... @@ -656,17 +657,16 @@ public static InputStream unwrapPack200(InputStream packed) throws IOException { in = new GZIPInputStream(in); } - Unpacker unpacker = Pack200.newUnpacker(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JarOutputStream jar = new JarOutputStream(baos); - unpacker.unpack(new UncloseInputStream(in), jar); + newUnpacker().unpack(new UncloseInputStream(in), jar); jar.close(); return new ByteArrayInputStream(baos.toByteArray()); } /** * Wrap an input stream and do not close the stream on call to close(). Used to avoid closing a - * {@link ZipInputStream} used with {@link Unpacker#unpack(File, JarOutputStream)} + * {@link ZipInputStream} used with {@link Pack200.Unpacker#unpack(File, JarOutputStream)} */ private static final class UncloseInputStream extends InputStream { diff --git a/src/java/org/apache/ivy/util/cli/CommandLineParser.java b/src/java/org/apache/ivy/util/cli/CommandLineParser.java index e098b3b20..4d81a37a1 100644 --- a/src/java/org/apache/ivy/util/cli/CommandLineParser.java +++ b/src/java/org/apache/ivy/util/cli/CommandLineParser.java @@ -101,10 +101,8 @@ public void printHelp(PrintWriter pw, int width, String command, boolean showDep // print options help for (Entry> entry : categories.entrySet()) { - String category = entry.getKey(); - pw.println("==== " + category); - List