Polish and fix sonar warnings

This commit is contained in:
Phillip Webb
2013-07-07 16:23:32 -07:00
parent 346a0bace7
commit 9fde0a3715
135 changed files with 1023 additions and 611 deletions

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.zero.cli;
/**
* Simple logger used by the CLI.
*
* @author Phillip Webb
*/
public abstract class Log {
public static void info(String message) {
System.out.println(message);
}
public static void error(String message) {
System.err.println(message);
}
public static void error(Exception ex) {
ex.printStackTrace(System.err);
}
}

View File

@@ -92,23 +92,27 @@ public class SpringZeroCli {
return 1;
}
catch (Exception ex) {
Set<SpringZeroCliException.Option> options = NO_EXCEPTION_OPTIONS;
if (ex instanceof SpringZeroCliException) {
options = ((SpringZeroCliException) ex).getOptions();
}
if (!(ex instanceof NoHelpCommandArgumentsException)) {
errorMessage(ex.getMessage());
}
if (options.contains(SpringZeroCliException.Option.SHOW_USAGE)) {
showUsage();
}
if (debug || options.contains(SpringZeroCliException.Option.STACK_TRACE)) {
printStackTrace(ex);
}
return 1;
return handleError(debug, ex);
}
}
private int handleError(boolean debug, Exception ex) {
Set<SpringZeroCliException.Option> options = NO_EXCEPTION_OPTIONS;
if (ex instanceof SpringZeroCliException) {
options = ((SpringZeroCliException) ex).getOptions();
}
if (!(ex instanceof NoHelpCommandArgumentsException)) {
errorMessage(ex.getMessage());
}
if (options.contains(SpringZeroCliException.Option.SHOW_USAGE)) {
showUsage();
}
if (debug || options.contains(SpringZeroCliException.Option.STACK_TRACE)) {
printStackTrace(ex);
}
return 1;
}
/**
* Parse the arguments and run a suitable command.
* @param args the arguments
@@ -133,28 +137,28 @@ public class SpringZeroCli {
}
protected void showUsage() {
System.out.print("usage: " + CLI_APP + " ");
System.out.println("");
System.out.println(" <command> [<args>]");
System.out.println("");
System.out.println("Available commands are:");
Log.info("usage: " + CLI_APP + " ");
Log.info("");
Log.info(" <command> [<args>]");
Log.info("");
Log.info("Available commands are:");
for (Command command : this.commands) {
System.out.println(String.format("\n %1$s %2$-15s\n %3$s",
command.getName(), command.getUsageHelp(), command.getDescription()));
Log.info(String.format("\n %1$s %2$-15s\n %3$s", command.getName(),
command.getUsageHelp(), command.getDescription()));
}
System.out.println("");
System.out.println("See '" + CLI_APP
Log.info("");
Log.info("See '" + CLI_APP
+ " help <command>' for more information on a specific command.");
}
protected void errorMessage(String message) {
System.err.println(message == null ? "Unexpected error" : message);
Log.error(message == null ? "Unexpected error" : message);
}
protected void printStackTrace(Exception ex) {
System.err.println("");
ex.printStackTrace(System.err);
System.err.println("");
Log.error("");
Log.error(ex);
Log.error("");
}
private String[] removeDebugFlags(String[] args) {
@@ -187,16 +191,16 @@ public class SpringZeroCli {
String commandName = args[0];
for (Command command : SpringZeroCli.this.commands) {
if (command.getName().equals(commandName)) {
System.out.println(CLI_APP + " " + command.getName() + " - "
Log.info(CLI_APP + " " + command.getName() + " - "
+ command.getDescription());
System.out.println();
Log.info("");
if (command.getUsageHelp() != null) {
System.out.println("usage: " + CLI_APP + " " + command.getName()
+ " " + command.getUsageHelp());
System.out.println();
Log.info("usage: " + CLI_APP + " " + command.getName() + " "
+ command.getUsageHelp());
Log.info("");
}
if (command.getHelp() != null) {
System.out.println(command.getHelp());
Log.info(command.getHelp());
}
return;
}

View File

@@ -25,6 +25,7 @@ import joptsimple.OptionSpec;
import org.apache.ivy.util.FileUtil;
import org.springframework.zero.cli.Command;
import org.springframework.zero.cli.Log;
/**
* {@link Command} to 'clean' up grapes, removing cached dependencies and forcing a
@@ -35,9 +36,8 @@ import org.springframework.zero.cli.Command;
public class CleanCommand extends OptionParsingCommand {
public CleanCommand() {
super(
"clean",
"Clean up groovy grapes (useful if snapshots are needed and you need an update)",
super("clean", "Clean up groovy grapes "
+ "(useful if snapshots are needed and you need an update)",
new CleanOptionHandler());
}
@@ -48,10 +48,6 @@ public class CleanCommand extends OptionParsingCommand {
private static class CleanOptionHandler extends OptionHandler {
private static enum Layout {
IVY, MAVEN;
}
private OptionSpec<Void> allOption;
private OptionSpec<Void> ivyOption;
@@ -61,61 +57,68 @@ public class CleanCommand extends OptionParsingCommand {
@Override
protected void options() {
this.allOption = option("all", "Clean all files (not just snapshots)");
this.ivyOption = option("ivy",
"Clean just ivy (grapes) cache. Default is on unless --maven is used.");
this.ivyOption = option("ivy", "Clean just ivy (grapes) cache. "
+ "Default is on unless --maven is used.");
this.mvnOption = option("maven", "Clean just maven cache. Default is off.");
}
@Override
protected void run(OptionSet options) throws Exception {
if (!options.has(this.ivyOption)) {
clean(options, getGrapesHome(options), Layout.IVY);
clean(options, getGrapesHome(), Layout.IVY);
}
if (options.has(this.mvnOption)) {
if (options.has(this.ivyOption)) {
clean(options, getGrapesHome(options), Layout.IVY);
clean(options, getGrapesHome(), Layout.IVY);
}
clean(options, getMavenHome(options), Layout.MAVEN);
clean(options, getMavenHome(), Layout.MAVEN);
}
}
private void clean(OptionSet options, File root, Layout layout) {
if (root == null || !root.exists()) {
return;
}
ArrayList<String> specs = new ArrayList<String>(options.nonOptionArguments());
if (!specs.contains("org.springframework.zero") && layout == Layout.IVY) {
specs.add(0, "org.springframework.zero");
}
for (String spec : specs) {
String group = spec;
String module = null;
if (spec.contains(":")) {
group = spec.substring(0, spec.indexOf(":"));
module = spec.substring(spec.indexOf(":") + 1);
}
File file = getModulePath(root, group, module, layout);
if (file.exists()) {
if (options.has(this.allOption)
|| group.equals("org.springframework.zero")) {
System.out.println("Deleting: " + file);
FileUtil.forceDelete(file);
}
else {
for (Object obj : FileUtil.listAll(file, Collections.emptyList())) {
File candidate = (File) obj;
if (candidate.getName().contains("SNAPSHOT")) {
System.out.println("Deleting: " + candidate);
FileUtil.forceDelete(candidate);
}
}
}
clean(options, root, layout, spec);
}
}
private void clean(OptionSet options, File root, Layout layout, String spec) {
String group = spec;
String module = null;
if (spec.contains(":")) {
group = spec.substring(0, spec.indexOf(':'));
module = spec.substring(spec.indexOf(':') + 1);
}
File file = getModulePath(root, group, module, layout);
if (!file.exists()) {
return;
}
if (options.has(this.allOption) || group.equals("org.springframework.zero")) {
delete(file);
return;
}
for (Object obj : FileUtil.listAll(file, Collections.emptyList())) {
File candidate = (File) obj;
if (candidate.getName().contains("SNAPSHOT")) {
delete(candidate);
}
}
}
private void delete(File file) {
Log.info("Deleting: " + file);
FileUtil.forceDelete(file);
}
private File getModulePath(File root, String group, String module, Layout layout) {
File parent = root;
if (layout == Layout.IVY) {
@@ -133,11 +136,9 @@ public class CleanCommand extends OptionParsingCommand {
return new File(parent, module);
}
private File getGrapesHome(OptionSet options) {
private File getGrapesHome() {
String dir = System.getenv("GROOVY_HOME");
String userdir = System.getProperty("user.home");
File home;
if (dir == null || !new File(dir).exists()) {
dir = userdir;
@@ -149,20 +150,20 @@ public class CleanCommand extends OptionParsingCommand {
if (dir == null || !new File(dir).exists()) {
return null;
}
File grapes = new File(home, "grapes");
return grapes;
return new File(home, "grapes");
}
private File getMavenHome(OptionSet options) {
private File getMavenHome() {
String dir = System.getProperty("user.home");
if (dir == null || !new File(dir).exists()) {
return null;
}
File home = new File(dir);
File grapes = new File(new File(home, ".m2"), "repository");
return grapes;
return new File(new File(home, ".m2"), "repository");
}
private static enum Layout {
IVY, MAVEN;
}
}

View File

@@ -78,7 +78,7 @@ public class OptionHandler {
try {
getParser().printHelpOn(out);
}
catch (IOException e) {
catch (IOException ex) {
return "Help not available";
}
return out.toString();

View File

@@ -41,7 +41,7 @@ import org.springframework.zero.cli.compiler.GroovyCompilerConfiguration;
*/
public class ScriptCommand implements Command {
private static String[] DEFAULT_PATHS = new String[] { "${SPRING_HOME}/ext",
private static final String[] DEFAULT_PATHS = new String[] { "${SPRING_HOME}/ext",
"${SPRING_HOME}/bin" };
private String[] paths = DEFAULT_PATHS;
@@ -124,7 +124,7 @@ public class ScriptCommand implements Command {
* @param paths the paths to set
*/
public void setPaths(String[] paths) {
this.paths = paths;
this.paths = (paths == null ? null : paths.clone());
}
@Override
@@ -140,9 +140,9 @@ public class ScriptCommand implements Command {
try {
this.main = getMainClass().newInstance();
}
catch (Exception e) {
catch (Exception ex) {
throw new IllegalStateException("Cannot create main class: " + this.name,
e);
ex);
}
if (this.main instanceof OptionHandler) {
((OptionHandler) this.main).options();
@@ -167,11 +167,11 @@ public class ScriptCommand implements Command {
try {
classes = compiler.compile(source);
}
catch (CompilationFailedException e) {
throw new IllegalStateException("Could not compile script", e);
catch (CompilationFailedException ex) {
throw new IllegalStateException("Could not compile script", ex);
}
catch (IOException e) {
throw new IllegalStateException("Could not compile script", e);
catch (IOException ex) {
throw new IllegalStateException("Could not compile script", ex);
}
this.mainClass = classes[0];
}
@@ -188,43 +188,44 @@ public class ScriptCommand implements Command {
if (!name.endsWith(".groovy")) {
resource = "commands/" + name + ".groovy";
}
URL url = getClass().getClassLoader().getResource(resource);
File file = null;
if (url != null) {
if (url.toString().startsWith("file:")) {
file = new File(url.toString().substring("file:".length()));
}
else {
// probably in JAR file
try {
file = File.createTempFile(name, ".groovy");
file.deleteOnExit();
FileUtil.copy(url, file, null);
}
catch (IOException e) {
throw new IllegalStateException(
"Could not create temp file for source: " + name);
}
return locateSourceFromUrl(name, url);
}
String home = System.getProperty("SPRING_HOME", System.getenv("SPRING_HOME"));
if (home == null) {
home = ".";
}
for (String path : this.paths) {
String subbed = path.replace("${SPRING_HOME}", home);
File file = new File(subbed, resource);
if (file.exists()) {
return file;
}
}
else {
String home = System.getProperty("SPRING_HOME", System.getenv("SPRING_HOME"));
if (home == null) {
home = ".";
}
for (String path : this.paths) {
String subbed = path.replace("${SPRING_HOME}", home);
File test = new File(subbed, resource);
if (test.exists()) {
file = test;
break;
}
}
throw new IllegalStateException("No script found for : " + name);
}
private File locateSourceFromUrl(String name, URL url) {
if (url.toString().startsWith("file:")) {
return new File(url.toString().substring("file:".length()));
}
if (file == null) {
throw new IllegalStateException("No script found for : " + name);
// probably in JAR file
try {
File file = File.createTempFile(name, ".groovy");
file.deleteOnExit();
FileUtil.copy(url, file, null);
return file;
}
catch (IOException ex) {
throw new IllegalStateException("Could not create temp file for source: "
+ name);
}
return file;
}
private static class ScriptConfiguration implements GroovyCompilerConfiguration {

View File

@@ -73,7 +73,7 @@ public class DependencyCustomizer {
try {
DependencyCustomizer.this.loader.loadClass(classname);
}
catch (Exception e) {
catch (Exception ex) {
return true;
}
}
@@ -97,7 +97,8 @@ public class DependencyCustomizer {
DependencyCustomizer.this.loader.loadClass(classname);
return false;
}
catch (Exception e) {
catch (Exception ex) {
// swallow exception and continue
}
}
return DependencyCustomizer.this.canAdd();
@@ -122,7 +123,8 @@ public class DependencyCustomizer {
}
return true;
}
catch (Exception e) {
catch (Exception ex) {
// swallow exception and continue
}
}
return DependencyCustomizer.this.canAdd();
@@ -147,7 +149,8 @@ public class DependencyCustomizer {
}
return false;
}
catch (Exception e) {
catch (Exception ex) {
// swallow exception and continue
}
}
return DependencyCustomizer.this.canAdd();

View File

@@ -84,9 +84,8 @@ public class SpringZeroCompilerAutoConfiguration extends CompilerAutoConfigurati
public void applyToMainClass(GroovyClassLoader loader,
GroovyCompilerConfiguration configuration, GeneratorContext generatorContext,
SourceUnit source, ClassNode classNode) throws CompilationFailedException {
if (true) { // FIXME: add switch for auto config
addEnableAutoConfigurationAnnotation(source, classNode);
}
// FIXME: add switch for auto config
addEnableAutoConfigurationAnnotation(source, classNode);
}
private void addEnableAutoConfigurationAnnotation(SourceUnit source,
@@ -101,8 +100,8 @@ public class SpringZeroCompilerAutoConfiguration extends CompilerAutoConfigurati
annotationClass));
classNode.addAnnotation(annotationNode);
}
catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
catch (ClassNotFoundException ex) {
throw new IllegalStateException(ex);
}
}
}

View File

@@ -56,8 +56,8 @@ public class SpringZeroRunner {
public SpringZeroRunner(final SpringZeroRunnerConfiguration configuration,
File[] files, String... args) {
this.configuration = configuration;
this.files = files;
this.args = args;
this.files = files.clone();
this.args = args.clone();
this.compiler = new GroovyCompiler(configuration);
if (configuration.getLogLevel().intValue() <= Level.FINE.intValue()) {
System.setProperty("groovy.grape.report.downloads", "true");

View File

@@ -30,7 +30,7 @@ import org.codehaus.groovy.control.CompilationFailedException;
/**
* @author Dave Syer
*/
public class GroovyTemplate {
public abstract class GroovyTemplate {
// FIXME is this used?

View File

@@ -36,6 +36,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Integration tests to exercise the samples.
*
* @author Dave Syer
*/
public class SampleIntegrationTests {

View File

@@ -13,22 +13,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.zero.cli.command;
import groovy.lang.GroovyObjectSupport;
import groovy.lang.Script;
import org.junit.Test;
import org.springframework.zero.cli.command.OptionHandler;
import org.springframework.zero.cli.command.ScriptCommand;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
/**
* @author Dave Syer
* Tests for {@link ScriptCommand}.
*
* @author Dave Syer
*/
public class ScriptCommandTests {