You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by el...@apache.org on 2023/03/12 11:40:13 UTC
[maven-shared-utils] branch master updated: [MSHARED-1196] Bump maven-shared-components from 37 to 39 (#134)
This is an automated email from the ASF dual-hosted git repository.
elharo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-shared-utils.git
The following commit(s) were added to refs/heads/master by this push:
new c75a4ee [MSHARED-1196] Bump maven-shared-components from 37 to 39 (#134)
c75a4ee is described below
commit c75a4ee4e7cec7a1b6871d1ab97947526c27824d
Author: Elliotte Rusty Harold <el...@users.noreply.github.com>
AuthorDate: Sun Mar 12 07:40:08 2023 -0400
[MSHARED-1196] Bump maven-shared-components from 37 to 39 (#134)
* update parent to 39
---
pom.xml | 20 +-
.../java/org/apache/maven/shared/utils/Os.java | 239 +-
.../org/apache/maven/shared/utils/PathTool.java | 193 +-
.../apache/maven/shared/utils/PropertyUtils.java | 117 +-
.../apache/maven/shared/utils/ReaderFactory.java | 60 +-
.../org/apache/maven/shared/utils/StringUtils.java | 1446 ++++-----
.../apache/maven/shared/utils/WriterFactory.java | 53 +-
.../shared/utils/cli/AbstractStreamHandler.java | 28 +-
.../org/apache/maven/shared/utils/cli/Arg.java | 17 +-
.../shared/utils/cli/CommandLineCallable.java | 10 +-
.../shared/utils/cli/CommandLineException.java | 19 +-
.../utils/cli/CommandLineTimeOutException.java | 17 +-
.../maven/shared/utils/cli/CommandLineUtils.java | 468 ++-
.../apache/maven/shared/utils/cli/Commandline.java | 295 +-
.../maven/shared/utils/cli/DefaultConsumer.java | 18 +-
.../maven/shared/utils/cli/ShutdownHookUtils.java | 39 +-
.../maven/shared/utils/cli/StreamConsumer.java | 8 +-
.../maven/shared/utils/cli/StreamFeeder.java | 91 +-
.../maven/shared/utils/cli/StreamPumper.java | 84 +-
.../shared/utils/cli/WriterStreamConsumer.java | 18 +-
.../utils/cli/javatool/AbstractJavaTool.java | 215 +-
.../cli/javatool/AbstractJavaToolRequest.java | 19 +-
.../maven/shared/utils/cli/javatool/JavaTool.java | 11 +-
.../utils/cli/javatool/JavaToolException.java | 17 +-
.../shared/utils/cli/javatool/JavaToolRequest.java | 10 +-
.../shared/utils/cli/javatool/JavaToolResult.java | 24 +-
.../maven/shared/utils/cli/shell/BourneShell.java | 71 +-
.../maven/shared/utils/cli/shell/CmdShell.java | 32 +-
.../maven/shared/utils/cli/shell/CommandShell.java | 16 +-
.../apache/maven/shared/utils/cli/shell/Shell.java | 226 +-
.../maven/shared/utils/introspection/ClassMap.java | 264 +-
.../introspection/IntrospectionException.java | 22 +-
.../shared/utils/introspection/MethodMap.java | 212 +-
.../introspection/ReflectionValueExtractor.java | 296 +-
.../maven/shared/utils/io/DirectoryScanResult.java | 21 +-
.../maven/shared/utils/io/DirectoryScanner.java | 529 ++--
.../shared/utils/io/DirectoryWalkListener.java | 16 +-
.../apache/maven/shared/utils/io/FileUtils.java | 1298 ++++----
.../org/apache/maven/shared/utils/io/IOUtil.java | 390 +--
.../apache/maven/shared/utils/io/Java7Support.java | 44 +-
.../apache/maven/shared/utils/io/MatchPattern.java | 108 +-
.../maven/shared/utils/io/MatchPatterns.java | 46 +-
.../maven/shared/utils/io/ScanConductor.java | 17 +-
.../maven/shared/utils/io/SelectorUtils.java | 487 ++--
.../maven/shared/utils/io/WalkCollector.java | 32 +-
.../shared/utils/logging/AnsiMessageBuilder.java | 116 +-
.../shared/utils/logging/LoggerLevelRenderer.java | 22 +-
.../maven/shared/utils/logging/MessageBuilder.java | 43 +-
.../maven/shared/utils/logging/MessageUtils.java | 130 +-
.../shared/utils/logging/PlainMessageBuilder.java | 111 +-
.../apache/maven/shared/utils/logging/Style.java | 157 +-
.../maven/shared/utils/logging/package-info.java | 16 +-
.../shared/utils/xml/PrettyPrintXMLWriter.java | 247 +-
.../apache/maven/shared/utils/xml/XMLEncode.java | 137 +-
.../apache/maven/shared/utils/xml/XMLWriter.java | 30 +-
.../maven/shared/utils/xml/XmlStreamReader.java | 83 +-
.../maven/shared/utils/xml/XmlStreamWriter.java | 20 +-
.../maven/shared/utils/xml/XmlWriterUtil.java | 195 +-
.../org/apache/maven/shared/utils/xml/Xpp3Dom.java | 241 +-
.../maven/shared/utils/xml/Xpp3DomBuilder.java | 234 +-
.../maven/shared/utils/xml/Xpp3DomUtils.java | 115 +-
.../maven/shared/utils/xml/Xpp3DomWriter.java | 53 +-
.../utils/xml/pull/XmlPullParserException.java | 34 +-
.../org/apache/maven/shared/utils/CaseTest.java | 142 +-
.../java/org/apache/maven/shared/utils/OsTest.java | 195 +-
.../apache/maven/shared/utils/PathToolTest.java | 127 +-
.../maven/shared/utils/PropertyUtilsTest.java | 162 +-
.../apache/maven/shared/utils/StringUtilsTest.java | 2053 +++++--------
.../maven/shared/utils/XmlStreamReaderTest.java | 178 +-
.../shared/utils/cli/CommandLineUtilsTest.java | 136 +-
.../shared/utils/cli/shell/BourneShellTest.java | 232 +-
.../shared/utils/exceptionutils/TestException.java | 24 +-
.../exceptionutils/TestExceptionWithDetail.java | 18 +-
.../ReflectionValueExtractorTest.java | 414 ++-
.../shared/utils/io/DirectoryScannerTest.java | 474 ++-
.../maven/shared/utils/io/FileUtilsTest.java | 1828 +++++-------
.../apache/maven/shared/utils/io/IOUtilTest.java | 3083 ++++++++------------
.../maven/shared/utils/io/MatchPatternTest.java | 19 +-
.../maven/shared/utils/io/MatchPatternsTest.java | 21 +-
.../maven/shared/utils/io/SelectorUtilsTest.java | 73 +-
.../maven/shared/utils/io/SymlinkTestSetup.java | 63 +-
.../utils/logging/AnsiMessageBuilderTest.java | 75 +-
.../shared/utils/logging/MessageUtilsTest.java | 204 +-
.../shared/utils/testhelpers/FileTestHelper.java | 62 +-
.../shared/utils/xml/PrettyPrintXmlWriterTest.java | 196 +-
.../maven/shared/utils/xml/XmlWriterUtilTest.java | 425 +--
.../maven/shared/utils/xml/Xpp3DomBuilderTest.java | 174 +-
.../maven/shared/utils/xml/pull/Xpp3DomTest.java | 273 +-
88 files changed, 8076 insertions(+), 12222 deletions(-)
diff --git a/pom.xml b/pom.xml
index 2f5e6e3..c19bdcd 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,4 +1,4 @@
-<?xml version='1.0' encoding='UTF-8'?>
+<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-shared-components</artifactId>
- <version>37</version>
+ <version>39</version>
</parent>
<artifactId>maven-shared-utils</artifactId>
@@ -32,12 +32,18 @@
<name>Apache Maven Shared Utils</name>
<description>Shared utilities for use by Maven core and plugins</description>
+ <contributors>
+ <contributor>
+ <name>Kathryn Newbould</name>
+ </contributor>
+ </contributors>
+
<scm>
<connection>scm:git:https://gitbox.apache.org/repos/asf/maven-shared-utils.git</connection>
<developerConnection>scm:git:https://gitbox.apache.org/repos/asf/maven-shared-utils.git</developerConnection>
- <url>https://github.com/apache/maven-shared-utils/tree/${project.scm.tag}</url>
<tag>HEAD</tag>
- </scm>
+ <url>https://github.com/apache/maven-shared-utils/tree/${project.scm.tag}</url>
+ </scm>
<issueManagement>
<system>jira</system>
<url>https://issues.apache.org/jira/issues/?jql=project%20%3D%20MSHARED%20AND%20component%20%3D%20maven-shared-utils</url>
@@ -53,12 +59,6 @@
</site>
</distributionManagement>
- <contributors>
- <contributor>
- <name>Kathryn Newbould</name>
- </contributor>
- </contributors>
-
<properties>
<checkstyle.violation.ignore>RedundantThrows,NewlineAtEndOfFile,ParameterNumber,MethodLength,FileLength,ModifierOrder</checkstyle.violation.ignore>
<project.build.outputTimestamp>2021-04-26T13:54:25Z</project.build.outputTimestamp>
diff --git a/src/main/java/org/apache/maven/shared/utils/Os.java b/src/main/java/org/apache/maven/shared/utils/Os.java
index a2c3d52..184b98a 100644
--- a/src/main/java/org/apache/maven/shared/utils/Os.java
+++ b/src/main/java/org/apache/maven/shared/utils/Os.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils;
import java.util.Collections;
import java.util.HashSet;
@@ -37,34 +36,33 @@ import java.util.Set;
* @author Magesh Umasankar
* @author Brian Fox
* @author Mark Struberg
- *
+ *
*/
-public class Os
-{
+public class Os {
/**
* The OS Name.
*/
- public static final String OS_NAME = System.getProperty( "os.name" ).toLowerCase( Locale.ENGLISH );
+ public static final String OS_NAME = System.getProperty("os.name").toLowerCase(Locale.ENGLISH);
/**
* The OA architecture.
*/
- public static final String OS_ARCH = System.getProperty( "os.arch" ).toLowerCase( Locale.ENGLISH );
+ public static final String OS_ARCH = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH);
/**
* The OS version.
*/
- public static final String OS_VERSION = System.getProperty( "os.version" ).toLowerCase( Locale.ENGLISH );
+ public static final String OS_VERSION = System.getProperty("os.version").toLowerCase(Locale.ENGLISH);
/**
* The path separator.
*/
- public static final String PATH_SEP = System.getProperty( "path.separator" );
+ public static final String PATH_SEP = System.getProperty("path.separator");
/**
* system line separator , e.g. "\n" on unixoid systems and "\r\n" on Windows
*/
- public static final String LINE_SEP = System.getProperty( "line.separator" );
+ public static final String LINE_SEP = System.getProperty("line.separator");
/**
* OS Family
@@ -74,7 +72,6 @@ public class Os
// store the valid families
private static final Set<String> VALID_FAMILIES = getValidFamilies();
-
/**
* OS family to look for
*/
@@ -148,42 +145,38 @@ public class Os
*/
private static final String DARWIN = "darwin";
-
/**
* The set of valid families. This methods initializes the set until
* VALID_FAMILIES constant is set.
* @return The set of families.
*/
- public static Set<String> getValidFamilies()
- {
- if ( VALID_FAMILIES != null )
- {
+ public static Set<String> getValidFamilies() {
+ if (VALID_FAMILIES != null) {
return VALID_FAMILIES;
}
Set<String> valid = new HashSet<String>();
- valid.add( FAMILY_DOS );
- valid.add( FAMILY_MAC );
- valid.add( FAMILY_NETWARE );
- valid.add( FAMILY_NT );
- valid.add( FAMILY_OPENVMS );
- valid.add( FAMILY_OS2 );
- valid.add( FAMILY_OS400 );
- valid.add( FAMILY_TANDEM );
- valid.add( FAMILY_UNIX );
- valid.add( FAMILY_WIN9X );
- valid.add( FAMILY_WINDOWS );
- valid.add( FAMILY_ZOS );
-
- return Collections.unmodifiableSet( valid );
+ valid.add(FAMILY_DOS);
+ valid.add(FAMILY_MAC);
+ valid.add(FAMILY_NETWARE);
+ valid.add(FAMILY_NT);
+ valid.add(FAMILY_OPENVMS);
+ valid.add(FAMILY_OS2);
+ valid.add(FAMILY_OS400);
+ valid.add(FAMILY_TANDEM);
+ valid.add(FAMILY_UNIX);
+ valid.add(FAMILY_WIN9X);
+ valid.add(FAMILY_WINDOWS);
+ valid.add(FAMILY_ZOS);
+
+ return Collections.unmodifiableSet(valid);
}
/**
* Default constructor
*/
- public Os()
- {
- //default
+ public Os() {
+ // default
}
/**
@@ -191,9 +184,8 @@ public class Os
*
* @param family a String value
*/
- public Os( String family )
- {
- setFamily( family );
+ public Os(String family) {
+ setFamily(family);
}
/**
@@ -214,9 +206,8 @@ public class Os
* <li>os/400</li>
* </ul>
*/
- private void setFamily( String f )
- {
- family = f.toLowerCase( Locale.ENGLISH );
+ private void setFamily(String f) {
+ family = f.toLowerCase(Locale.ENGLISH);
}
/**
@@ -226,9 +217,8 @@ public class Os
* @return true if the os matches.
* @see Os#setFamily(String)
*/
- boolean eval()
- {
- return isOs( family, null, null, null );
+ boolean eval() {
+ return isOs(family, null, null, null);
}
/**
@@ -237,11 +227,10 @@ public class Os
*
* @param family the family to check for
* @return true if the OS matches
- *
+ *
*/
- public static boolean isFamily( String family )
- {
- return isOs( family, null, null, null );
+ public static boolean isFamily(String family) {
+ return isOs(family, null, null, null);
}
/**
@@ -250,11 +239,10 @@ public class Os
*
* @param name the OS name to check for
* @return true if the OS matches
- *
+ *
*/
- public static boolean isName( String name )
- {
- return isOs( null, name, null, null );
+ public static boolean isName(String name) {
+ return isOs(null, name, null, null);
}
/**
@@ -263,11 +251,10 @@ public class Os
*
* @param arch the OS architecture to check for
* @return true if the OS matches
- *
+ *
*/
- public static boolean isArch( String arch )
- {
- return isOs( null, null, arch, null );
+ public static boolean isArch(String arch) {
+ return isOs(null, null, arch, null);
}
/**
@@ -276,11 +263,10 @@ public class Os
*
* @param version the OS version to check for
* @return true if the OS matches
- *
+ *
*/
- public static boolean isVersion( String version )
- {
- return isOs( null, null, null, version );
+ public static boolean isVersion(String version) {
+ return isOs(null, null, null, version);
}
/**
@@ -292,103 +278,73 @@ public class Os
* @param arch The OS architecture
* @param version The OS version
* @return true if the OS matches
- *
+ *
*/
- private static boolean isOs( String family, String name, String arch, String version )
- {
+ private static boolean isOs(String family, String name, String arch, String version) {
boolean retValue = false;
- if ( family != null || name != null || arch != null || version != null )
- {
+ if (family != null || name != null || arch != null || version != null) {
boolean isFamily = true;
boolean isName = true;
boolean isArch = true;
boolean isVersion = true;
- if ( family != null )
- {
+ if (family != null) {
- //windows probing logic relies on the word 'windows' in
- //the OS
- boolean isWindows = OS_NAME.contains( FAMILY_WINDOWS );
+ // windows probing logic relies on the word 'windows' in
+ // the OS
+ boolean isWindows = OS_NAME.contains(FAMILY_WINDOWS);
boolean is9x = false;
boolean isNT = false;
- if ( isWindows )
- {
- //there are only four 9x platforms that we look for
- is9x =
- ( OS_NAME.contains( "95" ) || OS_NAME.contains( "98" ) || OS_NAME.contains( "me" )
- //wince isn't really 9x, but crippled enough to
- //be a muchness. Ant doesnt run on CE, anyway.
- || OS_NAME.contains( "ce" ) );
+ if (isWindows) {
+ // there are only four 9x platforms that we look for
+ is9x = (OS_NAME.contains("95")
+ || OS_NAME.contains("98")
+ || OS_NAME.contains("me")
+ // wince isn't really 9x, but crippled enough to
+ // be a muchness. Ant doesnt run on CE, anyway.
+ || OS_NAME.contains("ce"));
isNT = !is9x;
}
- if ( family.equals( FAMILY_WINDOWS ) )
- {
+ if (family.equals(FAMILY_WINDOWS)) {
isFamily = isWindows;
- }
- else if ( family.equals( FAMILY_WIN9X ) )
- {
+ } else if (family.equals(FAMILY_WIN9X)) {
isFamily = isWindows && is9x;
- }
- else if ( family.equals( FAMILY_NT ) )
- {
+ } else if (family.equals(FAMILY_NT)) {
isFamily = isWindows && isNT;
- }
- else if ( family.equals( FAMILY_OS2 ) )
- {
- isFamily = OS_NAME.contains( FAMILY_OS2 );
- }
- else if ( family.equals( FAMILY_NETWARE ) )
- {
- isFamily = OS_NAME.contains( FAMILY_NETWARE );
- }
- else if ( family.equals( FAMILY_DOS ) )
- {
- isFamily = PATH_SEP.equals( ";" ) && !isFamily( FAMILY_NETWARE );
- }
- else if ( family.equals( FAMILY_MAC ) )
- {
- isFamily = OS_NAME.contains( FAMILY_MAC ) || OS_NAME.contains( DARWIN );
- }
- else if ( family.equals( FAMILY_TANDEM ) )
- {
- isFamily = OS_NAME.contains( "nonstop_kernel" );
- }
- else if ( family.equals( FAMILY_UNIX ) )
- {
- isFamily = PATH_SEP.equals( ":" ) && !isFamily( FAMILY_OPENVMS ) && ( !isFamily( FAMILY_MAC )
- || OS_NAME.endsWith( "x" ) || OS_NAME.contains( DARWIN ) );
- }
- else if ( family.equals( FAMILY_ZOS ) )
- {
- isFamily = OS_NAME.contains( FAMILY_ZOS ) || OS_NAME.contains( "os/390" );
- }
- else if ( family.equals( FAMILY_OS400 ) )
- {
- isFamily = OS_NAME.contains( FAMILY_OS400 );
- }
- else if ( family.equals( FAMILY_OPENVMS ) )
- {
- isFamily = OS_NAME.contains( FAMILY_OPENVMS );
- }
- else
- {
- isFamily = OS_NAME.contains( family.toLowerCase( Locale.US ) );
+ } else if (family.equals(FAMILY_OS2)) {
+ isFamily = OS_NAME.contains(FAMILY_OS2);
+ } else if (family.equals(FAMILY_NETWARE)) {
+ isFamily = OS_NAME.contains(FAMILY_NETWARE);
+ } else if (family.equals(FAMILY_DOS)) {
+ isFamily = PATH_SEP.equals(";") && !isFamily(FAMILY_NETWARE);
+ } else if (family.equals(FAMILY_MAC)) {
+ isFamily = OS_NAME.contains(FAMILY_MAC) || OS_NAME.contains(DARWIN);
+ } else if (family.equals(FAMILY_TANDEM)) {
+ isFamily = OS_NAME.contains("nonstop_kernel");
+ } else if (family.equals(FAMILY_UNIX)) {
+ isFamily = PATH_SEP.equals(":")
+ && !isFamily(FAMILY_OPENVMS)
+ && (!isFamily(FAMILY_MAC) || OS_NAME.endsWith("x") || OS_NAME.contains(DARWIN));
+ } else if (family.equals(FAMILY_ZOS)) {
+ isFamily = OS_NAME.contains(FAMILY_ZOS) || OS_NAME.contains("os/390");
+ } else if (family.equals(FAMILY_OS400)) {
+ isFamily = OS_NAME.contains(FAMILY_OS400);
+ } else if (family.equals(FAMILY_OPENVMS)) {
+ isFamily = OS_NAME.contains(FAMILY_OPENVMS);
+ } else {
+ isFamily = OS_NAME.contains(family.toLowerCase(Locale.US));
}
}
- if ( name != null )
- {
- isName = name.equals( OS_NAME );
+ if (name != null) {
+ isName = name.equals(OS_NAME);
}
- if ( arch != null )
- {
- isArch = arch.equals( OS_ARCH );
+ if (arch != null) {
+ isArch = arch.equals(OS_ARCH);
}
- if ( version != null )
- {
- isVersion = version.equals( OS_VERSION );
+ if (version != null) {
+ isVersion = version.equals(OS_VERSION);
}
retValue = isFamily && isName && isArch && isVersion;
}
@@ -400,14 +356,11 @@ public class Os
*
* @return name of current OS family.
*/
- private static String getOsFamily()
- {
+ private static String getOsFamily() {
Set<String> families = getValidFamilies();
- for ( String fam : families )
- {
- if ( Os.isFamily( fam ) )
- {
+ for (String fam : families) {
+ if (Os.isFamily(fam)) {
return fam;
}
}
@@ -420,9 +373,7 @@ public class Os
* @param family the os family
* @return <code>true</code> if 'family' represents a valid OS-Family, <code>false</code> otherwise.
*/
- public static boolean isValidFamily( String family )
- {
- return VALID_FAMILIES.contains( family );
+ public static boolean isValidFamily(String family) {
+ return VALID_FAMILIES.contains(family);
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/PathTool.java b/src/main/java/org/apache/maven/shared/utils/PathTool.java
index 2a0b0fe..bf0fd49 100644
--- a/src/main/java/org/apache/maven/shared/utils/PathTool.java
+++ b/src/main/java/org/apache/maven/shared/utils/PathTool.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,13 +16,14 @@ package org.apache.maven.shared.utils;
* specific language governing permissions and limitations
* under the License.
*/
-
-import java.io.File;
-import java.util.StringTokenizer;
+package org.apache.maven.shared.utils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
+import java.io.File;
+import java.util.StringTokenizer;
+
/**
* <p>Path tool contains static methods to assist in determining path-related
* information such as relative paths.</p>
@@ -34,19 +33,16 @@ import javax.annotation.Nullable;
* Some external fixes by Apache Committers have been applied later.
* </p>
*/
-public class PathTool
-{
-
+public class PathTool {
+
/**
* The constructor.
*
* @deprecated This is a utility class with only static methods. Don't create instances of it.
*/
@Deprecated
- public PathTool()
- {
- }
-
+ public PathTool() {}
+
/**
* Determines the relative path of a filename from a base directory.
* This method is useful in building relative links within pages of
@@ -77,18 +73,19 @@ public class PathTool
* the base directory, <code>basedir</code> is null or zero-length,
* or <code>filename</code> is null or zero-length.
*/
- public static String getRelativePath( @Nullable String basedir, @Nullable String filename )
- {
- basedir = uppercaseDrive( basedir );
- filename = uppercaseDrive( filename );
+ public static String getRelativePath(@Nullable String basedir, @Nullable String filename) {
+ basedir = uppercaseDrive(basedir);
+ filename = uppercaseDrive(filename);
/*
* Verify the arguments and make sure the filename is relative
* to the base directory.
*/
- if ( basedir == null || basedir.length() == 0 || filename == null || filename.length() == 0
- || !filename.startsWith( basedir ) )
- {
+ if (basedir == null
+ || basedir.length() == 0
+ || filename == null
+ || filename.length() == 0
+ || !filename.startsWith(basedir)) {
return "";
}
@@ -97,18 +94,18 @@ public class PathTool
* that is being used, then strip that off the end of both the
* base directory and filename.
*/
- String separator = determineSeparator( filename );
- basedir = StringUtils.chompLast( basedir, separator );
- filename = StringUtils.chompLast( filename, separator );
+ String separator = determineSeparator(filename);
+ basedir = StringUtils.chompLast(basedir, separator);
+ filename = StringUtils.chompLast(filename, separator);
/*
* Remove the base directory from the filename to end up with a
* relative filename (relative to the base directory). This
* filename is then used to determine the relative path.
*/
- String relativeFilename = filename.substring( basedir.length() );
+ String relativeFilename = filename.substring(basedir.length());
- return determineRelativePath( relativeFilename, separator );
+ return determineRelativePath(relativeFilename, separator);
}
/**
@@ -131,59 +128,50 @@ public class PathTool
* @param newPath new path
* @return a relative file path from <code>oldPath</code>.
*/
- public static String getRelativeFilePath( final String oldPath, final String newPath )
- {
- if ( StringUtils.isEmpty( oldPath ) || StringUtils.isEmpty( newPath ) )
- {
+ public static String getRelativeFilePath(final String oldPath, final String newPath) {
+ if (StringUtils.isEmpty(oldPath) || StringUtils.isEmpty(newPath)) {
return "";
}
// normalise the path delimiters
- String fromPath = new File( oldPath ).getPath();
- String toPath = new File( newPath ).getPath();
+ String fromPath = new File(oldPath).getPath();
+ String toPath = new File(newPath).getPath();
// strip any leading slashes if its a windows path
- if ( toPath.matches( "^\\[a-zA-Z]:" ) )
- {
- toPath = toPath.substring( 1 );
+ if (toPath.matches("^\\[a-zA-Z]:")) {
+ toPath = toPath.substring(1);
}
- if ( fromPath.matches( "^\\[a-zA-Z]:" ) )
- {
- fromPath = fromPath.substring( 1 );
+ if (fromPath.matches("^\\[a-zA-Z]:")) {
+ fromPath = fromPath.substring(1);
}
// lowercase windows drive letters.
- if ( fromPath.startsWith( ":", 1 ) )
- {
- fromPath = Character.toLowerCase( fromPath.charAt( 0 ) ) + fromPath.substring( 1 );
+ if (fromPath.startsWith(":", 1)) {
+ fromPath = Character.toLowerCase(fromPath.charAt(0)) + fromPath.substring(1);
}
- if ( toPath.startsWith( ":", 1 ) )
- {
- toPath = Character.toLowerCase( toPath.charAt( 0 ) ) + toPath.substring( 1 );
+ if (toPath.startsWith(":", 1)) {
+ toPath = Character.toLowerCase(toPath.charAt(0)) + toPath.substring(1);
}
// check for the presence of windows drives. No relative way of
// traversing from one to the other.
- if ( ( toPath.startsWith( ":", 1 ) && fromPath.startsWith( ":", 1 ) )
- && ( !toPath.substring( 0, 1 ).equals( fromPath.substring( 0, 1 ) ) ) )
- {
+ if ((toPath.startsWith(":", 1) && fromPath.startsWith(":", 1))
+ && (!toPath.substring(0, 1).equals(fromPath.substring(0, 1)))) {
// they both have drive path element but they dont match, no
// relative path
return null;
}
- if ( ( toPath.startsWith( ":", 1 ) && !fromPath.startsWith( ":", 1 ) )
- || ( !toPath.startsWith( ":", 1 ) && fromPath.startsWith( ":", 1 ) ) )
- {
+ if ((toPath.startsWith(":", 1) && !fromPath.startsWith(":", 1))
+ || (!toPath.startsWith(":", 1) && fromPath.startsWith(":", 1))) {
// one has a drive path element and the other doesnt, no relative
// path.
return null;
}
- String resultPath = buildRelativePath( toPath, fromPath, File.separatorChar );
+ String resultPath = buildRelativePath(toPath, fromPath, File.separatorChar);
- if ( newPath.endsWith( File.separator ) && !resultPath.endsWith( File.separator ) )
- {
+ if (newPath.endsWith(File.separator) && !resultPath.endsWith(File.separator)) {
return resultPath + File.separator;
}
@@ -205,21 +193,19 @@ public class PathTool
* terminated with a forward slash. A zero-length string is
* returned if: the filename is zero-length.
*/
- @Nonnull private static String determineRelativePath( @Nonnull String filename, @Nonnull String separator )
- {
- if ( filename.length() == 0 )
- {
+ @Nonnull
+ private static String determineRelativePath(@Nonnull String filename, @Nonnull String separator) {
+ if (filename.length() == 0) {
return "";
}
/*
- * Count the slashes in the relative filename, but exclude the
- * leading slash. If the path has no slashes, then the filename
- * is relative to the current directory.
- */
- int slashCount = StringUtils.countMatches( filename, separator ) - 1;
- if ( slashCount <= 0 )
- {
+ * Count the slashes in the relative filename, but exclude the
+ * leading slash. If the path has no slashes, then the filename
+ * is relative to the current directory.
+ */
+ int slashCount = StringUtils.countMatches(filename, separator) - 1;
+ if (slashCount <= 0) {
return ".";
}
@@ -229,16 +215,15 @@ public class PathTool
* slash represents a "../" in the relative path.
*/
StringBuilder sb = new StringBuilder();
- for ( int i = 0; i < slashCount; i++ )
- {
- sb.append( "../" );
+ for (int i = 0; i < slashCount; i++) {
+ sb.append("../");
}
/*
* Finally, return the relative path but strip the trailing
* slash to mimic Anakia's behavior.
*/
- return StringUtils.chop( sb.toString() );
+ return StringUtils.chop(sb.toString());
}
/**
@@ -251,10 +236,9 @@ public class PathTool
* @return The file separator used within <code>filename</code>.
* This value is either a forward or backward slash.
*/
- private static String determineSeparator( String filename )
- {
- int forwardCount = StringUtils.countMatches( filename, "/" );
- int backwardCount = StringUtils.countMatches( filename, "\\" );
+ private static String determineSeparator(String filename) {
+ int forwardCount = StringUtils.countMatches(filename, "/");
+ int backwardCount = StringUtils.countMatches(filename, "\\");
return forwardCount >= backwardCount ? "/" : "\\";
}
@@ -265,42 +249,33 @@ public class PathTool
* @param path old path
* @return String
*/
- static String uppercaseDrive( @Nullable String path )
- {
- if ( path == null )
- {
+ static String uppercaseDrive(@Nullable String path) {
+ if (path == null) {
return null;
}
- if ( path.length() >= 2 && path.charAt( 1 ) == ':' )
- {
- path = Character.toUpperCase( path.charAt( 0 ) ) + path.substring( 1 );
+ if (path.length() >= 2 && path.charAt(1) == ':') {
+ path = Character.toUpperCase(path.charAt(0)) + path.substring(1);
}
return path;
}
- @Nonnull private static String buildRelativePath( @Nonnull String toPath, @Nonnull String fromPath,
- final char separatorChar )
- {
+ @Nonnull
+ private static String buildRelativePath(
+ @Nonnull String toPath, @Nonnull String fromPath, final char separatorChar) {
// use tokeniser to traverse paths and for lazy checking
- StringTokenizer toTokeniser = new StringTokenizer( toPath, String.valueOf( separatorChar ) );
- StringTokenizer fromTokeniser = new StringTokenizer( fromPath, String.valueOf( separatorChar ) );
+ StringTokenizer toTokeniser = new StringTokenizer(toPath, String.valueOf(separatorChar));
+ StringTokenizer fromTokeniser = new StringTokenizer(fromPath, String.valueOf(separatorChar));
int count = 0;
// walk along the to path looking for divergence from the from path
- while ( toTokeniser.hasMoreTokens() && fromTokeniser.hasMoreTokens() )
- {
- if ( separatorChar == '\\' )
- {
- if ( !fromTokeniser.nextToken().equalsIgnoreCase( toTokeniser.nextToken() ) )
- {
+ while (toTokeniser.hasMoreTokens() && fromTokeniser.hasMoreTokens()) {
+ if (separatorChar == '\\') {
+ if (!fromTokeniser.nextToken().equalsIgnoreCase(toTokeniser.nextToken())) {
break;
}
- }
- else
- {
- if ( !fromTokeniser.nextToken().equals( toTokeniser.nextToken() ) )
- {
+ } else {
+ if (!fromTokeniser.nextToken().equals(toTokeniser.nextToken())) {
break;
}
}
@@ -311,11 +286,10 @@ public class PathTool
// reinitialise the tokenisers to count positions to retrieve the
// gobbled token
- toTokeniser = new StringTokenizer( toPath, String.valueOf( separatorChar ) );
- fromTokeniser = new StringTokenizer( fromPath, String.valueOf( separatorChar ) );
+ toTokeniser = new StringTokenizer(toPath, String.valueOf(separatorChar));
+ fromTokeniser = new StringTokenizer(fromPath, String.valueOf(separatorChar));
- while ( count-- > 0 )
- {
+ while (count-- > 0) {
fromTokeniser.nextToken();
toTokeniser.nextToken();
}
@@ -323,31 +297,26 @@ public class PathTool
StringBuilder relativePath = new StringBuilder();
// add back refs for the rest of from location.
- while ( fromTokeniser.hasMoreTokens() )
- {
+ while (fromTokeniser.hasMoreTokens()) {
fromTokeniser.nextToken();
- relativePath.append( ".." );
+ relativePath.append("..");
- if ( fromTokeniser.hasMoreTokens() )
- {
- relativePath.append( separatorChar );
+ if (fromTokeniser.hasMoreTokens()) {
+ relativePath.append(separatorChar);
}
}
- if ( relativePath.length() != 0 && toTokeniser.hasMoreTokens() )
- {
- relativePath.append( separatorChar );
+ if (relativePath.length() != 0 && toTokeniser.hasMoreTokens()) {
+ relativePath.append(separatorChar);
}
// add fwd fills for whatevers left of newPath.
- while ( toTokeniser.hasMoreTokens() )
- {
- relativePath.append( toTokeniser.nextToken() );
+ while (toTokeniser.hasMoreTokens()) {
+ relativePath.append(toTokeniser.nextToken());
- if ( toTokeniser.hasMoreTokens() )
- {
- relativePath.append( separatorChar );
+ if (toTokeniser.hasMoreTokens()) {
+ relativePath.append(separatorChar);
}
}
return relativePath.toString();
diff --git a/src/main/java/org/apache/maven/shared/utils/PropertyUtils.java b/src/main/java/org/apache/maven/shared/utils/PropertyUtils.java
index 70e21ed..0730828 100644
--- a/src/main/java/org/apache/maven/shared/utils/PropertyUtils.java
+++ b/src/main/java/org/apache/maven/shared/utils/PropertyUtils.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@ package org.apache.maven.shared.utils;
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,6 +16,10 @@ package org.apache.maven.shared.utils;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import java.io.File;
import java.io.FileInputStream;
@@ -26,14 +28,10 @@ import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
/**
* Static utility methods for loading properties.
*/
-public class PropertyUtils
-{
+public class PropertyUtils {
/**
* The constructor.
@@ -41,9 +39,7 @@ public class PropertyUtils
* @deprecated This is a utility class with only static methods. Don't create instances of it.
*/
@Deprecated
- public PropertyUtils()
- {
- }
+ public PropertyUtils() {}
/**
* @param url the URL which should be used to load the properties
@@ -53,14 +49,10 @@ public class PropertyUtils
* instead of an empty {@code Properties} instance when the given {@code URL} is {@code null}.
*/
@Deprecated
- public static java.util.Properties loadProperties( @Nonnull URL url )
- {
- try ( InputStream in = url.openStream() )
- {
- return loadProperties( in );
- }
- catch ( Exception e )
- {
+ public static java.util.Properties loadProperties(@Nonnull URL url) {
+ try (InputStream in = url.openStream()) {
+ return loadProperties(in);
+ } catch (Exception e) {
// ignore
}
return null;
@@ -74,14 +66,10 @@ public class PropertyUtils
* instead of an empty {@code Properties} instance when the given {@code File} is {@code null}.
*/
@Deprecated
- public static Properties loadProperties( @Nonnull File file )
- {
- try ( InputStream in = new FileInputStream( file ) )
- {
- return loadProperties( in );
- }
- catch ( Exception e )
- {
+ public static Properties loadProperties(@Nonnull File file) {
+ try (InputStream in = new FileInputStream(file)) {
+ return loadProperties(in);
+ } catch (Exception e) {
// ignore
}
return null;
@@ -90,34 +78,26 @@ public class PropertyUtils
/**
* Loads {@code Properties} from an {@code InputStream} and closes the stream.
* In a future release, this will no longer close the stream, so callers
- * should close the stream themselves.
- *
+ * should close the stream themselves.
+ *
* @param is {@link InputStream}
* @return the loaded properties
* @deprecated use {@link #loadOptionalProperties(java.io.InputStream)} instead. This method
* should not be used as it suppresses exceptions silently when loading properties fails.
*/
@Deprecated
- public static Properties loadProperties( @Nullable InputStream is )
- {
- try
- {
+ public static Properties loadProperties(@Nullable InputStream is) {
+ try {
Properties result = new Properties();
- if ( is != null )
- {
- try ( InputStream in = is )
- {
- result.load( in );
- }
- catch ( IOException e )
- {
+ if (is != null) {
+ try (InputStream in = is) {
+ result.load(in);
+ } catch (IOException e) {
// ignore
}
}
return result;
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
// ignore
}
return null;
@@ -134,18 +114,13 @@ public class PropertyUtils
* @since 3.1.0
*/
@Nonnull
- public static Properties loadOptionalProperties( final @Nullable URL url )
- {
+ public static Properties loadOptionalProperties(final @Nullable URL url) {
Properties properties = new Properties();
- if ( url != null )
- {
- try ( InputStream in = url.openStream() )
- {
- properties.load( in );
- }
- catch ( IllegalArgumentException | IOException ex )
- {
+ if (url != null) {
+ try (InputStream in = url.openStream()) {
+ properties.load(in);
+ } catch (IllegalArgumentException | IOException ex) {
// ignore and return empty properties
}
}
@@ -164,55 +139,43 @@ public class PropertyUtils
* @since 3.1.0
*/
@Nonnull
- public static Properties loadOptionalProperties( final @Nullable File file )
- {
+ public static Properties loadOptionalProperties(final @Nullable File file) {
Properties properties = new Properties();
- if ( file != null )
- {
- try ( InputStream in = new FileInputStream( file ) )
- {
- properties.load( in );
- }
- catch ( IllegalArgumentException | IOException ex )
- {
+ if (file != null) {
+ try (InputStream in = new FileInputStream(file)) {
+ properties.load(in);
+ } catch (IllegalArgumentException | IOException ex) {
// ignore and return empty properties
}
}
return properties;
-
}
/**
* Loads {@code Properties} from an {@code InputStream} and closes the stream.
* If the given {@code InputStream} is {@code null} or the properties can't be read, an empty properties object is
* returned. In a future release, this will no longer close the stream, so callers
- * should close the stream themselves.
+ * should close the stream themselves.
*
* @param inputStream the properties resource to load or {@code null}
* @return the loaded properties or an empty {@code Properties} instance if properties fail to load
* @since 3.1.0
*/
@Nonnull
- public static Properties loadOptionalProperties( final @Nullable InputStream inputStream )
- {
+ public static Properties loadOptionalProperties(final @Nullable InputStream inputStream) {
Properties properties = new Properties();
- if ( inputStream != null )
- {
- try ( InputStream in = inputStream ) // reassign inputStream to autoclose
- {
- properties.load( in );
- }
- catch ( IllegalArgumentException | IOException ex )
+ if (inputStream != null) {
+ try (InputStream in = inputStream) // reassign inputStream to autoclose
{
+ properties.load(in);
+ } catch (IllegalArgumentException | IOException ex) {
// ignore and return empty properties
}
}
return properties;
-
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/ReaderFactory.java b/src/main/java/org/apache/maven/shared/utils/ReaderFactory.java
index a92a1bd..efdb8a2 100644
--- a/src/main/java/org/apache/maven/shared/utils/ReaderFactory.java
+++ b/src/main/java/org/apache/maven/shared/utils/ReaderFactory.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@ package org.apache.maven.shared.utils;
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,6 +16,9 @@ package org.apache.maven.shared.utils;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils;
+
+import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileInputStream;
@@ -29,10 +30,8 @@ import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
-import org.apache.commons.io.input.XmlStreamReader;
-
-import javax.annotation.Nonnull;
+import org.apache.commons.io.input.XmlStreamReader;
/**
* Utility to create Readers from streams, with explicit encoding choice: platform default,
@@ -42,8 +41,7 @@ import javax.annotation.Nonnull;
* @see java.nio.charset.Charset
* @see <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html">Supported encodings</a>
*/
-public class ReaderFactory
-{
+public class ReaderFactory {
/**
* ISO Latin Alphabet #1, also known as ISO-LATIN-1.
* Every implementation of the Java platform is required to support this character encoding.
@@ -102,7 +100,7 @@ public class ReaderFactory
/**
* The <code>file.encoding</code> System Property.
*/
- public static final String FILE_ENCODING = System.getProperty( "file.encoding" );
+ public static final String FILE_ENCODING = System.getProperty("file.encoding");
/**
* Create a new Reader with XML encoding detection rules.
@@ -113,10 +111,8 @@ public class ReaderFactory
* @deprecated use org.apache.commons.io.input.XmlStreamReader instead
*/
@Deprecated
- public static Reader newXmlReader( @Nonnull InputStream in )
- throws IOException
- {
- return new XmlStreamReader( in );
+ public static Reader newXmlReader(@Nonnull InputStream in) throws IOException {
+ return new XmlStreamReader(in);
}
/**
@@ -128,10 +124,8 @@ public class ReaderFactory
* @deprecated use org.apache.commons.io.input.XmlStreamReader instead
*/
@Deprecated
- public static Reader newXmlReader( @Nonnull File file )
- throws IOException
- {
- return new XmlStreamReader( file );
+ public static Reader newXmlReader(@Nonnull File file) throws IOException {
+ return new XmlStreamReader(file);
}
/**
@@ -143,10 +137,8 @@ public class ReaderFactory
* @deprecated use {@code org.apache.commons.io.input.XmlStreamReader} instead
*/
@Deprecated
- public static Reader newXmlReader( @Nonnull URL url )
- throws IOException
- {
- return new XmlStreamReader( url );
+ public static Reader newXmlReader(@Nonnull URL url) throws IOException {
+ return new XmlStreamReader(url);
}
/**
@@ -159,10 +151,8 @@ public class ReaderFactory
* @deprecated always specify an encoding. Do not depend on the default platform character set.
*/
@Deprecated
- public static Reader newPlatformReader( @Nonnull File file )
- throws FileNotFoundException
- {
- return new FileReader( file );
+ public static Reader newPlatformReader(@Nonnull File file) throws FileNotFoundException {
+ return new FileReader(file);
}
/**
@@ -175,10 +165,9 @@ public class ReaderFactory
* @see <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html">Supported
* encodings</a>
*/
- public static Reader newReader( @Nonnull InputStream in, @Nonnull String encoding )
- throws UnsupportedEncodingException
- {
- return new InputStreamReader( in, encoding );
+ public static Reader newReader(@Nonnull InputStream in, @Nonnull String encoding)
+ throws UnsupportedEncodingException {
+ return new InputStreamReader(in, encoding);
}
/**
@@ -192,10 +181,9 @@ public class ReaderFactory
* @see <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html">Supported
* encodings</a>
*/
- public static Reader newReader( @Nonnull File file, @Nonnull String encoding )
- throws FileNotFoundException, UnsupportedEncodingException
- {
- return new InputStreamReader( new FileInputStream( file ), encoding );
+ public static Reader newReader(@Nonnull File file, @Nonnull String encoding)
+ throws FileNotFoundException, UnsupportedEncodingException {
+ return new InputStreamReader(new FileInputStream(file), encoding);
}
/**
@@ -208,9 +196,7 @@ public class ReaderFactory
* @see <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html">Supported
* encodings</a>
*/
- public static Reader newReader( @Nonnull URL url, @Nonnull String encoding )
- throws IOException
- {
- return new InputStreamReader( url.openStream(), encoding );
+ public static Reader newReader(@Nonnull URL url, @Nonnull String encoding) throws IOException {
+ return new InputStreamReader(url.openStream(), encoding);
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/StringUtils.java b/src/main/java/org/apache/maven/shared/utils/StringUtils.java
index a355e2e..dff90cb 100644
--- a/src/main/java/org/apache/maven/shared/utils/StringUtils.java
+++ b/src/main/java/org/apache/maven/shared/utils/StringUtils.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,7 +16,10 @@ package org.apache.maven.shared.utils;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Iterator;
@@ -26,9 +27,6 @@ import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
/**
* <p>Common <code>String</code> manipulation routines.</p>
*
@@ -49,10 +47,9 @@ import javax.annotation.Nullable;
* @author <a href="mailto:fredrik@westermarck.com">Fredrik Westermarck</a>
* @author Holger Krauth
* @author <a href="mailto:alex@purpletech.com">Alexander Day Chaffee</a>
- *
+ *
*/
-public class StringUtils
-{
+public class StringUtils {
/**
* <p><code>StringUtils</code> instances should NOT be constructed in
* standard programming. Instead, the class should be used as
@@ -61,12 +58,10 @@ public class StringUtils
* <p>This constructor is public to permit tools that require a JavaBean
* manager to operate.</p>
*/
- public StringUtils()
- {
- }
+ public StringUtils() {}
// Empty
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Removes C0 control characters, including ASCII whitespace, from both
@@ -77,9 +72,9 @@ public class StringUtils
* @return the trimmed text (never <code>null</code>)
* @see java.lang.String#trim()
*/
- @Nonnull public static String clean( String str )
- {
- return ( str == null ? "" : str.trim() );
+ @Nonnull
+ public static String clean(String str) {
+ return (str == null ? "" : str.trim());
}
/**
@@ -91,9 +86,8 @@ public class StringUtils
* @return the trimmed text (or <code>null</code>)
* @see java.lang.String#trim()
*/
- public static String trim( String str )
- {
- return ( str == null ? null : str.trim() );
+ public static String trim(String str) {
+ return (str == null ? null : str.trim());
}
/**
@@ -105,15 +99,13 @@ public class StringUtils
* @param str String target to delete whitespace from
* @return the String without whitespace
*/
- @Nonnull public static String deleteWhitespace( @Nonnull String str )
- {
+ @Nonnull
+ public static String deleteWhitespace(@Nonnull String str) {
StringBuilder buffer = new StringBuilder();
int sz = str.length();
- for ( int i = 0; i < sz; i++ )
- {
- if ( !Character.isWhitespace( str.charAt( i ) ) )
- {
- buffer.append( str.charAt( i ) );
+ for (int i = 0; i < sz; i++) {
+ if (!Character.isWhitespace(str.charAt(i))) {
+ buffer.append(str.charAt(i));
}
}
return buffer.toString();
@@ -126,14 +118,13 @@ public class StringUtils
* @param str the String to check
* @return true if the String is non-null, and not length zero
*/
- public static boolean isNotEmpty( @Nullable String str )
- {
- return ( ( str != null ) && ( str.length() > 0 ) );
+ public static boolean isNotEmpty(@Nullable String str) {
+ return ((str != null) && (str.length() > 0));
}
/**
* <p>Checks if a (trimmed) String is <code>null</code> or empty.</p>
- *
+ *
* <p><strong>Note:</strong> In future releases, this method will no longer trim the input string such that it works
* complementary to {@link #isNotEmpty(String)}. Code that wants to test for whitespace-only strings should be
* migrated to use {@link #isBlank(String)} instead.</p>
@@ -142,16 +133,15 @@ public class StringUtils
* @return <code>true</code> if the String is <code>null</code>, or
* length zero once trimmed
*/
- public static boolean isEmpty( @Nullable String str )
- {
- return ( ( str == null ) || ( str.trim().length() == 0 ) );
+ public static boolean isEmpty(@Nullable String str) {
+ return ((str == null) || (str.trim().length() == 0));
}
/**
* <p>
* Checks if a String is whitespace, empty ("") or null.
* </p>
- *
+ *
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
@@ -162,21 +152,18 @@ public class StringUtils
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace
- *
+ *
*/
- public static boolean isBlank( @Nullable String str )
- {
+ public static boolean isBlank(@Nullable String str) {
int strLen;
// CHECKSTYLE_OFF: InnerAssignment
- if ( str == null || ( strLen = str.length() ) == 0 )
+ if (str == null || (strLen = str.length()) == 0)
// CHECKSTYLE_ON: InnerAssignment
{
return true;
}
- for ( int i = 0; i < strLen; i++ )
- {
- if ( !Character.isWhitespace( str.charAt( i ) ) )
- {
+ for (int i = 0; i < strLen; i++) {
+ if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
@@ -187,7 +174,7 @@ public class StringUtils
* <p>
* Checks if a String is not empty (""), not null and not whitespace only.
* </p>
- *
+ *
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
@@ -198,19 +185,18 @@ public class StringUtils
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is not empty and not null and not whitespace
- *
+ *
*/
- public static boolean isNotBlank( @Nullable String str )
- {
- return !isBlank( str );
+ public static boolean isNotBlank(@Nullable String str) {
+ return !isBlank(str);
}
// Equals and IndexOf
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Compares two Strings, returning <code>true</code> if they are equal.</p>
- *
+ *
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case sensitive.</p>
*
@@ -222,15 +208,14 @@ public class StringUtils
* @deprecated use {@code java.lang.Objects.equals()}
*/
@Deprecated
- public static boolean equals( @Nullable String str1, @Nullable String str2 )
- {
- return ( str1 == null ? str2 == null : str1.equals( str2 ) );
+ public static boolean equals(@Nullable String str1, @Nullable String str2) {
+ return (str1 == null ? str2 == null : str1.equals(str2));
}
/**
* <p>Compares two Strings, returning <code>true</code> if they are equal ignoring
* the case.</p>
- *
+ *
* <p><code>Nulls</code> are handled without exceptions. Two <code>null</code>
* references are considered equal. Comparison is case insensitive.</p>
*
@@ -240,14 +225,13 @@ public class StringUtils
* both <code>null</code>
* @see java.lang.String#equalsIgnoreCase(String)
*/
- public static boolean equalsIgnoreCase( String str1, String str2 )
- {
- return ( str1 == null ? str2 == null : str1.equalsIgnoreCase( str2 ) );
+ public static boolean equalsIgnoreCase(String str1, String str2) {
+ return (str1 == null ? str2 == null : str1.equalsIgnoreCase(str2));
}
/**
* <p>Find the first index of any of a set of potential substrings.</p>
- *
+ *
* <p><code>null</code> String will return <code>-1</code>.</p>
*
* @param str the String to check
@@ -255,36 +239,31 @@ public class StringUtils
* @return the first index of any of the searchStrs in str
* @throws NullPointerException if any of searchStrs[i] is <code>null</code>
*/
- public static int indexOfAny( String str, String... searchStrs )
- {
- if ( ( str == null ) || ( searchStrs == null ) )
- {
+ public static int indexOfAny(String str, String... searchStrs) {
+ if ((str == null) || (searchStrs == null)) {
return -1;
}
// String's can't have a MAX_VALUEth index.
int ret = Integer.MAX_VALUE;
int tmp;
- for ( String searchStr : searchStrs )
- {
- tmp = str.indexOf( searchStr );
- if ( tmp == -1 )
- {
+ for (String searchStr : searchStrs) {
+ tmp = str.indexOf(searchStr);
+ if (tmp == -1) {
continue;
}
- if ( tmp < ret )
- {
+ if (tmp < ret) {
ret = tmp;
}
}
- return ( ret == Integer.MAX_VALUE ) ? -1 : ret;
+ return (ret == Integer.MAX_VALUE) ? -1 : ret;
}
/**
* <p>Find the latest index of any of a set of potential substrings.</p>
- *
+ *
* <p><code>null</code> string will return <code>-1</code>.</p>
*
* @param str the String to check
@@ -292,19 +271,15 @@ public class StringUtils
* @return the last index of any of the Strings
* @throws NullPointerException if any of searchStrs[i] is <code>null</code>
*/
- public static int lastIndexOfAny( String str, String... searchStrs )
- {
- if ( ( str == null ) || ( searchStrs == null ) )
- {
+ public static int lastIndexOfAny(String str, String... searchStrs) {
+ if ((str == null) || (searchStrs == null)) {
return -1;
}
int ret = -1;
int tmp;
- for ( String searchStr : searchStrs )
- {
- tmp = str.lastIndexOf( searchStr );
- if ( tmp > ret )
- {
+ for (String searchStr : searchStrs) {
+ tmp = str.lastIndexOf(searchStr);
+ if (tmp > ret) {
ret = tmp;
}
}
@@ -312,7 +287,7 @@ public class StringUtils
}
// Substring
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Gets a substring from the specified string avoiding exceptions.</p>
@@ -325,34 +300,29 @@ public class StringUtils
* count back from the end of the String by this many characters
* @return substring from start position
*/
- public static String substring( String str, int start )
- {
- if ( str == null )
- {
+ public static String substring(String str, int start) {
+ if (str == null) {
return null;
}
// handle negatives, which means last n characters
- if ( start < 0 )
- {
+ if (start < 0) {
start = str.length() + start; // remember start is negative
}
- if ( start < 0 )
- {
+ if (start < 0) {
start = 0;
}
- if ( start > str.length() )
- {
+ if (start > str.length()) {
return "";
}
- return str.substring( start );
+ return str.substring(start);
}
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
- *
+ *
* <p>A negative start position can be used to start/end <code>n</code>
* characters from the end of the String.</p>
*
@@ -363,51 +333,43 @@ public class StringUtils
* count back from the end of the String by this many characters
* @return substring from start position to end position
*/
- public static String substring( String str, int start, int end )
- {
- if ( str == null )
- {
+ public static String substring(String str, int start, int end) {
+ if (str == null) {
return null;
}
// handle negatives
- if ( end < 0 )
- {
+ if (end < 0) {
end = str.length() + end; // remember end is negative
}
- if ( start < 0 )
- {
+ if (start < 0) {
start = str.length() + start; // remember start is negative
}
// check length next
- if ( end > str.length() )
- {
+ if (end > str.length()) {
// check this works.
end = str.length();
}
// if start is greater than end, return ""
- if ( start > end )
- {
+ if (start > end) {
return "";
}
- if ( start < 0 )
- {
+ if (start < 0) {
start = 0;
}
- if ( end < 0 )
- {
+ if (end < 0) {
end = 0;
}
- return str.substring( start, end );
+ return str.substring(start, end);
}
/**
* <p>Gets the leftmost <code>n</code> characters of a String.</p>
- *
+ *
* <p>If <code>n</code> characters are not available, or the
* String is <code>null</code>, the String will be returned without
* an exception.</p>
@@ -417,25 +379,20 @@ public class StringUtils
* @return the leftmost characters
* @throws IllegalArgumentException if len is less than zero
*/
- public static String left( String str, int len )
- {
- if ( len < 0 )
- {
- throw new IllegalArgumentException( "Requested String length " + len + " is less than zero" );
+ public static String left(String str, int len) {
+ if (len < 0) {
+ throw new IllegalArgumentException("Requested String length " + len + " is less than zero");
}
- if ( ( str == null ) || ( str.length() <= len ) )
- {
+ if ((str == null) || (str.length() <= len)) {
return str;
- }
- else
- {
- return str.substring( 0, len );
+ } else {
+ return str.substring(0, len);
}
}
/**
* <p>Gets the rightmost <code>n</code> characters of a String.</p>
- *
+ *
* <p>If <code>n</code> characters are not available, or the String
* is <code>null</code>, the String will be returned without an
* exception.</p>
@@ -445,25 +402,20 @@ public class StringUtils
* @return the leftmost characters
* @throws IllegalArgumentException if len is less than zero
*/
- public static String right( String str, int len )
- {
- if ( len < 0 )
- {
- throw new IllegalArgumentException( "Requested String length " + len + " is less than zero" );
+ public static String right(String str, int len) {
+ if (len < 0) {
+ throw new IllegalArgumentException("Requested String length " + len + " is less than zero");
}
- if ( ( str == null ) || ( str.length() <= len ) )
- {
+ if ((str == null) || (str.length() <= len)) {
return str;
- }
- else
- {
- return str.substring( str.length() - len );
+ } else {
+ return str.substring(str.length() - len);
}
}
/**
* <p>Gets <code>n</code> characters from the middle of a String.</p>
- *
+ *
* <p>If <code>n</code> characters are not available, the remainder
* of the String will be returned without an exception. If the
* String is <code>null</code>, <code>null</code> will be returned.</p>
@@ -475,45 +427,38 @@ public class StringUtils
* @throws IndexOutOfBoundsException if pos is out of bounds
* @throws IllegalArgumentException if len is less than zero
*/
- public static String mid( String str, int pos, int len )
- {
- if ( ( pos < 0 ) || ( ( str != null ) && ( pos > str.length() ) ) )
- {
- throw new StringIndexOutOfBoundsException( "String index " + pos + " is out of bounds" );
+ public static String mid(String str, int pos, int len) {
+ if ((pos < 0) || ((str != null) && (pos > str.length()))) {
+ throw new StringIndexOutOfBoundsException("String index " + pos + " is out of bounds");
}
- if ( len < 0 )
- {
- throw new IllegalArgumentException( "Requested String length " + len + " is less than zero" );
+ if (len < 0) {
+ throw new IllegalArgumentException("Requested String length " + len + " is less than zero");
}
- if ( str == null )
- {
+ if (str == null) {
return null;
}
- if ( str.length() <= ( pos + len ) )
- {
- return str.substring( pos );
- }
- else
- {
- return str.substring( pos, pos + len );
+ if (str.length() <= (pos + len)) {
+ return str.substring(pos);
+ } else {
+ return str.substring(pos, pos + len);
}
}
// Splitting
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Splits the provided text into a array, using whitespace as the
* separator.</p>
- *
+ *
* <p>The separator is not included in the returned String array.</p>
*
* @param str the String to parse
* @return an array of parsed Strings
*/
- @Nonnull public static String[] split( @Nonnull String str )
- {
- return split( str, null, -1 );
+ @Nonnull
+ public static String[] split(@Nonnull String str) {
+ return split(str, null, -1);
}
/**
@@ -522,18 +467,18 @@ public class StringUtils
* @return the resulting array
* @see #split(String, String, int)
*/
- @Nonnull public static String[] split( @Nonnull String text, @Nullable String separator )
- {
- return split( text, separator, -1 );
+ @Nonnull
+ public static String[] split(@Nonnull String text, @Nullable String separator) {
+ return split(text, separator, -1);
}
/**
* <p>Splits the provided text into a array, based on a given separator.</p>
- *
+ *
* <p>The separator is not included in the returned String array. The
* maximum number of splits to perform can be controlled. A <code>null</code>
* separator causes splitting on whitespace.</p>
- *
+ *
* <p>This is useful for quickly splitting a String into
* an array of tokens, instead of an enumeration of tokens (as
* <code>StringTokenizer</code> does).</p>
@@ -545,23 +490,19 @@ public class StringUtils
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings
*/
- @Nonnull public static String[] split( @Nonnull String str, @Nullable String separator, int max )
- {
+ @Nonnull
+ public static String[] split(@Nonnull String str, @Nullable String separator, int max) {
StringTokenizer tok;
- if ( separator == null )
- {
+ if (separator == null) {
// Null separator means we're using StringTokenizer's default
// delimiter, which comprises all whitespace characters.
- tok = new StringTokenizer( str );
- }
- else
- {
- tok = new StringTokenizer( str, separator );
+ tok = new StringTokenizer(str);
+ } else {
+ tok = new StringTokenizer(str, separator);
}
int listSize = tok.countTokens();
- if ( ( max > 0 ) && ( listSize > max ) )
- {
+ if ((max > 0) && (listSize > max)) {
listSize = max;
}
@@ -569,22 +510,18 @@ public class StringUtils
int i = 0;
int lastTokenBegin;
int lastTokenEnd = 0;
- while ( tok.hasMoreTokens() )
- {
- if ( ( max > 0 ) && ( i == listSize - 1 ) )
- {
+ while (tok.hasMoreTokens()) {
+ if ((max > 0) && (i == listSize - 1)) {
// In the situation where we hit the max yet have
// tokens left over in our input, the last list
// element gets all remaining text.
String endToken = tok.nextToken();
- lastTokenBegin = str.indexOf( endToken, lastTokenEnd );
- list[i] = str.substring( lastTokenBegin );
+ lastTokenBegin = str.indexOf(endToken, lastTokenEnd);
+ list[i] = str.substring(lastTokenBegin);
break;
- }
- else
- {
+ } else {
list[i] = tok.nextToken();
- lastTokenBegin = str.indexOf( list[i], lastTokenEnd );
+ lastTokenBegin = str.indexOf(list[i], lastTokenEnd);
lastTokenEnd = lastTokenBegin + list[i].length();
}
i++;
@@ -593,25 +530,25 @@ public class StringUtils
}
// Joining
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Concatenates elements of an array into a single String.</p>
- *
+ *
* <p>The difference from join is that concatenate has no delimiter.</p>
*
* @param array the array of values to concatenate.
* @return the concatenated string.
*/
- @Nonnull public static String concatenate( @Nonnull Object... array )
- {
- return join( array, "" );
+ @Nonnull
+ public static String concatenate(@Nonnull Object... array) {
+ return join(array, "");
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
- *
+ *
* <p>No delimiter is added before or after the list. A
* <code>null</code> separator is the same as a blank String.</p>
*
@@ -621,23 +558,20 @@ public class StringUtils
* @deprecated use <code>java.lang.String.join(</code>) instead
*/
@Deprecated
- @Nonnull public static String join( @Nonnull Object[] array, @Nullable String separator )
- {
- if ( separator == null )
- {
+ @Nonnull
+ public static String join(@Nonnull Object[] array, @Nullable String separator) {
+ if (separator == null) {
separator = "";
}
int arraySize = array.length;
- int bufSize = ( arraySize == 0 ? 0 : ( array[0].toString().length() + separator.length() ) * arraySize );
- StringBuilder buf = new StringBuilder( bufSize );
+ int bufSize = (arraySize == 0 ? 0 : (array[0].toString().length() + separator.length()) * arraySize);
+ StringBuilder buf = new StringBuilder(bufSize);
- for ( int i = 0; i < arraySize; i++ )
- {
- if ( i > 0 )
- {
- buf.append( separator );
+ for (int i = 0; i < arraySize; i++) {
+ if (i > 0) {
+ buf.append(separator);
}
- buf.append( array[i] );
+ buf.append(array[i]);
}
return buf.toString();
}
@@ -645,7 +579,7 @@ public class StringUtils
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
- *
+ *
* <p>No delimiter is added before or after the list. A
* <code>null</code> separator is the same as a blank String.</p>
*
@@ -655,26 +589,23 @@ public class StringUtils
* @deprecated use <code>java.lang.String.join(</code>) instead
*/
@Deprecated
- @Nonnull public static String join( @Nonnull Iterator<?> iterator, String separator )
- {
- if ( separator == null )
- {
+ @Nonnull
+ public static String join(@Nonnull Iterator<?> iterator, String separator) {
+ if (separator == null) {
separator = "";
}
- StringBuilder buf = new StringBuilder( 256 ); // Java default is 16, probably too small
- while ( iterator.hasNext() )
- {
- buf.append( iterator.next() );
- if ( iterator.hasNext() )
- {
- buf.append( separator );
+ StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
+ while (iterator.hasNext()) {
+ buf.append(iterator.next());
+ if (iterator.hasNext()) {
+ buf.append(separator);
}
}
return buf.toString();
}
// Replacing
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Replace a char with another char inside a larger String, once.</p>
@@ -687,9 +618,8 @@ public class StringUtils
* @return the text with any replacements processed
* @see #replace(String text, char repl, char with, int max)
*/
- public static String replaceOnce( @Nullable String text, char repl, char with )
- {
- return replace( text, repl, with, 1 );
+ public static String replaceOnce(@Nullable String text, char repl, char with) {
+ return replace(text, repl, with, 1);
}
/**
@@ -703,9 +633,8 @@ public class StringUtils
* @return the text with any replacements processed
* @see #replace(String text, char repl, char with, int max)
*/
- public static String replace( @Nullable String text, char repl, char with )
- {
- return replace( text, repl, with, -1 );
+ public static String replace(@Nullable String text, char repl, char with) {
+ return replace(text, repl, with, -1);
}
/**
@@ -720,9 +649,8 @@ public class StringUtils
* @param max maximum number of values to replace, or <code>-1</code> if no maximum
* @return the text with any replacements processed
*/
- public static String replace( @Nullable String text, char repl, char with, int max )
- {
- return replace( text, String.valueOf( repl ), String.valueOf( with ), max );
+ public static String replace(@Nullable String text, char repl, char with, int max) {
+ return replace(text, String.valueOf(repl), String.valueOf(with), max);
}
/**
@@ -736,14 +664,13 @@ public class StringUtils
* @return the text with any replacements processed
* @see #replace(String text, String repl, String with, int max)
*/
- public static String replaceOnce( @Nullable String text, @Nullable String repl, @Nullable String with )
- {
- return replace( text, repl, with, 1 );
+ public static String replaceOnce(@Nullable String text, @Nullable String repl, @Nullable String with) {
+ return replace(text, repl, with, 1);
}
/**
* <p>Replace all occurrences of a String within another String.</p>
- *
+ *
* <p>A <code>null</code> reference passed to this method is a no-op.</p>
*
* @param text text to search and replace in
@@ -752,9 +679,8 @@ public class StringUtils
* @return the text with any replacements processed
* @see #replace(String text, String repl, String with, int max)
*/
- public static String replace( @Nullable String text, @Nullable String repl, @Nullable String with )
- {
- return replace( text, repl, with, -1 );
+ public static String replace(@Nullable String text, @Nullable String repl, @Nullable String with) {
+ return replace(text, repl, with, -1);
}
/**
@@ -769,26 +695,22 @@ public class StringUtils
* @param max maximum number of values to replace, or <code>-1</code> if no maximum
* @return the text with any replacements processed
*/
- public static String replace( @Nullable String text, @Nullable String repl, @Nullable String with, int max )
- {
- if ( ( text == null ) || ( repl == null ) || ( with == null ) || ( repl.length() == 0 ) )
- {
+ public static String replace(@Nullable String text, @Nullable String repl, @Nullable String with, int max) {
+ if ((text == null) || (repl == null) || (with == null) || (repl.length() == 0)) {
return text;
}
- StringBuilder buf = new StringBuilder( text.length() );
+ StringBuilder buf = new StringBuilder(text.length());
int start = 0, end;
- while ( ( end = text.indexOf( repl, start ) ) != -1 )
- {
- buf.append( text, start, end ).append( with );
+ while ((end = text.indexOf(repl, start)) != -1) {
+ buf.append(text, start, end).append(with);
start = end + repl.length();
- if ( --max == 0 )
- {
+ if (--max == 0) {
break;
}
}
- buf.append( text, start, text.length() );
+ buf.append(text, start, text.length());
return buf.toString();
}
@@ -802,21 +724,20 @@ public class StringUtils
* @return String with overlaid text
* @throws NullPointerException if text or overlay is <code>null</code>
*/
- @Nonnull public static String overlayString( @Nonnull String text, @Nonnull String overlay, int start, int end )
- {
- if ( overlay == null )
- {
- throw new NullPointerException( "overlay is null" );
+ @Nonnull
+ public static String overlayString(@Nonnull String text, @Nonnull String overlay, int start, int end) {
+ if (overlay == null) {
+ throw new NullPointerException("overlay is null");
}
- return new StringBuilder( start + overlay.length() + text.length() - end + 1 )
- .append( text, 0, start )
- .append( overlay )
- .append( text, end, text.length() )
- .toString();
+ return new StringBuilder(start + overlay.length() + text.length() - end + 1)
+ .append(text, 0, start)
+ .append(overlay)
+ .append(text, end, text.length())
+ .toString();
}
// Centering
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Center a String in a larger String of size <code>n</code>.</p>
@@ -829,9 +750,9 @@ public class StringUtils
* @return String containing centered String
* @throws NullPointerException if str is <code>null</code>
*/
- @Nonnull public static String center( @Nonnull String str, int size )
- {
- return center( str, size, " " );
+ @Nonnull
+ public static String center(@Nonnull String str, int size) {
+ return center(str, size, " ");
}
/**
@@ -846,21 +767,20 @@ public class StringUtils
* @throws NullPointerException if str or delim is <code>null</code>
* @throws ArithmeticException if delim is the empty String
*/
- @Nonnull public static String center( @Nonnull String str, int size, @Nonnull String delim )
- {
+ @Nonnull
+ public static String center(@Nonnull String str, int size, @Nonnull String delim) {
int sz = str.length();
int p = size - sz;
- if ( p < 1 )
- {
+ if (p < 1) {
return str;
}
- str = leftPad( str, sz + p / 2, delim );
- str = rightPad( str, size, delim );
+ str = leftPad(str, sz + p / 2, delim);
+ str = rightPad(str, size, delim);
return str;
}
// Chomping
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Remove the last newline, and everything after it from a String.</p>
@@ -869,9 +789,9 @@ public class StringUtils
* @return String without chomped newline
* @throws NullPointerException if str is <code>null</code>
*/
- @Nonnull public static String chomp( @Nonnull String str )
- {
- return chomp( str, "\n" );
+ @Nonnull
+ public static String chomp(@Nonnull String str) {
+ return chomp(str, "\n");
}
/**
@@ -883,15 +803,12 @@ public class StringUtils
* @return String without chomped ending
* @throws NullPointerException if str or sep is <code>null</code>
*/
- @Nonnull public static String chomp( @Nonnull String str, @Nonnull String sep )
- {
- int idx = str.lastIndexOf( sep );
- if ( idx != -1 )
- {
- return str.substring( 0, idx );
- }
- else
- {
+ @Nonnull
+ public static String chomp(@Nonnull String str, @Nonnull String sep) {
+ int idx = str.lastIndexOf(sep);
+ if (idx != -1) {
+ return str.substring(0, idx);
+ } else {
return str;
}
}
@@ -904,9 +821,9 @@ public class StringUtils
* @return String without chomped ending
* @throws NullPointerException if str is <code>null</code>
*/
- @Nonnull public static String chompLast( @Nonnull String str )
- {
- return chompLast( str, "\n" );
+ @Nonnull
+ public static String chompLast(@Nonnull String str) {
+ return chompLast(str, "\n");
}
/**
@@ -917,19 +834,15 @@ public class StringUtils
* @return String without chomped ending
* @throws NullPointerException if str or sep is <code>null</code>
*/
- @Nonnull public static String chompLast( @Nonnull String str, @Nonnull String sep )
- {
- if ( str.length() == 0 )
- {
+ @Nonnull
+ public static String chompLast(@Nonnull String str, @Nonnull String sep) {
+ if (str.length() == 0) {
return str;
}
- String sub = str.substring( str.length() - sep.length() );
- if ( sep.equals( sub ) )
- {
- return str.substring( 0, str.length() - sep.length() );
- }
- else
- {
+ String sub = str.substring(str.length() - sep.length());
+ if (sep.equals(sub)) {
+ return str.substring(0, str.length() - sep.length());
+ } else {
return str;
}
}
@@ -943,19 +856,14 @@ public class StringUtils
* @return String chomped
* @throws NullPointerException if str or sep is <code>null</code>
*/
- @Nonnull public static String getChomp( @Nonnull String str, @Nonnull String sep )
- {
- int idx = str.lastIndexOf( sep );
- if ( idx == str.length() - sep.length() )
- {
+ @Nonnull
+ public static String getChomp(@Nonnull String str, @Nonnull String sep) {
+ int idx = str.lastIndexOf(sep);
+ if (idx == str.length() - sep.length()) {
return sep;
- }
- else if ( idx != -1 )
- {
- return str.substring( idx );
- }
- else
- {
+ } else if (idx != -1) {
+ return str.substring(idx);
+ } else {
return "";
}
}
@@ -969,15 +877,12 @@ public class StringUtils
* @return String without chomped beginning
* @throws NullPointerException if str or sep is <code>null</code>
*/
- @Nonnull public static String prechomp( @Nonnull String str, @Nonnull String sep )
- {
- int idx = str.indexOf( sep );
- if ( idx != -1 )
- {
- return str.substring( idx + sep.length() );
- }
- else
- {
+ @Nonnull
+ public static String prechomp(@Nonnull String str, @Nonnull String sep) {
+ int idx = str.indexOf(sep);
+ if (idx != -1) {
+ return str.substring(idx + sep.length());
+ } else {
return str;
}
}
@@ -991,21 +896,18 @@ public class StringUtils
* @return String prechomped
* @throws NullPointerException if str or sep is <code>null</code>
*/
- @Nonnull public static String getPrechomp( @Nonnull String str, @Nonnull String sep )
- {
- int idx = str.indexOf( sep );
- if ( idx != -1 )
- {
- return str.substring( 0, idx + sep.length() );
- }
- else
- {
+ @Nonnull
+ public static String getPrechomp(@Nonnull String str, @Nonnull String sep) {
+ int idx = str.indexOf(sep);
+ if (idx != -1) {
+ return str.substring(0, idx + sep.length());
+ } else {
return "";
}
}
// Chopping
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Remove the last character from a String.</p>
@@ -1017,24 +919,20 @@ public class StringUtils
* @return String without last character
* @throws NullPointerException if str is <code>null</code>
*/
- @Nonnull public static String chop( @Nonnull String str )
- {
- if ( "".equals( str ) )
- {
+ @Nonnull
+ public static String chop(@Nonnull String str) {
+ if ("".equals(str)) {
return "";
}
- if ( str.length() == 1 )
- {
+ if (str.length() == 1) {
return "";
}
int lastIdx = str.length() - 1;
- String ret = str.substring( 0, lastIdx );
- char last = str.charAt( lastIdx );
- if ( last == '\n' )
- {
- if ( ret.charAt( lastIdx - 1 ) == '\r' )
- {
- return ret.substring( 0, lastIdx - 1 );
+ String ret = str.substring(0, lastIdx);
+ char last = str.charAt(lastIdx);
+ if (last == '\n') {
+ if (ret.charAt(lastIdx - 1) == '\r') {
+ return ret.substring(0, lastIdx - 1);
}
}
return ret;
@@ -1048,26 +946,22 @@ public class StringUtils
* @return String without newline
* @throws NullPointerException if str is <code>null</code>
*/
- @Nonnull public static String chopNewline( @Nonnull String str )
- {
+ @Nonnull
+ public static String chopNewline(@Nonnull String str) {
int lastIdx = str.length() - 1;
- char last = str.charAt( lastIdx );
- if ( last == '\n' )
- {
- if ( str.charAt( lastIdx - 1 ) == '\r' )
- {
+ char last = str.charAt(lastIdx);
+ if (last == '\n') {
+ if (str.charAt(lastIdx - 1) == '\r') {
lastIdx--;
}
- }
- else
- {
+ } else {
lastIdx++;
}
- return str.substring( 0, lastIdx );
+ return str.substring(0, lastIdx);
}
// Conversion
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
// spec 3.10.6
@@ -1081,85 +975,71 @@ public class StringUtils
* @return String with escaped values
* @throws NullPointerException if str is <code>null</code>
*/
- @Nonnull public static String escape( @Nonnull String str )
- {
+ @Nonnull
+ public static String escape(@Nonnull String str) {
// improved with code from cybertiger@cyberiantiger.org
// unicode from him, and defaul for < 32's.
int sz = str.length();
- StringBuilder buffer = new StringBuilder( 2 * sz );
- for ( int i = 0; i < sz; i++ )
- {
- char ch = str.charAt( i );
+ StringBuilder buffer = new StringBuilder(2 * sz);
+ for (int i = 0; i < sz; i++) {
+ char ch = str.charAt(i);
// handle unicode
// CHECKSTYLE_OFF: MagicNumber
- if ( ch > 0xfff )
- {
- buffer.append( "\\u" ).append( Integer.toHexString( ch ) );
- }
- else if ( ch > 0xff )
- {
- buffer.append( "\\u0" ).append( Integer.toHexString( ch ) );
- }
- else if ( ch > 0x7f )
- {
- buffer.append( "\\u00" ).append( Integer.toHexString( ch ) );
+ if (ch > 0xfff) {
+ buffer.append("\\u").append(Integer.toHexString(ch));
+ } else if (ch > 0xff) {
+ buffer.append("\\u0").append(Integer.toHexString(ch));
+ } else if (ch > 0x7f) {
+ buffer.append("\\u00").append(Integer.toHexString(ch));
}
// CHECKSTYLE_ON: MagicNumber
- else if ( ch < 32 )
- {
- switch ( ch )
- {
+ else if (ch < 32) {
+ switch (ch) {
case '\b':
- buffer.append( '\\' );
- buffer.append( 'b' );
+ buffer.append('\\');
+ buffer.append('b');
break;
case '\n':
- buffer.append( '\\' );
- buffer.append( 'n' );
+ buffer.append('\\');
+ buffer.append('n');
break;
case '\t':
- buffer.append( '\\' );
- buffer.append( 't' );
+ buffer.append('\\');
+ buffer.append('t');
break;
case '\f':
- buffer.append( '\\' );
- buffer.append( 'f' );
+ buffer.append('\\');
+ buffer.append('f');
break;
case '\r':
- buffer.append( '\\' );
- buffer.append( 'r' );
+ buffer.append('\\');
+ buffer.append('r');
break;
default:
- if ( ch > 0xf )
- {
- buffer.append( "\\u00" ).append( Integer.toHexString( ch ) );
- }
- else
- {
- buffer.append( "\\u000" ).append( Integer.toHexString( ch ) );
+ if (ch > 0xf) {
+ buffer.append("\\u00").append(Integer.toHexString(ch));
+ } else {
+ buffer.append("\\u000").append(Integer.toHexString(ch));
}
break;
}
- }
- else
- {
- switch ( ch )
- {
+ } else {
+ switch (ch) {
case '\'':
- buffer.append( '\\' );
- buffer.append( '\'' );
+ buffer.append('\\');
+ buffer.append('\'');
break;
case '"':
- buffer.append( '\\' );
- buffer.append( '"' );
+ buffer.append('\\');
+ buffer.append('"');
break;
case '\\':
- buffer.append( '\\' );
- buffer.append( '\\' );
+ buffer.append('\\');
+ buffer.append('\\');
break;
default:
- buffer.append( ch );
+ buffer.append(ch);
break;
}
}
@@ -1168,7 +1048,7 @@ public class StringUtils
}
// Padding
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Repeat a String <code>n</code> times to form a
@@ -1180,12 +1060,11 @@ public class StringUtils
* @throws NegativeArraySizeException if <code>repeat < 0</code>
* @throws NullPointerException if str is <code>null</code>
*/
- @Nonnull public static String repeat( @Nonnull String str, int repeat )
- {
- StringBuilder buffer = new StringBuilder( repeat * str.length() );
- for ( int i = 0; i < repeat; i++ )
- {
- buffer.append( str );
+ @Nonnull
+ public static String repeat(@Nonnull String str, int repeat) {
+ StringBuilder buffer = new StringBuilder(repeat * str.length());
+ for (int i = 0; i < repeat; i++) {
+ buffer.append(str);
}
return buffer.toString();
}
@@ -1200,9 +1079,9 @@ public class StringUtils
* @return right padded String
* @throws NullPointerException if str is <code>null</code>
*/
- @Nonnull public static String rightPad( @Nonnull String str, int size )
- {
- return rightPad( str, size, " " );
+ @Nonnull
+ public static String rightPad(@Nonnull String str, int size) {
+ return rightPad(str, size, " ");
}
/**
@@ -1217,12 +1096,11 @@ public class StringUtils
* @throws NullPointerException if str or delim is <code>null</code>
* @throws ArithmeticException if delim is the empty String
*/
- @Nonnull public static String rightPad( @Nonnull String str, int size, @Nonnull String delim )
- {
- size = ( size - str.length() ) / delim.length();
- if ( size > 0 )
- {
- str += repeat( delim, size );
+ @Nonnull
+ public static String rightPad(@Nonnull String str, int size, @Nonnull String delim) {
+ size = (size - str.length()) / delim.length();
+ if (size > 0) {
+ str += repeat(delim, size);
}
return str;
}
@@ -1237,9 +1115,9 @@ public class StringUtils
* @return left padded String
* @throws NullPointerException if str or delim is <code>null</code>
*/
- @Nonnull public static String leftPad( @Nonnull String str, int size )
- {
- return leftPad( str, size, " " );
+ @Nonnull
+ public static String leftPad(@Nonnull String str, int size) {
+ return leftPad(str, size, " ");
}
/**
@@ -1252,18 +1130,17 @@ public class StringUtils
* @throws NullPointerException if str or delim is null
* @throws ArithmeticException if delim is the empty string
*/
- @Nonnull public static String leftPad( @Nonnull String str, int size, @Nonnull String delim )
- {
- size = ( size - str.length() ) / delim.length();
- if ( size > 0 )
- {
- str = repeat( delim, size ) + str;
+ @Nonnull
+ public static String leftPad(@Nonnull String str, int size, @Nonnull String delim) {
+ size = (size - str.length()) / delim.length();
+ if (size > 0) {
+ str = repeat(delim, size) + str;
}
return str;
}
// Stripping
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Remove whitespace from the front and back of a String.</p>
@@ -1271,9 +1148,8 @@ public class StringUtils
* @param str the String to remove whitespace from
* @return the stripped String
*/
- public static String strip( String str )
- {
- return strip( str, null );
+ public static String strip(String str) {
+ return strip(str, null);
}
/**
@@ -1287,10 +1163,9 @@ public class StringUtils
* @param delim the String to remove at start and end
* @return the stripped String
*/
- public static String strip( String str, @Nullable String delim )
- {
- str = stripStart( str, delim );
- return stripEnd( str, delim );
+ public static String strip(String str, @Nullable String delim) {
+ str = stripStart(str, delim);
+ return stripEnd(str, delim);
}
/**
@@ -1300,9 +1175,8 @@ public class StringUtils
* @param strs the Strings to remove whitespace from
* @return the stripped Strings
*/
- public static String[] stripAll( String... strs )
- {
- return stripAll( strs, null );
+ public static String[] stripAll(String... strs) {
+ return stripAll(strs, null);
}
/**
@@ -1313,17 +1187,14 @@ public class StringUtils
* @param delimiter the String to remove at start and end
* @return the stripped Strings
*/
- public static String[] stripAll( String[] strs, @Nullable String delimiter )
- {
- if ( ( strs == null ) || ( strs.length == 0 ) )
- {
+ public static String[] stripAll(String[] strs, @Nullable String delimiter) {
+ if ((strs == null) || (strs.length == 0)) {
return strs;
}
int sz = strs.length;
String[] newArr = new String[sz];
- for ( int i = 0; i < sz; i++ )
- {
- newArr[i] = strip( strs[i], delimiter );
+ for (int i = 0; i < sz; i++) {
+ newArr[i] = strip(strs[i], delimiter);
}
return newArr;
}
@@ -1338,29 +1209,22 @@ public class StringUtils
* @param strip the String to remove
* @return the stripped String
*/
- public static String stripEnd( String str, @Nullable String strip )
- {
- if ( str == null )
- {
+ public static String stripEnd(String str, @Nullable String strip) {
+ if (str == null) {
return null;
}
int end = str.length();
- if ( strip == null )
- {
- while ( ( end != 0 ) && Character.isWhitespace( str.charAt( end - 1 ) ) )
- {
+ if (strip == null) {
+ while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
- }
- else
- {
- while ( ( end != 0 ) && ( strip.indexOf( str.charAt( end - 1 ) ) != -1 ) )
- {
+ } else {
+ while ((end != 0) && (strip.indexOf(str.charAt(end - 1)) != -1)) {
end--;
}
}
- return str.substring( 0, end );
+ return str.substring(0, end);
}
/**
@@ -1373,10 +1237,8 @@ public class StringUtils
* @param strip the String to remove
* @return the stripped String
*/
- public static String stripStart( String str, @Nullable String strip )
- {
- if ( str == null )
- {
+ public static String stripStart(String str, @Nullable String strip) {
+ if (str == null) {
return null;
}
@@ -1384,25 +1246,20 @@ public class StringUtils
int sz = str.length();
- if ( strip == null )
- {
- while ( ( start != sz ) && Character.isWhitespace( str.charAt( start ) ) )
- {
+ if (strip == null) {
+ while ((start != sz) && Character.isWhitespace(str.charAt(start))) {
start++;
}
- }
- else
- {
- while ( ( start != sz ) && ( strip.indexOf( str.charAt( start ) ) != -1 ) )
- {
+ } else {
+ while ((start != sz) && (strip.indexOf(str.charAt(start)) != -1)) {
start++;
}
}
- return str.substring( start );
+ return str.substring(start);
}
// Case conversion
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Convert a String to upper case, <code>null</code> String
@@ -1411,10 +1268,8 @@ public class StringUtils
* @param str the String to uppercase
* @return the upper cased String
*/
- public static String upperCase( String str )
- {
- if ( str == null )
- {
+ public static String upperCase(String str) {
+ if (str == null) {
return null;
}
return str.toUpperCase();
@@ -1427,10 +1282,8 @@ public class StringUtils
* @param str the string to lowercase
* @return the lower cased String
*/
- public static String lowerCase( String str )
- {
- if ( str == null )
- {
+ public static String lowerCase(String str) {
+ if (str == null) {
return null;
}
return str.toLowerCase();
@@ -1445,25 +1298,18 @@ public class StringUtils
* @param str the String to uncapitalise
* @return uncapitalised String
*/
- public static String uncapitalise( String str )
- {
- if ( str == null )
- {
+ public static String uncapitalise(String str) {
+ if (str == null) {
return null;
- }
- else
- {
+ } else {
int length = str.length();
- if ( length == 0 )
- {
+ if (length == 0) {
return "";
- }
- else
- {
- return new StringBuffer( length )
- .append( Character.toLowerCase( str.charAt( 0 ) ) )
- .append( str, 1, length )
- .toString();
+ } else {
+ return new StringBuffer(length)
+ .append(Character.toLowerCase(str.charAt(0)))
+ .append(str, 1, length)
+ .toString();
}
}
}
@@ -1477,25 +1323,18 @@ public class StringUtils
* @param str the String to capitalise
* @return capitalised String
*/
- public static String capitalise( String str )
- {
- if ( str == null )
- {
+ public static String capitalise(String str) {
+ if (str == null) {
return null;
- }
- else
- {
+ } else {
int length = str.length();
- if ( length == 0 )
- {
+ if (length == 0) {
return "";
- }
- else
- {
- return new StringBuilder( length )
- .append( Character.toTitleCase( str.charAt( 0 ) ) )
- .append( str, 1, length )
- .toString();
+ } else {
+ return new StringBuilder(length)
+ .append(Character.toTitleCase(str.charAt(0)))
+ .append(str, 1, length)
+ .toString();
}
}
}
@@ -1511,52 +1350,38 @@ public class StringUtils
* @param str the String to swap the case of
* @return the modified String
*/
- public static String swapCase( String str )
- {
- if ( str == null )
- {
+ public static String swapCase(String str) {
+ if (str == null) {
return null;
}
int sz = str.length();
- StringBuilder buffer = new StringBuilder( sz );
+ StringBuilder buffer = new StringBuilder(sz);
boolean whitespace = false;
char ch;
char tmp;
- for ( int i = 0; i < sz; i++ )
- {
- ch = str.charAt( i );
- if ( Character.isUpperCase( ch ) )
- {
- tmp = Character.toLowerCase( ch );
- }
- else if ( Character.isTitleCase( ch ) )
- {
- tmp = Character.toLowerCase( ch );
- }
- else if ( Character.isLowerCase( ch ) )
- {
- if ( whitespace )
- {
- tmp = Character.toTitleCase( ch );
- }
- else
- {
- tmp = Character.toUpperCase( ch );
+ for (int i = 0; i < sz; i++) {
+ ch = str.charAt(i);
+ if (Character.isUpperCase(ch)) {
+ tmp = Character.toLowerCase(ch);
+ } else if (Character.isTitleCase(ch)) {
+ tmp = Character.toLowerCase(ch);
+ } else if (Character.isLowerCase(ch)) {
+ if (whitespace) {
+ tmp = Character.toTitleCase(ch);
+ } else {
+ tmp = Character.toUpperCase(ch);
}
- }
- else
- {
+ } else {
tmp = ch;
}
- buffer.append( tmp );
- whitespace = Character.isWhitespace( ch );
+ buffer.append(tmp);
+ whitespace = Character.isWhitespace(ch);
}
return buffer.toString();
}
-
/**
* <p>Capitalise all the words in a String.</p>
*
@@ -1568,31 +1393,23 @@ public class StringUtils
* @param str the String to capitalise
* @return capitalised String
*/
- public static String capitaliseAllWords( String str )
- {
- if ( str == null )
- {
+ public static String capitaliseAllWords(String str) {
+ if (str == null) {
return null;
}
int sz = str.length();
- StringBuilder buffer = new StringBuilder( sz );
+ StringBuilder buffer = new StringBuilder(sz);
boolean space = true;
- for ( int i = 0; i < sz; i++ )
- {
- char ch = str.charAt( i );
- if ( Character.isWhitespace( ch ) )
- {
- buffer.append( ch );
+ for (int i = 0; i < sz; i++) {
+ char ch = str.charAt(i);
+ if (Character.isWhitespace(ch)) {
+ buffer.append(ch);
space = true;
- }
- else if ( space )
- {
- buffer.append( Character.toTitleCase( ch ) );
+ } else if (space) {
+ buffer.append(Character.toTitleCase(ch));
space = false;
- }
- else
- {
- buffer.append( ch );
+ } else {
+ buffer.append(ch);
}
}
return buffer.toString();
@@ -1609,38 +1426,30 @@ public class StringUtils
* @param str the string to uncapitalise
* @return uncapitalised string
*/
- public static String uncapitaliseAllWords( String str )
- {
- if ( str == null )
- {
+ public static String uncapitaliseAllWords(String str) {
+ if (str == null) {
return null;
}
int sz = str.length();
- StringBuilder buffer = new StringBuilder( sz );
+ StringBuilder buffer = new StringBuilder(sz);
boolean space = true;
- for ( int i = 0; i < sz; i++ )
- {
- char ch = str.charAt( i );
- if ( Character.isWhitespace( ch ) )
- {
- buffer.append( ch );
+ for (int i = 0; i < sz; i++) {
+ char ch = str.charAt(i);
+ if (Character.isWhitespace(ch)) {
+ buffer.append(ch);
space = true;
- }
- else if ( space )
- {
- buffer.append( Character.toLowerCase( ch ) );
+ } else if (space) {
+ buffer.append(Character.toLowerCase(ch));
space = false;
- }
- else
- {
- buffer.append( ch );
+ } else {
+ buffer.append(ch);
}
}
return buffer.toString();
}
// Nested extraction
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Get the String that is nested in between two instances of the
@@ -1654,9 +1463,8 @@ public class StringUtils
* @return the String that was nested, or <code>null</code>
* @throws NullPointerException if tag is <code>null</code>
*/
- public static String getNestedString( String str, @Nonnull String tag )
- {
- return getNestedString( str, tag, tag );
+ public static String getNestedString(String str, @Nonnull String tag) {
+ return getNestedString(str, tag, tag);
}
/**
@@ -1668,19 +1476,15 @@ public class StringUtils
* @return the String that was nested, or <code>null</code>
* @throws NullPointerException if open or close is <code>null</code>
*/
- public static String getNestedString( String str, @Nonnull String open, @Nonnull String close )
- {
- if ( str == null )
- {
+ public static String getNestedString(String str, @Nonnull String open, @Nonnull String close) {
+ if (str == null) {
return null;
}
- int start = str.indexOf( open );
- if ( start != -1 )
- {
- int end = str.indexOf( close, start + open.length() );
- if ( end != -1 )
- {
- return str.substring( start + open.length(), end );
+ int start = str.indexOf(open);
+ if (start != -1) {
+ int end = str.indexOf(close, start + open.length());
+ if (end != -1) {
+ return str.substring(start + open.length(), end);
}
}
return null;
@@ -1696,20 +1500,16 @@ public class StringUtils
* @return the number of occurrences, 0 if the String is <code>null</code>
* @throws NullPointerException if sub is <code>null</code>
*/
- public static int countMatches( @Nullable String str, @Nonnull String sub )
- {
- if ( sub.equals( "" ) )
- {
+ public static int countMatches(@Nullable String str, @Nonnull String sub) {
+ if (sub.equals("")) {
return 0;
}
- if ( str == null )
- {
+ if (str == null) {
return 0;
}
int count = 0;
int idx = 0;
- while ( ( idx = str.indexOf( sub, idx ) ) != -1 )
- {
+ while ((idx = str.indexOf(sub, idx)) != -1) {
count++;
idx += sub.length();
}
@@ -1717,7 +1517,7 @@ public class StringUtils
}
// Character Tests
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Checks if the String contains only Unicode letters.</p>
@@ -1728,17 +1528,13 @@ public class StringUtils
* @param str the String to check
* @return <code>true</code> if only contains letters, and is non-null
*/
- public static boolean isAlpha( String str )
- {
- if ( str == null )
- {
+ public static boolean isAlpha(String str) {
+ if (str == null) {
return false;
}
int sz = str.length();
- for ( int i = 0; i < sz; i++ )
- {
- if ( !Character.isLetter( str.charAt( i ) ) )
- {
+ for (int i = 0; i < sz; i++) {
+ if (!Character.isLetter(str.charAt(i))) {
return false;
}
}
@@ -1754,17 +1550,13 @@ public class StringUtils
* @param str the String to check
* @return <code>true</code> if only contains whitespace, and is non-null
*/
- public static boolean isWhitespace( String str )
- {
- if ( str == null )
- {
+ public static boolean isWhitespace(String str) {
+ if (str == null) {
return false;
}
int sz = str.length();
- for ( int i = 0; i < sz; i++ )
- {
- if ( ( !Character.isWhitespace( str.charAt( i ) ) ) )
- {
+ for (int i = 0; i < sz; i++) {
+ if ((!Character.isWhitespace(str.charAt(i)))) {
return false;
}
}
@@ -1782,17 +1574,13 @@ public class StringUtils
* @return <code>true</code> if only contains letters and space,
* and is non-null
*/
- public static boolean isAlphaSpace( String str )
- {
- if ( str == null )
- {
+ public static boolean isAlphaSpace(String str) {
+ if (str == null) {
return false;
}
int sz = str.length();
- for ( int i = 0; i < sz; i++ )
- {
- if ( ( !Character.isLetter( str.charAt( i ) ) ) && ( str.charAt( i ) != ' ' ) )
- {
+ for (int i = 0; i < sz; i++) {
+ if ((!Character.isLetter(str.charAt(i))) && (str.charAt(i) != ' ')) {
return false;
}
}
@@ -1809,17 +1597,13 @@ public class StringUtils
* @return <code>true</code> if only contains letters or digits,
* and is non-null
*/
- public static boolean isAlphanumeric( String str )
- {
- if ( str == null )
- {
+ public static boolean isAlphanumeric(String str) {
+ if (str == null) {
return false;
}
int sz = str.length();
- for ( int i = 0; i < sz; i++ )
- {
- if ( !Character.isLetterOrDigit( str.charAt( i ) ) )
- {
+ for (int i = 0; i < sz; i++) {
+ if (!Character.isLetterOrDigit(str.charAt(i))) {
return false;
}
}
@@ -1837,17 +1621,13 @@ public class StringUtils
* @return <code>true</code> if only contains letters, digits or space,
* and is non-null
*/
- public static boolean isAlphanumericSpace( String str )
- {
- if ( str == null )
- {
+ public static boolean isAlphanumericSpace(String str) {
+ if (str == null) {
return false;
}
int sz = str.length();
- for ( int i = 0; i < sz; i++ )
- {
- if ( ( !Character.isLetterOrDigit( str.charAt( i ) ) ) && ( str.charAt( i ) != ' ' ) )
- {
+ for (int i = 0; i < sz; i++) {
+ if ((!Character.isLetterOrDigit(str.charAt(i))) && (str.charAt(i) != ' ')) {
return false;
}
}
@@ -1863,17 +1643,13 @@ public class StringUtils
* @param str the String to check
* @return <code>true</code> if only contains digits, and is non-null
*/
- public static boolean isNumeric( String str )
- {
- if ( str == null )
- {
+ public static boolean isNumeric(String str) {
+ if (str == null) {
return false;
}
int sz = str.length();
- for ( int i = 0; i < sz; i++ )
- {
- if ( !Character.isDigit( str.charAt( i ) ) )
- {
+ for (int i = 0; i < sz; i++) {
+ if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
@@ -1881,7 +1657,7 @@ public class StringUtils
}
// Defaults
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Returns either the passed in <code>Object</code> as a String,
@@ -1894,9 +1670,9 @@ public class StringUtils
* @deprecated use {@code java.lang.Objects.toString()}
*/
@Deprecated
- @Nonnull public static String defaultString( Object obj )
- {
- return defaultString( obj, "" );
+ @Nonnull
+ public static String defaultString(Object obj) {
+ return defaultString(obj, "");
}
/**
@@ -1912,13 +1688,13 @@ public class StringUtils
* @deprecated use {@code java.lang.Objects.toString()}
*/
@Deprecated
- @Nonnull public static String defaultString( Object obj, @Nonnull String defaultString )
- {
- return ( obj == null ) ? defaultString : obj.toString();
+ @Nonnull
+ public static String defaultString(Object obj, @Nonnull String defaultString) {
+ return (obj == null) ? defaultString : obj.toString();
}
// Reversing
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Reverse a String.</p>
@@ -1928,13 +1704,11 @@ public class StringUtils
* @param str the String to reverse
* @return the reversed String
*/
- public static String reverse( String str )
- {
- if ( str == null )
- {
+ public static String reverse(String str) {
+ if (str == null) {
return null;
}
- return new StringBuffer( str ).reverse().toString();
+ return new StringBuffer(str).reverse().toString();
}
/**
@@ -1948,13 +1722,13 @@ public class StringUtils
* @param delimiter the delimiter to use
* @return the reversed String
*/
- @Nonnull public static String reverseDelimitedString( @Nonnull String str, String delimiter )
- {
+ @Nonnull
+ public static String reverseDelimitedString(@Nonnull String str, String delimiter) {
// could implement manually, but simple way is to reuse other,
// probably slower, methods.
- String[] strs = split( str, delimiter );
- reverseArray( strs );
- return join( strs, delimiter );
+ String[] strs = split(str, delimiter);
+ reverseArray(strs);
+ return join(strs, delimiter);
}
/**
@@ -1962,14 +1736,12 @@ public class StringUtils
*
* @param array the array to reverse
*/
- private static void reverseArray( @Nonnull String... array )
- {
+ private static void reverseArray(@Nonnull String... array) {
int i = 0;
int j = array.length - 1;
String tmp;
- while ( j > i )
- {
+ while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
@@ -1979,7 +1751,7 @@ public class StringUtils
}
// Abbreviating
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* <p>Turn "Now is the time for all good men" into "Now is the time for..."</p>
@@ -1988,14 +1760,14 @@ public class StringUtils
* Else abbreviate it to (substring(str, 0, max-3) + "...").
* If maxWidth is less than 3, throw an IllegalArgumentException.
* In no case will it return a string of length greater than maxWidth.</p>
- *
+ *
* @param s The string to be abbreviated.
* @param maxWidth maximum length of result string
* @return The abbreviated string.
*/
- @Nonnull public static String abbreviate( @Nonnull String s, int maxWidth )
- {
- return abbreviate( s, 0, maxWidth );
+ @Nonnull
+ public static String abbreviate(@Nonnull String s, int maxWidth) {
+ return abbreviate(s, 0, maxWidth);
}
/**
@@ -2007,47 +1779,40 @@ public class StringUtils
* character following the ellipses, but it will appear somewhere in the result.
* In no case will it return a string of length greater than maxWidth.
* </p>
- *
+ *
* @param s String to abbreviate.
* @param offset left edge of source string
* @param maxWidth maximum length of result string
* @return The abbreviated string.
*/
- @Nonnull public static String abbreviate( @Nonnull String s, int offset, int maxWidth )
- {
- if ( maxWidth < 4 )
- {
- throw new IllegalArgumentException( "Minimum abbreviation width is 4" );
+ @Nonnull
+ public static String abbreviate(@Nonnull String s, int offset, int maxWidth) {
+ if (maxWidth < 4) {
+ throw new IllegalArgumentException("Minimum abbreviation width is 4");
}
- if ( s.length() <= maxWidth )
- {
+ if (s.length() <= maxWidth) {
return s;
}
- if ( offset > s.length() )
- {
+ if (offset > s.length()) {
offset = s.length();
}
- if ( ( s.length() - offset ) < ( maxWidth - 3 ) )
- {
- offset = s.length() - ( maxWidth - 3 );
+ if ((s.length() - offset) < (maxWidth - 3)) {
+ offset = s.length() - (maxWidth - 3);
}
- if ( offset <= 4 )
- {
- return s.substring( 0, maxWidth - 3 ) + "...";
+ if (offset <= 4) {
+ return s.substring(0, maxWidth - 3) + "...";
}
- if ( maxWidth < 7 )
- {
- throw new IllegalArgumentException( "Minimum abbreviation width with offset is 7" );
+ if (maxWidth < 7) {
+ throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");
}
- if ( ( offset + ( maxWidth - 3 ) ) < s.length() )
- {
- return "..." + abbreviate( s.substring( offset ), maxWidth - 3 );
+ if ((offset + (maxWidth - 3)) < s.length()) {
+ return "..." + abbreviate(s.substring(offset), maxWidth - 3);
}
- return "..." + s.substring( s.length() - ( maxWidth - 3 ) );
+ return "..." + s.substring(s.length() - (maxWidth - 3));
}
// Difference
- //--------------------------------------------------------------------------
+ // --------------------------------------------------------------------------
/**
* Compare two strings, and return the portion where they differ.
@@ -2061,14 +1826,12 @@ public class StringUtils
* @param s2 The second string.
* @return the portion of s2 where it differs from s1; returns the empty string ("") if they are equal
*/
- public static String difference( @Nonnull String s1, @Nonnull String s2 )
- {
- int at = differenceAt( s1, s2 );
- if ( at == -1 )
- {
+ public static String difference(@Nonnull String s1, @Nonnull String s2) {
+ int at = differenceAt(s1, s2);
+ if (at == -1) {
return "";
}
- return s2.substring( at );
+ return s2.substring(at);
}
/**
@@ -2081,18 +1844,14 @@ public class StringUtils
* @param s2 The second string.
* @return the index where s2 and s1 begin to differ; -1 if they are equal
*/
- public static int differenceAt( @Nonnull String s1, @Nonnull String s2 )
- {
+ public static int differenceAt(@Nonnull String s1, @Nonnull String s2) {
int i;
- for ( i = 0; ( i < s1.length() ) && ( i < s2.length() ); ++i )
- {
- if ( s1.charAt( i ) != s2.charAt( i ) )
- {
+ for (i = 0; (i < s1.length()) && (i < s2.length()); ++i) {
+ if (s1.charAt(i) != s2.charAt(i)) {
break;
}
}
- if ( ( i < s2.length() ) || ( i < s1.length() ) )
- {
+ if ((i < s2.length()) || (i < s1.length())) {
return i;
}
return -1;
@@ -2107,26 +1866,22 @@ public class StringUtils
* @param namespace The namespace which contains the replacements.
* @return the interpolated text.
*/
- public static String interpolate( String text, @Nonnull Map<?, ?> namespace )
- {
- for ( Map.Entry<?, ?> entry : namespace.entrySet() )
- {
+ public static String interpolate(String text, @Nonnull Map<?, ?> namespace) {
+ for (Map.Entry<?, ?> entry : namespace.entrySet()) {
String key = entry.getKey().toString();
Object obj = entry.getValue();
- if ( obj == null )
- {
- throw new NullPointerException( "The value of the key '" + key + "' is null." );
+ if (obj == null) {
+ throw new NullPointerException("The value of the key '" + key + "' is null.");
}
String value = obj.toString();
- text = replace( text, "${" + key + "}", value );
+ text = replace(text, "${" + key + "}", value);
- if ( !key.contains( " " ) )
- {
- text = replace( text, "$" + key, value );
+ if (!key.contains(" ")) {
+ text = replace(text, "$" + key, value);
}
}
return text;
@@ -2145,21 +1900,20 @@ public class StringUtils
* @param replaceThis The things which should be replaced.
* @return humped String
*/
- @Nonnull public static String removeAndHump( @Nonnull String data, @Nonnull String replaceThis )
- {
+ @Nonnull
+ public static String removeAndHump(@Nonnull String data, @Nonnull String replaceThis) {
String temp;
StringBuilder out = new StringBuilder();
temp = data;
- StringTokenizer st = new StringTokenizer( temp, replaceThis );
+ StringTokenizer st = new StringTokenizer(temp, replaceThis);
- while ( st.hasMoreTokens() )
- {
+ while (st.hasMoreTokens()) {
String element = st.nextToken();
- out.append( capitalizeFirstLetter( element ) );
+ out.append(capitalizeFirstLetter(element));
}
return out.toString();
@@ -2174,17 +1928,16 @@ public class StringUtils
* @throws NullPointerException if data is <code>null</code>
* @throws IndexOutOfBoundsException if data is empty
*/
- @Nonnull public static String capitalizeFirstLetter( @Nonnull String data )
- {
- char firstChar = data.charAt( 0 );
- char titleCase = Character.toTitleCase( firstChar );
- if ( firstChar == titleCase )
- {
+ @Nonnull
+ public static String capitalizeFirstLetter(@Nonnull String data) {
+ char firstChar = data.charAt(0);
+ char titleCase = Character.toTitleCase(firstChar);
+ if (firstChar == titleCase) {
return data;
}
- StringBuilder result = new StringBuilder( data.length() );
- result.append( titleCase );
- result.append( data, 1, data.length() );
+ StringBuilder result = new StringBuilder(data.length());
+ result.append(titleCase);
+ result.append(data, 1, data.length());
return result.toString();
}
@@ -2197,11 +1950,11 @@ public class StringUtils
* @throws NullPointerException if data is <code>null</code>
* @throws IndexOutOfBoundsException if data is empty
*/
- @Nonnull public static String lowercaseFirstLetter( @Nonnull String data )
- {
- char firstLetter = Character.toLowerCase( data.substring( 0, 1 ).charAt( 0 ) );
+ @Nonnull
+ public static String lowercaseFirstLetter(@Nonnull String data) {
+ char firstLetter = Character.toLowerCase(data.substring(0, 1).charAt(0));
- String restLetters = data.substring( 1 );
+ String restLetters = data.substring(1);
return firstLetter + restLetters;
}
@@ -2213,26 +1966,24 @@ public class StringUtils
* @param view the view
* @return deHumped String
*/
- @Nonnull public static String addAndDeHump( @Nonnull String view )
- {
+ @Nonnull
+ public static String addAndDeHump(@Nonnull String view) {
StringBuilder sb = new StringBuilder();
- for ( int i = 0; i < view.length(); i++ )
- {
- if ( ( i != 0 ) && Character.isUpperCase( view.charAt( i ) ) )
- {
- sb.append( '-' );
+ for (int i = 0; i < view.length(); i++) {
+ if ((i != 0) && Character.isUpperCase(view.charAt(i))) {
+ sb.append('-');
}
- sb.append( view.charAt( i ) );
+ sb.append(view.charAt(i));
}
- return sb.toString().trim().toLowerCase( Locale.ENGLISH );
+ return sb.toString().trim().toLowerCase(Locale.ENGLISH);
}
/**
* <p>Quote and escape a String with the given character, handling <code>null</code>.</p>
- *
+ *
* <pre>
* StringUtils.quoteAndEscape(null, *) = null
* StringUtils.quoteAndEscape("", *) = ""
@@ -2246,11 +1997,10 @@ public class StringUtils
* @return the String quoted and escaped
* @see #quoteAndEscape(String, char, char[], char[], char, boolean)
* @see #quoteAndEscape(String, char, char[], char[], char, boolean)
- *
+ *
*/
- public static String quoteAndEscape( @Nullable String source, char quoteChar )
- {
- return quoteAndEscape( source, quoteChar, new char[]{ quoteChar }, new char[]{ ' ' }, '\\', false );
+ public static String quoteAndEscape(@Nullable String source, char quoteChar) {
+ return quoteAndEscape(source, quoteChar, new char[] {quoteChar}, new char[] {' '}, '\\', false);
}
/**
@@ -2261,11 +2011,10 @@ public class StringUtils
* @param quotingTriggers the quoting trigger
* @return the String quoted and escaped
* @see #quoteAndEscape(String, char, char[], char[], char, boolean)
- *
+ *
*/
- public static String quoteAndEscape( @Nullable String source, char quoteChar, @Nonnull char[] quotingTriggers )
- {
- return quoteAndEscape( source, quoteChar, new char[]{ quoteChar }, quotingTriggers, '\\', false );
+ public static String quoteAndEscape(@Nullable String source, char quoteChar, @Nonnull char[] quotingTriggers) {
+ return quoteAndEscape(source, quoteChar, new char[] {quoteChar}, quotingTriggers, '\\', false);
}
/**
@@ -2276,12 +2025,15 @@ public class StringUtils
* @param force true/false
* @return the String quoted and escaped
* @see #quoteAndEscape(String, char, char[], char[], char, boolean)
- *
+ *
*/
- public static String quoteAndEscape( @Nullable String source, char quoteChar,
- @Nonnull final char[] escapedChars, char escapeChar, boolean force )
- {
- return quoteAndEscape( source, quoteChar, escapedChars, new char[]{ ' ' }, escapeChar, force );
+ public static String quoteAndEscape(
+ @Nullable String source,
+ char quoteChar,
+ @Nonnull final char[] escapedChars,
+ char escapeChar,
+ boolean force) {
+ return quoteAndEscape(source, quoteChar, escapedChars, new char[] {' '}, escapeChar, force);
}
/**
@@ -2293,45 +2045,40 @@ public class StringUtils
* @param force true/false
* @return the String quoted and escaped
*/
- public static String quoteAndEscape( @Nullable String source, char quoteChar, @Nonnull final char[] escapedChars,
- @Nonnull final char[] quotingTriggers, char escapeChar, boolean force )
- {
- if ( source == null )
- {
+ public static String quoteAndEscape(
+ @Nullable String source,
+ char quoteChar,
+ @Nonnull final char[] escapedChars,
+ @Nonnull final char[] quotingTriggers,
+ char escapeChar,
+ boolean force) {
+ if (source == null) {
return null;
}
- if ( !force && source.startsWith( Character.toString( quoteChar ) ) && source.endsWith(
- Character.toString( quoteChar ) ) )
- {
+ if (!force
+ && source.startsWith(Character.toString(quoteChar))
+ && source.endsWith(Character.toString(quoteChar))) {
return source;
}
- String escaped = escape( source, escapedChars, escapeChar );
+ String escaped = escape(source, escapedChars, escapeChar);
boolean quote = false;
- if ( force )
- {
+ if (force) {
quote = true;
- }
- else if ( !escaped.equals( source ) )
- {
+ } else if (!escaped.equals(source)) {
quote = true;
- }
- else
- {
- for ( char quotingTrigger : quotingTriggers )
- {
- if ( escaped.indexOf( quotingTrigger ) > -1 )
- {
+ } else {
+ for (char quotingTrigger : quotingTriggers) {
+ if (escaped.indexOf(quotingTrigger) > -1) {
quote = true;
break;
}
}
}
- if ( quote )
- {
+ if (quote) {
return quoteChar + escaped + quoteChar;
}
@@ -2344,29 +2091,25 @@ public class StringUtils
* @param escapeChar prefix for escaping a character
* @return the String escaped
*/
- public static String escape( @Nullable String source, @Nonnull final char[] escapedChars, char escapeChar )
- {
- if ( source == null )
- {
+ public static String escape(@Nullable String source, @Nonnull final char[] escapedChars, char escapeChar) {
+ if (source == null) {
return null;
}
char[] eqc = new char[escapedChars.length];
- System.arraycopy( escapedChars, 0, eqc, 0, escapedChars.length );
- Arrays.sort( eqc );
+ System.arraycopy(escapedChars, 0, eqc, 0, escapedChars.length);
+ Arrays.sort(eqc);
- StringBuilder buffer = new StringBuilder( source.length() );
+ StringBuilder buffer = new StringBuilder(source.length());
- for ( int i = 0; i < source.length(); i++ )
- {
- final char c = source.charAt( i );
- int result = Arrays.binarySearch( eqc, c );
+ for (int i = 0; i < source.length(); i++) {
+ final char c = source.charAt(i);
+ int result = Arrays.binarySearch(eqc, c);
- if ( result > -1 )
- {
- buffer.append( escapeChar );
+ if (result > -1) {
+ buffer.append(escapeChar);
}
- buffer.append( c );
+ buffer.append(c);
}
return buffer.toString();
@@ -2377,20 +2120,18 @@ public class StringUtils
*
* @param s a not null String
* @return a string with unique whitespace
- *
+ *
*/
- @Nonnull public static String removeDuplicateWhitespace( @Nonnull String s )
- {
+ @Nonnull
+ public static String removeDuplicateWhitespace(@Nonnull String s) {
StringBuilder result = new StringBuilder();
int length = s.length();
boolean isPreviousWhiteSpace = false;
- for ( int i = 0; i < length; i++ )
- {
- char c = s.charAt( i );
- boolean thisCharWhiteSpace = Character.isWhitespace( c );
- if ( !( isPreviousWhiteSpace && thisCharWhiteSpace ) )
- {
- result.append( c );
+ for (int i = 0; i < length; i++) {
+ char c = s.charAt(i);
+ boolean thisCharWhiteSpace = Character.isWhitespace(c);
+ if (!(isPreviousWhiteSpace && thisCharWhiteSpace)) {
+ result.append(c);
}
isPreviousWhiteSpace = thisCharWhiteSpace;
}
@@ -2404,15 +2145,14 @@ public class StringUtils
* @param s a not null String
* @return a String that contains only System line separators
* @see #unifyLineSeparators(String, String)
- * @deprecated this method produces platform dependent code and contributes to
+ * @deprecated this method produces platform dependent code and contributes to
* non-reproducible builds. In the context of Maven, this is almost never what's needed.
* Remove calls to this method and do not replace them. That is, change
* {@code Stringutils.unifyLineSeparators(s)} to simply {@code s}.
*/
@Deprecated
- public static String unifyLineSeparators( @Nullable String s )
- {
- return unifyLineSeparators( s, System.getProperty( "line.separator" ) );
+ public static String unifyLineSeparators(@Nullable String s) {
+ return unifyLineSeparators(s, System.getProperty("line.separator"));
}
/**
@@ -2423,46 +2163,35 @@ public class StringUtils
* @param ls the wanted line separator ("\n" on UNIX), if null using the System line separator
* @return a String that contains only System line separators
* @throws IllegalArgumentException if ls is not '\n', '\r', or "\r\n"
- *
+ *
*/
- public static String unifyLineSeparators( @Nullable String s, @Nullable String ls )
- {
- if ( s == null )
- {
+ public static String unifyLineSeparators(@Nullable String s, @Nullable String ls) {
+ if (s == null) {
return null;
}
- if ( ls == null )
- {
- ls = System.getProperty( "line.separator" );
+ if (ls == null) {
+ ls = System.getProperty("line.separator");
}
- if ( !( ls.equals( "\n" ) || ls.equals( "\r" ) || ls.equals( "\r\n" ) ) )
- {
- throw new IllegalArgumentException( "Requested line separator is invalid." );
+ if (!(ls.equals("\n") || ls.equals("\r") || ls.equals("\r\n"))) {
+ throw new IllegalArgumentException("Requested line separator is invalid.");
}
int length = s.length();
- StringBuilder buffer = new StringBuilder( length );
- for ( int i = 0; i < length; i++ )
- {
- if ( s.charAt( i ) == '\r' )
- {
- if ( ( i + 1 ) < length && s.charAt( i + 1 ) == '\n' )
- {
+ StringBuilder buffer = new StringBuilder(length);
+ for (int i = 0; i < length; i++) {
+ if (s.charAt(i) == '\r') {
+ if ((i + 1) < length && s.charAt(i + 1) == '\n') {
i++;
}
- buffer.append( ls );
- }
- else if ( s.charAt( i ) == '\n' )
- {
- buffer.append( ls );
- }
- else
- {
- buffer.append( s.charAt( i ) );
+ buffer.append(ls);
+ } else if (s.charAt(i) == '\n') {
+ buffer.append(ls);
+ } else {
+ buffer.append(s.charAt(i));
}
}
@@ -2472,9 +2201,9 @@ public class StringUtils
/**
* <p>Checks if String contains a search character, handling <code>null</code>.
* This method uses {@link String#indexOf(int)}.</p>
- *
+ *
* <p>A <code>null</code> or empty ("") String will return <code>false</code>.</p>
- *
+ *
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains("", *) = false
@@ -2486,19 +2215,18 @@ public class StringUtils
* @param searchChar the character to find
* @return true if the String contains the search character,
* false if not or <code>null</code> string input
- *
+ *
*/
- public static boolean contains( @Nullable String str, char searchChar )
- {
- return !isEmpty( str ) && str.indexOf( searchChar ) >= 0;
+ public static boolean contains(@Nullable String str, char searchChar) {
+ return !isEmpty(str) && str.indexOf(searchChar) >= 0;
}
/**
* <p>Checks if String contains a search String, handling <code>null</code>.
* This method uses {@link String#indexOf(int)}.</p>
- *
+ *
* <p>A <code>null</code> String will return <code>false</code>.</p>
- *
+ *
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
@@ -2513,9 +2241,8 @@ public class StringUtils
* @return true if the String contains the search String,
* false if not or <code>null</code> string input
*/
- public static boolean contains( @Nullable String str, @Nullable String searchStr )
- {
- return !( str == null || searchStr == null ) && str.contains( searchStr );
+ public static boolean contains(@Nullable String str, @Nullable String searchStr) {
+ return !(str == null || searchStr == null) && str.contains(searchStr);
}
/**
@@ -2535,21 +2262,18 @@ public class StringUtils
* @param searchStr the String to find at end, may be null
* @return true if the String ends with the search String,
* false if not or <code>null</code> string input
- *
+ *
*/
- public static boolean endsWithIgnoreCase( @Nullable String str, @Nullable String searchStr )
- {
- if ( str == null || searchStr == null )
- {
+ public static boolean endsWithIgnoreCase(@Nullable String str, @Nullable String searchStr) {
+ if (str == null || searchStr == null) {
// for consistency with contains
return false;
}
- if ( str.length() < searchStr.length() )
- {
+ if (str.length() < searchStr.length()) {
return false;
}
- return str.regionMatches( true, str.length() - searchStr.length(), searchStr, 0, searchStr.length() );
+ return str.regionMatches(true, str.length() - searchStr.length(), searchStr, 0, searchStr.length());
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/WriterFactory.java b/src/main/java/org/apache/maven/shared/utils/WriterFactory.java
index f7c5d90..1679d88 100644
--- a/src/main/java/org/apache/maven/shared/utils/WriterFactory.java
+++ b/src/main/java/org/apache/maven/shared/utils/WriterFactory.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@ package org.apache.maven.shared.utils;
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,6 +16,9 @@ package org.apache.maven.shared.utils;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils;
+
+import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileNotFoundException;
@@ -28,10 +29,8 @@ import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
-import org.apache.maven.shared.utils.xml.XmlStreamWriter;
-
-import javax.annotation.Nonnull;
+import org.apache.maven.shared.utils.xml.XmlStreamWriter;
/**
* Utility to create Writers, with explicit encoding choice: platform default,
@@ -41,8 +40,7 @@ import javax.annotation.Nonnull;
* @see java.nio.charset.Charset
* @see <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html">Supported encodings</a>
*/
-public class WriterFactory
-{
+public class WriterFactory {
/**
* ISO Latin Alphabet #1, also known as ISO-LATIN-1.
* Every implementation of the Java platform is required to support this character encoding.
@@ -101,7 +99,7 @@ public class WriterFactory
/**
* The <code>file.encoding</code> System Property.
*/
- public static final String FILE_ENCODING = System.getProperty( "file.encoding" );
+ public static final String FILE_ENCODING = System.getProperty("file.encoding");
/**
* Create a new Writer with XML encoding detection rules.
@@ -113,10 +111,8 @@ public class WriterFactory
* @deprecated use org.apache.commons.io.input.XmlStreamWriter instead
*/
@Deprecated
- public static XmlStreamWriter newXmlWriter( @Nonnull OutputStream out )
- throws IOException
- {
- return new XmlStreamWriter( out );
+ public static XmlStreamWriter newXmlWriter(@Nonnull OutputStream out) throws IOException {
+ return new XmlStreamWriter(out);
}
/**
@@ -129,10 +125,8 @@ public class WriterFactory
* @deprecated use org.apache.commons.io.input.XmlStreamWriter instead
*/
@Deprecated
- public static XmlStreamWriter newXmlWriter( @Nonnull File file )
- throws IOException
- {
- return new XmlStreamWriter( file );
+ public static XmlStreamWriter newXmlWriter(@Nonnull File file) throws IOException {
+ return new XmlStreamWriter(file);
}
/**
@@ -143,9 +137,8 @@ public class WriterFactory
* @deprecated always specify an encoding. Do not depend on the default platform character set.
*/
@Deprecated
- public static Writer newPlatformWriter( @Nonnull OutputStream out )
- {
- return new OutputStreamWriter( out );
+ public static Writer newPlatformWriter(@Nonnull OutputStream out) {
+ return new OutputStreamWriter(out);
}
/**
@@ -157,10 +150,8 @@ public class WriterFactory
* @deprecated always specify an encoding. Do not depend on the default platform character set.
*/
@Deprecated
- public static Writer newPlatformWriter( @Nonnull File file )
- throws IOException
- {
- return new FileWriter( file );
+ public static Writer newPlatformWriter(@Nonnull File file) throws IOException {
+ return new FileWriter(file);
}
/**
@@ -173,10 +164,9 @@ public class WriterFactory
* @see <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html">Supported
* encodings</a>
*/
- public static Writer newWriter( @Nonnull OutputStream out, @Nonnull String encoding )
- throws UnsupportedEncodingException
- {
- return new OutputStreamWriter( out, encoding );
+ public static Writer newWriter(@Nonnull OutputStream out, @Nonnull String encoding)
+ throws UnsupportedEncodingException {
+ return new OutputStreamWriter(out, encoding);
}
/**
@@ -190,9 +180,8 @@ public class WriterFactory
* @see <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html">Supported
* encodings</a>
*/
- public static Writer newWriter( @Nonnull File file, @Nonnull String encoding )
- throws UnsupportedEncodingException, FileNotFoundException
- {
- return newWriter( new FileOutputStream( file ), encoding );
+ public static Writer newWriter(@Nonnull File file, @Nonnull String encoding)
+ throws UnsupportedEncodingException, FileNotFoundException {
+ return newWriter(new FileOutputStream(file), encoding);
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/AbstractStreamHandler.java b/src/main/java/org/apache/maven/shared/utils/cli/AbstractStreamHandler.java
index 979e861..97ffb47 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/AbstractStreamHandler.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/AbstractStreamHandler.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,45 +16,35 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
/**
* @author <a href="mailto:kristian.rosenvold@gmail.com">Kristian Rosenvold</a>
*/
-class AbstractStreamHandler
- extends Thread
-{
+class AbstractStreamHandler extends Thread {
private volatile boolean done;
private volatile boolean disabled;
- boolean isDone()
- {
+ boolean isDone() {
return done;
}
- public synchronized void waitUntilDone()
- throws InterruptedException
- {
- while ( !isDone() )
- {
+ public synchronized void waitUntilDone() throws InterruptedException {
+ while (!isDone()) {
wait();
}
}
-
- boolean isDisabled()
- {
+ boolean isDisabled() {
return disabled;
}
- public void disable()
- {
+ public void disable() {
disabled = true;
}
- protected void setDone()
- {
+ protected void setDone() {
done = true;
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/Arg.java b/src/main/java/org/apache/maven/shared/utils/cli/Arg.java
index 62f14ea..df7be1f 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/Arg.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/Arg.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,29 +16,29 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
import java.io.File;
/**
- *
+ *
*/
-public interface Arg
-{
+public interface Arg {
/**
* @param value the value to be set
*/
- void setValue( String value );
+ void setValue(String value);
/**
* @param line the line of arguments
* @throws CommandLineException in case of unbalanced quotes.
*/
- void setLine( String line ) throws CommandLineException;
+ void setLine(String line) throws CommandLineException;
/**
* @param file the file to be set
*/
- void setFile( File file );
+ void setFile(File file);
/**
* Whether to hide the argument value when a command line prints the arguments.
@@ -48,6 +46,5 @@ public interface Arg
* @param mask new state of the {@code mask} property
* @since 0.6
*/
- void setMask( boolean mask );
-
+ void setMask(boolean mask);
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineCallable.java b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineCallable.java
index b4e4586..ae806f0 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineCallable.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineCallable.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
import java.util.concurrent.Callable;
@@ -26,12 +25,9 @@ import java.util.concurrent.Callable;
*
* @author Kristian Rosenvold
*/
-public interface CommandLineCallable
- extends Callable<Integer>
-{
+public interface CommandLineCallable extends Callable<Integer> {
/**
* {@inheritDoc}
*/
- Integer call()
- throws CommandLineException;
+ Integer call() throws CommandLineException;
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineException.java b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineException.java
index 9954e35..cb32678 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineException.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineException.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,32 +16,29 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
-public class CommandLineException
- extends Exception
-{
+public class CommandLineException extends Exception {
/**
- *
+ *
*/
private static final long serialVersionUID = 1344773066470228441L;
/**
* @param message The message of the exception.
*/
- public CommandLineException( String message )
- {
- super( message );
+ public CommandLineException(String message) {
+ super(message);
}
/**
* @param message The message of the exception.
* @param cause The problem which caused the exception.
*/
- public CommandLineException( String message, Throwable cause )
- {
- super( message, cause );
+ public CommandLineException(String message, Throwable cause) {
+ super(message, cause);
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java
index c1f8209..8aead3d 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,17 +16,16 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
/**
* @author Olivier Lamy
- *
+ *
*/
-public class CommandLineTimeOutException
- extends CommandLineException
-{
+public class CommandLineTimeOutException extends CommandLineException {
/**
- *
+ *
*/
private static final long serialVersionUID = 7322428741683224481L;
@@ -36,9 +33,7 @@ public class CommandLineTimeOutException
* @param message The message of the exception.
* @param cause The cause of the exception.
*/
- public CommandLineTimeOutException( String message, Throwable cause )
- {
- super( message, cause );
+ public CommandLineTimeOutException(String message, Throwable cause) {
+ super(message, cause);
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java
index 2b17245..5422af8 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,10 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import java.io.InputStream;
import java.nio.charset.Charset;
@@ -28,48 +30,39 @@ import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
import org.apache.maven.shared.utils.Os;
import org.apache.maven.shared.utils.StringUtils;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl </a>
*/
-public abstract class CommandLineUtils
-{
+public abstract class CommandLineUtils {
/**
* A {@code StreamConsumer} providing consumed lines as a {@code String}.
*
* @see #getOutput()
*/
- public static class StringStreamConsumer
- implements StreamConsumer
- {
+ public static class StringStreamConsumer implements StreamConsumer {
private final StringBuffer string = new StringBuffer();
- private static final String LS = System.getProperty( "line.separator", "\n" );
+ private static final String LS = System.getProperty("line.separator", "\n");
/**
* {@inheritDoc}
*/
@Override
- public void consumeLine( String line )
- {
- string.append( line ).append( LS );
+ public void consumeLine(String line) {
+ string.append(line).append(LS);
}
/**
* @return The output.
*/
- public String getOutput()
- {
+ public String getOutput() {
return string.toString();
}
-
}
/**
@@ -89,10 +82,9 @@ public abstract class CommandLineUtils
* @return return code.
* @throws CommandLineException in case of a problem.
*/
- public static int executeCommandLine( @Nonnull Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr )
- throws CommandLineException
- {
- return executeCommandLine( cl, null, systemOut, systemErr, 0 );
+ public static int executeCommandLine(@Nonnull Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr)
+ throws CommandLineException {
+ return executeCommandLine(cl, null, systemOut, systemErr, 0);
}
/**
@@ -103,11 +95,10 @@ public abstract class CommandLineUtils
* @return return code.
* @throws CommandLineException in case of a problem.
*/
- public static int executeCommandLine( @Nonnull Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr,
- int timeoutInSeconds )
- throws CommandLineException
- {
- return executeCommandLine( cl, null, systemOut, systemErr, timeoutInSeconds );
+ public static int executeCommandLine(
+ @Nonnull Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr, int timeoutInSeconds)
+ throws CommandLineException {
+ return executeCommandLine(cl, null, systemOut, systemErr, timeoutInSeconds);
}
/**
@@ -118,11 +109,10 @@ public abstract class CommandLineUtils
* @return return code.
* @throws CommandLineException in case of a problem.
*/
- public static int executeCommandLine( @Nonnull Commandline cl, InputStream systemIn, StreamConsumer systemOut,
- StreamConsumer systemErr )
- throws CommandLineException
- {
- return executeCommandLine( cl, systemIn, systemOut, systemErr, 0 );
+ public static int executeCommandLine(
+ @Nonnull Commandline cl, InputStream systemIn, StreamConsumer systemOut, StreamConsumer systemErr)
+ throws CommandLineException {
+ return executeCommandLine(cl, systemIn, systemOut, systemErr, 0);
}
/**
@@ -134,11 +124,14 @@ public abstract class CommandLineUtils
* @return A return value, see {@link Process#exitValue()}
* @throws CommandLineException or CommandLineTimeOutException if time out occurs
*/
- public static int executeCommandLine( @Nonnull Commandline cl, InputStream systemIn, StreamConsumer systemOut,
- StreamConsumer systemErr, int timeoutInSeconds )
- throws CommandLineException
- {
- return executeCommandLine( cl, systemIn, systemOut, systemErr, timeoutInSeconds, null );
+ public static int executeCommandLine(
+ @Nonnull Commandline cl,
+ InputStream systemIn,
+ StreamConsumer systemOut,
+ StreamConsumer systemErr,
+ int timeoutInSeconds)
+ throws CommandLineException {
+ return executeCommandLine(cl, systemIn, systemOut, systemErr, timeoutInSeconds, null);
}
/**
@@ -152,13 +145,16 @@ public abstract class CommandLineUtils
* @return A return value, see {@link Process#exitValue()}
* @throws CommandLineException or CommandLineTimeOutException if time out occurs
*/
- public static int executeCommandLine( @Nonnull Commandline cl, InputStream systemIn, StreamConsumer systemOut,
- StreamConsumer systemErr, int timeoutInSeconds,
- @Nullable Runnable runAfterProcessTermination )
- throws CommandLineException
- {
- return executeCommandLine( cl, systemIn, systemOut, systemErr, timeoutInSeconds, runAfterProcessTermination,
- null );
+ public static int executeCommandLine(
+ @Nonnull Commandline cl,
+ InputStream systemIn,
+ StreamConsumer systemOut,
+ StreamConsumer systemErr,
+ int timeoutInSeconds,
+ @Nullable Runnable runAfterProcessTermination)
+ throws CommandLineException {
+ return executeCommandLine(
+ cl, systemIn, systemOut, systemErr, timeoutInSeconds, runAfterProcessTermination, null);
}
/**
@@ -173,15 +169,17 @@ public abstract class CommandLineUtils
* @return A return value, see {@link Process#exitValue()}
* @throws CommandLineException or CommandLineTimeOutException if time out occurs
*/
- public static int executeCommandLine( @Nonnull Commandline cl, InputStream systemIn, StreamConsumer systemOut,
- StreamConsumer systemErr, int timeoutInSeconds,
- @Nullable Runnable runAfterProcessTermination,
- @Nullable final Charset streamCharset )
- throws CommandLineException
- {
- final CommandLineCallable future =
- executeCommandLineAsCallable( cl, systemIn, systemOut, systemErr, timeoutInSeconds,
- runAfterProcessTermination, streamCharset );
+ public static int executeCommandLine(
+ @Nonnull Commandline cl,
+ InputStream systemIn,
+ StreamConsumer systemOut,
+ StreamConsumer systemErr,
+ int timeoutInSeconds,
+ @Nullable Runnable runAfterProcessTermination,
+ @Nullable final Charset streamCharset)
+ throws CommandLineException {
+ final CommandLineCallable future = executeCommandLineAsCallable(
+ cl, systemIn, systemOut, systemErr, timeoutInSeconds, runAfterProcessTermination, streamCharset);
return future.call();
}
@@ -199,16 +197,16 @@ public abstract class CommandLineUtils
* any internal state before after the completion of the call statements
* @throws CommandLineException or CommandLineTimeOutException if time out occurs
*/
- public static CommandLineCallable executeCommandLineAsCallable( @Nonnull final Commandline cl,
- @Nullable final InputStream systemIn,
- final StreamConsumer systemOut,
- final StreamConsumer systemErr,
- final int timeoutInSeconds,
- @Nullable final Runnable runAfterProcessTermination )
- throws CommandLineException
- {
- return executeCommandLineAsCallable( cl, systemIn, systemOut, systemErr, timeoutInSeconds,
- runAfterProcessTermination, null );
+ public static CommandLineCallable executeCommandLineAsCallable(
+ @Nonnull final Commandline cl,
+ @Nullable final InputStream systemIn,
+ final StreamConsumer systemOut,
+ final StreamConsumer systemErr,
+ final int timeoutInSeconds,
+ @Nullable final Runnable runAfterProcessTermination)
+ throws CommandLineException {
+ return executeCommandLineAsCallable(
+ cl, systemIn, systemOut, systemErr, timeoutInSeconds, runAfterProcessTermination, null);
}
/**
@@ -226,191 +224,156 @@ public abstract class CommandLineUtils
* any internal state before after the completion of the call statements
* @throws CommandLineException or CommandLineTimeOutException if time out occurs
*/
- public static CommandLineCallable executeCommandLineAsCallable( @Nonnull final Commandline cl,
- @Nullable final InputStream systemIn,
- final StreamConsumer systemOut,
- final StreamConsumer systemErr,
- final int timeoutInSeconds,
- @Nullable final Runnable runAfterProcessTermination,
- @Nullable final Charset streamCharset )
- throws CommandLineException
- {
+ public static CommandLineCallable executeCommandLineAsCallable(
+ @Nonnull final Commandline cl,
+ @Nullable final InputStream systemIn,
+ final StreamConsumer systemOut,
+ final StreamConsumer systemErr,
+ final int timeoutInSeconds,
+ @Nullable final Runnable runAfterProcessTermination,
+ @Nullable final Charset streamCharset)
+ throws CommandLineException {
//noinspection ConstantConditions
- if ( cl == null )
- {
- throw new IllegalArgumentException( "cl cannot be null." );
+ if (cl == null) {
+ throw new IllegalArgumentException("cl cannot be null.");
}
final Process p = cl.execute();
- final Thread processHook = new Thread()
- {
+ final Thread processHook = new Thread() {
{
- this.setName( "CommandLineUtils process shutdown hook" );
- this.setContextClassLoader( null );
+ this.setName("CommandLineUtils process shutdown hook");
+ this.setContextClassLoader(null);
}
@Override
- public void run()
- {
+ public void run() {
p.destroy();
}
-
};
- ShutdownHookUtils.addShutDownHook( processHook );
+ ShutdownHookUtils.addShutDownHook(processHook);
- return new CommandLineCallable()
- {
+ return new CommandLineCallable() {
@Override
- public Integer call()
- throws CommandLineException
- {
+ public Integer call() throws CommandLineException {
StreamFeeder inputFeeder = null;
StreamPumper outputPumper = null;
StreamPumper errorPumper = null;
- try
- {
- if ( systemIn != null )
- {
- inputFeeder = new StreamFeeder( systemIn, p.getOutputStream() );
- inputFeeder.setName( "StreamFeeder-systemIn" );
+ try {
+ if (systemIn != null) {
+ inputFeeder = new StreamFeeder(systemIn, p.getOutputStream());
+ inputFeeder.setName("StreamFeeder-systemIn");
inputFeeder.start();
}
- outputPumper = new StreamPumper( p.getInputStream(), systemOut );
- outputPumper.setName( "StreamPumper-systemOut" );
+ outputPumper = new StreamPumper(p.getInputStream(), systemOut);
+ outputPumper.setName("StreamPumper-systemOut");
outputPumper.start();
- errorPumper = new StreamPumper( p.getErrorStream(), systemErr );
- errorPumper.setName( "StreamPumper-systemErr" );
+ errorPumper = new StreamPumper(p.getErrorStream(), systemErr);
+ errorPumper.setName("StreamPumper-systemErr");
errorPumper.start();
int returnValue;
- if ( timeoutInSeconds <= 0 )
- {
+ if (timeoutInSeconds <= 0) {
returnValue = p.waitFor();
- }
- else
- {
+ } else {
final long now = System.nanoTime();
final long timeout = now + NANOS_PER_SECOND * timeoutInSeconds;
- while ( isAlive( p ) && ( System.nanoTime() < timeout ) )
- {
+ while (isAlive(p) && (System.nanoTime() < timeout)) {
// The timeout is specified in seconds. Therefore we must not sleep longer than one second
// but we should sleep as long as possible to reduce the number of iterations performed.
- Thread.sleep( MILLIS_PER_SECOND - 1L );
+ Thread.sleep(MILLIS_PER_SECOND - 1L);
}
- if ( isAlive( p ) )
- {
- throw new InterruptedException( String.format( "Process timed out after %d seconds.",
- timeoutInSeconds ) );
-
+ if (isAlive(p)) {
+ throw new InterruptedException(
+ String.format("Process timed out after %d seconds.", timeoutInSeconds));
}
returnValue = p.exitValue();
}
-// TODO Find out if waitUntilDone needs to be called using a try-finally construct. The method may throw an
-// InterruptedException so that calls to waitUntilDone may be skipped.
-// try
-// {
-// if ( inputFeeder != null )
-// {
-// inputFeeder.waitUntilDone();
-// }
-// }
-// finally
-// {
-// try
-// {
-// outputPumper.waitUntilDone();
-// }
-// finally
-// {
-// errorPumper.waitUntilDone();
-// }
-// }
- if ( inputFeeder != null )
- {
+ // TODO Find out if waitUntilDone needs to be called using a try-finally construct. The method may
+ // throw an
+ // InterruptedException so that calls to waitUntilDone may be skipped.
+ // try
+ // {
+ // if ( inputFeeder != null )
+ // {
+ // inputFeeder.waitUntilDone();
+ // }
+ // }
+ // finally
+ // {
+ // try
+ // {
+ // outputPumper.waitUntilDone();
+ // }
+ // finally
+ // {
+ // errorPumper.waitUntilDone();
+ // }
+ // }
+ if (inputFeeder != null) {
inputFeeder.waitUntilDone();
}
outputPumper.waitUntilDone();
errorPumper.waitUntilDone();
- if ( inputFeeder != null )
- {
+ if (inputFeeder != null) {
inputFeeder.close();
- if ( inputFeeder.getException() != null )
- {
- throw new CommandLineException( "Failure processing stdin.", inputFeeder.getException() );
+ if (inputFeeder.getException() != null) {
+ throw new CommandLineException("Failure processing stdin.", inputFeeder.getException());
}
}
- if ( outputPumper.getException() != null )
- {
- throw new CommandLineException( "Failure processing stdout.", outputPumper.getException() );
+ if (outputPumper.getException() != null) {
+ throw new CommandLineException("Failure processing stdout.", outputPumper.getException());
}
- if ( errorPumper.getException() != null )
- {
- throw new CommandLineException( "Failure processing stderr.", errorPumper.getException() );
+ if (errorPumper.getException() != null) {
+ throw new CommandLineException("Failure processing stderr.", errorPumper.getException());
}
return returnValue;
- }
- catch ( InterruptedException ex )
- {
- throw new CommandLineTimeOutException( "Error while executing external command, process killed.",
- ex );
+ } catch (InterruptedException ex) {
+ throw new CommandLineTimeOutException(
+ "Error while executing external command, process killed.", ex);
- }
- finally
- {
- if ( inputFeeder != null )
- {
+ } finally {
+ if (inputFeeder != null) {
inputFeeder.disable();
}
- if ( outputPumper != null )
- {
+ if (outputPumper != null) {
outputPumper.disable();
}
- if ( errorPumper != null )
- {
+ if (errorPumper != null) {
errorPumper.disable();
}
- try
- {
- if ( runAfterProcessTermination != null )
- {
+ try {
+ if (runAfterProcessTermination != null) {
runAfterProcessTermination.run();
}
- }
- finally
- {
- ShutdownHookUtils.removeShutdownHook( processHook );
+ } finally {
+ ShutdownHookUtils.removeShutdownHook(processHook);
- try
- {
+ try {
processHook.run();
- }
- finally
- {
- if ( inputFeeder != null )
- {
+ } finally {
+ if (inputFeeder != null) {
inputFeeder.close();
}
}
}
}
}
-
};
}
@@ -424,9 +387,8 @@ public abstract class CommandLineUtils
* @deprecated use System#getenv()
*/
@Deprecated
- public static Properties getSystemEnvVars()
- {
- return getSystemEnvVars( !Os.isFamily( Os.FAMILY_WINDOWS ) );
+ public static Properties getSystemEnvVars() {
+ return getSystemEnvVars(!Os.isFamily(Os.FAMILY_WINDOWS));
}
/**
@@ -438,26 +400,20 @@ public abstract class CommandLineUtils
* @deprecated use System#getenv()
*/
@Deprecated
- public static Properties getSystemEnvVars( boolean caseSensitive )
- {
+ public static Properties getSystemEnvVars(boolean caseSensitive) {
Map<String, String> envs = System.getenv();
- return ensureCaseSensitivity( envs, caseSensitive );
+ return ensureCaseSensitivity(envs, caseSensitive);
}
- private static boolean isAlive( Process p )
- {
- if ( p == null )
- {
+ private static boolean isAlive(Process p) {
+ if (p == null) {
return false;
}
- try
- {
+ try {
p.exitValue();
return false;
- }
- catch ( IllegalThreadStateException e )
- {
+ } catch (IllegalThreadStateException e) {
return true;
}
}
@@ -467,10 +423,8 @@ public abstract class CommandLineUtils
* @return The array of translated parts.
* @throws CommandLineException in case of unbalanced quotes.
*/
- public static String[] translateCommandline( String toProcess ) throws CommandLineException
- {
- if ( ( toProcess == null ) || ( toProcess.length() == 0 ) )
- {
+ public static String[] translateCommandline(String toProcess) throws CommandLineException {
+ if ((toProcess == null) || (toProcess.length() == 0)) {
return new String[0];
}
@@ -481,139 +435,103 @@ public abstract class CommandLineUtils
final int inDoubleQuote = 2;
boolean inEscape = false;
int state = normal;
- final StringTokenizer tok = new StringTokenizer( toProcess, "\"\' \\", true );
+ final StringTokenizer tok = new StringTokenizer(toProcess, "\"\' \\", true);
List<String> tokens = new ArrayList<String>();
StringBuilder current = new StringBuilder();
- while ( tok.hasMoreTokens() )
- {
+ while (tok.hasMoreTokens()) {
String nextTok = tok.nextToken();
- switch ( state )
- {
+ switch (state) {
case inQuote:
- if ( "\'".equals( nextTok ) )
- {
- if ( inEscape )
- {
- current.append( nextTok );
+ if ("\'".equals(nextTok)) {
+ if (inEscape) {
+ current.append(nextTok);
inEscape = false;
- }
- else
- {
+ } else {
state = normal;
}
- }
- else
- {
- current.append( nextTok );
- inEscape = "\\".equals( nextTok );
+ } else {
+ current.append(nextTok);
+ inEscape = "\\".equals(nextTok);
}
break;
case inDoubleQuote:
- if ( "\"".equals( nextTok ) )
- {
- if ( inEscape )
- {
- current.append( nextTok );
+ if ("\"".equals(nextTok)) {
+ if (inEscape) {
+ current.append(nextTok);
inEscape = false;
- }
- else
- {
+ } else {
state = normal;
}
- }
- else
- {
- current.append( nextTok );
- inEscape = "\\".equals( nextTok );
+ } else {
+ current.append(nextTok);
+ inEscape = "\\".equals(nextTok);
}
break;
default:
- if ( "\'".equals( nextTok ) )
- {
- if ( inEscape )
- {
+ if ("\'".equals(nextTok)) {
+ if (inEscape) {
inEscape = false;
- current.append( nextTok );
- }
- else
- {
+ current.append(nextTok);
+ } else {
state = inQuote;
}
- }
- else if ( "\"".equals( nextTok ) )
- {
- if ( inEscape )
- {
+ } else if ("\"".equals(nextTok)) {
+ if (inEscape) {
inEscape = false;
- current.append( nextTok );
- }
- else
- {
+ current.append(nextTok);
+ } else {
state = inDoubleQuote;
}
- }
- else if ( " ".equals( nextTok ) )
- {
- if ( current.length() != 0 )
- {
- tokens.add( current.toString() );
- current.setLength( 0 );
+ } else if (" ".equals(nextTok)) {
+ if (current.length() != 0) {
+ tokens.add(current.toString());
+ current.setLength(0);
}
- }
- else
- {
- current.append( nextTok );
- inEscape = "\\".equals( nextTok );
+ } else {
+ current.append(nextTok);
+ inEscape = "\\".equals(nextTok);
}
break;
}
}
- if ( current.length() != 0 )
- {
- tokens.add( current.toString() );
+ if (current.length() != 0) {
+ tokens.add(current.toString());
}
- if ( ( state == inQuote ) || ( state == inDoubleQuote ) )
- {
- throw new CommandLineException( "unbalanced quotes in " + toProcess );
+ if ((state == inQuote) || (state == inDoubleQuote)) {
+ throw new CommandLineException("unbalanced quotes in " + toProcess);
}
- return tokens.toArray( new String[tokens.size()] );
+ return tokens.toArray(new String[tokens.size()]);
}
/**
* @param line the lines
* @return the concatenated lines, quoted and escaped, separated by spaces
*/
- public static String toString( String... line )
- {
+ public static String toString(String... line) {
// empty path return empty string
- if ( ( line == null ) || ( line.length == 0 ) )
- {
+ if ((line == null) || (line.length == 0)) {
return "";
}
final StringBuilder result = new StringBuilder();
- for ( int i = 0; i < line.length; i++ )
- {
- if ( i > 0 )
- {
- result.append( ' ' );
+ for (int i = 0; i < line.length; i++) {
+ if (i > 0) {
+ result.append(' ');
}
- result.append( StringUtils.quoteAndEscape( line[i], '\"' ) );
+ result.append(StringUtils.quoteAndEscape(line[i], '\"'));
}
return result.toString();
}
- static Properties ensureCaseSensitivity( Map<String, String> envs, boolean preserveKeyCase )
- {
+ static Properties ensureCaseSensitivity(Map<String, String> envs, boolean preserveKeyCase) {
Properties envVars = new Properties();
- for ( Map.Entry<String, String> entry : envs.entrySet() )
- {
- envVars.put( !preserveKeyCase ? entry.getKey().toUpperCase( Locale.ENGLISH ) : entry.getKey(),
- entry.getValue() );
+ for (Map.Entry<String, String> entry : envs.entrySet()) {
+ envVars.put(
+ !preserveKeyCase ? entry.getKey().toUpperCase(Locale.ENGLISH) : entry.getKey(), entry.getValue());
}
return envVars;
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java b/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java
index 2d5d63c..4f93957 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
import java.io.File;
import java.io.IOException;
@@ -62,12 +61,10 @@ import org.apache.maven.shared.utils.cli.shell.Shell;
* @author thomas.haas@softwired-inc.com
* @author <a href="mailto:stefan.bodewig@epost.de">Stefan Bodewig</a>
*/
-public class Commandline
- implements Cloneable
-{
+public class Commandline implements Cloneable {
private final List<Arg> arguments = new Vector<>();
- private final Map<String, String> envVars = Collections.synchronizedMap( new LinkedHashMap<String, String>() );
+ private final Map<String, String> envVars = Collections.synchronizedMap(new LinkedHashMap<String, String>());
private Shell shell;
@@ -76,11 +73,10 @@ public class Commandline
/**
* Create a new command line object.
* Shell is autodetected from operating system.
- *
+ *
* @param shell the shell instance
*/
- public Commandline( Shell shell )
- {
+ public Commandline(Shell shell) {
this.shell = shell;
}
@@ -91,16 +87,13 @@ public class Commandline
* @param toProcess the command to process
* @throws CommandLineException in case of unbalanced quotes.
*/
- public Commandline( String toProcess ) throws CommandLineException
- {
+ public Commandline(String toProcess) throws CommandLineException {
setDefaultShell();
- String[] tmp = CommandLineUtils.translateCommandline( toProcess );
- if ( ( tmp.length > 0 ) )
- {
- setExecutable( tmp[0] );
- for ( int i = 1; i < tmp.length; i++ )
- {
- createArg().setValue( tmp[i] );
+ String[] tmp = CommandLineUtils.translateCommandline(toProcess);
+ if ((tmp.length > 0)) {
+ setExecutable(tmp[0]);
+ for (int i = 1; i < tmp.length; i++) {
+ createArg().setValue(tmp[i]);
}
}
}
@@ -109,8 +102,7 @@ public class Commandline
* Create a new command line object.
* Shell is autodetected from operating system.
*/
- public Commandline()
- {
+ public Commandline() {
setDefaultShell();
}
@@ -118,16 +110,12 @@ public class Commandline
* <p>Sets the shell or command-line interpreter for the detected operating system,
* and the shell arguments.</p>
*/
- private void setDefaultShell()
- {
- //If this is windows set the shell to command.com or cmd.exe with correct arguments.
- if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
- {
- setShell( new CmdShell() );
- }
- else
- {
- setShell( new BourneShell() );
+ private void setDefaultShell() {
+ // If this is windows set the shell to command.com or cmd.exe with correct arguments.
+ if (Os.isFamily(Os.FAMILY_WINDOWS)) {
+ setShell(new CmdShell());
+ } else {
+ setShell(new BourneShell());
}
}
@@ -136,9 +124,8 @@ public class Commandline
*
* @return the argument object
*/
- public Arg createArg()
- {
- return this.createArg( false );
+ public Arg createArg() {
+ return this.createArg(false);
}
/**
@@ -148,35 +135,29 @@ public class Commandline
* beginning of the list of args. Otherwise it is appended.
* @return the argument
*/
- public Arg createArg( boolean insertAtStart )
- {
+ public Arg createArg(boolean insertAtStart) {
Arg argument = new Argument();
- if ( insertAtStart )
- {
- arguments.add( 0, argument );
- }
- else
- {
- arguments.add( argument );
+ if (insertAtStart) {
+ arguments.add(0, argument);
+ } else {
+ arguments.add(argument);
}
return argument;
}
/**
* Sets the executable to run.
- *
+ *
* @param executable the executable
*/
- public void setExecutable( String executable )
- {
- shell.setExecutable( executable );
+ public void setExecutable(String executable) {
+ shell.setExecutable(executable);
}
/**
* @return the executable
*/
- public String getExecutable()
- {
+ public String getExecutable() {
return shell.getExecutable();
}
@@ -184,92 +165,79 @@ public class Commandline
/**
* @param line the arguments
*/
- public void addArguments( String... line )
- {
- for ( String aLine : line )
- {
- createArg().setValue( aLine );
+ public void addArguments(String... line) {
+ for (String aLine : line) {
+ createArg().setValue(aLine);
}
}
/**
* Add an environment variable.
- *
+ *
* @param name the name of the environment variable
* @param value the appropriate value
*/
- public void addEnvironment( String name, String value )
- {
- envVars.put( name, value );
+ public void addEnvironment(String name, String value) {
+ envVars.put(name, value);
}
/**
* Add system environment variables.
*/
- private void addSystemEnvironment()
- {
+ private void addSystemEnvironment() {
Properties systemEnvVars = CommandLineUtils.getSystemEnvVars();
- for ( Object o : systemEnvVars.keySet() )
- {
+ for (Object o : systemEnvVars.keySet()) {
String key = (String) o;
- if ( !envVars.containsKey( key ) )
- {
- addEnvironment( key, systemEnvVars.getProperty( key ) );
+ if (!envVars.containsKey(key)) {
+ addEnvironment(key, systemEnvVars.getProperty(key));
}
}
}
/**
* Return the list of environment variables.
- *
+ *
* @return an array of all environment variables
*/
- public String[] getEnvironmentVariables()
- {
- if ( isShellEnvironmentInherited() )
- {
+ public String[] getEnvironmentVariables() {
+ if (isShellEnvironmentInherited()) {
addSystemEnvironment();
}
List<String> environmentVars = new ArrayList<>();
- for ( String name : envVars.keySet() )
- {
- String value = envVars.get( name );
- if ( value != null )
- {
- environmentVars.add( name + "=" + value );
+ for (String name : envVars.keySet()) {
+ String value = envVars.get(name);
+ if (value != null) {
+ environmentVars.add(name + "=" + value);
}
}
- return environmentVars.toArray( new String[0] );
+ return environmentVars.toArray(new String[0]);
}
/**
* Returns the executable and all defined arguments.
- *
+ *
* @return an array of all arguments including the executable
*/
- public String[] getCommandline()
- {
+ public String[] getCommandline() {
final String[] args = getArguments();
String executable = getExecutable();
- if ( executable == null )
- {
+ if (executable == null) {
return args;
}
final String[] result = new String[args.length + 1];
result[0] = executable;
- System.arraycopy( args, 0, result, 1, args.length );
+ System.arraycopy(args, 0, result, 1, args.length);
return result;
}
/**
* @return the shell, executable and all defined arguments without masking any arguments
*/
- private String[] getShellCommandline()
- {
- return getShellCommandline( false ) ;
+ private String[] getShellCommandline() {
+ return getShellCommandline(false);
}
/**
@@ -277,10 +245,9 @@ public class Commandline
* @return the shell, executable and all defined arguments with masking some arguments if
* {@code mask} parameter is on
*/
- private String[] getShellCommandline( boolean mask )
- {
- List<String> shellCommandLine = getShell().getShellCommandLine( getArguments( mask ) );
- return shellCommandLine.toArray( new String[shellCommandLine.size()] );
+ private String[] getShellCommandline(boolean mask) {
+ List<String> shellCommandLine = getShell().getShellCommandLine(getArguments(mask));
+ return shellCommandLine.toArray(new String[shellCommandLine.size()]);
}
/**
@@ -288,9 +255,8 @@ public class Commandline
* <code>addValue</code> or the argument object.
* @return an array of arguments.
*/
- public String[] getArguments()
- {
- return getArguments( false );
+ public String[] getArguments() {
+ return getArguments(false);
}
/**
@@ -300,85 +266,73 @@ public class Commandline
* @param mask flag to mask any arguments (having his {@code mask} field to {@code true})
* @return an array of arguments
*/
- public String[] getArguments( boolean mask )
- {
- List<String> result = new ArrayList<>( arguments.size() * 2 );
- for ( Arg argument : arguments )
- {
+ public String[] getArguments(boolean mask) {
+ List<String> result = new ArrayList<>(arguments.size() * 2);
+ for (Arg argument : arguments) {
Argument arg = (Argument) argument;
String[] s = arg.getParts();
- if ( s != null )
- {
- if ( mask && ( arg.isMask() ) )
- {
+ if (s != null) {
+ if (mask && (arg.isMask())) {
// should be a key-pair argument
- if ( s.length > 0 )
- {
+ if (s.length > 0) {
// use a masked copy
String[] copy = new String[s.length];
- Arrays.fill( copy, "*****" );
+ Arrays.fill(copy, "*****");
s = copy;
}
}
- Collections.addAll( result, s );
+ Collections.addAll(result, s);
}
}
- return result.toArray( new String[result.size()] );
+ return result.toArray(new String[result.size()]);
}
/** {@inheritDoc}
*/
- public String toString()
- {
- return StringUtils.join( getShellCommandline( true ), " " );
+ public String toString() {
+ return StringUtils.join(getShellCommandline(true), " ");
}
-
/** {@inheritDoc}
*/
- public Object clone()
- {
- throw new RuntimeException( "Do we ever clone a commandline?" );
-/* Commandline c = new Commandline( (Shell) shell.clone() );
- c.addArguments( getArguments() );
- return c;*/
+ public Object clone() {
+ throw new RuntimeException("Do we ever clone a commandline?");
+ /* Commandline c = new Commandline( (Shell) shell.clone() );
+ c.addArguments( getArguments() );
+ return c;*/
}
/**
* Sets working directory.
- *
+ *
* @param path the working directory
*/
- public void setWorkingDirectory( String path )
- {
- shell.setWorkingDirectory( path );
+ public void setWorkingDirectory(String path) {
+ shell.setWorkingDirectory(path);
}
/**
* Sets working directory.
- *
+ *
* @param workingDirectory the working directory
*/
- public void setWorkingDirectory( File workingDirectory )
- {
- shell.setWorkingDirectory( workingDirectory );
+ public void setWorkingDirectory(File workingDirectory) {
+ shell.setWorkingDirectory(workingDirectory);
}
/**
* @return the working directory
*/
- public File getWorkingDirectory()
- {
+ public File getWorkingDirectory() {
return shell.getWorkingDirectory();
}
/**
* Clear out the arguments but leave the executable in place for another operation.
*/
- public void clearArgs()
- {
+ public void clearArgs() {
arguments.clear();
}
@@ -389,8 +343,7 @@ public class Commandline
*
* @return <code>true</code> if the environment variables should be propagated, <code>false</code> otherwise.
*/
- public boolean isShellEnvironmentInherited()
- {
+ public boolean isShellEnvironmentInherited() {
return shellEnvironmentInherited;
}
@@ -400,51 +353,39 @@ public class Commandline
* @param shellEnvironmentInherited <code>true</code> if the environment variables should be propagated,
* <code>false</code> otherwise.
*/
- public void setShellEnvironmentInherited( boolean shellEnvironmentInherited )
- {
+ public void setShellEnvironmentInherited(boolean shellEnvironmentInherited) {
this.shellEnvironmentInherited = shellEnvironmentInherited;
}
/**
* Execute the command.
- *
+ *
* @return the process
* @throws CommandLineException in case of errors
*/
- public Process execute()
- throws CommandLineException
- {
+ public Process execute() throws CommandLineException {
Process process;
String[] environment = getEnvironmentVariables();
File workingDir = shell.getWorkingDirectory();
- try
- {
- if ( workingDir == null )
- {
- process = Runtime.getRuntime().exec( getShellCommandline(), environment );
- }
- else
- {
- if ( !workingDir.exists() )
- {
+ try {
+ if (workingDir == null) {
+ process = Runtime.getRuntime().exec(getShellCommandline(), environment);
+ } else {
+ if (!workingDir.exists()) {
throw new CommandLineException(
- "Working directory \"" + workingDir.getPath() + "\" does not exist!" );
- }
- else if ( !workingDir.isDirectory() )
- {
+ "Working directory \"" + workingDir.getPath() + "\" does not exist!");
+ } else if (!workingDir.isDirectory()) {
throw new CommandLineException(
- "Path \"" + workingDir.getPath() + "\" does not specify a directory." );
+ "Path \"" + workingDir.getPath() + "\" does not specify a directory.");
}
- process = Runtime.getRuntime().exec( getShellCommandline(), environment, workingDir );
+ process = Runtime.getRuntime().exec(getShellCommandline(), environment, workingDir);
}
- }
- catch ( IOException ex )
- {
- throw new CommandLineException( "Error while executing process.", ex );
+ } catch (IOException ex) {
+ throw new CommandLineException("Error while executing process.", ex);
}
return process;
@@ -455,27 +396,23 @@ public class Commandline
*
* @param shell the shell
*/
- void setShell( Shell shell )
- {
+ void setShell(Shell shell) {
this.shell = shell;
}
/**
* Get the shell to be used in this command line.
- *
+ *
* @return the shell
*/
- public Shell getShell()
- {
+ public Shell getShell() {
return shell;
}
/**
* A single command line argument
*/
- public static class Argument
- implements Arg
- {
+ public static class Argument implements Arg {
private String[] parts;
private boolean mask;
@@ -483,55 +420,47 @@ public class Commandline
/**
* {@inheritDoc}
*/
- public void setValue( String value )
- {
- if ( value != null )
- {
- parts = new String[]{ value };
+ public void setValue(String value) {
+ if (value != null) {
+ parts = new String[] {value};
}
}
/**
* {@inheritDoc}
*/
- public void setLine( String line ) throws CommandLineException
- {
- if ( line == null )
- {
+ public void setLine(String line) throws CommandLineException {
+ if (line == null) {
return;
}
- parts = CommandLineUtils.translateCommandline( line );
+ parts = CommandLineUtils.translateCommandline(line);
}
/**
* {@inheritDoc}
*/
- public void setFile( File value )
- {
- parts = new String[]{ value.getAbsolutePath() };
+ public void setFile(File value) {
+ parts = new String[] {value.getAbsolutePath()};
}
/**
* {@inheritDoc}
*/
- public void setMask( boolean mask )
- {
+ public void setMask(boolean mask) {
this.mask = mask;
}
/**
* @return the parts
*/
- private String[] getParts()
- {
+ private String[] getParts() {
return parts;
}
/**
* @return true/false
*/
- public boolean isMask()
- {
+ public boolean isMask() {
return mask;
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java b/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java
index 59d9971..f264046 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,27 +16,23 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
import java.io.IOException;
/**
* @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a>
*/
-public class DefaultConsumer
- implements StreamConsumer
-{
+public class DefaultConsumer implements StreamConsumer {
/**
* {@inheritDoc}
*/
@Override
- public void consumeLine( String line ) throws IOException
- {
- System.out.println( line );
- if ( System.out.checkError() )
- {
- throw new IOException( String.format( "Failure writing line '%s' to stdout.", line ) );
+ public void consumeLine(String line) throws IOException {
+ System.out.println(line);
+ if (System.out.checkError()) {
+ throw new IOException(String.format("Failure writing line '%s' to stdout.", line));
}
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/ShutdownHookUtils.java b/src/main/java/org/apache/maven/shared/utils/cli/ShutdownHookUtils.java
index d1ea568..5ec3bbc 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/ShutdownHookUtils.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/ShutdownHookUtils.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
import java.security.AccessControlException;
@@ -29,24 +28,17 @@ import java.security.AccessControlException;
*
* @author Kristian Rosenvold
*/
-public class ShutdownHookUtils
-{
+public class ShutdownHookUtils {
/**
* @param hook The thread hook.
*/
- public static void addShutDownHook( Thread hook )
- {
- try
- {
- Runtime.getRuntime().addShutdownHook( hook );
- }
- catch ( IllegalStateException ignore )
- {
+ public static void addShutDownHook(Thread hook) {
+ try {
+ Runtime.getRuntime().addShutdownHook(hook);
+ } catch (IllegalStateException ignore) {
// ignore
- }
- catch ( AccessControlException ignore )
- {
+ } catch (AccessControlException ignore) {
// ignore
}
}
@@ -54,20 +46,13 @@ public class ShutdownHookUtils
/**
* @param hook The hook which should be removed.
*/
- public static void removeShutdownHook( Thread hook )
- {
- try
- {
- Runtime.getRuntime().removeShutdownHook( hook );
- }
- catch ( IllegalStateException ignore )
- {
+ public static void removeShutdownHook(Thread hook) {
+ try {
+ Runtime.getRuntime().removeShutdownHook(hook);
+ } catch (IllegalStateException ignore) {
// ignore
- }
- catch ( AccessControlException ignore )
- {
+ } catch (AccessControlException ignore) {
// ignore
}
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java b/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java
index d64fba9..9279aca 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
import java.io.IOException;
@@ -31,12 +30,11 @@ import java.io.IOException;
* @author <a href="mailto:fvancea@maxiq.com">Florin Vancea</a>
* @author <a href="mailto:pj@thoughtworks.com">Paul Julius</a>
*/
-public interface StreamConsumer
-{
+public interface StreamConsumer {
/**
* Called when the StreamPumper pumps a line from the Stream.
* @param line The line to be consumed.
* @throws IOException if consuming {@code line} fails.
*/
- void consumeLine( String line ) throws IOException;
+ void consumeLine(String line) throws IOException;
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/StreamFeeder.java b/src/main/java/org/apache/maven/shared/utils/cli/StreamFeeder.java
index 6f6723c..e5743a8 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/StreamFeeder.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/StreamFeeder.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
import java.io.IOException;
import java.io.InputStream;
@@ -29,9 +28,7 @@ import java.util.concurrent.atomic.AtomicReference;
*
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
-class StreamFeeder
- extends AbstractStreamHandler
-{
+class StreamFeeder extends AbstractStreamHandler {
private final AtomicReference<InputStream> input;
@@ -45,69 +42,49 @@ class StreamFeeder
* @param input Stream to read from
* @param output Stream to write to
*/
- StreamFeeder( InputStream input, OutputStream output )
- {
+ StreamFeeder(InputStream input, OutputStream output) {
super();
- this.input = new AtomicReference<InputStream>( input );
- this.output = new AtomicReference<OutputStream>( output );
+ this.input = new AtomicReference<InputStream>(input);
+ this.output = new AtomicReference<OutputStream>(output);
}
@Override
- public void run()
- {
- try
- {
+ public void run() {
+ try {
feed();
- }
- catch ( Throwable e )
- {
+ } catch (Throwable e) {
// Catch everything so the streams will be closed and flagged as done.
- if ( this.exception != null )
- {
+ if (this.exception != null) {
this.exception = e;
}
- }
- finally
- {
+ } finally {
close();
- synchronized ( this )
- {
+ synchronized (this) {
notifyAll();
}
}
}
- public void close()
- {
+ public void close() {
setDone();
- final InputStream is = input.getAndSet( null );
- if ( is != null )
- {
- try
- {
+ final InputStream is = input.getAndSet(null);
+ if (is != null) {
+ try {
is.close();
- }
- catch ( IOException ex )
- {
- if ( this.exception != null )
- {
+ } catch (IOException ex) {
+ if (this.exception != null) {
this.exception = ex;
}
}
}
- final OutputStream os = output.getAndSet( null );
- if ( os != null )
- {
- try
- {
+ final OutputStream os = output.getAndSet(null);
+ if (os != null) {
+ try {
os.close();
- }
- catch ( IOException ex )
- {
- if ( this.exception != null )
- {
+ } catch (IOException ex) {
+ if (this.exception != null) {
this.exception = ex;
}
}
@@ -117,35 +94,27 @@ class StreamFeeder
/**
* @since 3.2.0
*/
- public Throwable getException()
- {
+ public Throwable getException() {
return this.exception;
}
- @SuppressWarnings( "checkstyle:innerassignment" )
- private void feed()
- throws IOException
- {
+ @SuppressWarnings("checkstyle:innerassignment")
+ private void feed() throws IOException {
InputStream is = input.get();
OutputStream os = output.get();
boolean flush = false;
- if ( is != null && os != null )
- {
- for ( int data; !isDone() && ( data = is.read() ) != -1; )
- {
- if ( !isDisabled() )
- {
- os.write( data );
+ if (is != null && os != null) {
+ for (int data; !isDone() && (data = is.read()) != -1; ) {
+ if (!isDisabled()) {
+ os.write(data);
flush = true;
}
}
- if ( flush )
- {
+ if (flush) {
os.flush();
}
}
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/StreamPumper.java b/src/main/java/org/apache/maven/shared/utils/cli/StreamPumper.java
index 980bfb6..03a79ca 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/StreamPumper.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/StreamPumper.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,9 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
+
+import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.IOException;
@@ -25,7 +26,6 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
-import javax.annotation.Nullable;
/**
* Class to pump the error stream during Process's runtime. Copied from the Ant built-in task.
@@ -33,9 +33,7 @@ import javax.annotation.Nullable;
* @author <a href="mailto:fvancea@maxiq.com">Florin Vancea </a>
* @author <a href="mailto:pj@thoughtworks.com">Paul Julius </a>
*/
-public class StreamPumper
- extends AbstractStreamHandler
-{
+public class StreamPumper extends AbstractStreamHandler {
private final BufferedReader in;
private final StreamConsumer consumer;
@@ -48,9 +46,8 @@ public class StreamPumper
* @param in {@link InputStream}
* @param consumer {@link StreamConsumer}
*/
- public StreamPumper( InputStream in, StreamConsumer consumer )
- {
- this( new InputStreamReader( in ), consumer );
+ public StreamPumper(InputStream in, StreamConsumer consumer) {
+ this(new InputStreamReader(in), consumer);
}
/**
@@ -58,62 +55,44 @@ public class StreamPumper
* @param consumer {@link StreamConsumer}
* @param charset {@link Charset}
*/
- public StreamPumper( InputStream in, StreamConsumer consumer, @Nullable Charset charset )
- {
- this( null == charset ? new InputStreamReader( in ) : new InputStreamReader( in, charset ), consumer );
+ public StreamPumper(InputStream in, StreamConsumer consumer, @Nullable Charset charset) {
+ this(null == charset ? new InputStreamReader(in) : new InputStreamReader(in, charset), consumer);
}
/**
* @param in {@link Reader}
* @param consumer {@link StreamConsumer}
*/
- private StreamPumper( Reader in, StreamConsumer consumer )
- {
+ private StreamPumper(Reader in, StreamConsumer consumer) {
super();
- this.in = new BufferedReader( in, SIZE );
+ this.in = new BufferedReader(in, SIZE);
this.consumer = consumer;
}
/** run it. */
- public void run()
- {
- try
- {
- for ( String line = in.readLine(); line != null; line = in.readLine() )
- {
- try
- {
- if ( exception == null )
- {
- consumeLine( line );
+ public void run() {
+ try {
+ for (String line = in.readLine(); line != null; line = in.readLine()) {
+ try {
+ if (exception == null) {
+ consumeLine(line);
}
- }
- catch ( Exception t )
- {
+ } catch (Exception t) {
exception = t;
}
}
- }
- catch ( IOException e )
- {
+ } catch (IOException e) {
exception = e;
- }
- finally
- {
- try
- {
+ } finally {
+ try {
in.close();
- }
- catch ( final IOException e2 )
- {
- if ( this.exception == null )
- {
+ } catch (final IOException e2) {
+ if (this.exception == null) {
this.exception = e2;
}
}
- synchronized ( this )
- {
+ synchronized (this) {
setDone();
this.notifyAll();
@@ -127,8 +106,7 @@ public class StreamPumper
* @deprecated As of 3.2.0, removed without replacement.
*/
@Deprecated
- public void flush()
- {
+ public void flush() {
// Nothing to flush.
}
@@ -138,24 +116,20 @@ public class StreamPumper
* @deprecated As of 3.2.0, removed without replacement.
*/
@Deprecated
- public void close()
- {
+ public void close() {
// Nothing to close.
}
/**
* @return {@link Exception}
*/
- public Exception getException()
- {
+ public Exception getException() {
return exception;
}
- private void consumeLine( String line ) throws IOException
- {
- if ( consumer != null && !isDisabled() )
- {
- consumer.consumeLine( line );
+ private void consumeLine(String line) throws IOException {
+ if (consumer != null && !isDisabled()) {
+ consumer.consumeLine(line);
}
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/WriterStreamConsumer.java b/src/main/java/org/apache/maven/shared/utils/cli/WriterStreamConsumer.java
index b93ccb7..d3dbbbe 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/WriterStreamConsumer.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/WriterStreamConsumer.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli;
import java.io.BufferedWriter;
import java.io.IOException;
@@ -27,30 +26,25 @@ import java.io.Writer;
* @author <a href="mailto:jason@maven.org">Jason van Zyl</a>
*
*/
-public class WriterStreamConsumer
- implements StreamConsumer
-{
+public class WriterStreamConsumer implements StreamConsumer {
private final BufferedWriter writer;
/**
* @param writer {@link Writer}
*/
- public WriterStreamConsumer( Writer writer )
- {
+ public WriterStreamConsumer(Writer writer) {
super();
- this.writer = new BufferedWriter( writer );
+ this.writer = new BufferedWriter(writer);
}
/**
* {@inheritDoc}
*/
@Override
- public void consumeLine( String line ) throws IOException
- {
- this.writer.append( line );
+ public void consumeLine(String line) throws IOException {
+ this.writer.append(line);
this.writer.newLine();
this.writer.flush();
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java
index 971b962..813ccc0 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli.javatool;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,13 @@ package org.apache.maven.shared.utils.cli.javatool;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli.javatool;
+
+import java.io.File;
+import java.io.InputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
import org.apache.maven.shared.utils.Os;
import org.apache.maven.shared.utils.StringUtils;
@@ -28,12 +33,6 @@ import org.apache.maven.shared.utils.cli.StreamConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.InputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Map;
-
/**
* Abstract implementation of a {@link JavaTool}.
*
@@ -41,10 +40,8 @@ import java.util.Map;
* @since 0.5
* @param <Request> Tool-specific request type
*/
-public abstract class AbstractJavaTool<Request extends JavaToolRequest>
- implements JavaTool<Request>
-{
- private final Logger logger = LoggerFactory.getLogger( getClass() );
+public abstract class AbstractJavaTool<Request extends JavaToolRequest> implements JavaTool<Request> {
+ private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* The java tool name to find out in the jdk.
@@ -64,8 +61,7 @@ public abstract class AbstractJavaTool<Request extends JavaToolRequest>
/**
* @param javaToolName The name of the java tool.
*/
- protected AbstractJavaTool( String javaToolName )
- {
+ protected AbstractJavaTool(String javaToolName) {
this.javaToolName = javaToolName;
}
@@ -77,57 +73,48 @@ public abstract class AbstractJavaTool<Request extends JavaToolRequest>
* @return the command line
* @throws JavaToolException if could not create the command line from the request
*/
- protected abstract Commandline createCommandLine( Request request, String javaToolFileLocation )
- throws JavaToolException;
+ protected abstract Commandline createCommandLine(Request request, String javaToolFileLocation)
+ throws JavaToolException;
- protected Logger getLogger()
- {
+ protected Logger getLogger() {
return logger;
}
/**
* {@inheritDoc}
*/
- public String getJavaToolName()
- {
+ public String getJavaToolName() {
return javaToolName;
}
/**
* {@inheritDoc}
*/
- public void setToolchain( Object toolchain )
- {
+ public void setToolchain(Object toolchain) {
this.toolchain = toolchain;
}
/**
* {@inheritDoc}
*/
- public JavaToolResult execute( Request request )
- throws JavaToolException
- {
+ public JavaToolResult execute(Request request) throws JavaToolException {
- if ( javaToolFile == null )
- {
+ if (javaToolFile == null) {
// find the java tool file to use
- try
- {
+ try {
javaToolFile = findJavaToolExecutable();
- }
- catch ( Exception e )
- {
- throw new JavaToolException( "Error finding " + javaToolName + " executable. Reason: " + e.getMessage(),
- e );
+ } catch (Exception e) {
+ throw new JavaToolException(
+ "Error finding " + javaToolName + " executable. Reason: " + e.getMessage(), e);
}
}
// creates the command line from the given request
- Commandline cli = createCommandLine( request, javaToolFile );
+ Commandline cli = createCommandLine(request, javaToolFile);
// execute it
- JavaToolResult result = executeCommandLine( cli, request );
+ JavaToolResult result = executeCommandLine(cli, request);
// return result
return result;
@@ -136,19 +123,15 @@ public abstract class AbstractJavaTool<Request extends JavaToolRequest>
/**
* @return {@link InputStream}
*/
- protected InputStream createSystemInputStream()
- {
- InputStream systemIn = new InputStream()
- {
+ protected InputStream createSystemInputStream() {
+ InputStream systemIn = new InputStream() {
/**
* {@inheritDoc}
*/
- public int read()
- {
+ public int read() {
return -1;
}
-
};
return systemIn;
}
@@ -158,32 +141,27 @@ public abstract class AbstractJavaTool<Request extends JavaToolRequest>
* @param request The request.
* @return {@link JavaToolRequest}
*/
- protected JavaToolResult executeCommandLine( Commandline cli, Request request )
- {
- if ( getLogger().isDebugEnabled() )
- {
- getLogger().debug( "Executing: " + cli );
+ protected JavaToolResult executeCommandLine(Commandline cli, Request request) {
+ if (getLogger().isDebugEnabled()) {
+ getLogger().debug("Executing: " + cli);
}
JavaToolResult result = createResult();
- result.setCommandline( cli );
+ result.setCommandline(cli);
InputStream systemIn = createSystemInputStream();
- StreamConsumer systemOut = createSystemOutStreamConsumer( request );
+ StreamConsumer systemOut = createSystemOutStreamConsumer(request);
- StreamConsumer systemErr = createSystemErrorStreamConsumer( request );
+ StreamConsumer systemErr = createSystemErrorStreamConsumer(request);
- try
- {
- int resultCode = CommandLineUtils.executeCommandLine( cli, systemIn, systemOut, systemErr );
+ try {
+ int resultCode = CommandLineUtils.executeCommandLine(cli, systemIn, systemOut, systemErr);
- result.setExitCode( resultCode );
- }
- catch ( CommandLineException e )
- {
- result.setExecutionException( e );
+ result.setExitCode(resultCode);
+ } catch (CommandLineException e) {
+ result.setExecutionException(e);
}
return result;
@@ -193,24 +171,19 @@ public abstract class AbstractJavaTool<Request extends JavaToolRequest>
* @param request The request.
* @return {@link StreamConsumer}
*/
- protected StreamConsumer createSystemErrorStreamConsumer( Request request )
- {
+ protected StreamConsumer createSystemErrorStreamConsumer(Request request) {
StreamConsumer systemErr = request.getSystemErrorStreamConsumer();
- if ( systemErr == null )
- {
- systemErr = new StreamConsumer()
- {
+ if (systemErr == null) {
+ systemErr = new StreamConsumer() {
/**
* {@inheritDoc}
*/
@Override
- public void consumeLine( final String line )
- {
- getLogger().warn( line );
+ public void consumeLine(final String line) {
+ getLogger().warn(line);
}
-
};
}
return systemErr;
@@ -220,26 +193,20 @@ public abstract class AbstractJavaTool<Request extends JavaToolRequest>
* @param request The request.
* @return {@link StreamConsumer}
*/
- protected StreamConsumer createSystemOutStreamConsumer( Request request )
- {
+ protected StreamConsumer createSystemOutStreamConsumer(Request request) {
StreamConsumer systemOut = request.getSystemOutStreamConsumer();
- if ( systemOut == null )
- {
+ if (systemOut == null) {
- systemOut = new StreamConsumer()
- {
+ systemOut = new StreamConsumer() {
/**
* {@inheritDoc}
*/
@Override
- public void consumeLine( final String line )
- {
- getLogger().info( line );
-
+ public void consumeLine(final String line) {
+ getLogger().info(line);
}
-
};
}
return systemOut;
@@ -248,49 +215,41 @@ public abstract class AbstractJavaTool<Request extends JavaToolRequest>
/**
* @return The JavaToolResult.
*/
- protected JavaToolResult createResult()
- {
+ protected JavaToolResult createResult() {
return new JavaToolResult();
}
/**
* @return The location of the java tool executable.
*/
- protected String findJavaToolExecutable()
- {
+ protected String findJavaToolExecutable() {
String executable = null;
- if ( toolchain != null )
- {
+ if (toolchain != null) {
executable = findToolchainExecutable();
}
- String command = javaToolName + ( Os.isFamily( Os.FAMILY_WINDOWS ) ? ".exe" : "" );
+ String command = javaToolName + (Os.isFamily(Os.FAMILY_WINDOWS) ? ".exe" : "");
- if ( executable == null )
- {
- executable = findExecutable( command, System.getProperty( "java.home" ), "../bin", "bin", "../sh" );
+ if (executable == null) {
+ executable = findExecutable(command, System.getProperty("java.home"), "../bin", "bin", "../sh");
}
- if ( executable == null )
- {
+ if (executable == null) {
Map<String, String> env = System.getenv();
- String[] variables = { "JDK_HOME", "JAVA_HOME" };
+ String[] variables = {"JDK_HOME", "JAVA_HOME"};
- for ( String variable : variables )
- {
- executable = findExecutable( command, env.get( variable ), "bin", "sh" );
- if ( executable != null )
- {
+ for (String variable : variables) {
+ executable = findExecutable(command, env.get(variable), "bin", "sh");
+ if (executable != null) {
break;
}
}
}
- if ( executable == null )
- {
+ if (executable == null) {
executable = command;
}
@@ -301,37 +260,25 @@ public abstract class AbstractJavaTool<Request extends JavaToolRequest>
* Run toolchain.findTool( javaToolName ); through reflection to avoid compile dependency on
* Maven core.
*/
- private String findToolchainExecutable()
- {
- try
- {
- Method m = toolchain.getClass().getMethod( "findTool", String.class );
- return (String) m.invoke( toolchain, javaToolName );
- }
- catch ( NoSuchMethodException e )
- {
+ private String findToolchainExecutable() {
+ try {
+ Method m = toolchain.getClass().getMethod("findTool", String.class);
+ return (String) m.invoke(toolchain, javaToolName);
+ } catch (NoSuchMethodException e) {
// should not happen if toolchain is really a Toolchain object
- getLogger().warn( "unexpected NoSuchMethodException", e );
- }
- catch ( SecurityException e )
- {
+ getLogger().warn("unexpected NoSuchMethodException", e);
+ } catch (SecurityException e) {
// should not happen
- getLogger().warn( "unexpected SecurityException", e );
- }
- catch ( IllegalAccessException e )
- {
+ getLogger().warn("unexpected SecurityException", e);
+ } catch (IllegalAccessException e) {
// should not happen
- getLogger().warn( "unexpected IllegalAccessException", e );
- }
- catch ( IllegalArgumentException e )
- {
+ getLogger().warn("unexpected IllegalAccessException", e);
+ } catch (IllegalArgumentException e) {
// should not happen: parameter is the right type
- getLogger().warn( "unexpected IllegalArgumentException", e );
- }
- catch ( InvocationTargetException e )
- {
+ getLogger().warn("unexpected IllegalArgumentException", e);
+ } catch (InvocationTargetException e) {
// not expected...
- getLogger().warn( "unexpected InvocationTargetException", e );
+ getLogger().warn("unexpected InvocationTargetException", e);
}
return null;
}
@@ -344,17 +291,13 @@ public abstract class AbstractJavaTool<Request extends JavaToolRequest>
* @param subDirs The sub directories of the home directory to search in, must not be <code>null</code>.
* @return The (absolute) path to the command if found, <code>null</code> otherwise.
*/
- private String findExecutable( String command, String homeDir, String... subDirs )
- {
+ private String findExecutable(String command, String homeDir, String... subDirs) {
String result = null;
- if ( StringUtils.isNotEmpty( homeDir ) )
- {
- for ( String subDir : subDirs )
- {
- File file = new File( new File( homeDir, subDir ), command );
-
- if ( file.isFile() )
- {
+ if (StringUtils.isNotEmpty(homeDir)) {
+ for (String subDir : subDirs) {
+ File file = new File(new File(homeDir, subDir), command);
+
+ if (file.isFile()) {
result = file.getAbsolutePath();
break;
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java
index 597041b..e2bcce3 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli.javatool;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli.javatool;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli.javatool;
import org.apache.maven.shared.utils.cli.StreamConsumer;
@@ -27,9 +26,7 @@ import org.apache.maven.shared.utils.cli.StreamConsumer;
* @author <a href="mailto:chemit@codelutin.com">Tony Chemit</a>
* @since 0.5
*/
-public class AbstractJavaToolRequest
- implements JavaToolRequest
-{
+public class AbstractJavaToolRequest implements JavaToolRequest {
/**
* Optional system out stream consumer used by the commandline execution.
@@ -44,32 +41,28 @@ public class AbstractJavaToolRequest
/**
* {@inheritDoc}
*/
- public StreamConsumer getSystemOutStreamConsumer()
- {
+ public StreamConsumer getSystemOutStreamConsumer() {
return systemOutStreamConsumer;
}
/**
* {@inheritDoc}
*/
- public StreamConsumer getSystemErrorStreamConsumer()
- {
+ public StreamConsumer getSystemErrorStreamConsumer() {
return systemErrorStreamConsumer;
}
/**
* {@inheritDoc}
*/
- public void setSystemOutStreamConsumer( StreamConsumer systemOutStreamConsumer )
- {
+ public void setSystemOutStreamConsumer(StreamConsumer systemOutStreamConsumer) {
this.systemOutStreamConsumer = systemOutStreamConsumer;
}
/**
* {@inheritDoc}
*/
- public void setSystemErrorStreamConsumer( StreamConsumer systemErrorStreamConsumer )
- {
+ public void setSystemErrorStreamConsumer(StreamConsumer systemErrorStreamConsumer) {
this.systemErrorStreamConsumer = systemErrorStreamConsumer;
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java
index 78b0170..dd3ba02 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli.javatool;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli.javatool;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli.javatool;
/**
* <p>Describes a java tool, means a executable available in the jdk.</p>
@@ -30,8 +29,7 @@ package org.apache.maven.shared.utils.cli.javatool;
* @since 0.5
* @param <Request> Tool-specific request type
*/
-public interface JavaTool<Request extends JavaToolRequest>
-{
+public interface JavaTool<Request extends JavaToolRequest> {
/**
* <p>Return the name of the java tool. This is exactly the name (without his extension) of the executable to
@@ -49,7 +47,7 @@ public interface JavaTool<Request extends JavaToolRequest>
* To avoid direct dependency on Maven core, this parameter is an Object that will be
* used as Toolchain through reflection
*/
- void setToolchain( Object toolchain );
+ void setToolchain(Object toolchain);
/**
* <p>Execute the input request and then returns the result of the execution.</p>
@@ -62,6 +60,5 @@ public interface JavaTool<Request extends JavaToolRequest>
* @return the result of the tool execution
* @throws JavaToolException if could not create the java tool invocation
*/
- JavaToolResult execute( Request request )
- throws JavaToolException;
+ JavaToolResult execute(Request request) throws JavaToolException;
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java
index fb9d694..ee3465d 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli.javatool;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli.javatool;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli.javatool;
/**
* <p>Signals an error during the construction of the command line used to invoke java tool, e.g. illegal invocation
@@ -30,25 +29,21 @@ package org.apache.maven.shared.utils.cli.javatool;
* @see JavaToolResult#getExitCode()
* @since 0.5
*/
-public class JavaToolException
- extends Exception
-{
+public class JavaToolException extends Exception {
private static final long serialVersionUID = 1L;
/**
* @param message The message of the exception.
*/
- public JavaToolException( String message )
- {
- super( message );
+ public JavaToolException(String message) {
+ super(message);
}
/**
* @param message The message of the exception.
* @param cause The cause of the exception.
*/
- public JavaToolException( String message, Throwable cause )
- {
- super( message, cause );
+ public JavaToolException(String message, Throwable cause) {
+ super(message, cause);
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java
index 6ad86b1..4dc7787 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli.javatool;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli.javatool;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli.javatool;
import org.apache.maven.shared.utils.cli.StreamConsumer;
@@ -27,8 +26,7 @@ import org.apache.maven.shared.utils.cli.StreamConsumer;
* @author <a href="mailto:chemit@codelutin.com">Tony Chemit</a>
* @since 0.5
*/
-public interface JavaToolRequest
-{
+public interface JavaToolRequest {
/**
* <p>Gets the value of the {@code systemOutStreamConsumer} field.</p>
@@ -53,12 +51,12 @@ public interface JavaToolRequest
*
* @param systemOutStreamConsumer the new value of the field {@code systemOutStreamConsumer}.
*/
- void setSystemOutStreamConsumer( StreamConsumer systemOutStreamConsumer );
+ void setSystemOutStreamConsumer(StreamConsumer systemOutStreamConsumer);
/**
* Sets the new given value to the field {@code systemErrorStreamConsumer} of the request.
*
* @param systemErrorStreamConsumer the new value of the field {@code systemErrorStreamConsumer}.
*/
- void setSystemErrorStreamConsumer( StreamConsumer systemErrorStreamConsumer );
+ void setSystemErrorStreamConsumer(StreamConsumer systemErrorStreamConsumer);
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java
index deb830e..49ccd03 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli.javatool;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli.javatool;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli.javatool;
import org.apache.maven.shared.utils.cli.CommandLineException;
import org.apache.maven.shared.utils.cli.Commandline;
@@ -28,8 +27,7 @@ import org.apache.maven.shared.utils.cli.Commandline;
* @author <a href="mailto:chemit@codelutin.com">Tony Chemit</a>
* @since 0.5
*/
-public class JavaToolResult
-{
+public class JavaToolResult {
/**
* The exception that prevented to execute the command line, will be <code>null</code> if jarSigner could be
* successfully started.
@@ -52,8 +50,7 @@ public class JavaToolResult
*
* @return The exit code from the tool invocation.
*/
- public int getExitCode()
- {
+ public int getExitCode() {
return exitCode;
}
@@ -62,8 +59,7 @@ public class JavaToolResult
*
* @return The command line used
*/
- public Commandline getCommandline()
- {
+ public Commandline getCommandline() {
return commandline;
}
@@ -73,8 +69,7 @@ public class JavaToolResult
* @return The exception that prevented to invoke tool or <code>null</code> if the command line was successfully
* processed by the operating system.
*/
- public CommandLineException getExecutionException()
- {
+ public CommandLineException getExecutionException() {
return executionException;
}
@@ -83,8 +78,7 @@ public class JavaToolResult
*
* @param exitCode The exit code reported by the tool invocation.
*/
- public void setExitCode( int exitCode )
- {
+ public void setExitCode(int exitCode) {
this.exitCode = exitCode;
}
@@ -93,8 +87,7 @@ public class JavaToolResult
*
* @param executionException The exception that prevented to execute the command line, may be <code>null</code>.
*/
- public void setExecutionException( CommandLineException executionException )
- {
+ public void setExecutionException(CommandLineException executionException) {
this.executionException = executionException;
}
@@ -103,8 +96,7 @@ public class JavaToolResult
*
* @param commandline the commandline used to obtain this result
*/
- public void setCommandline( Commandline commandline )
- {
+ public void setCommandline(Commandline commandline) {
this.commandline = commandline;
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java
index f04864e..0825bb4 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli.shell;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,76 +16,67 @@ package org.apache.maven.shared.utils.cli.shell;
* specific language governing permissions and limitations
* under the License.
*/
-
+package org.apache.maven.shared.utils.cli.shell;
import java.util.ArrayList;
import java.util.List;
+
import org.apache.maven.shared.utils.Os;
/**
* @author Jason van Zyl
*/
-public class BourneShell
- extends Shell
-{
+public class BourneShell extends Shell {
/**
* Create instance of BourneShell.
*/
- public BourneShell()
- {
- setUnconditionalQuoting( true );
- setShellCommand( "/bin/sh" );
- setArgumentQuoteDelimiter( '\'' );
- setExecutableQuoteDelimiter( '\'' );
- setSingleQuotedArgumentEscaped( true );
- setSingleQuotedExecutableEscaped( false );
- setQuotedExecutableEnabled( true );
+ public BourneShell() {
+ setUnconditionalQuoting(true);
+ setShellCommand("/bin/sh");
+ setArgumentQuoteDelimiter('\'');
+ setExecutableQuoteDelimiter('\'');
+ setSingleQuotedArgumentEscaped(true);
+ setSingleQuotedExecutableEscaped(false);
+ setQuotedExecutableEnabled(true);
}
/**
* {@inheritDoc}
*/
- public String getExecutable()
- {
- if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
- {
+ public String getExecutable() {
+ if (Os.isFamily(Os.FAMILY_WINDOWS)) {
return super.getExecutable();
}
- return quoteOneItem( super.getExecutable(), true );
+ return quoteOneItem(super.getExecutable(), true);
}
/** {@inheritDoc} */
- public List<String> getShellArgsList()
- {
+ public List<String> getShellArgsList() {
List<String> shellArgs = new ArrayList<String>();
List<String> existingShellArgs = super.getShellArgsList();
- if ( ( existingShellArgs != null ) && !existingShellArgs.isEmpty() )
- {
- shellArgs.addAll( existingShellArgs );
+ if ((existingShellArgs != null) && !existingShellArgs.isEmpty()) {
+ shellArgs.addAll(existingShellArgs);
}
- shellArgs.add( "-c" );
+ shellArgs.add("-c");
return shellArgs;
}
/** {@inheritDoc} */
- public String[] getShellArgs()
- {
+ public String[] getShellArgs() {
String[] shellArgs = super.getShellArgs();
- if ( shellArgs == null )
- {
+ if (shellArgs == null) {
shellArgs = new String[0];
}
- if ( ( shellArgs.length > 0 ) && !shellArgs[shellArgs.length - 1].equals( "-c" ) )
- {
+ if ((shellArgs.length > 0) && !shellArgs[shellArgs.length - 1].equals("-c")) {
String[] newArgs = new String[shellArgs.length + 1];
- System.arraycopy( shellArgs, 0, newArgs, 0, shellArgs.length );
+ System.arraycopy(shellArgs, 0, newArgs, 0, shellArgs.length);
newArgs[shellArgs.length] = "-c";
shellArgs = newArgs;
@@ -97,16 +86,14 @@ public class BourneShell
}
/** {@inheritDoc} */
- protected String getExecutionPreamble()
- {
- if ( getWorkingDirectoryAsString() == null )
- {
+ protected String getExecutionPreamble() {
+ if (getWorkingDirectoryAsString() == null) {
return null;
}
String dir = getWorkingDirectoryAsString();
- return "cd " + quoteOneItem( dir, false ) + " && ";
+ return "cd " + quoteOneItem(dir, false) + " && ";
}
/**
@@ -125,13 +112,11 @@ public class BourneShell
* @param path not null path.
* @return the path unified correctly for the Bourne shell.
*/
- protected String quoteOneItem( String path, boolean isExecutable )
- {
- if ( path == null )
- {
+ protected String quoteOneItem(String path, boolean isExecutable) {
+ if (path == null) {
return null;
}
- return "'" + path.replace( "'", "'\"'\"'" ) + "'";
+ return "'" + path.replace("'", "'\"'\"'") + "'";
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java
index 06b7df7..3d72e32 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli.shell;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.cli.shell;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.cli.shell;
import java.util.Arrays;
import java.util.List;
@@ -26,19 +25,16 @@ import java.util.List;
* Implementation to call the CMD Shell present on Windows NT, 2000, XP, 7, 8, and 10.
*
* @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a>
- *
+ *
*/
-public class CmdShell
- extends Shell
-{
+public class CmdShell extends Shell {
/**
* Create an instance of CmdShell.
*/
- public CmdShell()
- {
- setShellCommand( "cmd.exe" );
- setQuotedExecutableEnabled( true );
- setShellArgs( new String[]{ "/X", "/C" } );
+ public CmdShell() {
+ setShellCommand("cmd.exe");
+ setQuotedExecutableEnabled(true);
+ setShellArgs(new String[] {"/X", "/C"});
}
/**
@@ -77,19 +73,17 @@ public class CmdShell
* Always quoting the entire command line, regardless of these conditions
* appears to make Windows processes invoke successfully.
* </p>
- *
+ *
* @param executable The executable.
* @param arguments The arguments for the executable.
* @return The resulting command line.
*/
- public List<String> getCommandLine( String executable, String... arguments )
- {
+ public List<String> getCommandLine(String executable, String... arguments) {
StringBuilder sb = new StringBuilder();
- sb.append( '"' );
- sb.append( super.getCommandLine( executable, arguments ).get( 0 ) );
- sb.append( '"' );
+ sb.append('"');
+ sb.append(super.getCommandLine(executable, arguments).get(0));
+ sb.append('"');
- return Arrays.asList( sb.toString() );
+ return Arrays.asList(sb.toString());
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java
index ba85633..f1b5cd4 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli.shell;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,7 +16,7 @@ package org.apache.maven.shared.utils.cli.shell;
* specific language governing permissions and limitations
* under the License.
*/
-
+package org.apache.maven.shared.utils.cli.shell;
/**
* Implementation to call the Command.com Shell present on Windows 95, 98 and Me
@@ -27,16 +25,12 @@ package org.apache.maven.shared.utils.cli.shell;
* @deprecated Windows ME is long dead. Update to Windows 10 and use {@link CmdShell}.
*/
@Deprecated
-public class CommandShell
- extends Shell
-{
+public class CommandShell extends Shell {
/**
* Create an instance.
*/
- public CommandShell()
- {
- setShellCommand( "command.com" );
- setShellArgs( new String[]{ "/C" } );
+ public CommandShell() {
+ setShellCommand("command.com");
+ setShellArgs(new String[] {"/C"});
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java
index 47ec0da..c8208af 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.cli.shell;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,30 +16,29 @@ package org.apache.maven.shared.utils.cli.shell;
* specific language governing permissions and limitations
* under the License.
*/
-
+package org.apache.maven.shared.utils.cli.shell;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+
import org.apache.maven.shared.utils.StringUtils;
/**
* Class that abstracts the Shell functionality,
* with subclasses for shells that behave particularly, like
- *
+ *
* <ul>
* <li><code>command.com</code></li>
* <li><code>cmd.exe</code></li>
* </ul>
*
* @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a>
- *
+ *
*/
-public class Shell
- implements Cloneable
-{
- private static final char[] DEFAULT_QUOTING_TRIGGER_CHARS = { ' ' };
+public class Shell implements Cloneable {
+ private static final char[] DEFAULT_QUOTING_TRIGGER_CHARS = {' '};
private String shellCommand;
@@ -70,8 +67,7 @@ public class Shell
*
* @param shellCommand the command
*/
- void setShellCommand( String shellCommand )
- {
+ void setShellCommand(String shellCommand) {
this.shellCommand = shellCommand;
}
@@ -80,8 +76,7 @@ public class Shell
*
* @return the command
*/
- String getShellCommand()
- {
+ String getShellCommand() {
return shellCommand;
}
@@ -91,10 +86,9 @@ public class Shell
*
* @param shellArgs the arguments to the shell
*/
- void setShellArgs( String[] shellArgs )
- {
+ void setShellArgs(String[] shellArgs) {
this.shellArgs.clear();
- this.shellArgs.addAll( Arrays.asList( shellArgs ) );
+ this.shellArgs.addAll(Arrays.asList(shellArgs));
}
/**
@@ -102,29 +96,23 @@ public class Shell
*
* @return the arguments
*/
- String[] getShellArgs()
- {
- if ( shellArgs.isEmpty() )
- {
+ String[] getShellArgs() {
+ if (shellArgs.isEmpty()) {
return null;
- }
- else
- {
- return shellArgs.toArray( new String[0] );
+ } else {
+ return shellArgs.toArray(new String[0]);
}
}
- protected String quoteOneItem( String inputString, boolean isExecutable )
- {
- char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() );
+ protected String quoteOneItem(String inputString, boolean isExecutable) {
+ char[] escapeChars = getEscapeChars(isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped());
return StringUtils.quoteAndEscape(
inputString,
isExecutable ? getExecutableQuoteDelimiter() : getArgumentQuoteDelimiter(),
escapeChars,
getQuotingTriggerChars(),
'\\',
- unconditionalQuoting
- );
+ unconditionalQuoting);
}
/**
@@ -134,9 +122,8 @@ public class Shell
* @param argumentsParameter arguments for the executable, not the shell
* @return list with one String object with executable and arguments quoted as needed
*/
- List<String> getCommandLine( String executableParameter, String... argumentsParameter )
- {
- return getRawCommandLine( executableParameter, argumentsParameter );
+ List<String> getCommandLine(String executableParameter, String... argumentsParameter) {
+ return getRawCommandLine(executableParameter, argumentsParameter);
}
/**
@@ -144,128 +131,104 @@ public class Shell
* @param argumentsParameter the arguments for the executable
* @return the list on command line
*/
- List<String> getRawCommandLine( String executableParameter, String... argumentsParameter )
- {
+ List<String> getRawCommandLine(String executableParameter, String... argumentsParameter) {
List<String> commandLine = new ArrayList<>();
StringBuilder sb = new StringBuilder();
- if ( executableParameter != null )
- {
+ if (executableParameter != null) {
String preamble = getExecutionPreamble();
- if ( preamble != null )
- {
- sb.append( preamble );
+ if (preamble != null) {
+ sb.append(preamble);
}
- if ( isQuotedExecutableEnabled() )
- {
- sb.append( quoteOneItem( executableParameter, true ) );
- }
- else
- {
- sb.append( executableParameter );
+ if (isQuotedExecutableEnabled()) {
+ sb.append(quoteOneItem(executableParameter, true));
+ } else {
+ sb.append(executableParameter);
}
}
- for ( String argument : argumentsParameter )
- {
- if ( sb.length() > 0 )
- {
- sb.append( ' ' );
+ for (String argument : argumentsParameter) {
+ if (sb.length() > 0) {
+ sb.append(' ');
}
- if ( isQuotedArgumentsEnabled() )
- {
- sb.append( quoteOneItem( argument, false ) );
- }
- else
- {
- sb.append( argument );
+ if (isQuotedArgumentsEnabled()) {
+ sb.append(quoteOneItem(argument, false));
+ } else {
+ sb.append(argument);
}
}
- commandLine.add( sb.toString() );
+ commandLine.add(sb.toString());
return commandLine;
}
- char[] getQuotingTriggerChars()
- {
+ char[] getQuotingTriggerChars() {
return DEFAULT_QUOTING_TRIGGER_CHARS;
}
- String getExecutionPreamble()
- {
+ String getExecutionPreamble() {
return null;
}
- char[] getEscapeChars( boolean includeSingleQuote, boolean includeDoubleQuote )
- {
- StringBuilder buf = new StringBuilder( 2 );
- if ( includeSingleQuote )
- {
- buf.append( '\'' );
+ char[] getEscapeChars(boolean includeSingleQuote, boolean includeDoubleQuote) {
+ StringBuilder buf = new StringBuilder(2);
+ if (includeSingleQuote) {
+ buf.append('\'');
}
- if ( includeDoubleQuote )
- {
- buf.append( '\"' );
+ if (includeDoubleQuote) {
+ buf.append('\"');
}
char[] result = new char[buf.length()];
- buf.getChars( 0, buf.length(), result, 0 );
+ buf.getChars(0, buf.length(), result, 0);
return result;
}
/**
- * @return false in all cases
+ * @return false in all cases
*/
- protected boolean isDoubleQuotedArgumentEscaped()
- {
+ protected boolean isDoubleQuotedArgumentEscaped() {
return false;
}
/**
* @return {@link #singleQuotedArgumentEscaped}
*/
- protected boolean isSingleQuotedArgumentEscaped()
- {
+ protected boolean isSingleQuotedArgumentEscaped() {
return singleQuotedArgumentEscaped;
}
- boolean isDoubleQuotedExecutableEscaped()
- {
+ boolean isDoubleQuotedExecutableEscaped() {
return false;
}
- boolean isSingleQuotedExecutableEscaped()
- {
+ boolean isSingleQuotedExecutableEscaped() {
return singleQuotedExecutableEscaped;
}
/**
* @param argQuoteDelimiterParameter {@link #argQuoteDelimiter}
*/
- void setArgumentQuoteDelimiter( char argQuoteDelimiterParameter )
- {
+ void setArgumentQuoteDelimiter(char argQuoteDelimiterParameter) {
this.argQuoteDelimiter = argQuoteDelimiterParameter;
}
- char getArgumentQuoteDelimiter()
- {
+ char getArgumentQuoteDelimiter() {
return argQuoteDelimiter;
}
/**
* @param exeQuoteDelimiterParameter {@link #exeQuoteDelimiter}
*/
- void setExecutableQuoteDelimiter( char exeQuoteDelimiterParameter )
- {
+ void setExecutableQuoteDelimiter(char exeQuoteDelimiterParameter) {
this.exeQuoteDelimiter = exeQuoteDelimiterParameter;
}
- char getExecutableQuoteDelimiter()
- {
+ char getExecutableQuoteDelimiter() {
return exeQuoteDelimiter;
}
@@ -277,52 +240,43 @@ public class Shell
* @return List of String objects, whose array version is suitable to be used as argument
* of Runtime.getRuntime().exec()
*/
- public List<String> getShellCommandLine( String... arguments )
- {
+ public List<String> getShellCommandLine(String... arguments) {
List<String> commandLine = new ArrayList<>();
- if ( getShellCommand() != null )
- {
- commandLine.add( getShellCommand() );
+ if (getShellCommand() != null) {
+ commandLine.add(getShellCommand());
}
- if ( getShellArgs() != null )
- {
- commandLine.addAll( getShellArgsList() );
+ if (getShellArgs() != null) {
+ commandLine.addAll(getShellArgsList());
}
- commandLine.addAll( getCommandLine( executable, arguments ) );
+ commandLine.addAll(getCommandLine(executable, arguments));
return commandLine;
-
}
- List<String> getShellArgsList()
- {
+ List<String> getShellArgsList() {
return shellArgs;
}
/**
* @param quotedArgumentsEnabled {@link #quotedArgumentsEnabled}
*/
- public void setQuotedArgumentsEnabled( boolean quotedArgumentsEnabled )
- {
+ public void setQuotedArgumentsEnabled(boolean quotedArgumentsEnabled) {
this.quotedArgumentsEnabled = quotedArgumentsEnabled;
}
- boolean isQuotedArgumentsEnabled()
- {
+ boolean isQuotedArgumentsEnabled() {
return quotedArgumentsEnabled;
}
- void setQuotedExecutableEnabled( boolean quotedExecutableEnabled )
- {
+ void setQuotedExecutableEnabled(boolean quotedExecutableEnabled) {
this.quotedExecutableEnabled = quotedExecutableEnabled;
}
- boolean isQuotedExecutableEnabled()
- {
+ boolean isQuotedExecutableEnabled() {
return quotedExecutableEnabled;
}
@@ -330,20 +284,17 @@ public class Shell
* Sets the executable to run.
* @param executable The executable.
*/
- public void setExecutable( String executable )
- {
- if ( ( executable == null ) || ( executable.length() == 0 ) )
- {
+ public void setExecutable(String executable) {
+ if ((executable == null) || (executable.length() == 0)) {
return;
}
- this.executable = executable.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar );
+ this.executable = executable.replace('/', File.separatorChar).replace('\\', File.separatorChar);
}
/**
* @return The executable.
*/
- public String getExecutable()
- {
+ public String getExecutable() {
return executable;
}
@@ -351,23 +302,19 @@ public class Shell
* Sets execution directory.
* @param path The path which should be used as working directory.
*/
- public void setWorkingDirectory( String path )
- {
- if ( path != null )
- {
+ public void setWorkingDirectory(String path) {
+ if (path != null) {
this.workingDir = path;
}
}
/**
* Sets execution directory.
- *
+ *
* @param workingDirectory the working directory
*/
- public void setWorkingDirectory( File workingDirectory )
- {
- if ( workingDirectory != null )
- {
+ public void setWorkingDirectory(File workingDirectory) {
+ if (workingDirectory != null) {
this.workingDir = workingDirectory.getAbsolutePath();
}
}
@@ -375,44 +322,37 @@ public class Shell
/**
* @return the working directory
*/
- public File getWorkingDirectory()
- {
- return workingDir == null ? null : new File( workingDir );
+ public File getWorkingDirectory() {
+ return workingDir == null ? null : new File(workingDir);
}
- String getWorkingDirectoryAsString()
- {
+ String getWorkingDirectoryAsString() {
return workingDir;
}
/** {@inheritDoc} */
- public Object clone()
- {
- throw new RuntimeException( "Do we ever clone this?" );
-/* Shell shell = new Shell();
+ public Object clone() {
+ throw new RuntimeException("Do we ever clone this?");
+ /* Shell shell = new Shell();
shell.setExecutable( getExecutable() );
shell.setWorkingDirectory( getWorkingDirectory() );
shell.setShellArgs( getShellArgs() );
return shell;*/
}
- void setSingleQuotedArgumentEscaped( boolean singleQuotedArgumentEscaped )
- {
+ void setSingleQuotedArgumentEscaped(boolean singleQuotedArgumentEscaped) {
this.singleQuotedArgumentEscaped = singleQuotedArgumentEscaped;
}
- void setSingleQuotedExecutableEscaped( boolean singleQuotedExecutableEscaped )
- {
+ void setSingleQuotedExecutableEscaped(boolean singleQuotedExecutableEscaped) {
this.singleQuotedExecutableEscaped = singleQuotedExecutableEscaped;
}
- public boolean isUnconditionalQuoting()
- {
+ public boolean isUnconditionalQuoting() {
return unconditionalQuoting;
}
- public void setUnconditionalQuoting( boolean unconditionalQuoting )
- {
+ public void setUnconditionalQuoting(boolean unconditionalQuoting) {
this.unconditionalQuoting = unconditionalQuoting;
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java b/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java
index 357eab4..17f2593 100644
--- a/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java
+++ b/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.introspection;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@ package org.apache.maven.shared.utils.introspection;
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.introspection;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.introspection;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
@@ -35,11 +34,8 @@ import java.util.Map;
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
*
*/
-public class ClassMap
-{
- private static final class CacheMiss
- {
- }
+public class ClassMap {
+ private static final class CacheMiss {}
private static final CacheMiss CACHE_MISS = new CacheMiss();
@@ -49,7 +45,6 @@ public class ClassMap
* Class passed into the constructor used to as
* the basis for the Method map.
*/
-
private final Class<?> clazz;
/**
@@ -64,8 +59,7 @@ public class ClassMap
* Standard constructor
* @param clazz The class.
*/
- public ClassMap( Class<?> clazz )
- {
+ public ClassMap(Class<?> clazz) {
this.clazz = clazz;
populateMethodCache();
}
@@ -73,8 +67,7 @@ public class ClassMap
/**
* @return the class object whose methods are cached by this map.
*/
- Class<?> getCachedClass()
- {
+ Class<?> getCachedClass() {
return clazz;
}
@@ -91,41 +84,31 @@ public class ClassMap
* @return The found method.
* @throws MethodMap.AmbiguousException in case of duplicate methods.
*/
- public Method findMethod( String name, Object... params )
- throws MethodMap.AmbiguousException
- {
- String methodKey = makeMethodKey( name, params );
- Object cacheEntry = methodCache.get( methodKey );
-
- if ( cacheEntry == CACHE_MISS )
- {
+ public Method findMethod(String name, Object... params) throws MethodMap.AmbiguousException {
+ String methodKey = makeMethodKey(name, params);
+ Object cacheEntry = methodCache.get(methodKey);
+
+ if (cacheEntry == CACHE_MISS) {
return null;
}
- if ( cacheEntry == null )
- {
- try
- {
- cacheEntry = methodMap.find( name, params );
- }
- catch ( MethodMap.AmbiguousException ae )
- {
+ if (cacheEntry == null) {
+ try {
+ cacheEntry = methodMap.find(name, params);
+ } catch (MethodMap.AmbiguousException ae) {
/*
* that's a miss :)
*/
- methodCache.put( methodKey, CACHE_MISS );
+ methodCache.put(methodKey, CACHE_MISS);
throw ae;
}
- if ( cacheEntry == null )
- {
- methodCache.put( methodKey, CACHE_MISS );
- }
- else
- {
- methodCache.put( methodKey, cacheEntry );
+ if (cacheEntry == null) {
+ methodCache.put(methodKey, CACHE_MISS);
+ } else {
+ methodCache.put(methodKey, cacheEntry);
}
}
@@ -139,28 +122,26 @@ public class ClassMap
* are taken from all the public methods
* that our class provides.
*/
- private void populateMethodCache()
- {
+ private void populateMethodCache() {
/*
* get all publicly accessible methods
*/
- Method[] methods = getAccessibleMethods( clazz );
+ Method[] methods = getAccessibleMethods(clazz);
/*
* map and cache them
*/
- for ( Method method : methods )
- {
+ for (Method method : methods) {
/*
* now get the 'public method', the method declared by a
* public interface or class. (because the actual implementing
* class may be a facade...
*/
- Method publicMethod = getPublicMethod( method );
+ Method publicMethod = getPublicMethod(method);
/*
* it is entirely possible that there is no public method for
@@ -169,10 +150,9 @@ public class ClassMap
* in which case, ignore it. Otherwise, map and cache
*/
- if ( publicMethod != null )
- {
- methodMap.add( publicMethod );
- methodCache.put( makeMethodKey( publicMethod ), publicMethod );
+ if (publicMethod != null) {
+ methodMap.add(publicMethod);
+ methodCache.put(makeMethodKey(publicMethod), publicMethod);
}
}
}
@@ -182,78 +162,55 @@ public class ClassMap
* the concatenation of the name and the
* types of the method parameters.
*/
- private String makeMethodKey( Method method )
- {
+ private String makeMethodKey(Method method) {
Class<?>[] parameterTypes = method.getParameterTypes();
- StringBuilder methodKey = new StringBuilder( method.getName() );
+ StringBuilder methodKey = new StringBuilder(method.getName());
- for ( Class<?> parameterType : parameterTypes )
- {
+ for (Class<?> parameterType : parameterTypes) {
/*
* If the argument type is primitive then we want
* to convert our primitive type signature to the
* corresponding Object type so introspection for
* methods with primitive types will work correctly.
*/
- if ( parameterType.isPrimitive() )
- {
- if ( parameterType.equals( Boolean.TYPE ) )
- {
- methodKey.append( "java.lang.Boolean" );
- }
- else if ( parameterType.equals( Byte.TYPE ) )
- {
- methodKey.append( "java.lang.Byte" );
+ if (parameterType.isPrimitive()) {
+ if (parameterType.equals(Boolean.TYPE)) {
+ methodKey.append("java.lang.Boolean");
+ } else if (parameterType.equals(Byte.TYPE)) {
+ methodKey.append("java.lang.Byte");
+ } else if (parameterType.equals(Character.TYPE)) {
+ methodKey.append("java.lang.Character");
+ } else if (parameterType.equals(Double.TYPE)) {
+ methodKey.append("java.lang.Double");
+ } else if (parameterType.equals(Float.TYPE)) {
+ methodKey.append("java.lang.Float");
+ } else if (parameterType.equals(Integer.TYPE)) {
+ methodKey.append("java.lang.Integer");
+ } else if (parameterType.equals(Long.TYPE)) {
+ methodKey.append("java.lang.Long");
+ } else if (parameterType.equals(Short.TYPE)) {
+ methodKey.append("java.lang.Short");
}
- else if ( parameterType.equals( Character.TYPE ) )
- {
- methodKey.append( "java.lang.Character" );
- }
- else if ( parameterType.equals( Double.TYPE ) )
- {
- methodKey.append( "java.lang.Double" );
- }
- else if ( parameterType.equals( Float.TYPE ) )
- {
- methodKey.append( "java.lang.Float" );
- }
- else if ( parameterType.equals( Integer.TYPE ) )
- {
- methodKey.append( "java.lang.Integer" );
- }
- else if ( parameterType.equals( Long.TYPE ) )
- {
- methodKey.append( "java.lang.Long" );
- }
- else if ( parameterType.equals( Short.TYPE ) )
- {
- methodKey.append( "java.lang.Short" );
- }
- }
- else
- {
- methodKey.append( parameterType.getName() );
+ } else {
+ methodKey.append(parameterType.getName());
}
}
return methodKey.toString();
}
- private static String makeMethodKey( String method, Object... params )
- {
- StringBuilder methodKey = new StringBuilder().append( method );
+ private static String makeMethodKey(String method, Object... params) {
+ StringBuilder methodKey = new StringBuilder().append(method);
- for ( Object param : params )
- {
+ for (Object param : params) {
Object arg = param;
- if ( arg == null )
- {
+ if (arg == null) {
arg = OBJECT;
}
- methodKey.append( arg.getClass().getName() );
+ methodKey.append(arg.getClass().getName());
}
return methodKey.toString();
@@ -265,8 +222,7 @@ public class ClassMap
* from public superclasses and interfaces (if they exist). Basically
* upcasts every method to the nearest acccessible method.
*/
- private static Method[] getAccessibleMethods( Class<?> clazz )
- {
+ private static Method[] getAccessibleMethods(Class<?> clazz) {
Method[] methods = clazz.getMethods();
/*
@@ -274,8 +230,7 @@ public class ClassMap
* clazz is public
*/
- if ( Modifier.isPublic( clazz.getModifiers() ) )
- {
+ if (Modifier.isPublic(clazz.getModifiers())) {
return methods;
}
@@ -285,27 +240,23 @@ public class ClassMap
MethodInfo[] methodInfos = new MethodInfo[methods.length];
- for ( int i = methods.length; i-- > 0; )
- {
- methodInfos[i] = new MethodInfo( methods[i] );
+ for (int i = methods.length; i-- > 0; ) {
+ methodInfos[i] = new MethodInfo(methods[i]);
}
- int upcastCount = getAccessibleMethods( clazz, methodInfos, 0 );
+ int upcastCount = getAccessibleMethods(clazz, methodInfos, 0);
/*
* Reallocate array in case some method had no accessible counterpart.
*/
- if ( upcastCount < methods.length )
- {
+ if (upcastCount < methods.length) {
methods = new Method[upcastCount];
}
int j = 0;
- for ( MethodInfo methodInfo : methodInfos )
- {
- if ( methodInfo.upcast )
- {
+ for (MethodInfo methodInfo : methodInfos) {
+ if (methodInfo.upcast) {
methods[j++] = methodInfo.method;
}
}
@@ -321,8 +272,7 @@ public class ClassMap
* @param upcastCount current number of methods we have matched
* @return count of matched methods
*/
- private static int getAccessibleMethods( Class<?> clazz, MethodInfo[] methodInfos, int upcastCount )
- {
+ private static int getAccessibleMethods(Class<?> clazz, MethodInfo[] methodInfos, int upcastCount) {
int l = methodInfos.length;
/*
@@ -330,22 +280,16 @@ public class ClassMap
* 'non-upcasted' methods to see if we have a match
*/
- if ( Modifier.isPublic( clazz.getModifiers() ) )
- {
- for ( int i = 0; i < l && upcastCount < l; ++i )
- {
- try
- {
+ if (Modifier.isPublic(clazz.getModifiers())) {
+ for (int i = 0; i < l && upcastCount < l; ++i) {
+ try {
MethodInfo methodInfo = methodInfos[i];
- if ( !methodInfo.upcast )
- {
- methodInfo.tryUpcasting( clazz );
+ if (!methodInfo.upcast) {
+ methodInfo.tryUpcasting(clazz);
upcastCount++;
}
- }
- catch ( NoSuchMethodException e )
- {
+ } catch (NoSuchMethodException e) {
/*
* Intentionally ignored - it means
* it wasn't found in the current class
@@ -357,8 +301,7 @@ public class ClassMap
* Short circuit if all methods were upcast
*/
- if ( upcastCount == l )
- {
+ if (upcastCount == l) {
return upcastCount;
}
}
@@ -369,16 +312,14 @@ public class ClassMap
Class<?> superclazz = clazz.getSuperclass();
- if ( superclazz != null )
- {
- upcastCount = getAccessibleMethods( superclazz, methodInfos, upcastCount );
+ if (superclazz != null) {
+ upcastCount = getAccessibleMethods(superclazz, methodInfos, upcastCount);
/*
* Short circuit if all methods were upcast
*/
- if ( upcastCount == l )
- {
+ if (upcastCount == l) {
return upcastCount;
}
}
@@ -391,16 +332,14 @@ public class ClassMap
Class<?>[] interfaces = clazz.getInterfaces();
- for ( int i = interfaces.length; i-- > 0; )
- {
- upcastCount = getAccessibleMethods( interfaces[i], methodInfos, upcastCount );
+ for (int i = interfaces.length; i-- > 0; ) {
+ upcastCount = getAccessibleMethods(interfaces[i], methodInfos, upcastCount);
/*
* Short circuit if all methods were upcast
*/
- if ( upcastCount == l )
- {
+ if (upcastCount == l) {
return upcastCount;
}
}
@@ -419,8 +358,7 @@ public class ClassMap
* method is itself declared by a public class, this method is an identity
* function.
*/
- private static Method getPublicMethod( Method method )
- {
+ private static Method getPublicMethod(Method method) {
Class<?> clazz = method.getDeclaringClass();
/*
@@ -428,12 +366,11 @@ public class ClassMap
* class is public.
*/
- if ( ( clazz.getModifiers() & Modifier.PUBLIC ) != 0 )
- {
+ if ((clazz.getModifiers() & Modifier.PUBLIC) != 0) {
return method;
}
- return getPublicMethod( clazz, method.getName(), method.getParameterTypes() );
+ return getPublicMethod(clazz, method.getName(), method.getParameterTypes());
}
/**
@@ -444,20 +381,15 @@ public class ClassMap
* @param name the name of the method
* @param paramTypes the classes of method parameters
*/
- private static Method getPublicMethod( Class<?> clazz, String name, Class<?>... paramTypes )
- {
+ private static Method getPublicMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
/*
* if this class is public, then try to get it
*/
- if ( ( clazz.getModifiers() & Modifier.PUBLIC ) != 0 )
- {
- try
- {
- return clazz.getMethod( name, paramTypes );
- }
- catch ( NoSuchMethodException e )
- {
+ if ((clazz.getModifiers() & Modifier.PUBLIC) != 0) {
+ try {
+ return clazz.getMethod(name, paramTypes);
+ } catch (NoSuchMethodException e) {
/*
* If the class does not have the method, then neither its
* superclass nor any of its interfaces has it so quickly return
@@ -473,12 +405,10 @@ public class ClassMap
Class<?> superclazz = clazz.getSuperclass();
- if ( superclazz != null )
- {
- Method superclazzMethod = getPublicMethod( superclazz, name, paramTypes );
+ if (superclazz != null) {
+ Method superclazzMethod = getPublicMethod(superclazz, name, paramTypes);
- if ( superclazzMethod != null )
- {
+ if (superclazzMethod != null) {
return superclazzMethod;
}
}
@@ -489,12 +419,10 @@ public class ClassMap
Class<?>[] interfaces = clazz.getInterfaces();
- for ( Class<?> anInterface : interfaces )
- {
- Method interfaceMethod = getPublicMethod( anInterface, name, paramTypes );
+ for (Class<?> anInterface : interfaces) {
+ Method interfaceMethod = getPublicMethod(anInterface, name, paramTypes);
- if ( interfaceMethod != null )
- {
+ if (interfaceMethod != null) {
return interfaceMethod;
}
}
@@ -505,8 +433,7 @@ public class ClassMap
/**
* Used for the iterative discovery process for public methods.
*/
- private static final class MethodInfo
- {
+ private static final class MethodInfo {
Method method;
String name;
@@ -515,18 +442,15 @@ public class ClassMap
boolean upcast;
- MethodInfo( Method method )
- {
+ MethodInfo(Method method) {
this.method = null;
name = method.getName();
parameterTypes = method.getParameterTypes();
upcast = false;
}
- void tryUpcasting( Class<?> clazz )
- throws NoSuchMethodException
- {
- method = clazz.getMethod( name, parameterTypes );
+ void tryUpcasting(Class<?> clazz) throws NoSuchMethodException {
+ method = clazz.getMethod(name, parameterTypes);
name = null;
parameterTypes = null;
upcast = true;
diff --git a/src/main/java/org/apache/maven/shared/utils/introspection/IntrospectionException.java b/src/main/java/org/apache/maven/shared/utils/introspection/IntrospectionException.java
index 924137c..bf751cc 100644
--- a/src/main/java/org/apache/maven/shared/utils/introspection/IntrospectionException.java
+++ b/src/main/java/org/apache/maven/shared/utils/introspection/IntrospectionException.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.introspection;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@ package org.apache.maven.shared.utils.introspection;
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,24 +16,20 @@ package org.apache.maven.shared.utils.introspection;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.introspection;
-class IntrospectionException
- extends Exception
-{
+class IntrospectionException extends Exception {
/**
- *
+ *
*/
private static final long serialVersionUID = -6090771282553728784L;
- IntrospectionException( String message )
- {
- super( message );
+ IntrospectionException(String message) {
+ super(message);
}
- IntrospectionException( Throwable cause )
- {
- super( cause );
+ IntrospectionException(Throwable cause) {
+ super(cause);
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/introspection/MethodMap.java b/src/main/java/org/apache/maven/shared/utils/introspection/MethodMap.java
index 8cf80f8..edafdfb 100644
--- a/src/main/java/org/apache/maven/shared/utils/introspection/MethodMap.java
+++ b/src/main/java/org/apache/maven/shared/utils/introspection/MethodMap.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.introspection;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@ package org.apache.maven.shared.utils.introspection;
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,6 +16,7 @@ package org.apache.maven.shared.utils.introspection;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.introspection;
import java.lang.reflect.Method;
import java.util.ArrayList;
@@ -35,8 +34,7 @@ import java.util.Map;
* @author <a href="mailto:szegedia@freemail.hu">Attila Szegedi</a>
*
*/
-class MethodMap
-{
+class MethodMap {
private static final int MORE_SPECIFIC = 0;
private static final int LESS_SPECIFIC = 1;
@@ -55,19 +53,17 @@ class MethodMap
*
* @param method The method
*/
- void add( Method method )
- {
+ void add(Method method) {
String methodName = method.getName();
- List<Method> l = get( methodName );
+ List<Method> l = get(methodName);
- if ( l == null )
- {
+ if (l == null) {
l = new ArrayList<Method>();
- methodByNameMap.put( methodName, l );
+ methodByNameMap.put(methodName, l);
}
- l.add( method );
+ l.add(method);
}
/**
@@ -76,9 +72,8 @@ class MethodMap
* @param key The name of the method.
* @return List list of methods
*/
- List<Method> get( String key )
- {
- return methodByNameMap.get( key );
+ List<Method> get(String key) {
+ return methodByNameMap.get(key);
}
/**
@@ -109,21 +104,17 @@ class MethodMap
* @throws AmbiguousException if there is more than one maximally
* specific applicable method
*/
- Method find( String methodName, Object... args )
- throws AmbiguousException
- {
- List<Method> methodList = get( methodName );
+ Method find(String methodName, Object... args) throws AmbiguousException {
+ List<Method> methodList = get(methodName);
- if ( methodList == null )
- {
+ if (methodList == null) {
return null;
}
int l = args.length;
Class<?>[] classes = new Class[l];
- for ( int i = 0; i < l; ++i )
- {
+ for (int i = 0; i < l; ++i) {
Object arg = args[i];
/*
@@ -133,33 +124,26 @@ class MethodMap
classes[i] = arg == null ? null : arg.getClass();
}
- return getMostSpecific( methodList, classes );
+ return getMostSpecific(methodList, classes);
}
/**
* simple distinguishable exception, used when
* we run across ambiguous overloading
*/
- static class AmbiguousException
- extends Exception
- {
+ static class AmbiguousException extends Exception {
private static final long serialVersionUID = 751688436639650618L;
}
+ private static Method getMostSpecific(List<Method> methods, Class<?>... classes) throws AmbiguousException {
+ LinkedList<Method> applicables = getApplicables(methods, classes);
- private static Method getMostSpecific( List<Method> methods, Class<?>... classes )
- throws AmbiguousException
- {
- LinkedList<Method> applicables = getApplicables( methods, classes );
-
- if ( applicables.isEmpty() )
- {
+ if (applicables.isEmpty()) {
return null;
}
- if ( applicables.size() == 1 )
- {
+ if (applicables.size() == 1) {
return applicables.getFirst();
}
@@ -171,17 +155,14 @@ class MethodMap
LinkedList<Method> maximals = new LinkedList<Method>();
- for ( Method app : applicables )
- {
+ for (Method app : applicables) {
Class<?>[] appArgs = app.getParameterTypes();
boolean lessSpecific = false;
- for ( Iterator<Method> maximal = maximals.iterator(); !lessSpecific && maximal.hasNext(); )
- {
+ for (Iterator<Method> maximal = maximals.iterator(); !lessSpecific && maximal.hasNext(); ) {
Method max = maximal.next();
- switch ( moreSpecific( appArgs, max.getParameterTypes() ) )
- {
+ switch (moreSpecific(appArgs, max.getParameterTypes())) {
case MORE_SPECIFIC:
/*
* This method is more specific than the previously
@@ -206,14 +187,12 @@ class MethodMap
}
}
- if ( !lessSpecific )
- {
- maximals.addLast( app );
+ if (!lessSpecific) {
+ maximals.addLast(app);
}
}
- if ( maximals.size() > 1 )
- {
+ if (maximals.size() > 1) {
// We have more than one maximally specific method
throw new AmbiguousException();
}
@@ -230,24 +209,19 @@ class MethodMap
* @return MORE_SPECIFIC if c1 is more specific than c2, LESS_SPECIFIC if
* c1 is less specific than c2, INCOMPARABLE if they are incomparable.
*/
- private static int moreSpecific( Class<?>[] c1, Class<?>[] c2 )
- {
+ private static int moreSpecific(Class<?>[] c1, Class<?>[] c2) {
boolean c1MoreSpecific = false;
boolean c2MoreSpecific = false;
- for ( int i = 0; i < c1.length; ++i )
- {
- if ( c1[i] != c2[i] )
- {
- c1MoreSpecific = c1MoreSpecific || isStrictMethodInvocationConvertible( c2[i], c1[i] );
- c2MoreSpecific = c2MoreSpecific || isStrictMethodInvocationConvertible( c1[i], c2[i] );
+ for (int i = 0; i < c1.length; ++i) {
+ if (c1[i] != c2[i]) {
+ c1MoreSpecific = c1MoreSpecific || isStrictMethodInvocationConvertible(c2[i], c1[i]);
+ c2MoreSpecific = c2MoreSpecific || isStrictMethodInvocationConvertible(c1[i], c2[i]);
}
}
- if ( c1MoreSpecific )
- {
- if ( c2MoreSpecific )
- {
+ if (c1MoreSpecific) {
+ if (c2MoreSpecific) {
/*
* Incomparable due to cross-assignable arguments (i.e.
* foo(String, Object) vs. foo(Object, String))
@@ -259,8 +233,7 @@ class MethodMap
return MORE_SPECIFIC;
}
- if ( c2MoreSpecific )
- {
+ if (c2MoreSpecific) {
return LESS_SPECIFIC;
}
@@ -281,15 +254,12 @@ class MethodMap
* formal and actual arguments matches, and argument types are assignable
* to formal types through a method invocation conversion).
*/
- private static LinkedList<Method> getApplicables( List<Method> methods, Class<?>... classes )
- {
+ private static LinkedList<Method> getApplicables(List<Method> methods, Class<?>... classes) {
LinkedList<Method> list = new LinkedList<Method>();
- for ( Method method : methods )
- {
- if ( isApplicable( method, classes ) )
- {
- list.add( method );
+ for (Method method : methods) {
+ if (isApplicable(method, classes)) {
+ list.add(method);
}
}
return list;
@@ -303,19 +273,15 @@ class MethodMap
* @param classes The arguments
* @return true if the method applies to the parameter types
*/
- private static boolean isApplicable( Method method, Class<?>... classes )
- {
+ private static boolean isApplicable(Method method, Class<?>... classes) {
Class<?>[] methodArgs = method.getParameterTypes();
- if ( methodArgs.length != classes.length )
- {
+ if (methodArgs.length != classes.length) {
return false;
}
- for ( int i = 0; i < classes.length; ++i )
- {
- if ( !isMethodInvocationConvertible( methodArgs[i], classes[i] ) )
- {
+ for (int i = 0; i < classes.length; ++i) {
+ if (!isMethodInvocationConvertible(methodArgs[i], classes[i])) {
return false;
}
}
@@ -341,13 +307,11 @@ class MethodMap
* type or an object type of a primitive type that can be converted to
* the formal type.
*/
- private static boolean isMethodInvocationConvertible( Class<?> formal, Class<?> actual )
- {
+ private static boolean isMethodInvocationConvertible(Class<?> formal, Class<?> actual) {
/*
* if it's a null, it means the arg was null
*/
- if ( actual == null && !formal.isPrimitive() )
- {
+ if (actual == null && !formal.isPrimitive()) {
return true;
}
@@ -355,8 +319,7 @@ class MethodMap
* Check for identity or widening reference conversion
*/
- if ( actual != null && formal.isAssignableFrom( actual ) )
- {
+ if (actual != null && formal.isAssignableFrom(actual)) {
return true;
}
@@ -365,45 +328,44 @@ class MethodMap
* actual parameters are never primitives.
*/
- if ( formal.isPrimitive() )
- {
- if ( formal == Boolean.TYPE && actual == Boolean.class )
- {
+ if (formal.isPrimitive()) {
+ if (formal == Boolean.TYPE && actual == Boolean.class) {
return true;
}
- if ( formal == Character.TYPE && actual == Character.class )
- {
+ if (formal == Character.TYPE && actual == Character.class) {
return true;
}
- if ( formal == Byte.TYPE && actual == Byte.class )
- {
+ if (formal == Byte.TYPE && actual == Byte.class) {
return true;
}
- if ( formal == Short.TYPE && ( actual == Short.class || actual == Byte.class ) )
- {
+ if (formal == Short.TYPE && (actual == Short.class || actual == Byte.class)) {
return true;
}
- if ( formal == Integer.TYPE
- && ( actual == Integer.class || actual == Short.class || actual == Byte.class ) )
- {
+ if (formal == Integer.TYPE && (actual == Integer.class || actual == Short.class || actual == Byte.class)) {
return true;
}
- if ( formal == Long.TYPE
- && ( actual == Long.class || actual == Integer.class || actual == Short.class
- || actual == Byte.class ) )
- {
+ if (formal == Long.TYPE
+ && (actual == Long.class
+ || actual == Integer.class
+ || actual == Short.class
+ || actual == Byte.class)) {
return true;
}
- if ( formal == Float.TYPE
- && ( actual == Float.class || actual == Long.class || actual == Integer.class
- || actual == Short.class || actual == Byte.class ) )
- {
+ if (formal == Float.TYPE
+ && (actual == Float.class
+ || actual == Long.class
+ || actual == Integer.class
+ || actual == Short.class
+ || actual == Byte.class)) {
return true;
}
- if ( formal == Double.TYPE
- && ( actual == Double.class || actual == Float.class || actual == Long.class || actual == Integer.class
- || actual == Short.class || actual == Byte.class ) )
- {
+ if (formal == Double.TYPE
+ && (actual == Double.class
+ || actual == Float.class
+ || actual == Long.class
+ || actual == Integer.class
+ || actual == Short.class
+ || actual == Byte.class)) {
return true;
}
}
@@ -425,13 +387,11 @@ class MethodMap
* or formal and actual are both primitive types and actual can be
* subject to widening conversion to formal.
*/
- private static boolean isStrictMethodInvocationConvertible( Class<?> formal, Class<?> actual )
- {
+ private static boolean isStrictMethodInvocationConvertible(Class<?> formal, Class<?> actual) {
/*
* we shouldn't get a null into, but if so
*/
- if ( actual == null && !formal.isPrimitive() )
- {
+ if (actual == null && !formal.isPrimitive()) {
return true;
}
@@ -439,8 +399,7 @@ class MethodMap
* Check for identity or widening reference conversion
*/
- if ( formal.isAssignableFrom( actual ) )
- {
+ if (formal.isAssignableFrom(actual)) {
return true;
}
@@ -448,29 +407,26 @@ class MethodMap
* Check for widening primitive conversion.
*/
- if ( formal.isPrimitive() )
- {
- if ( formal == Short.TYPE && ( actual == Byte.TYPE ) )
- {
+ if (formal.isPrimitive()) {
+ if (formal == Short.TYPE && (actual == Byte.TYPE)) {
return true;
}
- if ( formal == Integer.TYPE && ( actual == Short.TYPE || actual == Byte.TYPE ) )
- {
+ if (formal == Integer.TYPE && (actual == Short.TYPE || actual == Byte.TYPE)) {
return true;
}
- if ( formal == Long.TYPE && ( actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE ) )
- {
+ if (formal == Long.TYPE && (actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE)) {
return true;
}
- if ( formal == Float.TYPE
- && ( actual == Long.TYPE || actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE ) )
- {
+ if (formal == Float.TYPE
+ && (actual == Long.TYPE || actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE)) {
return true;
}
- if ( formal == Double.TYPE
- && ( actual == Float.TYPE || actual == Long.TYPE || actual == Integer.TYPE || actual == Short.TYPE
- || actual == Byte.TYPE ) )
- {
+ if (formal == Double.TYPE
+ && (actual == Float.TYPE
+ || actual == Long.TYPE
+ || actual == Integer.TYPE
+ || actual == Short.TYPE
+ || actual == Byte.TYPE)) {
return true;
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java b/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java
index cf007cc..7e21277 100644
--- a/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java
+++ b/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.introspection;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@ package org.apache.maven.shared.utils.introspection;
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,6 +16,10 @@ package org.apache.maven.shared.utils.introspection;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.introspection;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
@@ -29,10 +31,6 @@ import java.util.WeakHashMap;
import org.apache.maven.shared.utils.StringUtils;
import org.apache.maven.shared.utils.introspection.MethodMap.AmbiguousException;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
-
/**
* <p>Using simple dotted expressions to extract the values from an Object instance,
* For example we might want to extract a value like: <code>project.build.sourceDirectory</code></p>
@@ -44,8 +42,7 @@ import javax.annotation.Nullable;
* @see <a href="http://struts.apache.org/1.x/struts-taglib/indexedprops.html">
* http://struts.apache.org/1.x/struts-taglib/indexedprops.html</a>
*/
-public class ReflectionValueExtractor
-{
+public class ReflectionValueExtractor {
private static final Class<?>[] CLASS_ARGS = new Class[0];
private static final Object[] OBJECT_ARGS = new Object[0];
@@ -69,79 +66,65 @@ public class ReflectionValueExtractor
static final char MAPPED_END = ')';
- static class Tokenizer
- {
+ static class Tokenizer {
final String expression;
int idx;
- Tokenizer( String expression )
- {
+ Tokenizer(String expression) {
this.expression = expression;
}
- public int peekChar()
- {
- return idx < expression.length() ? expression.charAt( idx ) : EOF;
+ public int peekChar() {
+ return idx < expression.length() ? expression.charAt(idx) : EOF;
}
- public int skipChar()
- {
- return idx < expression.length() ? expression.charAt( idx++ ) : EOF;
+ public int skipChar() {
+ return idx < expression.length() ? expression.charAt(idx++) : EOF;
}
- public String nextToken( char delimiter )
- {
+ public String nextToken(char delimiter) {
int start = idx;
- while ( idx < expression.length() && delimiter != expression.charAt( idx ) )
- {
+ while (idx < expression.length() && delimiter != expression.charAt(idx)) {
idx++;
}
// delimiter MUST be present
- if ( idx <= start || idx >= expression.length() )
- {
+ if (idx <= start || idx >= expression.length()) {
return null;
}
- return expression.substring( start, idx++ );
+ return expression.substring(start, idx++);
}
- public String nextPropertyName()
- {
+ public String nextPropertyName() {
final int start = idx;
- while ( idx < expression.length() && Character.isJavaIdentifierPart( expression.charAt( idx ) ) )
- {
+ while (idx < expression.length() && Character.isJavaIdentifierPart(expression.charAt(idx))) {
idx++;
}
// property name does not require delimiter
- if ( idx <= start || idx > expression.length() )
- {
+ if (idx <= start || idx > expression.length()) {
return null;
}
- return expression.substring( start, idx );
+ return expression.substring(start, idx);
}
- public int getPosition()
- {
+ public int getPosition() {
return idx < expression.length() ? idx : EOF;
}
// to make tokenizer look pretty in debugger
@Override
- public String toString()
- {
- return idx < expression.length() ? expression.substring( idx ) : "<EOF>";
+ public String toString() {
+ return idx < expression.length() ? expression.substring(idx) : "<EOF>";
}
}
- private ReflectionValueExtractor()
- {
- }
+ private ReflectionValueExtractor() {}
/**
* <p>The implementation supports indexed, nested and mapped properties.</p>
@@ -158,10 +141,8 @@ public class ReflectionValueExtractor
* @return the object defined by the expression
* @throws IntrospectionException if any
*/
- public static Object evaluate( @Nonnull String expression, @Nullable Object root )
- throws IntrospectionException
- {
- return evaluate( expression, root, true );
+ public static Object evaluate(@Nonnull String expression, @Nullable Object root) throws IntrospectionException {
+ return evaluate(expression, root, true);
}
/**
@@ -182,9 +163,8 @@ public class ReflectionValueExtractor
* @return the object defined by the expression
* @throws IntrospectionException if any
*/
- public static Object evaluate( @Nonnull String expression, @Nullable Object root, boolean trimRootToken )
- throws IntrospectionException
- {
+ public static Object evaluate(@Nonnull String expression, @Nullable Object root, boolean trimRootToken)
+ throws IntrospectionException {
Object value = root;
// ----------------------------------------------------------------------
@@ -192,46 +172,45 @@ public class ReflectionValueExtractor
// MavenProject instance.
// ----------------------------------------------------------------------
- if ( StringUtils.isEmpty( expression ) || !Character.isJavaIdentifierStart( expression.charAt( 0 ) ) )
- {
+ if (StringUtils.isEmpty(expression) || !Character.isJavaIdentifierStart(expression.charAt(0))) {
return null;
}
- boolean hasDots = expression.indexOf( PROPERTY_START ) >= 0;
+ boolean hasDots = expression.indexOf(PROPERTY_START) >= 0;
final Tokenizer tokenizer;
- if ( trimRootToken && hasDots )
- {
- tokenizer = new Tokenizer( expression );
+ if (trimRootToken && hasDots) {
+ tokenizer = new Tokenizer(expression);
tokenizer.nextPropertyName();
- if ( tokenizer.getPosition() == EOF )
- {
+ if (tokenizer.getPosition() == EOF) {
return null;
}
- }
- else
- {
- tokenizer = new Tokenizer( "." + expression );
+ } else {
+ tokenizer = new Tokenizer("." + expression);
}
int propertyPosition = tokenizer.getPosition();
- while ( value != null && tokenizer.peekChar() != EOF )
- {
- switch ( tokenizer.skipChar() )
- {
+ while (value != null && tokenizer.peekChar() != EOF) {
+ switch (tokenizer.skipChar()) {
case INDEXED_START:
- value =
- getIndexedValue( expression, propertyPosition, tokenizer.getPosition(), value,
- tokenizer.nextToken( INDEXED_END ) );
+ value = getIndexedValue(
+ expression,
+ propertyPosition,
+ tokenizer.getPosition(),
+ value,
+ tokenizer.nextToken(INDEXED_END));
break;
case MAPPED_START:
- value =
- getMappedValue( expression, propertyPosition, tokenizer.getPosition(), value,
- tokenizer.nextToken( MAPPED_END ) );
+ value = getMappedValue(
+ expression,
+ propertyPosition,
+ tokenizer.getPosition(),
+ value,
+ tokenizer.nextToken(MAPPED_END));
break;
case PROPERTY_START:
propertyPosition = tokenizer.getPosition();
- value = getPropertyValue( value, tokenizer.nextPropertyName() );
+ value = getPropertyValue(value, tokenizer.nextPropertyName());
break;
default:
// could not parse expression
@@ -242,155 +221,118 @@ public class ReflectionValueExtractor
return value;
}
- private static Object getMappedValue( final String expression, final int from, final int to, final Object value,
- final String key )
- throws IntrospectionException
- {
- if ( value == null || key == null )
- {
+ private static Object getMappedValue(
+ final String expression, final int from, final int to, final Object value, final String key)
+ throws IntrospectionException {
+ if (value == null || key == null) {
return null;
}
- if ( value instanceof Map )
- {
- Object[] localParams = new Object[] { key };
- ClassMap classMap = getClassMap( value.getClass() );
- try
- {
- Method method = classMap.findMethod( "get", localParams );
- return method.invoke( value, localParams );
+ if (value instanceof Map) {
+ Object[] localParams = new Object[] {key};
+ ClassMap classMap = getClassMap(value.getClass());
+ try {
+ Method method = classMap.findMethod("get", localParams);
+ return method.invoke(value, localParams);
+ } catch (AmbiguousException e) {
+ throw new IntrospectionException(e);
+ } catch (IllegalAccessException e) {
+ throw new IntrospectionException(e);
+ } catch (InvocationTargetException e) {
+ throw new IntrospectionException(e.getTargetException());
}
- catch ( AmbiguousException e )
- {
- throw new IntrospectionException( e );
- }
- catch ( IllegalAccessException e )
- {
- throw new IntrospectionException( e );
- }
- catch ( InvocationTargetException e )
- {
- throw new IntrospectionException( e.getTargetException() );
- }
-
}
- final String message =
- String.format( "The token '%s' at position '%d' refers to a java.util.Map, but the value "
- + "seems is an instance of '%s'", expression.subSequence( from, to ), from, value.getClass() );
+ final String message = String.format(
+ "The token '%s' at position '%d' refers to a java.util.Map, but the value "
+ + "seems is an instance of '%s'",
+ expression.subSequence(from, to), from, value.getClass());
- throw new IntrospectionException( message );
+ throw new IntrospectionException(message);
}
- private static Object getIndexedValue( final String expression, final int from, final int to, final Object value,
- final String indexStr )
- throws IntrospectionException
- {
- try
- {
- int index = Integer.parseInt( indexStr );
-
- if ( value.getClass().isArray() )
- {
- return Array.get( value, index );
+ private static Object getIndexedValue(
+ final String expression, final int from, final int to, final Object value, final String indexStr)
+ throws IntrospectionException {
+ try {
+ int index = Integer.parseInt(indexStr);
+
+ if (value.getClass().isArray()) {
+ return Array.get(value, index);
}
- if ( value instanceof List )
- {
- ClassMap classMap = getClassMap( value.getClass() );
+ if (value instanceof List) {
+ ClassMap classMap = getClassMap(value.getClass());
// use get method on List interface
- Object[] localParams = new Object[] { index };
+ Object[] localParams = new Object[] {index};
Method method = null;
- try
- {
- method = classMap.findMethod( "get", localParams );
- return method.invoke( value, localParams );
- }
- catch ( AmbiguousException e )
- {
- throw new IntrospectionException( e );
- }
- catch ( IllegalAccessException e )
- {
- throw new IntrospectionException( e );
+ try {
+ method = classMap.findMethod("get", localParams);
+ return method.invoke(value, localParams);
+ } catch (AmbiguousException e) {
+ throw new IntrospectionException(e);
+ } catch (IllegalAccessException e) {
+ throw new IntrospectionException(e);
}
}
- }
- catch ( NumberFormatException e )
- {
+ } catch (NumberFormatException e) {
return null;
- }
- catch ( InvocationTargetException e )
- {
+ } catch (InvocationTargetException e) {
// catch array index issues gracefully, otherwise release
- if ( e.getCause() instanceof IndexOutOfBoundsException )
- {
+ if (e.getCause() instanceof IndexOutOfBoundsException) {
return null;
}
- throw new IntrospectionException( e.getTargetException() );
+ throw new IntrospectionException(e.getTargetException());
}
- final String message =
- String.format( "The token '%s' at position '%d' refers to a java.util.List or an array, but the value "
- + "seems is an instance of '%s'", expression.subSequence( from, to ), from, value.getClass() );
+ final String message = String.format(
+ "The token '%s' at position '%d' refers to a java.util.List or an array, but the value "
+ + "seems is an instance of '%s'",
+ expression.subSequence(from, to), from, value.getClass());
- throw new IntrospectionException( message );
+ throw new IntrospectionException(message);
}
- private static Object getPropertyValue( Object value, String property )
- throws IntrospectionException
- {
- if ( value == null || property == null )
- {
+ private static Object getPropertyValue(Object value, String property) throws IntrospectionException {
+ if (value == null || property == null) {
return null;
}
- ClassMap classMap = getClassMap( value.getClass() );
- String methodBase = StringUtils.capitalizeFirstLetter( property );
+ ClassMap classMap = getClassMap(value.getClass());
+ String methodBase = StringUtils.capitalizeFirstLetter(property);
String methodName = "get" + methodBase;
- try
- {
- Method method = classMap.findMethod( methodName, CLASS_ARGS );
+ try {
+ Method method = classMap.findMethod(methodName, CLASS_ARGS);
- if ( method == null )
- {
+ if (method == null) {
// perhaps this is a boolean property??
methodName = "is" + methodBase;
- method = classMap.findMethod( methodName, CLASS_ARGS );
+ method = classMap.findMethod(methodName, CLASS_ARGS);
}
- if ( method == null )
- {
+ if (method == null) {
return null;
}
- return method.invoke( value, OBJECT_ARGS );
- }
- catch ( InvocationTargetException e )
- {
- throw new IntrospectionException( e.getTargetException() );
- }
- catch ( AmbiguousException e )
- {
- throw new IntrospectionException( e );
- }
- catch ( IllegalAccessException e )
- {
- throw new IntrospectionException( e );
+ return method.invoke(value, OBJECT_ARGS);
+ } catch (InvocationTargetException e) {
+ throw new IntrospectionException(e.getTargetException());
+ } catch (AmbiguousException e) {
+ throw new IntrospectionException(e);
+ } catch (IllegalAccessException e) {
+ throw new IntrospectionException(e);
}
}
- private static ClassMap getClassMap( Class<?> clazz )
- {
- ClassMap classMap = CLASS_MAPS.get( clazz );
+ private static ClassMap getClassMap(Class<?> clazz) {
+ ClassMap classMap = CLASS_MAPS.get(clazz);
- if ( classMap == null )
- {
- classMap = new ClassMap( clazz );
+ if (classMap == null) {
+ classMap = new ClassMap(clazz);
- CLASS_MAPS.put( clazz, classMap );
+ CLASS_MAPS.put(clazz, classMap);
}
return classMap;
diff --git a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanResult.java b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanResult.java
index ae5de32..9e94739 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanResult.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanResult.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.io;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@ package org.apache.maven.shared.utils.io;
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,17 +16,16 @@ package org.apache.maven.shared.utils.io;
* specific language governing permissions and limitations
* under the License.
*/
-
+package org.apache.maven.shared.utils.io;
/**
* Scan for files in a directory at a given time and reports removed and added files
* between captures.
- *
+ *
* @deprecated use {@code java.nio.file.DirectoryStream} and related classes
*/
@Deprecated
-public class DirectoryScanResult
-{
+public class DirectoryScanResult {
private final String[] filesAdded;
private final String[] filesRemoved;
@@ -37,8 +34,7 @@ public class DirectoryScanResult
* @param filesAdded Added files.
* @param filesRemoved Removed files.
*/
- public DirectoryScanResult( String[] filesAdded, String[] filesRemoved )
- {
+ public DirectoryScanResult(String[] filesAdded, String[] filesRemoved) {
this.filesAdded = filesAdded;
this.filesRemoved = filesRemoved;
}
@@ -46,17 +42,14 @@ public class DirectoryScanResult
/**
* @return all files which got detected as being added between 2 capture calls
*/
- public String[] getFilesAdded()
- {
+ public String[] getFilesAdded() {
return filesAdded;
}
/**
* @return all files which got detected as being removed between 2 capture calls
*/
- public String[] getFilesRemoved()
- {
+ public String[] getFilesRemoved() {
return filesRemoved;
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java
index 468e226..0ecb865 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.io;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -18,6 +16,10 @@ package org.apache.maven.shared.utils.io;
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.io;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
@@ -28,9 +30,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
/**
* <p>Class for scanning a directory for files/directories which match certain criteria.</p>
* <p>
@@ -119,8 +118,7 @@ import javax.annotation.Nullable;
* @deprecated use {@code java.nio.file.DirectoryStream} and related classes
*/
@Deprecated
-public class DirectoryScanner
-{
+public class DirectoryScanner {
/**
* Patterns which should be excluded by default.
*
@@ -128,19 +126,28 @@ public class DirectoryScanner
*/
public static final String[] DEFAULTEXCLUDES = {
// Miscellaneous typical temporary files
- "**/*~", "**/#*#", "**/.#*", "**/%*%", "**/._*",
+ "**/*~",
+ "**/#*#",
+ "**/.#*",
+ "**/%*%",
+ "**/._*",
// CVS
- "**/CVS", "**/CVS/**", "**/.cvsignore",
+ "**/CVS",
+ "**/CVS/**",
+ "**/.cvsignore",
// Subversion
- "**/.svn", "**/.svn/**",
+ "**/.svn",
+ "**/.svn/**",
// Arch
- "**/.arch-ids", "**/.arch-ids/**",
+ "**/.arch-ids",
+ "**/.arch-ids/**",
// Bazaar
- "**/.bzr", "**/.bzr/**",
+ "**/.bzr",
+ "**/.bzr/**",
// SurroundSCM
"**/.MySCMServerInfo",
@@ -149,19 +156,31 @@ public class DirectoryScanner
"**/.DS_Store",
// Serena Dimensions Version 10
- "**/.metadata", "**/.metadata/**",
+ "**/.metadata",
+ "**/.metadata/**",
// Mercurial
- "**/.hg", "**/.hg/**",
+ "**/.hg",
+ "**/.hg/**",
// git
- "**/.git", "**/.git/**",
+ "**/.git",
+ "**/.git/**",
// BitKeeper
- "**/BitKeeper", "**/BitKeeper/**", "**/ChangeSet", "**/ChangeSet/**",
+ "**/BitKeeper",
+ "**/BitKeeper/**",
+ "**/ChangeSet",
+ "**/ChangeSet/**",
// darcs
- "**/_darcs", "**/_darcs/**", "**/.darcsrepo", "**/.darcsrepo/**", "**/-darcs-backup*", "**/.darcs-temp-mail" };
+ "**/_darcs",
+ "**/_darcs/**",
+ "**/.darcsrepo",
+ "**/.darcsrepo/**",
+ "**/-darcs-backup*",
+ "**/.darcs-temp-mail"
+ };
/**
* The base directory to be scanned.
@@ -182,7 +201,6 @@ public class DirectoryScanner
private MatchPatterns includesPatterns;
-
/**
* The files which matched at least one include and no excludes and were selected.
*/
@@ -226,11 +244,10 @@ public class DirectoryScanner
/**
* Whether or not symbolic links should be followed.
*
- *
+ *
*/
private boolean followSymlinks = true;
-
/**
* A {@link ScanConductor} an control the scanning process.
*/
@@ -244,9 +261,7 @@ public class DirectoryScanner
/**
* Sole constructor.
*/
- public DirectoryScanner()
- {
- }
+ public DirectoryScanner() {}
/**
* Sets the base directory to be scanned. This is the directory which is scanned recursively. All '/' and '\'
@@ -255,9 +270,8 @@ public class DirectoryScanner
*
* @param basedir The base directory to scan. Must not be <code>null</code>.
*/
- public void setBasedir( final String basedir )
- {
- setBasedir( new File( basedir.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ) ) );
+ public void setBasedir(final String basedir) {
+ setBasedir(new File(basedir.replace('/', File.separatorChar).replace('\\', File.separatorChar)));
}
/**
@@ -265,8 +279,7 @@ public class DirectoryScanner
*
* @param basedir The base directory for scanning. Should not be <code>null</code>.
*/
- public void setBasedir( @Nonnull final File basedir )
- {
+ public void setBasedir(@Nonnull final File basedir) {
this.basedir = basedir;
}
@@ -275,8 +288,7 @@ public class DirectoryScanner
*
* @return the base directory to be scanned
*/
- public File getBasedir()
- {
+ public File getBasedir() {
return basedir;
}
@@ -285,8 +297,7 @@ public class DirectoryScanner
*
* @param isCaseSensitiveParameter whether or not the file system should be regarded as a case sensitive one
*/
- public void setCaseSensitive( final boolean isCaseSensitiveParameter )
- {
+ public void setCaseSensitive(final boolean isCaseSensitiveParameter) {
this.isCaseSensitive = isCaseSensitiveParameter;
}
@@ -295,8 +306,7 @@ public class DirectoryScanner
*
* @param followSymlinks whether or not symbolic links should be followed
*/
- public void setFollowSymlinks( final boolean followSymlinks )
- {
+ public void setFollowSymlinks(final boolean followSymlinks) {
this.followSymlinks = followSymlinks;
}
@@ -310,25 +320,18 @@ public class DirectoryScanner
* @param includes A list of include patterns. May be <code>null</code>, indicating that all files should be
* included. If a non-<code>null</code> list is given, all elements must be non-<code>null</code>.
*/
- public void setIncludes( final String... includes )
- {
- if ( includes == null )
- {
+ public void setIncludes(final String... includes) {
+ if (includes == null) {
this.includes = null;
- }
- else
- {
+ } else {
this.includes = new String[includes.length];
- for ( int i = 0; i < includes.length; i++ )
- {
- if ( includes[i] == null )
- {
- throw new NullPointerException( messageForNullListElement( "includes" ) );
+ for (int i = 0; i < includes.length; i++) {
+ if (includes[i] == null) {
+ throw new NullPointerException(messageForNullListElement("includes"));
}
String pattern;
- pattern = includes[i].trim().replace( '/', File.separatorChar ).replace( '\\', File.separatorChar );
- if ( pattern.endsWith( File.separator ) )
- {
+ pattern = includes[i].trim().replace('/', File.separatorChar).replace('\\', File.separatorChar);
+ if (pattern.endsWith(File.separator)) {
pattern += "**";
}
this.includes[i] = pattern;
@@ -346,25 +349,18 @@ public class DirectoryScanner
* @param excludes A list of exclude patterns. May be <code>null</code>, indicating that no files should be
* excluded. If a non-<code>null</code> list is given, all elements must be non-<code>null</code>.
*/
- public void setExcludes( final String... excludes )
- {
- if ( excludes == null )
- {
+ public void setExcludes(final String... excludes) {
+ if (excludes == null) {
this.excludes = null;
- }
- else
- {
+ } else {
this.excludes = new String[excludes.length];
- for ( int i = 0; i < excludes.length; i++ )
- {
- if ( excludes[i] == null )
- {
- throw new NullPointerException( messageForNullListElement( "excludes" ) );
+ for (int i = 0; i < excludes.length; i++) {
+ if (excludes[i] == null) {
+ throw new NullPointerException(messageForNullListElement("excludes"));
}
String pattern;
- pattern = excludes[i].trim().replace( '/', File.separatorChar ).replace( '\\', File.separatorChar );
- if ( pattern.endsWith( File.separator ) )
- {
+ pattern = excludes[i].trim().replace('/', File.separatorChar).replace('\\', File.separatorChar);
+ if (pattern.endsWith(File.separator)) {
pattern += "**";
}
this.excludes[i] = pattern;
@@ -372,16 +368,14 @@ public class DirectoryScanner
}
}
- private static String messageForNullListElement( String listName )
- {
+ private static String messageForNullListElement(String listName) {
return "If a non-null " + listName + " list is given, all elements must be non-null";
}
/**
* @param scanConductor {@link #scanConductor}
*/
- public void setScanConductor( final ScanConductor scanConductor )
- {
+ public void setScanConductor(final ScanConductor scanConductor) {
this.scanConductor = scanConductor;
}
@@ -392,20 +386,15 @@ public class DirectoryScanner
* @throws IllegalStateException if the base directory was set incorrectly (i.e. if it is <code>null</code>,
* doesn't exist, or isn't a directory).
*/
- public void scan()
- throws IllegalStateException
- {
- if ( basedir == null )
- {
- throw new IllegalStateException( "No basedir set" );
+ public void scan() throws IllegalStateException {
+ if (basedir == null) {
+ throw new IllegalStateException("No basedir set");
}
- if ( !basedir.exists() )
- {
- throw new IllegalStateException( "basedir " + basedir + " does not exist" );
+ if (!basedir.exists()) {
+ throw new IllegalStateException("basedir " + basedir + " does not exist");
}
- if ( !basedir.isDirectory() )
- {
- throw new IllegalStateException( "basedir " + basedir + " is not a directory" );
+ if (!basedir.isDirectory()) {
+ throw new IllegalStateException("basedir " + basedir + " is not a directory");
}
setupDefaultFilters();
@@ -419,34 +408,26 @@ public class DirectoryScanner
dirsExcluded = new ArrayList<String>();
scanAction = ScanConductor.ScanAction.CONTINUE;
- if ( isIncluded( "" ) )
- {
- if ( !isExcluded( "" ) )
- {
- if ( scanConductor != null )
- {
- scanAction = scanConductor.visitDirectory( "", basedir );
-
- if ( ScanConductor.ScanAction.ABORT.equals( scanAction )
- || ScanConductor.ScanAction.ABORT_DIRECTORY.equals( scanAction )
- || ScanConductor.ScanAction.NO_RECURSE.equals( scanAction ) )
- {
+ if (isIncluded("")) {
+ if (!isExcluded("")) {
+ if (scanConductor != null) {
+ scanAction = scanConductor.visitDirectory("", basedir);
+
+ if (ScanConductor.ScanAction.ABORT.equals(scanAction)
+ || ScanConductor.ScanAction.ABORT_DIRECTORY.equals(scanAction)
+ || ScanConductor.ScanAction.NO_RECURSE.equals(scanAction)) {
return;
}
}
- dirsIncluded.add( "" );
+ dirsIncluded.add("");
+ } else {
+ dirsExcluded.add("");
}
- else
- {
- dirsExcluded.add( "" );
- }
- }
- else
- {
- dirsNotIncluded.add( "" );
+ } else {
+ dirsNotIncluded.add("");
}
- scandir( basedir, "", true );
+ scandir(basedir, "", true);
}
/**
@@ -467,15 +448,13 @@ public class DirectoryScanner
* @param oldFiles the list of previously captured files names.
* @return the result of the directory scan.
*/
- public DirectoryScanResult diffIncludedFiles( String... oldFiles )
- {
- if ( filesIncluded == null )
- {
+ public DirectoryScanResult diffIncludedFiles(String... oldFiles) {
+ if (filesIncluded == null) {
// perform a scan if the directory didn't got scanned yet
scan();
}
- return diffFiles( oldFiles, filesIncluded.toArray( new String[filesIncluded.size()] ) );
+ return diffFiles(oldFiles, filesIncluded.toArray(new String[filesIncluded.size()]));
}
/**
@@ -483,37 +462,31 @@ public class DirectoryScanner
* @param newFiles array of new files
* @return calculated difference
*/
- public static DirectoryScanResult diffFiles( @Nullable String[] oldFiles, @Nullable String[] newFiles )
- {
- Set<String> oldFileSet = arrayAsHashSet( oldFiles );
- Set<String> newFileSet = arrayAsHashSet( newFiles );
+ public static DirectoryScanResult diffFiles(@Nullable String[] oldFiles, @Nullable String[] newFiles) {
+ Set<String> oldFileSet = arrayAsHashSet(oldFiles);
+ Set<String> newFileSet = arrayAsHashSet(newFiles);
List<String> added = new ArrayList<String>();
List<String> removed = new ArrayList<String>();
- for ( String oldFile : oldFileSet )
- {
- if ( !newFileSet.contains( oldFile ) )
- {
- removed.add( oldFile );
+ for (String oldFile : oldFileSet) {
+ if (!newFileSet.contains(oldFile)) {
+ removed.add(oldFile);
}
}
- for ( String newFile : newFileSet )
- {
- if ( !oldFileSet.contains( newFile ) )
- {
- added.add( newFile );
+ for (String newFile : newFileSet) {
+ if (!oldFileSet.contains(newFile)) {
+ added.add(newFile);
}
}
- String[] filesAdded = added.toArray( new String[added.size()] );
- String[] filesRemoved = removed.toArray( new String[removed.size()] );
+ String[] filesAdded = added.toArray(new String[added.size()]);
+ String[] filesRemoved = removed.toArray(new String[removed.size()]);
- return new DirectoryScanResult( filesAdded, filesRemoved );
+ return new DirectoryScanResult(filesAdded, filesRemoved);
}
-
/**
* Take an array of type T and convert it into a HashSet of type T.
* If <code>null</code> or an empty array gets passed, an empty Set will be returned.
@@ -521,15 +494,13 @@ public class DirectoryScanner
* @param array The array
* @return the filled HashSet of type T
*/
- private static <T> Set<T> arrayAsHashSet( @Nullable T[] array )
- {
- if ( array == null || array.length == 0 )
- {
+ private static <T> Set<T> arrayAsHashSet(@Nullable T[] array) {
+ if (array == null || array.length == 0) {
return Collections.emptySet();
}
- Set<T> set = new HashSet<T>( array.length );
- Collections.addAll( set, array );
+ Set<T> set = new HashSet<T>(array.length);
+ Collections.addAll(set, array);
return set;
}
@@ -541,30 +512,24 @@ public class DirectoryScanner
* <p/>
* Returns immediately if a slow scan has already been completed.
*/
- void slowScan()
- {
- if ( haveSlowResults )
- {
+ void slowScan() {
+ if (haveSlowResults) {
return;
}
- final String[] excl = dirsExcluded.toArray( new String[dirsExcluded.size()] );
+ final String[] excl = dirsExcluded.toArray(new String[dirsExcluded.size()]);
- final String[] notIncl = dirsNotIncluded.toArray( new String[dirsNotIncluded.size()] );
+ final String[] notIncl = dirsNotIncluded.toArray(new String[dirsNotIncluded.size()]);
- for ( String anExcl : excl )
- {
- if ( !couldHoldIncluded( anExcl ) )
- {
- scandir( new File( basedir, anExcl ), anExcl + File.separator, false );
+ for (String anExcl : excl) {
+ if (!couldHoldIncluded(anExcl)) {
+ scandir(new File(basedir, anExcl), anExcl + File.separator, false);
}
}
- for ( String aNotIncl : notIncl )
- {
- if ( !couldHoldIncluded( aNotIncl ) )
- {
- scandir( new File( basedir, aNotIncl ), aNotIncl + File.separator, false );
+ for (String aNotIncl : notIncl) {
+ if (!couldHoldIncluded(aNotIncl)) {
+ scandir(new File(basedir, aNotIncl), aNotIncl + File.separator, false);
}
}
@@ -588,12 +553,10 @@ public class DirectoryScanner
* @see #dirsExcluded
* @see #slowScan
*/
- void scandir( @Nonnull final File dir, @Nonnull final String vpath, final boolean fast )
- {
+ void scandir(@Nonnull final File dir, @Nonnull final String vpath, final boolean fast) {
String[] newfiles = dir.list();
- if ( newfiles == null )
- {
+ if (newfiles == null) {
/*
* two reasons are mentioned in the API docs for File.list (1) dir is not a directory. This is impossible as
* we wouldn't get here in this case. (2) an IO error occurred (why doesn't it throw an exception then???)
@@ -609,166 +572,121 @@ public class DirectoryScanner
// throw new IOException( "IO error scanning directory " + dir.getAbsolutePath() );
}
- if ( !followSymlinks )
- {
- newfiles = doNotFollowSymbolicLinks( dir, vpath, newfiles );
+ if (!followSymlinks) {
+ newfiles = doNotFollowSymbolicLinks(dir, vpath, newfiles);
}
- for ( final String newfile : newfiles )
- {
+ for (final String newfile : newfiles) {
final String name = vpath + newfile;
- final File file = new File( dir, newfile );
- if ( file.isDirectory() )
- {
- if ( isIncluded( name ) )
- {
- if ( !isExcluded( name ) )
- {
- if ( scanConductor != null )
- {
- scanAction = scanConductor.visitDirectory( name, file );
-
- if ( ScanConductor.ScanAction.ABORT.equals( scanAction )
- || ScanConductor.ScanAction.ABORT_DIRECTORY.equals( scanAction ) )
- {
+ final File file = new File(dir, newfile);
+ if (file.isDirectory()) {
+ if (isIncluded(name)) {
+ if (!isExcluded(name)) {
+ if (scanConductor != null) {
+ scanAction = scanConductor.visitDirectory(name, file);
+
+ if (ScanConductor.ScanAction.ABORT.equals(scanAction)
+ || ScanConductor.ScanAction.ABORT_DIRECTORY.equals(scanAction)) {
return;
}
}
- if ( !ScanConductor.ScanAction.NO_RECURSE.equals( scanAction ) )
- {
- dirsIncluded.add( name );
- if ( fast )
- {
- scandir( file, name + File.separator, fast );
+ if (!ScanConductor.ScanAction.NO_RECURSE.equals(scanAction)) {
+ dirsIncluded.add(name);
+ if (fast) {
+ scandir(file, name + File.separator, fast);
- if ( ScanConductor.ScanAction.ABORT.equals( scanAction ) )
- {
+ if (ScanConductor.ScanAction.ABORT.equals(scanAction)) {
return;
}
}
}
scanAction = null;
- }
- else
- {
- dirsExcluded.add( name );
- if ( fast && couldHoldIncluded( name ) )
- {
- scandir( file, name + File.separator, fast );
- if ( ScanConductor.ScanAction.ABORT.equals( scanAction ) )
- {
+ } else {
+ dirsExcluded.add(name);
+ if (fast && couldHoldIncluded(name)) {
+ scandir(file, name + File.separator, fast);
+ if (ScanConductor.ScanAction.ABORT.equals(scanAction)) {
return;
}
scanAction = null;
}
}
- }
- else
- {
- if ( fast && couldHoldIncluded( name ) )
- {
- if ( scanConductor != null )
- {
- scanAction = scanConductor.visitDirectory( name, file );
-
- if ( ScanConductor.ScanAction.ABORT.equals( scanAction )
- || ScanConductor.ScanAction.ABORT_DIRECTORY.equals( scanAction ) )
- {
+ } else {
+ if (fast && couldHoldIncluded(name)) {
+ if (scanConductor != null) {
+ scanAction = scanConductor.visitDirectory(name, file);
+
+ if (ScanConductor.ScanAction.ABORT.equals(scanAction)
+ || ScanConductor.ScanAction.ABORT_DIRECTORY.equals(scanAction)) {
return;
}
}
- if ( !ScanConductor.ScanAction.NO_RECURSE.equals( scanAction ) )
- {
- dirsNotIncluded.add( name );
+ if (!ScanConductor.ScanAction.NO_RECURSE.equals(scanAction)) {
+ dirsNotIncluded.add(name);
- scandir( file, name + File.separator, fast );
- if ( ScanConductor.ScanAction.ABORT.equals( scanAction ) )
- {
+ scandir(file, name + File.separator, fast);
+ if (ScanConductor.ScanAction.ABORT.equals(scanAction)) {
return;
}
}
scanAction = null;
}
}
- if ( !fast )
- {
- scandir( file, name + File.separator, fast );
- if ( ScanConductor.ScanAction.ABORT.equals( scanAction ) )
- {
+ if (!fast) {
+ scandir(file, name + File.separator, fast);
+ if (ScanConductor.ScanAction.ABORT.equals(scanAction)) {
return;
}
scanAction = null;
}
- }
- else if ( file.isFile() )
- {
- if ( isIncluded( name ) )
- {
- if ( !isExcluded( name ) )
- {
- if ( scanConductor != null )
- {
- scanAction = scanConductor.visitFile( name, file );
+ } else if (file.isFile()) {
+ if (isIncluded(name)) {
+ if (!isExcluded(name)) {
+ if (scanConductor != null) {
+ scanAction = scanConductor.visitFile(name, file);
}
- if ( ScanConductor.ScanAction.ABORT.equals( scanAction )
- || ScanConductor.ScanAction.ABORT_DIRECTORY.equals( scanAction ) )
- {
+ if (ScanConductor.ScanAction.ABORT.equals(scanAction)
+ || ScanConductor.ScanAction.ABORT_DIRECTORY.equals(scanAction)) {
return;
}
- filesIncluded.add( name );
- }
- else
- {
- filesExcluded.add( name );
+ filesIncluded.add(name);
+ } else {
+ filesExcluded.add(name);
}
- }
- else
- {
- filesNotIncluded.add( name );
+ } else {
+ filesNotIncluded.add(name);
}
}
}
}
- private String[] doNotFollowSymbolicLinks( final File dir, final String vpath, String[] newfiles )
- {
+ private String[] doNotFollowSymbolicLinks(final File dir, final String vpath, String[] newfiles) {
final List<String> noLinks = new ArrayList<String>();
- for ( final String newfile : newfiles )
- {
- try
- {
- if ( isSymbolicLink( dir, newfile ) )
- {
+ for (final String newfile : newfiles) {
+ try {
+ if (isSymbolicLink(dir, newfile)) {
final String name = vpath + newfile;
- final File file = new File( dir, newfile );
- if ( file.isDirectory() )
- {
- dirsExcluded.add( name );
- }
- else
- {
- filesExcluded.add( name );
+ final File file = new File(dir, newfile);
+ if (file.isDirectory()) {
+ dirsExcluded.add(name);
+ } else {
+ filesExcluded.add(name);
}
+ } else {
+ noLinks.add(newfile);
}
- else
- {
- noLinks.add( newfile );
- }
- }
- catch ( final IOException ioe )
- {
- final String msg =
- "IOException caught while checking " + "for links, couldn't get canonical path!";
+ } catch (final IOException ioe) {
+ final String msg = "IOException caught while checking " + "for links, couldn't get canonical path!";
// will be caught and redirected to Ant's logging system
- System.err.println( msg );
- noLinks.add( newfile );
+ System.err.println(msg);
+ noLinks.add(newfile);
}
}
- newfiles = noLinks.toArray( new String[noLinks.size()] );
+ newfiles = noLinks.toArray(new String[noLinks.size()]);
return newfiles;
}
@@ -779,9 +697,8 @@ public class DirectoryScanner
* @return <code>true</code> when the name matches against at least one include pattern, or <code>false</code>
* otherwise.
*/
- boolean isIncluded( final String name )
- {
- return includesPatterns.matches( name, isCaseSensitive );
+ boolean isIncluded(final String name) {
+ return includesPatterns.matches(name, isCaseSensitive);
}
/**
@@ -791,9 +708,8 @@ public class DirectoryScanner
* @return <code>true</code> when the name matches against the start of at least one include pattern, or
* <code>false</code> otherwise.
*/
- boolean couldHoldIncluded( @Nonnull final String name )
- {
- return includesPatterns.matchesPatternStart( name, isCaseSensitive );
+ boolean couldHoldIncluded(@Nonnull final String name) {
+ return includesPatterns.matchesPatternStart(name, isCaseSensitive);
}
/**
@@ -803,27 +719,24 @@ public class DirectoryScanner
* @return <code>true</code> when the name matches against at least one exclude pattern, or <code>false</code>
* otherwise.
*/
- boolean isExcluded( @Nonnull final String name )
- {
- return excludesPatterns.matches( name, isCaseSensitive );
+ boolean isExcluded(@Nonnull final String name) {
+ return excludesPatterns.matches(name, isCaseSensitive);
}
/**
* Returns the names of the files which matched at least one of the include patterns and none of the exclude
* patterns. The names are relative to the base directory.
*
- * @deprecated this method does not work correctly on Windows.
+ * @deprecated this method does not work correctly on Windows.
* @return the names of the files which matched at least one of the include patterns and none of the exclude
* patterns. May also contain symbolic links to files.
*/
@Deprecated
- public String[] getIncludedFiles()
- {
- if ( filesIncluded == null )
- {
+ public String[] getIncludedFiles() {
+ if (filesIncluded == null) {
return new String[0];
}
- return filesIncluded.toArray( new String[filesIncluded.size()] );
+ return filesIncluded.toArray(new String[filesIncluded.size()]);
}
/**
@@ -833,10 +746,9 @@ public class DirectoryScanner
* @return the names of the files which matched none of the include patterns.
* @see #slowScan
*/
- public String[] getNotIncludedFiles()
- {
+ public String[] getNotIncludedFiles() {
slowScan();
- return filesNotIncluded.toArray( new String[filesNotIncluded.size()] );
+ return filesNotIncluded.toArray(new String[filesNotIncluded.size()]);
}
/**
@@ -848,24 +760,22 @@ public class DirectoryScanner
* exclude patterns.
* @see #slowScan
*/
- public String[] getExcludedFiles()
- {
+ public String[] getExcludedFiles() {
slowScan();
- return filesExcluded.toArray( new String[filesExcluded.size()] );
... 23626 lines suppressed ...