id
stringlengths
33
40
content
stringlengths
662
61.5k
max_stars_repo_path
stringlengths
85
97
bugs-dot-jar_data_LOG4J2-965_43517f15
--- BugID: LOG4J2-965 Summary: System.out no longer works after the Console appender and JANSI are initialized Description: |- h3. Demonstration The underlining project demonstrate the bug. The project's build.gradle file: {code:title=build.gradle} apply plugin: 'java' version = '1.0' repositories { mavenCentral() } def log4j2Version = '2.2' def log4j2GroupId = "org.apache.logging.log4j" dependencies { compile log4j2GroupId + ':log4j-core:' + log4j2Version compile log4j2GroupId + ":log4j-jcl:" + log4j2Version compile log4j2GroupId + ":log4j-slf4j-impl:" + log4j2Version compile 'org.fusesource.jansi:jansi:1.11' } {code} A log4j2.xml in classpath: {code:title=log4j2.xml} <?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <File name="root" fileName="${sys:user.home}/logs/windowsbug.log"> <PatternLayout> <Pattern>%d %p %c{1.} [%t] %m%n</Pattern> </PatternLayout> </File> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="root"/> </Root> </Loggers> </Configuration> {code} And the main class: {code:title=Log4j2WindowsBug.java} import org.slf4j.LoggerFactory; /** * @author khotyn 15/3/2 下午8:17 */ public class Log4j2WindowsBug { public static void main(String[] args) { System.out.println("Able to print on Windows"); LoggerFactory.getLogger(Log4j2WindowsBug.class); System.out.println("Unable to print on Windows"); } } {code} The output of the demo under Windows is: {code} Able to print on Windows {code} The third line did not print to Windows console. h3. Reason It seems that log4j2 will wrapper System.out to WindowsAnsiOutputStream if jansi is available in classpath. And in OutputStreamManager's close method, the wrapper WindowsAnsiOutputStream is not considered, and cause the underling System.out closed. {code:title=OutputStreamManager.java} protected synchronized void close() { final OutputStream stream = os; // access volatile field only once per method if (stream == System.out || stream == System.err) { return; } try { stream.close(); } catch (final IOException ex) { LOGGER.error("Unable to close stream " + getName() + ". " + ex); } } {code} diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/ConsoleAppender.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/ConsoleAppender.java index 760db2c..c318d37 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/ConsoleAppender.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/ConsoleAppender.java @@ -182,23 +182,28 @@ public final class ConsoleAppender extends AbstractOutputStreamAppender<OutputSt final String enc = Charset.defaultCharset().name(); PrintStream printStream = null; try { + // Cannot use a CloseShieldOutputStream here; + // see org.apache.logging.log4j.core.appender.ConsoleAppenderTest + // @formatter:off printStream = target == Target.SYSTEM_OUT ? - follow ? new PrintStream(new CloseShieldOutputStream(System.out), true, enc) : System.out : - follow ? new PrintStream(new CloseShieldOutputStream(System.err), true, enc) : System.err; + follow ? new PrintStream(new SystemOutStream(), true, enc) : System.out : + follow ? new PrintStream(new SystemErrStream(), true, enc) : System.err; + // @formatter:on } catch (final UnsupportedEncodingException ex) { // should never happen throw new IllegalStateException("Unsupported default encoding " + enc, ex); } final PropertiesUtil propsUtil = PropertiesUtil.getProperties(); - if (!propsUtil.getStringProperty("os.name").startsWith("Windows") || - propsUtil.getBooleanProperty("log4j.skipJansi")) { + if (!propsUtil.getStringProperty("os.name").startsWith("Windows") + || propsUtil.getBooleanProperty("log4j.skipJansi")) { return printStream; } try { // We type the parameter as a wildcard to avoid a hard reference to Jansi. final Class<?> clazz = Loader.loadClass(JANSI_CLASS); final Constructor<?> constructor = clazz.getConstructor(OutputStream.class); + OutputStream newInstance = (OutputStream) constructor.newInstance(printStream); // LOG4J-965 - return new CloseShieldOutputStream((OutputStream) constructor.newInstance(printStream)); + return follow ? new CloseShieldOutputStream(newInstance) : newInstance; } catch (final ClassNotFoundException cnfe) { LOGGER.debug("Jansi is not installed, cannot find {}", JANSI_CLASS); } catch (final NoSuchMethodException nsme) { @@ -210,6 +215,74 @@ public final class ConsoleAppender extends AbstractOutputStreamAppender<OutputSt } /** + * An implementation of OutputStream that redirects to the current System.err. + */ + private static class SystemErrStream extends OutputStream { + public SystemErrStream() { + } + + @Override + public void close() { + // do not close sys err! + } + + @Override + public void flush() { + System.err.flush(); + } + + @Override + public void write(final byte[] b) throws IOException { + System.err.write(b); + } + + @Override + public void write(final byte[] b, final int off, final int len) + throws IOException { + System.err.write(b, off, len); + } + + @Override + public void write(final int b) { + System.err.write(b); + } + } + + /** + * An implementation of OutputStream that redirects to the current System.out. + */ + private static class SystemOutStream extends OutputStream { + public SystemOutStream() { + } + + @Override + public void close() { + // do not close sys out! + } + + @Override + public void flush() { + System.out.flush(); + } + + @Override + public void write(final byte[] b) throws IOException { + System.out.write(b); + } + + @Override + public void write(final byte[] b, final int off, final int len) + throws IOException { + System.out.write(b, off, len); + } + + @Override + public void write(final int b) throws IOException { + System.out.write(b); + } + } + + /** * A delegating OutputStream that does not close its delegate. */ private static class CloseShieldOutputStream extends OutputStream {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-965_43517f15.diff
bugs-dot-jar_data_LOG4J2-492_a759d8ae
--- BugID: LOG4J2-492 Summary: 'MalformedObjectNameException: Invalid escape sequence... under Jetty' Description: |- Although it is not stopping my webapp from running, I am encountering the following exception when running jetty (via Maven) for a webapp using a trunk build of log4j2. My debug line is also included: {noformat} loggerContext.getName()= WebAppClassLoader=1320771902@4eb9613e 2014-01-09 13:28:52,904 ERROR Could not register mbeans java.lang.IllegalStateException: javax.management.MalformedObjectNameException: Invalid escape sequence '\=' in quoted value at org.apache.logging.log4j.core.jmx.LoggerContextAdmin.<init>(LoggerContextAdmin.java:81) at org.apache.logging.log4j.core.jmx.Server.registerContexts(Server.java:266) at org.apache.logging.log4j.core.jmx.Server.reregisterMBeansAfterReconfigure(Server.java:185) at org.apache.logging.log4j.core.jmx.Server.reregisterMBeansAfterReconfigure(Server.java:150) at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:387) at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:151) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:105) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:33) at org.apache.logging.log4j.LogManager.getContext(LogManager.java:222) at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:103) at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:63) at org.apache.logging.log4j.core.web.Log4jWebInitializerImpl.initializeNonJndi(Log4jWebInitializerImpl.java:136) at org.apache.logging.log4j.core.web.Log4jWebInitializerImpl.initialize(Log4jWebInitializerImpl.java:82) at org.apache.logging.log4j.core.web.Log4jServletContainerInitializer.onStartup(Log4jServletContainerInitializer.java:41) at org.eclipse.jetty.plus.annotation.ContainerInitializer.callStartup(ContainerInitializer.java:106) at org.eclipse.jetty.annotations.ServletContainerInitializerListener.doStart(ServletContainerInitializerListener.java:107) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.util.component.AggregateLifeCycle.doStart(AggregateLifeCycle.java:81) at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:58) at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:96) at org.eclipse.jetty.server.handler.ScopedHandler.doStart(ScopedHandler.java:115) at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:763) at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:249) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1242) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:717) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:494) at org.mortbay.jetty.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:298) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229) at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:172) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95) at org.eclipse.jetty.server.Server.doStart(Server.java:282) at org.mortbay.jetty.plugin.JettyServer.doStart(JettyServer.java:65) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.mortbay.jetty.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:520) at org.mortbay.jetty.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:365) at org.mortbay.jetty.plugin.JettyRunMojo.execute(JettyRunMojo.java:523) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196) at org.apache.maven.cli.MavenCli.main(MavenCli.java:141) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352) Caused by: javax.management.MalformedObjectNameException: Invalid escape sequence '\=' in quoted value at javax.management.ObjectName.construct(ObjectName.java:582) at javax.management.ObjectName.<init>(ObjectName.java:1382) at org.apache.logging.log4j.core.jmx.LoggerContextAdmin.<init>(LoggerContextAdmin.java:79) ... 60 more 2014-01-09 13:28:52.989:INFO:/wallboard:Initializing Spring root WebApplicationContext 2014-01-09 13:29:04.645:INFO:/wallboard:Log4jServletContextListener ensuring that Log4j starts up properly. 2014-01-09 13:29:04.651:INFO:/wallboard:Log4jServletFilter initialized. 2014-01-09 13:29:04.778:WARN:oejsh.RequestLogHandler:!RequestLog 2014-01-09 13:29:04.872:INFO:oejs.AbstractConnector:Started [email protected]:8080 [INFO] Started Jetty Server [INFO] Starting scanner at interval of 10 seconds. {noformat} diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java index 9c66b63..e7af983 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java @@ -74,14 +74,18 @@ public final class Server { for (int i = 0; i < name.length(); i++) { final char c = name.charAt(i); switch (c) { - case ',': - case '=': - case ':': case '\\': case '*': case '?': - sb.append('\\'); - needsQuotes = true; + case '\"': + sb.append('\\'); // quote, star, question & backslash must be escaped + needsQuotes = true; // ... and can only appear in quoted value + break; + case ',': + case '=': + case ':': + needsQuotes = true; // no need to escape these, but value must be quoted + break; } sb.append(c); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-492_a759d8ae.diff
bugs-dot-jar_data_LOG4J2-234_2d7d6311
--- BugID: LOG4J2-234 Summary: RegexFilter crashes as context-wide filter Description: "If a RegexFilter is used as a context-wide filter,\nthen a call like\n \ logger.isDebugEnabled()\nleads to a Null-Pointer-Exception, because the RegexFilter is called with the message \"null\".\nThe stack-trace (2.0-beta5) is:\n\tat org.apache.logging.log4j.core.filter.RegexFilter.filter(RegexFilter.java:60)\n\tat org.apache.logging.log4j.core.filter.CompositeFilter.filter(CompositeFilter.java:176)\n\tat org.apache.logging.log4j.core.Logger$PrivateConfig.filter(Logger.java:317)\n\tat org.apache.logging.log4j.core.Logger.isEnabled(Logger.java:128)\n\tat org.apache.logging.log4j.spi.AbstractLogger.isTraceEnabled(AbstractLogger.java:1129)\n\n\nIn the MarkerFilter is the code\n return marker != null && ...\ni.e. it is only necessary to change line 60 to\n return msg != null && filter(msg.toString)\nin RegexFilter (I do not know how to do this correctly...)\n\nIn line 77, this check is done; in line 66 and 72 the same problem may arise...\n\nGreetings,\nGerald Kroisandt\n" diff --git a/core/src/main/java/org/apache/logging/log4j/core/filter/RegexFilter.java b/core/src/main/java/org/apache/logging/log4j/core/filter/RegexFilter.java index ae41b86..56d8ec6 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/filter/RegexFilter.java +++ b/core/src/main/java/org/apache/logging/log4j/core/filter/RegexFilter.java @@ -57,12 +57,18 @@ public final class RegexFilter extends AbstractFilter { @Override public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg, final Throwable t) { + if (msg == null) { + return onMismatch; + } return filter(msg.toString()); } @Override public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg, final Throwable t) { + if (msg == null) { + return onMismatch; + } final String text = useRawMessage ? msg.getFormat() : msg.getFormattedMessage(); return filter(text); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-234_2d7d6311.diff
bugs-dot-jar_data_LOG4J2-71_2afe3dff
--- BugID: LOG4J2-71 Summary: RollingFileAppender does not create parent directories for the archive files and fails to roll. Description: FileRenameAction is not creating the parent directories for the archive files. This cause the file rename and file copy to fail. diff --git a/core/src/main/java/org/apache/logging/log4j/core/appender/rolling/helper/FileRenameAction.java b/core/src/main/java/org/apache/logging/log4j/core/appender/rolling/helper/FileRenameAction.java index 0f6c367..5d1cff9 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/appender/rolling/helper/FileRenameAction.java +++ b/core/src/main/java/org/apache/logging/log4j/core/appender/rolling/helper/FileRenameAction.java @@ -16,6 +16,9 @@ */ package org.apache.logging.log4j.core.appender.rolling.helper; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.status.StatusLogger; + import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -27,6 +30,9 @@ import java.nio.channels.FileChannel; * File rename action. */ public final class FileRenameAction extends ActionBase { + + private static final Logger LOGGER = StatusLogger.getLogger(); + /** * Source. */ @@ -74,17 +80,31 @@ public final class FileRenameAction extends ActionBase { */ public static boolean execute(final File source, final File destination, boolean renameEmptyFiles) { if (renameEmptyFiles || (source.length() > 0)) { + File parent = destination.getParentFile(); + if (!parent.exists()) { + if (!parent.mkdirs()) { + LOGGER.error("Unable to create directory {}", parent.getAbsolutePath()); + return false; + } + } try { - - boolean result = source.renameTo(destination); - //System.out.println("Rename of " + source.getName() + " to " + destination.getName() + ": " + result); - return result; + if (!source.renameTo(destination)) { + try { + copyFile(source, destination); + return source.delete(); + } catch (IOException iex) { + LOGGER.error("Unable to rename file {} to {} - {}", source.getAbsolutePath(), + destination.getAbsolutePath(), iex.getMessage()); + } + } + return true; } catch (Exception ex) { try { copyFile(source, destination); return source.delete(); } catch (IOException iex) { - iex.printStackTrace(); + LOGGER.error("Unable to rename file {} to {} - {}", source.getAbsolutePath(), + destination.getAbsolutePath(), iex.getMessage()); } } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-71_2afe3dff.diff
bugs-dot-jar_data_LOG4J2-94_d8af1c93
--- BugID: LOG4J2-94 Summary: 'Variable substitution: ${sys:foo} defaults to <property name=":foo">, should default to <property name="foo">' Description: |- The following configuration doesn't work (${sys:log.level} can't be resolved even though default value is provided). <?xml version="1.0" encoding="UTF-8"?> <configuration status="OFF"> <properties> <property name="log.level">error</property> <property name=":log.level">ACTUALLY_GETS_USED</property> </properties> <appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> </appenders> <loggers> <root level="${sys:log.level}"> <appender-ref ref="Console"/> </root> </loggers> </configuration> In org.apache.logging.log4j.core.lookup.Interpolator.lookup(LogEvent, String), on line 110, var = var.substring(prefixPos) should be var = var.substring(prefixPos + 1) instead. diff --git a/core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java b/core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java index 0819211..13cf5bb 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java +++ b/core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java @@ -107,7 +107,7 @@ public class Interpolator implements StrLookup { if (value != null) { return value; } - var = var.substring(prefixPos); + var = var.substring(prefixPos + 1); } if (defaultLookup != null) { return event == null ? defaultLookup.lookup(var) : defaultLookup.lookup(event, var);
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-94_d8af1c93.diff
bugs-dot-jar_data_LOG4J2-219_ed951c76
--- BugID: LOG4J2-219 Summary: Named logger without root logger ends up with empty Appenders map - does not log anything Description: "On the log4j-user mailing list, Peter DePasquale gave this test case that demonstrates the problem:\n\nNote that the configuration has no root logger, but only contains a named logger.\n\nIn a debugger I found that the LoggerConfig for \"logtest.LogTest\" ended up with an empty \"appenders\" Map<String, AppenderControl<?>>. The appenderRefs list did contain an AppenderRef object but in #callAppenders there are no AppenderControl objects to call... \n\n(Sorry, I have been unable to find out the underlying cause yet.)\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration status=\"warn\">\n\t<appenders>\n\t\t<File name=\"tracelog\" fileName=\"trace-log.txt\" \n\t\t\t\timmediateFlush=\"true\" append=\"false\">\n\t\t\t<PatternLayout pattern=\"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n\"/>\n\t\t</File>\n\t</appenders>\n\t\n\t<loggers>\n\t\t<logger name=\"logtest.LogTest\" level=\"trace\">\n\t\t\t<appender-ref ref=\"tracelog\"/>\n\t\t</logger>\n\t</loggers>\n</configuration>\n\n\n\npackage logtest;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.core.config.XMLConfigurationFactory;\n\npublic class LogTest {\n\tpublic static void main(String[] args) {\n\t\tSystem.setProperty(XMLConfigurationFactory.CONFIGURATION_FILE_PROPERTY,\n\t\t\t\t\"log4j2-roottest.xml\");\n\n\t\tLogger logger = LogManager.getLogger(LogTest.class);\n\t\tlogger.trace(\"This is a trace message\");\n\t\tlogger.info(\"This is an info message\");\n\t\tlogger.warn(\"This is a warning message\");\n\t}\n}\n" diff --git a/core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java b/core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java index dcdb988..8821f76 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java +++ b/core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java @@ -206,9 +206,9 @@ public class BaseConfiguration extends AbstractFilterable implements Configurati setToDefault(); return; } else if (!setRoot) { - LOGGER.warn("No Root logger was configured, using default"); + LOGGER.warn("No Root logger was configured, creating default ERROR-level Root logger with Console appender"); setToDefault(); - return; + // return; // LOG4J2-219: creating default root=ok, but don't exclude configured Loggers } for (final Map.Entry<String, LoggerConfig> entry : loggers.entrySet()) {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-219_ed951c76.diff
bugs-dot-jar_data_LOG4J2-492_61ccbb95
--- BugID: LOG4J2-492 Summary: 'MalformedObjectNameException: Invalid escape sequence... under Jetty' Description: |- Although it is not stopping my webapp from running, I am encountering the following exception when running jetty (via Maven) for a webapp using a trunk build of log4j2. My debug line is also included: {noformat} loggerContext.getName()= WebAppClassLoader=1320771902@4eb9613e 2014-01-09 13:28:52,904 ERROR Could not register mbeans java.lang.IllegalStateException: javax.management.MalformedObjectNameException: Invalid escape sequence '\=' in quoted value at org.apache.logging.log4j.core.jmx.LoggerContextAdmin.<init>(LoggerContextAdmin.java:81) at org.apache.logging.log4j.core.jmx.Server.registerContexts(Server.java:266) at org.apache.logging.log4j.core.jmx.Server.reregisterMBeansAfterReconfigure(Server.java:185) at org.apache.logging.log4j.core.jmx.Server.reregisterMBeansAfterReconfigure(Server.java:150) at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:387) at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:151) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:105) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:33) at org.apache.logging.log4j.LogManager.getContext(LogManager.java:222) at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:103) at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:63) at org.apache.logging.log4j.core.web.Log4jWebInitializerImpl.initializeNonJndi(Log4jWebInitializerImpl.java:136) at org.apache.logging.log4j.core.web.Log4jWebInitializerImpl.initialize(Log4jWebInitializerImpl.java:82) at org.apache.logging.log4j.core.web.Log4jServletContainerInitializer.onStartup(Log4jServletContainerInitializer.java:41) at org.eclipse.jetty.plus.annotation.ContainerInitializer.callStartup(ContainerInitializer.java:106) at org.eclipse.jetty.annotations.ServletContainerInitializerListener.doStart(ServletContainerInitializerListener.java:107) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.util.component.AggregateLifeCycle.doStart(AggregateLifeCycle.java:81) at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:58) at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:96) at org.eclipse.jetty.server.handler.ScopedHandler.doStart(ScopedHandler.java:115) at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:763) at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:249) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1242) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:717) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:494) at org.mortbay.jetty.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:298) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229) at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:172) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95) at org.eclipse.jetty.server.Server.doStart(Server.java:282) at org.mortbay.jetty.plugin.JettyServer.doStart(JettyServer.java:65) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.mortbay.jetty.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:520) at org.mortbay.jetty.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:365) at org.mortbay.jetty.plugin.JettyRunMojo.execute(JettyRunMojo.java:523) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196) at org.apache.maven.cli.MavenCli.main(MavenCli.java:141) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352) Caused by: javax.management.MalformedObjectNameException: Invalid escape sequence '\=' in quoted value at javax.management.ObjectName.construct(ObjectName.java:582) at javax.management.ObjectName.<init>(ObjectName.java:1382) at org.apache.logging.log4j.core.jmx.LoggerContextAdmin.<init>(LoggerContextAdmin.java:79) ... 60 more 2014-01-09 13:28:52.989:INFO:/wallboard:Initializing Spring root WebApplicationContext 2014-01-09 13:29:04.645:INFO:/wallboard:Log4jServletContextListener ensuring that Log4j starts up properly. 2014-01-09 13:29:04.651:INFO:/wallboard:Log4jServletFilter initialized. 2014-01-09 13:29:04.778:WARN:oejsh.RequestLogHandler:!RequestLog 2014-01-09 13:29:04.872:INFO:oejs.AbstractConnector:Started [email protected]:8080 [INFO] Started Jetty Server [INFO] Starting scanner at interval of 10 seconds. {noformat} diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java index 898e5e1..e2c03f9 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java @@ -88,12 +88,12 @@ public final class Server { needsQuotes = true; break; case '\r': - // replace by \\r, no need to quote - sb.append("\\r"); + // drop \r characters: \\r gives "invalid escape sequence" continue; case '\n': - // replace by \\n, no need to quote + // replace \n characters with \\n sequence sb.append("\\n"); + needsQuotes = true; continue; } sb.append(c); @@ -260,13 +260,14 @@ public final class Server { */ public static void unregisterContext(String contextName, MBeanServer mbs) { final String pattern = LoggerContextAdminMBean.PATTERN; - final String search = String.format(pattern, contextName, "*"); + final String safeContextName = escape(contextName); + final String search = String.format(pattern, safeContextName, "*"); unregisterAllMatching(search, mbs); // unregister context mbean - unregisterLoggerConfigs(contextName, mbs); - unregisterAppenders(contextName, mbs); - unregisterAsyncAppenders(contextName, mbs); - unregisterAsyncLoggerRingBufferAdmins(contextName, mbs); - unregisterAsyncLoggerConfigRingBufferAdmins(contextName, mbs); + unregisterLoggerConfigs(safeContextName, mbs); + unregisterAppenders(safeContextName, mbs); + unregisterAsyncAppenders(safeContextName, mbs); + unregisterAsyncLoggerRingBufferAdmins(safeContextName, mbs); + unregisterAsyncLoggerConfigRingBufferAdmins(safeContextName, mbs); } private static void registerStatusLogger(final MBeanServer mbs, final Executor executor)
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-492_61ccbb95.diff
bugs-dot-jar_data_LOG4J2-793_73400bfb
--- BugID: LOG4J2-793 Summary: Log4jLogger only accepts Log4jMarker, not SLF4J's Marker Description: |+ We're using Log4j 2 via SLF4J. A Logger's log methods have signatures like this: public abstract void warn(org.slf4j.Marker marker, java.lang.String msg) If you use an object that is an Marker but not a Log4jMarker this fails at org.apache.logging.slf4j.Log4jLogger.getMarker(Log4jLogger.java:378) due to "cannot be cast to org.apache.logging.slf4j.Log4jMarker". Use case: we have a defined set of Markers. There's an enum for this, implementing SLF4J's marker interface. Obviously with Log4j we cannot use this enum. I think an org.apache.logging.slf4j.Log4jLogger cannot expect an org.apache.logging.slf4j.Log4jMarker. diff --git a/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jLogger.java b/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jLogger.java index 5d37629..e5b2e1f 100644 --- a/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jLogger.java +++ b/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jLogger.java @@ -29,6 +29,7 @@ import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.spi.ExtendedLogger; import org.slf4j.Marker; import org.slf4j.MarkerFactory; +import org.slf4j.impl.StaticMarkerBinder; import org.slf4j.spi.LocationAwareLogger; /** @@ -375,7 +376,14 @@ public class Log4jLogger implements LocationAwareLogger, Serializable { } private static org.apache.logging.log4j.Marker getMarker(final Marker marker) { - return marker != null ? ((org.apache.logging.slf4j.Log4jMarker) marker).getLog4jMarker() : null; + if (marker == null) { + return null; + } else if (marker instanceof Log4jMarker) { + return ((Log4jMarker) marker).getLog4jMarker(); + } else { + final Log4jMarkerFactory factory = (Log4jMarkerFactory) StaticMarkerBinder.SINGLETON.getMarkerFactory(); + return ((Log4jMarker) factory.getMarker(marker)).getLog4jMarker(); + } } @Override diff --git a/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarkerFactory.java b/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarkerFactory.java index 4efd4d1..4183f2c 100644 --- a/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarkerFactory.java +++ b/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarkerFactory.java @@ -16,6 +16,7 @@ */ package org.apache.logging.slf4j; +import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -24,14 +25,14 @@ import org.slf4j.IMarkerFactory; import org.slf4j.Marker; /** - * + * Log4j/SLF4J bridge to create SLF4J Markers based on name or based on existing SLF4J Markers. */ public class Log4jMarkerFactory implements IMarkerFactory { private final ConcurrentMap<String, Marker> markerMap = new ConcurrentHashMap<String, Marker>(); /** - * Return a Log4j Marker that is compatible with SLF4J. + * Returns a Log4j Marker that is compatible with SLF4J. * @param name The name of the Marker. * @return A Marker. */ @@ -45,12 +46,49 @@ public class Log4jMarkerFactory implements IMarkerFactory { return marker; } final org.apache.logging.log4j.Marker log4jMarker = MarkerManager.getMarker(name); - marker = new Log4jMarker(log4jMarker); + return addMarkerIfAbsent(name, log4jMarker); + } + + private Marker addMarkerIfAbsent(final String name, final org.apache.logging.log4j.Marker log4jMarker) { + final Marker marker = new Log4jMarker(log4jMarker); final Marker existing = markerMap.putIfAbsent(name, marker); return existing == null ? marker : existing; } /** + * Returns a Log4j Marker converted from an existing custom SLF4J Marker. + * @param marker The SLF4J Marker to convert. + * @return A converted Log4j/SLF4J Marker. + * @since 2.1 + */ + public Marker getMarker(final Marker marker) { + if (marker == null) { + throw new IllegalArgumentException("Marker must not be null"); + } + Marker m = markerMap.get(marker.getName()); + if (m != null) { + return m; + } + return addMarkerIfAbsent(marker.getName(), convertMarker(marker)); + } + + private static org.apache.logging.log4j.Marker convertMarker(final Marker original) { + if (original == null) { + throw new IllegalArgumentException("Marker must not be null"); + } + final org.apache.logging.log4j.Marker marker = MarkerManager.getMarker(original.getName()); + if (original.hasReferences()) { + final Iterator it = original.iterator(); + while (it.hasNext()) { + final Marker next = (Marker) it.next(); + // kind of hope nobody uses cycles in their Markers. I mean, why would you do that? + marker.addParents(convertMarker(next)); + } + } + return marker; + } + + /** * Returns true if the Marker exists. * @param name The Marker name. * @return true if the Marker exists, false otherwise.
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-793_73400bfb.diff
bugs-dot-jar_data_LOG4J2-101_c79a743b
--- BugID: LOG4J2-101 Summary: Attribute "format" for SyslogAppender is mandatory Description: |- In the SyslogAppender the configuration attribute "Format" must be present, otherwise a NullPointerException is thrown in method "createAppender" when the following statement is executed: if (format.equalsIgnoreCase(RFC5424)) The fix is simply to add a check so the "equalsIgnoreCase" is called only if the format variable isn't Null. diff --git a/core/src/main/java/org/apache/logging/log4j/core/appender/SyslogAppender.java b/core/src/main/java/org/apache/logging/log4j/core/appender/SyslogAppender.java index d2392e9..39fbd38 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/appender/SyslogAppender.java +++ b/core/src/main/java/org/apache/logging/log4j/core/appender/SyslogAppender.java @@ -111,7 +111,7 @@ public class SyslogAppender extends SocketAppender { LOGGER.error("Charset " + charset + " is not supported for layout, using " + c.displayName()); } } - Layout layout = (format.equalsIgnoreCase(RFC5424)) ? + Layout layout = (RFC5424.equalsIgnoreCase(format)) ? RFC5424Layout.createLayout(facility, id, ein, includeMDC, mdcId, includeNL, appName, msgId, excludes, includes, required, charset, config) : SyslogLayout.createLayout(facility, includeNL, charset);
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-101_c79a743b.diff
bugs-dot-jar_data_LOG4J2-1046_11960820
--- BugID: LOG4J2-1046 Summary: Circular Exception cause throws StackOverflowError Description: "If an exception with a circular-referenced exception (suppressed, or otherwise) is logged, log4j will throw a StackOverflowError:\n{code:java}\n Exception e1 = new Exception();\n Exception e2 = new Exception(e1);\n e1.initCause(e2);\n \ LogManager.getLogger().error(\"Error\", e1);\n{code}\n\nWill throw the following:\n{code:java}\njava.lang.StackOverflowError\n\tat java.util.Vector.elementData(Vector.java:730)\n\tat java.util.Vector.elementAt(Vector.java:473)\n\tat java.util.Stack.peek(Stack.java:103)\n\tat org.apache.logging.log4j.core.impl.ThrowableProxy.toExtendedStackTrace(ThrowableProxy.java:555)\n\tat org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:147)\n\tat org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:148)\n\tat org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:148)\n\tat org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:148)\n\tat org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:148)\n\tat org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:148)\n\tat org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:148)\n \ ...\n{code}\n" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java index dbbc808..75aa5b4 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java @@ -121,7 +121,8 @@ public class ThrowableProxy implements Serializable { final Stack<Class<?>> stack = ReflectionUtil.getCurrentStackTrace(); this.extendedStackTrace = this.toExtendedStackTrace(stack, map, null, throwable.getStackTrace()); final Throwable throwableCause = throwable.getCause(); - this.causeProxy = throwableCause == null ? null : new ThrowableProxy(throwable, stack, map, throwableCause, visited); + final Set<Throwable> causeVisited = new HashSet<>(1); + this.causeProxy = throwableCause == null ? null : new ThrowableProxy(throwable, stack, map, throwableCause, visited, causeVisited); this.suppressedProxies = this.toSuppressedProxies(throwable, visited); } @@ -137,15 +138,19 @@ public class ThrowableProxy implements Serializable { * @param cause * The Throwable to wrap. * @param suppressedVisited TODO + * @param causeVisited TODO */ private ThrowableProxy(final Throwable parent, final Stack<Class<?>> stack, final Map<String, CacheEntry> map, - final Throwable cause, Set<Throwable> suppressedVisited) { + final Throwable cause, Set<Throwable> suppressedVisited, Set<Throwable> causeVisited) { + causeVisited.add(cause); this.throwable = cause; this.name = cause.getClass().getName(); this.message = this.throwable.getMessage(); this.localizedMessage = this.throwable.getLocalizedMessage(); this.extendedStackTrace = this.toExtendedStackTrace(stack, map, parent.getStackTrace(), cause.getStackTrace()); - this.causeProxy = cause.getCause() == null ? null : new ThrowableProxy(parent, stack, map, cause.getCause(), suppressedVisited); + final Throwable causeCause = cause.getCause(); + this.causeProxy = causeCause == null || causeVisited.contains(causeCause) ? null : new ThrowableProxy(parent, + stack, map, causeCause, suppressedVisited, causeVisited); this.suppressedProxies = this.toSuppressedProxies(cause, suppressedVisited); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1046_11960820.diff
bugs-dot-jar_data_LOG4J2-359_296ea4a5
--- BugID: LOG4J2-359 Summary: Log4jServletContextListener does not work on Weblogic 12.1.1 (12c) with web-app version "2.5" Description: "I have Weblogic 12c running. My web-app is version \"2.5\".\n\nFollowing is a snippet from my web.xml \n\n{code:xml}\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txmlns=\"http://java.sun.com/xml/ns/javaee\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n\tid=\"WebApp_ID\" version=\"2.5\">\n\t<display-name>pec-service</display-name>\n\t<context-param>\n\t\t<param-name>log4jConfiguration</param-name>\n\t\t<param-value>file:/C:/log4j/dev.log4j.xml</param-value>\n\t</context-param>\n\n\t<listener> \n\t\t<listener-class>org.apache.logging.log4j.core.web.Log4jServletContextListener</listener-class> \n\t</listener>\t\n\n\t<filter>\n\t\t<filter-name>log4jServletFilter</filter-name>\n\t\t<filter-class>org.apache.logging.log4j.core.web.Log4jServletFilter</filter-class> \n\t</filter>\n\t<filter-mapping>\n\t\t<filter-name>log4jServletFilter</filter-name> \n\t\t<url-pattern>/*</url-pattern>\n\t\t<dispatcher>REQUEST</dispatcher>\n\t\t<dispatcher>FORWARD</dispatcher> \n\t\t<dispatcher>INCLUDE</dispatcher>\n\t\t<dispatcher>ERROR</dispatcher>\n\t</filter-mapping>\n\t\n</web-app>\n{code}\n\nHowever, on my server startup I am getting the following error - \n{code}\n<Aug 16, 2013 3:12:32 PM PDT> <Warning> <HTTP> <BEA-101162> <User defined listener org.apache.logging.log4j.core.web.Log4jServletContextListener failed: java.lang.IllegalStateException: Context destroyed before it was initialized..\njava.lang.IllegalStateException: Context destroyed before it was initialized.\n\tat org.apache.logging.log4j.core.web.Log4jServletContextListener.contextDestroyed(Log4jServletContextListener.java:51)\n\tat weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:583)\n\tat weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)\n\tat weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)\n\tat weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)\n\tTruncated. see log file for complete stacktrace\n> \n<Aug 16, 2013 3:12:32 PM PDT> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID \"1376691143681\" for task \"2\". Error is: \"weblogic.application.ModuleException\"\nweblogic.application.ModuleException\n\tat weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1708)\n\tat weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:781)\n\tat weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:213)\n\tat weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:208)\n\tat weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)\n\tTruncated. see log file for complete stacktrace\nCaused By: java.lang.NullPointerException\n\tat org.apache.logging.log4j.core.web.Log4jServletContainerInitializer.onStartup(Log4jServletContainerInitializer.java:44)\n\tat weblogic.servlet.internal.WebAppServletContext.initContainerInitializer(WebAppServletContext.java:1271)\n\tat weblogic.servlet.internal.WebAppServletContext.initContainerInitializers(WebAppServletContext.java:1229)\n\tat weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1726)\n\tat weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:2740)\n\tTruncated. see log file for complete stacktrace\n> \n<Aug 16, 2013 3:12:32 PM PDT> <Error> <Deployer> <BEA-149202> <Encountered an exception while attempting to commit the 7 task for the application \"_auto_generated_ear_\".> \n<Aug 16, 2013 3:12:32 PM PDT> <Warning> <Deployer> <BEA-149004> <Failures were detected while initiating start task for application \"_auto_generated_ear_\".> \n<Aug 16, 2013 3:12:32 PM PDT> <Warning> <Deployer> <BEA-149078> <Stack trace for message 149004\nweblogic.application.ModuleException\n\tat weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1708)\n\tat weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:781)\n\tat weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:213)\n\tat weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:208)\n\tat weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)\n\tTruncated. see log file for complete stacktrace\nCaused By: java.lang.NullPointerException\n\tat org.apache.logging.log4j.core.web.Log4jServletContainerInitializer.onStartup(Log4jServletContainerInitializer.java:44)\n\tat weblogic.servlet.internal.WebAppServletContext.initContainerInitializer(WebAppServletContext.java:1271)\n\tat weblogic.servlet.internal.WebAppServletContext.initContainerInitializers(WebAppServletContext.java:1229)\n\tat weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1726)\n\tat weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:2740)\n\tTruncated. see log file for complete stacktrace\n{code}\n\nIf I remove the listener & the filter, it works fine.\n\n{color:red}\nI did some research and found that even though the web-app is version \"2.5\", the {code}Log4jServletContainerInitializer{code} is getting invoked. \n{color}" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java index 50b0820..7d3ce05 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java @@ -25,6 +25,9 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.UnavailableException; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.status.StatusLogger; + /** * In a Servlet 3.0 or newer environment, this initializer is responsible for starting up Log4j logging before anything * else happens in application initialization. For consistency across all containers, if the effective Servlet major @@ -34,21 +37,23 @@ public class Log4jServletContainerInitializer implements ServletContainerInitial @Override public void onStartup(final Set<Class<?>> classes, final ServletContext servletContext) throws ServletException { - if (servletContext.getMajorVersion() > 2) { + if (servletContext.getMajorVersion() > 2 && servletContext.getEffectiveMajorVersion() > 2) { servletContext.log("Log4jServletContainerInitializer starting up Log4j in Servlet 3.0+ environment."); + final FilterRegistration.Dynamic filter = + servletContext.addFilter("log4jServletFilter", new Log4jServletFilter()); + if (filter == null) { + servletContext.log("WARNING: In a Servlet 3.0+ application, you should not define a " + + "log4jServletFilter in web.xml. Log4j 2 normally does this for you automatically. Log4j 2 " + + "web auto-initialization has been canceled."); + return; + } + final Log4jWebInitializer initializer = Log4jWebInitializerImpl.getLog4jWebInitializer(servletContext); initializer.initialize(); initializer.setLoggerContext(); // the application is just now starting to start up servletContext.addListener(new Log4jServletContextListener()); - - final FilterRegistration.Dynamic filter = - servletContext.addFilter("log4jServletFilter", new Log4jServletFilter()); - if (filter == null) { - throw new UnavailableException("In a Servlet 3.0+ application, you must not define a " + - "log4jServletFilter in web.xml. Log4j 2 defines this for you automatically."); - } filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-359_296ea4a5.diff
bugs-dot-jar_data_LOG4J2-1061_86d8944f
--- BugID: LOG4J2-1061 Summary: Log4jMarker#remove(Marker) does not respect org.slf4j.Marker contract Description: Passing {{null}} to {{Log4jMarker#remove(Marker)}} throws a {{NullPointerException}} instead of return {{false}}. diff --git a/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java b/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java index c2273f5..d57cf19 100644 --- a/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java +++ b/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java @@ -55,9 +55,9 @@ public class Log4jMarker implements Marker { } @Override - public boolean remove(final Marker marker) { - return this.marker.remove(MarkerManager.getMarker(marker.getName())); - } + public boolean remove(final Marker marker) { + return marker != null ? this.marker.remove(MarkerManager.getMarker(marker.getName())) : false; + } @Override public String getName() {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1061_86d8944f.diff
bugs-dot-jar_data_LOG4J2-268_8faf7f77
--- BugID: LOG4J2-268 Summary: Berkeley (persistent) agent for FlumeAppender only works with MapMessages (and thus not slf4j) Description: "If I try and use the persistent FlumeAppender with slf4j then I get a NullPointerException in FlumePersistentManager.send because there is no GUID header.\n\n(My repro here was using a copy of Flume modified to use log4j2 - while this particular repro is exotic I'm confident that the general case detailed above will be very common).\n\nThere is no GUID header because the FlumeEvent constructor only creates one if the message is a MapMessage.\n\nIf the user is using slf4j then all messages are PersistentMessages - and thus will cause this logging to fail.\n\nThe GUID is required because it's used as a key in the BerkeleyDB storage.\n\nMy attempts at a simple fix ran afoul of the key lookup from the headers in FlumePersisentManager.WriterThread.run(). " diff --git a/flume-ng/src/main/java/org/apache/logging/log4j/flume/appender/FlumeEvent.java b/flume-ng/src/main/java/org/apache/logging/log4j/flume/appender/FlumeEvent.java index c8e4547..d448a66 100644 --- a/flume-ng/src/main/java/org/apache/logging/log4j/flume/appender/FlumeEvent.java +++ b/flume-ng/src/main/java/org/apache/logging/log4j/flume/appender/FlumeEvent.java @@ -128,11 +128,14 @@ public class FlumeEvent extends SimpleEvent implements LogEvent { final String guid = UUIDUtil.getTimeBasedUUID().toString(); final Message message = event.getMessage(); if (message instanceof MapMessage) { + // Add the guid to the Map so that it can be included in the Layout. ((MapMessage) message).put(GUID, guid); if (message instanceof StructuredDataMessage) { addStructuredData(eventPrefix, headers, (StructuredDataMessage) message); } addMapData(eventPrefix, headers, (MapMessage) message); + } else { + headers.put(GUID, guid); } addContextData(mdcPrefix, headers, ctx);
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-268_8faf7f77.diff
bugs-dot-jar_data_LOG4J2-639_a5a1f1a2
--- BugID: LOG4J2-639 Summary: NPE in AsyncLogger.log(..) Description: "Our production environment suffers from\n{noformat}\njava.lang.NullPointerException at org.apache.logging.log4j.core.async.AsyncLogger.log(AsyncLogger.java:273)\n at org.apache.logging.log4j.spi.AbstractLoggerWrapper.log(AbstractLoggerWrapper.java:121)\n \ at org.apache.logging.log4j.spi.AbstractLogger.info(AbstractLogger.java:1006) \n at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:873) \n at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:809)\n{noformat}\n\nIt looks like something in our app is still logging despite the AsyncLogger having been stopped (and the disruptor field set to null).\n\nThe logger could print out a more informative message in this situation." diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java index b99608c..c832973 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java @@ -230,10 +230,16 @@ public class AsyncLogger extends Logger { info = new Info(new RingBufferLogEventTranslator(), Thread.currentThread().getName(), false); threadlocalInfo.set(info); } + + Disruptor<RingBufferLogEvent> temp = disruptor; + if (temp == null) { // LOG4J2-639 + LOGGER.fatal("Ignoring log event after log4j was shut down"); + return; + } // LOG4J2-471: prevent deadlock when RingBuffer is full and object // being logged calls Logger.log() from its toString() method - if (info.isAppenderThread && disruptor.getRingBuffer().remainingCapacity() == 0) { + if (info.isAppenderThread && temp.getRingBuffer().remainingCapacity() == 0) { // bypass RingBuffer and invoke Appender directly config.loggerConfig.log(getName(), fqcn, marker, level, message, thrown); return; @@ -266,7 +272,15 @@ public class AsyncLogger extends Logger { // CachedClock: 10% faster than system clock, smaller gaps clock.currentTimeMillis()); - disruptor.publishEvent(info.translator); + // LOG4J2-639: catch NPE if disruptor field was set to null after our check above + try { + // Note: do NOT use the temp variable above! + // That could result in adding a log event to the disruptor after it was shut down, + // which could cause the publishEvent method to hang and never return. + disruptor.publishEvent(info.translator); + } catch (NullPointerException npe) { + LOGGER.fatal("Ignoring log event after log4j was shut down."); + } } private static StackTraceElement location(final String fqcnOfLogger) { diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigHelper.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigHelper.java index 9d2f4f0..2e8814c 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigHelper.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigHelper.java @@ -316,16 +316,29 @@ class AsyncLoggerConfigHelper { * calling thread needs to process the event itself */ public boolean callAppendersFromAnotherThread(final LogEvent event) { + Disruptor<Log4jEventWrapper> temp = disruptor; + if (temp == null) { // LOG4J2-639 + LOGGER.fatal("Ignoring log event after log4j was shut down"); + return true; + } // LOG4J2-471: prevent deadlock when RingBuffer is full and object // being logged calls Logger.log() from its toString() method if (isAppenderThread.get() == Boolean.TRUE // - && disruptor.getRingBuffer().remainingCapacity() == 0) { + && temp.getRingBuffer().remainingCapacity() == 0) { // bypass RingBuffer and invoke Appender directly return false; } - disruptor.getRingBuffer().publishEvent(translator, event, asyncLoggerConfig); + // LOG4J2-639: catch NPE if disruptor field was set to null after our check above + try { + // Note: do NOT use the temp variable above! + // That could result in adding a log event to the disruptor after it was shut down, + // which could cause the publishEvent method to hang and never return. + disruptor.getRingBuffer().publishEvent(translator, event, asyncLoggerConfig); + } catch (NullPointerException npe) { + LOGGER.fatal("Ignoring log event after log4j was shut down."); + } return true; }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-639_a5a1f1a2.diff
bugs-dot-jar_data_LOG4J2-102_7f391872
--- BugID: LOG4J2-102 Summary: Bad priority in Syslog messages Description: |- In class org.apache.logging.log4j.core.net.Priority the method getPriority returns a bad priority when used for Syslog messages (the only usage at the moment). The bug is in the statement: facility.getCode() << 3 + Severity.getSeverity(level).getCode() That's because the operator "+" takes precedence over "<<", and so the facility code isn't shifted by 3 but by "3 + Severity.getSeverity(level).getCode()". diff --git a/core/src/main/java/org/apache/logging/log4j/core/net/Priority.java b/core/src/main/java/org/apache/logging/log4j/core/net/Priority.java index 0e83dfa..00144e2 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/net/Priority.java +++ b/core/src/main/java/org/apache/logging/log4j/core/net/Priority.java @@ -43,7 +43,7 @@ public class Priority { * @return The integer value of the priority. */ public static int getPriority(Facility facility, Level level) { - return facility.getCode() << 3 + Severity.getSeverity(level).getCode(); + return (facility.getCode() << 3) + Severity.getSeverity(level).getCode(); } /**
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-102_7f391872.diff
bugs-dot-jar_data_LOG4J2-56_3eb44094
--- BugID: LOG4J2-56 Summary: Level.toLevel throws IllegalArgumentException instead of returning default Level Description: "org.apache.logging.log4j.Level.toLevel(String, Level) ( Level.java line 100) uses enum static method valueOf(String) which throws IllegalArgumentException instead of returning null when enum const doesnt exists. This makes the methods Level.toLevel throw the exception instead of return default value.\n\nSolution:\n\nYou can:\na) sorround it with a try-catch statement, like:\n try {\n\t\t\treturn valueOf(sArg);\n\t\t} catch (Exception e) {\n\t\t\t//exception doesnt matter\n\t\t\treturn defaultLevel;\n\t\t}\n\nb) translate manually de String to a enum constant, like:\n \ for (Level level : values()) {\n\t\t\tif (level.name().equals(sArg)) {\n\t\t\t\treturn level;\n\t\t\t}\n\t\t}\n return defaultLevel;\n\nI prefer b) because it saves the try-catch context and the for is nearly the same that the valueOf should do.\n" diff --git a/log4j2-api/src/main/java/org/apache/logging/log4j/Level.java b/log4j2-api/src/main/java/org/apache/logging/log4j/Level.java index 5d56417..4fd3115 100644 --- a/log4j2-api/src/main/java/org/apache/logging/log4j/Level.java +++ b/log4j2-api/src/main/java/org/apache/logging/log4j/Level.java @@ -96,9 +96,12 @@ public enum Level { if (sArg == null) { return defaultLevel; } - - Level level = valueOf(sArg); - return (level == null) ? defaultLevel : level; + for (Level level : values()) { + if (level.name().equals(sArg)) { + return level; + } + } + return defaultLevel; } /**
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-56_3eb44094.diff
bugs-dot-jar_data_LOG4J2-447_0343e9c7
--- BugID: LOG4J2-447 Summary: XMLLayout does not include marker name Description: |- Log4j2 supports the notion of markers, but this is not represented by the XMLLayout. For example, using SerializedLayout with SocketAppender will send marker information, but using XMLLayout with SocketAppender will not. It would be very helpful to have just the name of the leaf marker sent with the log event, not the corresponding marker hierarchy. diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/XMLLayout.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/XMLLayout.java index 59a511a..d0e4d48 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/XMLLayout.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/XMLLayout.java @@ -21,6 +21,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; @@ -195,6 +196,28 @@ public class XMLLayout extends AbstractStringLayout { buf.append(this.eol); } + if (event.getMarker() != null) { + final Marker marker = event.getMarker(); + buf.append(this.indent2); + buf.append('<'); + if (!complete) { + buf.append(this.namespacePrefix); + } + buf.append("Marker"); + final Marker parent = marker.getParent(); + if (parent != null) { + buf.append(" parent=\"").append(Transform.escapeHtmlTags(parent.getName())).append("\""); + } + buf.append('>'); + buf.append(Transform.escapeHtmlTags(marker.getName())); + buf.append("</"); + if (!complete) { + buf.append(this.namespacePrefix); + } + buf.append("Marker>"); + buf.append(this.eol); + } + final Throwable throwable = event.getThrown(); if (throwable != null) { final List<String> s = Throwables.toStringList(throwable);
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-447_0343e9c7.diff
bugs-dot-jar_data_LOG4J2-104_3b12e13d
--- BugID: LOG4J2-104 Summary: LogManager initialization failed when running from Jdeveloper. Description: "This issue was incorrectly opened in bugzilla as https://issues.apache.org/bugzilla/show_bug.cgi?id=54053 by Evgeny.\n\n\nSteps to Reproduce:\n//config file presents or not - does not meter.\n\nRun / Debug simple application:\n\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\npublic class test_log {\n public test_log() {\n super();\n }\n \n static Logger logger = LogManager.getLogger(test_log.class.getName());\n\n \ public static void main(String[] args) {\n test_log test_log = new test_log();\n \ \n logger.entry();\n\n logger.debug(\"test\");\n\n logger.error(\"test Err\");\n\n logger.exit();\n \n\n }\n...\n}\n\nActual Results:\nFailed with error\njava.lang.ExceptionInInitializerError\n\tat view.test_log.<clinit>(test_log.java:13)\nCaused by: java.lang.ClassCastException: oracle.xml.parser.v2.DTD cannot be cast to org.w3c.dom.Element\n\tat java.util.XMLUtils.load(XMLUtils.java:61)\n\tat java.util.Properties.loadFromXML(Properties.java:852)\n\tat org.apache.logging.log4j.LogManager.<clinit>(LogManager.java:77)\n\nAdditional Info:\nWhen xmlparserv2.jar is deleted - application run fine.\nBut - it have to be presents - when deleted, JDeveloper failed to start." diff --git a/api/src/main/java/org/apache/logging/log4j/LogManager.java b/api/src/main/java/org/apache/logging/log4j/LogManager.java index 8f050ee..a6452cb 100644 --- a/api/src/main/java/org/apache/logging/log4j/LogManager.java +++ b/api/src/main/java/org/apache/logging/log4j/LogManager.java @@ -39,7 +39,7 @@ public class LogManager { */ public static final String ROOT_LOGGER_NAME = ""; - private static final String LOGGER_RESOURCE = "META-INF/log4j-provider.xml"; + private static final String LOGGER_RESOURCE = "META-INF/log4j-provider.properties"; private static final String LOGGER_CONTEXT_FACTORY = "LoggerContextFactory"; private static final String API_VERSION = "Log4jAPIVersion"; private static final String FACTORY_PRIORITY = "FactoryPriority"; @@ -95,7 +95,7 @@ public class LogManager { Properties props = new Properties(); URL url = enumResources.nextElement(); try { - props.loadFromXML(url.openStream()); + props.load(url.openStream()); } catch (IOException ioe) { logger.error("Unable to read " + url.toString(), ioe); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-104_3b12e13d.diff
bugs-dot-jar_data_LOG4J2-127_029e79da
--- BugID: LOG4J2-127 Summary: Methods info, warn, error, fatal with marker and message do not pass the marker Description: | The follwing methods do not log the message, because the marker is not passed to isXxxEnabled: AbstractLogger.info(Marker, Message) AbstractLogger.warn(Marker, Message) AbstractLogger.error(Marker, Message) AbstractLogger.fatal(Marker, Message) diff --git a/api/src/main/java/org/apache/logging/log4j/spi/AbstractLogger.java b/api/src/main/java/org/apache/logging/log4j/spi/AbstractLogger.java index 8e50b5b..675d58c 100644 --- a/api/src/main/java/org/apache/logging/log4j/spi/AbstractLogger.java +++ b/api/src/main/java/org/apache/logging/log4j/spi/AbstractLogger.java @@ -1157,7 +1157,7 @@ public abstract class AbstractLogger implements Logger { */ public void error(Marker marker, Message msg) { if (isEnabled(Level.ERROR, marker, msg, null)) { - log(null, FQCN, Level.ERROR, msg, null); + log(marker, FQCN, Level.ERROR, msg, null); } } @@ -1354,7 +1354,7 @@ public abstract class AbstractLogger implements Logger { */ public void fatal(Marker marker, Message msg) { if (isEnabled(Level.FATAL, marker, msg, null)) { - log(null, FQCN, Level.FATAL, msg, null); + log(marker, FQCN, Level.FATAL, msg, null); } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-127_029e79da.diff
bugs-dot-jar_data_LOG4J2-1068_e7bbeceb
--- BugID: LOG4J2-1068 Summary: Exceptions not logged when using TcpSocketServer + SerializedLayout Description: | This issue was reported in BugZilla bug 57036: https://bz.apache.org/bugzilla/show_bug.cgi?id=57036. The description there covers the problem well: "... in the Method format(final LogEvent event, final StringBuilder toAppendTo) in ExtendedThrowablePatternConverter writing the Stacktrace in the logfile on condition that the Throwable throwable from Log4jLogEvent is not null, but on the Socketserver the Throwable throwable is always null, because it's defined as transient." I couldn't find the bug here in Jira, so I'm reporting again in case it has been lost in the migration. It's a major problem with a simple fix, so seems like it should be a high priority. I've worked around it for now by plugging in my own ExtendedThrowablePatternConverter. My fix is to change this line: if (throwable != null && options.anyLines() { to this: if ((throwable != null || proxy != null) && options.anyLines()) { diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/ExtendedThrowablePatternConverter.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/ExtendedThrowablePatternConverter.java index 3897721..2357093 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/ExtendedThrowablePatternConverter.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/ExtendedThrowablePatternConverter.java @@ -64,7 +64,7 @@ public final class ExtendedThrowablePatternConverter extends ThrowablePatternCon proxy = ((Log4jLogEvent) event).getThrownProxy(); } final Throwable throwable = event.getThrown(); - if (throwable != null && options.anyLines()) { + if ((throwable != null || proxy != null) && options.anyLines()) { if (proxy == null) { super.format(event, toAppendTo); return;
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1068_e7bbeceb.diff
bugs-dot-jar_data_LOG4J2-1310_c6318b63
--- BugID: LOG4J2-1310 Summary: JndiLookup mindlessly casts to String and should use String.valueOf() Description: The value returned from Context.lookup() is cast to String which can cause problems if the value is, well, anything else. diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java index d7d50cb..1cd4290 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java @@ -52,7 +52,7 @@ public class JndiLookup extends AbstractLookup { final String jndiName = convertJndiName(key); final JndiManager jndiManager = JndiManager.getDefaultManager(); try { - return jndiManager.lookup(jndiName); + return String.valueOf(jndiManager.lookup(jndiName)); } catch (final NamingException e) { LOGGER.warn(LOOKUP, "Error looking up JNDI resource [{}].", jndiName, e); return null;
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1310_c6318b63.diff
bugs-dot-jar_data_MNG-5459_c225847e
--- BugID: MNG-5459 Summary: failure to resolve pom artifact from snapshotVersion in maven-metadata.xml Description: |- We're using Artifactory on the server side, and ivy / sbt to publish artifacts upstream. After publishing several -SNAPSHOT versions of a project, trying to use it from Maven, resulted in a warning and ultimately a build failure because it cannot determine the dependencies: {code}[WARNING] The POM for com.foo:bar:jar:0.4.0-20130404.093655-3 is missing, no dependency information available{code} This is the corresponding maven-metadata-snapshots.xml: {code:xml} <metadata> <groupId>com.foo</groupId> <artifactId>bar</artifactId> <version>0.4.0-SNAPSHOT</version> <versioning> <snapshot> <timestamp>20130404.090532</timestamp> <buildNumber>2</buildNumber> </snapshot> <lastUpdated>20130404093657</lastUpdated> <snapshotVersions> <snapshotVersion> <extension>pom</extension> <value>0.4.0-20130404.090532-2</value> <updated>20130404090532</updated> </snapshotVersion> <snapshotVersion> <extension>jar</extension> <value>0.4.0-20130404.093655-3</value> <updated>20130404093655</updated> </snapshotVersion> </snapshotVersions> </versioning> </metadata> {code} As you can see, the <value> for the jar artifact and the pom artifact differ: 0.4.0-20130404.093655-3 0.4.0-20130404.090532-2 Apparently, artifactory optimizes the case when an artifact doesn't change; it does not create a new file, but just links to the existing one. Maven, however, takes a shortcut and makes the erroneous assumption that the values for pom and jar artifact always match up. The attached patch fixes this. diff --git a/maven-aether-provider/src/main/java/org/apache/maven/repository/internal/DefaultArtifactDescriptorReader.java b/maven-aether-provider/src/main/java/org/apache/maven/repository/internal/DefaultArtifactDescriptorReader.java index 380a607..59a955d 100644 --- a/maven-aether-provider/src/main/java/org/apache/maven/repository/internal/DefaultArtifactDescriptorReader.java +++ b/maven-aether-provider/src/main/java/org/apache/maven/repository/internal/DefaultArtifactDescriptorReader.java @@ -275,6 +275,7 @@ private Model loadPom( RepositorySystemSession session, ArtifactDescriptorReques Set<String> visited = new LinkedHashSet<String>(); for ( Artifact artifact = request.getArtifact();; ) { + Artifact pomArtifact = ArtifactDescriptorUtils.toPomArtifact( artifact ); try { VersionRequest versionRequest = @@ -283,6 +284,13 @@ private Model loadPom( RepositorySystemSession session, ArtifactDescriptorReques VersionResult versionResult = versionResolver.resolveVersion( session, versionRequest ); artifact = artifact.setVersion( versionResult.getVersion() ); + + versionRequest = + new VersionRequest( pomArtifact, request.getRepositories(), request.getRequestContext() ); + versionRequest.setTrace( trace ); + versionResult = versionResolver.resolveVersion( session, versionRequest ); + + pomArtifact = pomArtifact.setVersion( versionResult.getVersion() ); } catch ( VersionResolutionException e ) { @@ -303,8 +311,6 @@ private Model loadPom( RepositorySystemSession session, ArtifactDescriptorReques throw new ArtifactDescriptorException( result ); } - Artifact pomArtifact = ArtifactDescriptorUtils.toPomArtifact( artifact ); - ArtifactResult resolveResult; try {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5459_c225847e.diff
bugs-dot-jar_data_MNG-3131_56cd921f
--- BugID: MNG-3131 Summary: Error message is misleading if a missing plugin parameter is of a type like List Description: |- Here is a sample output I got when I was working on the changes-plugin: {code} [INFO] One or more required plugin parameters are invalid/missing for 'changes:announcement-mail' [0] inside the definition for plugin: 'maven-changes-plugin'specify the following: <configuration> ... <smtpHost>VALUE</smtpHost> </configuration>. [1] inside the definition for plugin: 'maven-changes-plugin'specify the following: <configuration> ... <toAddresses>VALUE</toAddresses> </configuration>. {code} Notice the second parameter toAdresses. It is of the type List, so the correct configuration would be something like this {code} <configuration> ... <toAddresses> <toAddress>VALUE</toAddress> </toAddresses> </configuration>. {code} I haven't found where in the code base the handling of List/Map/Array parameters is. That code could probably be borrowed/reused in maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java which is the class responsible for formating the above messages. diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java index 07302e5..350349d 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java @@ -19,8 +19,10 @@ * under the License. */ +import java.util.Collection; import java.util.Iterator; import java.util.List; +import java.util.Map; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.Parameter; @@ -75,12 +77,53 @@ private static void decomposeParameterIntoUserInstructions( MojoDescriptor mojo, StringBuilder messageBuffer ) { String expression = param.getExpression(); - + if ( param.isEditable() ) { - messageBuffer.append( "Inside the definition for plugin \'" + mojo.getPluginDescriptor().getArtifactId() - + "\', specify the following:\n\n<configuration>\n ...\n <" + param.getName() + ">VALUE</" - + param.getName() + ">\n</configuration>" ); + boolean isArray = param.getType().endsWith( "[]" ); + boolean isCollection = false; + boolean isMap = false; + if ( !isArray ) + { + try + { + //assuming Type is available in current ClassLoader + isCollection = Collection.class.isAssignableFrom( Class.forName( param.getType() ) ); + isMap = Map.class.isAssignableFrom( Class.forName( param.getType() ) ); + } + catch ( ClassNotFoundException e ) + { + // assume it is not assignable from Collection or Map + } + } + + messageBuffer.append( "Inside the definition for plugin \'"); + messageBuffer.append( mojo.getPluginDescriptor().getArtifactId() ); + messageBuffer.append( "\', specify the following:\n\n<configuration>\n ...\n" ); + messageBuffer.append( " <" ).append( param.getName() ).append( '>' ); + if( isArray || isCollection ) + { + messageBuffer.append( '\n' ); + messageBuffer.append( " <item>" ); + } + else if ( isMap ) + { + messageBuffer.append( '\n' ); + messageBuffer.append( " <KEY>" ); + } + messageBuffer.append( "VALUE" ); + if( isArray || isCollection ) + { + messageBuffer.append( "</item>\n" ); + messageBuffer.append( " " ); + } + else if ( isMap ) + { + messageBuffer.append( "</KEY>\n" ); + messageBuffer.append( " " ); + } + messageBuffer.append( "</" ).append( param.getName() ).append( ">\n" ); + messageBuffer.append( "</configuration>" ); String alias = param.getAlias(); if ( StringUtils.isNotEmpty( alias ) && !alias.equals( param.getName() ) )
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-3131_56cd921f.diff
bugs-dot-jar_data_MNG-5645_af1ecd5f
--- BugID: MNG-5645 Summary: version of "..." causes InternalErrorException. Description: |- The following dependency causes InternalErrorException. <dependency> <groupId>any</groupId> <artifactId>any</artifactId> <version>...</version> </dependency> This can be confusing to a new maven user trying to get a dependency to work. A patch is attached that fixes the problem. diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/DefaultArtifactVersion.java b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/DefaultArtifactVersion.java index 745afdd..6a6ab74 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/DefaultArtifactVersion.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/DefaultArtifactVersion.java @@ -21,6 +21,7 @@ import java.util.StringTokenizer; import java.util.regex.Pattern; +import java.util.NoSuchElementException; /** * Default implementation of artifact versioning. @@ -204,12 +205,18 @@ public final void parseVersion( String version ) private static Integer getNextIntegerToken( StringTokenizer tok ) { - String s = tok.nextToken(); - if ( ( s.length() > 1 ) && s.startsWith( "0" ) ) + try { + String s = tok.nextToken(); + if ( ( s.length() > 1 ) && s.startsWith( "0" ) ) + { + throw new NumberFormatException( "Number part has a leading 0: '" + s + "'" ); + } + return Integer.valueOf( s ); + } + catch( NoSuchElementException e ) { - throw new NumberFormatException( "Number part has a leading 0: '" + s + "'" ); + throw new NumberFormatException( "Number is invalid" ); } - return Integer.valueOf( s ); } @Override
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5645_af1ecd5f.diff
bugs-dot-jar_data_MNG-4941_c4002945
--- BugID: MNG-4941 Summary: PluginDescriptorBuilder doesn't populate expression/default-value fields for mojo parameters Description: As noted by Guo Du in his patch for MPH-81, the mojo descriptors created by the {{PluginDescriptorBuilder}} come out with parameter descriptors that always return null for the parameter expression and default value. diff --git a/maven-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/PluginDescriptorBuilder.java b/maven-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/PluginDescriptorBuilder.java index 8947094..66b1691 100644 --- a/maven-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/PluginDescriptorBuilder.java +++ b/maven-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/PluginDescriptorBuilder.java @@ -255,6 +255,13 @@ public class PluginDescriptorBuilder } // ---------------------------------------------------------------------- + // Configuration + // ---------------------------------------------------------------------- + + PlexusConfiguration mojoConfig = c.getChild( "configuration" ); + mojo.setMojoConfiguration( mojoConfig ); + + // ---------------------------------------------------------------------- // Parameters // ---------------------------------------------------------------------- @@ -292,6 +299,13 @@ public class PluginDescriptorBuilder parameter.setImplementation( d.getChild( "implementation" ).getValue() ); + PlexusConfiguration paramConfig = mojoConfig.getChild( parameter.getName(), false ); + if ( paramConfig != null ) + { + parameter.setExpression( paramConfig.getValue( null ) ); + parameter.setDefaultValue( paramConfig.getAttribute( "default-value" ) ); + } + parameters.add( parameter ); } @@ -300,15 +314,6 @@ public class PluginDescriptorBuilder // TODO: this should not need to be handed off... // ---------------------------------------------------------------------- - // Configuration - // ---------------------------------------------------------------------- - - mojo.setMojoConfiguration( c.getChild( "configuration" ) ); - - // TODO: Go back to this when we get the container ready to configure mojos... - // mojo.setConfiguration( c.getChild( "configuration" ) ); - - // ---------------------------------------------------------------------- // Requirements // ----------------------------------------------------------------------
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4941_c4002945.diff
bugs-dot-jar_data_MNG-1895_24db0eb9
--- BugID: MNG-1895 Summary: Dependencies in two paths are not added to resolution when scope needs to be updated in the nearest due to any of nearest parents Description: | scopes are not correctly calculated for this case my pom: a compile, b test a: c compile, d compile b: d compile then d ends in test scope because d is closer to my project through the path b-d I think scope importance should also be taken into account diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java index c467098..b6d379e 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java @@ -201,14 +201,15 @@ public class DefaultArtifactCollector if ( checkScopeUpdate( farthest, nearest, listeners ) ) { fireEvent( ResolutionListener.UPDATE_SCOPE, listeners, nearest, farthest.getArtifact() ); - - // previously we cloned the artifact, but it is more effecient to just update the scope - // if problems are later discovered that the original object needs its original scope value, cloning may - // again be appropriate - nearest.getArtifact().setScope( farthest.getArtifact().getScope() ); + /* we need nearest version but farthest scope */ + nearest.disable(); + farthest.getArtifact().setVersion( nearest.getArtifact().getVersion() ); + } + else + { + farthest.disable(); } fireEvent( ResolutionListener.OMIT_FOR_NEARER, listeners, farthest, nearest.getArtifact() ); - farthest.disable(); } } }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-1895_24db0eb9.diff
bugs-dot-jar_data_MNG-1895_806eaeb0
--- BugID: MNG-1895 Summary: Dependencies in two paths are not added to resolution when scope needs to be updated in the nearest due to any of nearest parents Description: | scopes are not correctly calculated for this case my pom: a compile, b test a: c compile, d compile b: d compile then d ends in test scope because d is closer to my project through the path b-d I think scope importance should also be taken into account diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java index b6d379e..108a976 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java @@ -81,7 +81,7 @@ public class DefaultArtifactCollector if ( node.filterTrail( filter ) ) { - // If it was optional and not a direct dependency, + // If it was optional and not a direct dependency, // we don't add it or its children, just allow the update of the version and scope if ( node.isChildOfRootNode() || !artifact.isOptional() ) { @@ -137,18 +137,7 @@ public class DefaultArtifactCollector VersionRange previousRange = previous.getArtifact().getVersionRange(); VersionRange currentRange = node.getArtifact().getVersionRange(); - // TODO: why do we force the version on it? what if they don't match? - if ( previousRange == null ) - { - // version was already resolved - node.getArtifact().setVersion( previous.getArtifact().getVersion() ); - } - else if ( currentRange == null ) - { - // version was already resolved - previous.getArtifact().setVersion( node.getArtifact().getVersion() ); - } - else + if ( previousRange != null && currentRange != null ) { // TODO: shouldn't need to double up on this work, only done for simplicity of handling recommended // version but the restriction is identical @@ -185,7 +174,8 @@ public class DefaultArtifactCollector // TODO: should this be part of mediation? // previous one is more dominant - ResolutionNode nearest, farthest; + ResolutionNode nearest; + ResolutionNode farthest; if ( previous.getDepth() <= node.getDepth() ) { nearest = previous; @@ -197,11 +187,9 @@ public class DefaultArtifactCollector farthest = previous; } - /* if we need to update scope of nearest to use farthest scope */ if ( checkScopeUpdate( farthest, nearest, listeners ) ) { - fireEvent( ResolutionListener.UPDATE_SCOPE, listeners, nearest, farthest.getArtifact() ); - /* we need nearest version but farthest scope */ + // if we need to update scope of nearest to use farthest scope, use the nearest version, but farthest scope nearest.disable(); farthest.getArtifact().setVersion( nearest.getArtifact().getVersion() ); } @@ -321,13 +309,14 @@ public class DefaultArtifactCollector } /** - * Check if the scope of the nearest needs to be updated with the scope of the farthest. + * Check if the scope needs to be updated. * <a href="http://docs.codehaus.org/x/IGU#DependencyMediationandConflictResolution-Scoperesolution">More info</a>. - * @param farthest farthest resolution node - * @param nearest nearest resolution node + * + * @param farthest farthest resolution node + * @param nearest nearest resolution node * @param listeners */ - private boolean checkScopeUpdate( ResolutionNode farthest, ResolutionNode nearest, List listeners ) + boolean checkScopeUpdate( ResolutionNode farthest, ResolutionNode nearest, List listeners ) { boolean updateScope = false; Artifact farthestArtifact = farthest.getArtifact(); @@ -354,6 +343,16 @@ public class DefaultArtifactCollector fireEvent( ResolutionListener.UPDATE_SCOPE_CURRENT_POM, listeners, nearest, farthestArtifact ); } + if ( updateScope ) + { + fireEvent( ResolutionListener.UPDATE_SCOPE, listeners, nearest, farthestArtifact ); + + // previously we cloned the artifact, but it is more effecient to just update the scope + // if problems are later discovered that the original object needs its original scope value, cloning may + // again be appropriate + nearestArtifact.setScope( farthestArtifact.getScope() ); + } + return updateScope; } diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java index 067e790..7d39bf9 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java @@ -146,7 +146,7 @@ public class ResolutionNode { return children != null; } - + public boolean isChildOfRootNode() { return parent != null && parent.parent == null; @@ -219,7 +219,7 @@ public class ResolutionNode public String toString() { - return artifact.toString() + " (" + depth + ")"; + return artifact.toString() + " (" + depth + "; " + ( active ? "enabled" : "disabled" ) + ")"; } }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-1895_806eaeb0.diff
bugs-dot-jar_data_MNG-5727_ce6f0bfd
--- BugID: MNG-5727 Summary: unexpected InvalidArtifactRTException from ProjectBuilder#build Description: "Calling into ProjectBuilder#build(File, ProjectBuildingRequest) results in InvalidArtifactRTException below if project pom.xml has managed dependency without <version>. Although the pom is invalid, I expected to get ProjectBuildingException that includes location of problematic dependency, similar to what I get during command line build.\n\n{code}\norg.apache.maven.artifact.InvalidArtifactRTException: For artifact {org.apache.maven.its:a:null:jar}: The version cannot be empty.\n\tat org.apache.maven.artifact.DefaultArtifact.validateIdentity(DefaultArtifact.java:148)\n\tat org.apache.maven.artifact.DefaultArtifact.<init>(DefaultArtifact.java:123)\n\tat org.apache.maven.bridge.MavenRepositorySystem.XcreateArtifact(MavenRepositorySystem.java:695)\n\tat org.apache.maven.bridge.MavenRepositorySystem.XcreateDependencyArtifact(MavenRepositorySystem.java:613)\n\tat org.apache.maven.bridge.MavenRepositorySystem.createDependencyArtifact(MavenRepositorySystem.java:121)\n\tat org.apache.maven.project.DefaultProjectBuilder.initProject(DefaultProjectBuilder.java:808)\n\tat org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:174)\n\tat org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:118)\n...\n{code}\n\n" diff --git a/maven-core/src/main/java/org/apache/maven/bridge/MavenRepositorySystem.java b/maven-core/src/main/java/org/apache/maven/bridge/MavenRepositorySystem.java index 839c089..e01ffc3 100644 --- a/maven-core/src/main/java/org/apache/maven/bridge/MavenRepositorySystem.java +++ b/maven-core/src/main/java/org/apache/maven/bridge/MavenRepositorySystem.java @@ -107,6 +107,11 @@ public Artifact createProjectArtifact( String groupId, String artifactId, String // DefaultProjectBuilder public Artifact createDependencyArtifact( Dependency d ) { + if ( d.getVersion() == null ) + { + return null; + } + VersionRange versionRange; try { diff --git a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java index e359bcf..5365756 100644 --- a/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java @@ -807,12 +807,10 @@ private void initProject( MavenProject project, Map<String, MavenProject> projec { Artifact artifact = repositorySystem.createDependencyArtifact( d ); - if ( artifact == null ) + if ( artifact != null ) { - map = Collections.emptyMap(); + map.put( d.getManagementKey(), artifact ); } - - map.put( d.getManagementKey(), artifact ); } } else
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5727_ce6f0bfd.diff
bugs-dot-jar_data_MNG-5647_cdb8ad6d
--- BugID: MNG-5647 Summary: "${maven.build.timestamp} uses incorrect ISO datetime separator" Description: Separator must be {{T}} and not {{-}} if we predefine ISO 8601 datetime format. Additionally, {{Z}} should be added to denote UTC time zone. diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/MavenBuildTimestamp.java b/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/MavenBuildTimestamp.java index d342566..447f0ef 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/MavenBuildTimestamp.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/MavenBuildTimestamp.java @@ -26,7 +26,8 @@ public class MavenBuildTimestamp { - public static final String DEFAULT_BUILD_TIMESTAMP_FORMAT = "yyyyMMdd-HHmm"; + // ISO 8601-compliant timestamp for machine readability + public static final String DEFAULT_BUILD_TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; public static final String BUILD_TIMESTAMP_FORMAT_PROPERTY = "maven.build.timestamp.format"; @@ -35,8 +36,8 @@ public MavenBuildTimestamp() { this( new Date() ); - } - + } + public MavenBuildTimestamp( Date time ) { this( time, DEFAULT_BUILD_TIMESTAMP_FORMAT );
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5647_cdb8ad6d.diff
bugs-dot-jar_data_MNG-1703_b68c84b8
--- BugID: MNG-1703 Summary: "<pluginManagement><dependencies> is not propagated to child POMs" Description: |- <executions> section in <pluginManagement> isn't propagated to child POMs (as <configuration> is). The workaround is to use <plugins> with <inherited>true</inherited> Is this on purpose ? diff --git a/maven-project/src/main/java/org/apache/maven/project/ModelUtils.java b/maven-project/src/main/java/org/apache/maven/project/ModelUtils.java index ec56f1b..b0c6c75 100644 --- a/maven-project/src/main/java/org/apache/maven/project/ModelUtils.java +++ b/maven-project/src/main/java/org/apache/maven/project/ModelUtils.java @@ -53,6 +53,7 @@ import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TreeMap; +import java.util.HashMap; public final class ModelUtils { @@ -64,7 +65,7 @@ public final class ModelUtils // nothing to do. return; } - + List mergedPlugins = new ArrayList(); List parentPlugins = parentContainer.getPlugins(); @@ -208,6 +209,8 @@ public final class ModelUtils child.setConfiguration( childConfiguration ); + child.setDependencies( mergeDependencyList( child.getDependencies(), parent.getDependencies() ) ); + // from here to the end of the method is dealing with merging of the <executions/> section. String parentInherited = parent.getInherited(); @@ -1000,4 +1003,30 @@ public final class ModelUtils } } } + + public static List mergeDependencyList( List child, List parent ) + { + Map depsMap = new HashMap(); + + if ( parent != null ) + { + for ( Iterator it = parent.iterator(); it.hasNext(); ) + { + Dependency dependency = (Dependency) it.next(); + depsMap.put( dependency.getManagementKey(), dependency ); + } + } + + if ( child != null ) + { + for ( Iterator it = child.iterator(); it.hasNext(); ) + { + Dependency dependency = (Dependency) it.next(); + depsMap.put( dependency.getManagementKey(), dependency ); + } + } + + return new ArrayList( depsMap.values() ); + } + }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-1703_b68c84b8.diff
bugs-dot-jar_data_MNG-4512_8cb04253
--- BugID: MNG-4512 Summary: "[regression] Profile activation based on JDK version range fails if current version is close to range boundary" Description: "The POM snippet\n{code:xml}\n<profiles>\n <profile>\n <id>test</id>\n \ <activation>\n <jdk>[1.5,1.6)</jdk>\n </activation>\n </profile>\n</profiles>\n{code}\nyields\n{noformat}\n[ERROR] \ The project org.apache.maven.its.mng:test:0.1 has 1 error\n[ERROR] Failed to determine activation for profile test: For input string: \"0_07\"\njava.lang.NumberFormatException: For input string: \"0_07\"\n at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)\n \ at java.lang.Integer.parseInt(Integer.java:456)\n at java.lang.Integer.parseInt(Integer.java:497)\n \ at o.a.m.model.profile.activation.JdkVersionProfileActivator.getRelationOrder(JdkVersionProfileActivator.java:124)\n \ at o.a.m.model.profile.activation.JdkVersionProfileActivator.isInRange(JdkVersionProfileActivator.java:96)\n \ at o.a.m.model.profile.activation.JdkVersionProfileActivator.isActive(JdkVersionProfileActivator.java:70)\n{noformat}\nwhen run with JDK 1.6.0_07 in this case. \n" diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java index 9cf3123..617ffa2 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java @@ -103,7 +103,9 @@ public class JdkVersionProfileActivator return isLeft ? 1 : -1; } - List<String> valueTokens = new ArrayList<String>( Arrays.asList( value.split( "\\." ) ) ); + value = value.replaceAll( "[^0-9\\.\\-\\_]", "" ); + + List<String> valueTokens = new ArrayList<String>( Arrays.asList( value.split( "[\\.\\-\\_]" ) ) ); List<String> rangeValueTokens = new ArrayList<String>( Arrays.asList( rangeValue.value.split( "\\." ) ) ); int max = Math.max( valueTokens.size(), rangeValueTokens.size() ); @@ -119,7 +121,7 @@ public class JdkVersionProfileActivator return 0; } - for ( int i = 0; i < valueTokens.size(); i++ ) + for ( int i = 0; i < valueTokens.size() && i < rangeValueTokens.size(); i++ ) { int x = Integer.parseInt( valueTokens.get( i ) ); int y = Integer.parseInt( rangeValueTokens.get( i ) );
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4512_8cb04253.diff
bugs-dot-jar_data_MNG-5716_2d0ec942
--- BugID: MNG-5716 Summary: ToolchainManagerPrivate.getToolchainsForType() returns toolchains that are not of expected type Description: |- found while working on maven-toolchains-plugin 1.1: {noformat}[INFO] Required toolchain: fake-type [ other-attribute='other-value' attribute='value' ] [DEBUG] Toolchain JDK[/home/opt/jdk1.5] is missing required property: other-attribute [DEBUG] Toolchain JDK[/home/opt/jdk1.6] is missing required property: other-attribute [DEBUG] Toolchain JDK[/home/opt/jdk1.7] is missing required property: other-attribute [DEBUG] Toolchain JDK[/home/opt/jdk1.8] is missing required property: other-attribute [ERROR] No toolchain matched for type fake-type [INFO] Required toolchain: another-fake-type [ any ] [INFO] Toolchain matched for type another-fake-type: JDK[/home/opt/jdk1.5]{noformat} these jdk toochains should not have been ever tested again non-jdk type requirement diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java index 923db00..e2eacea 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java @@ -74,7 +74,7 @@ throw new MisconfiguredToolchainException( e.getMessage(), e ); } - PersistedToolchains pers = buildResult.getEffectiveToolchains(); + PersistedToolchains effectiveToolchains = buildResult.getEffectiveToolchains(); List<ToolchainPrivate> toRet = new ArrayList<ToolchainPrivate>(); @@ -84,9 +84,9 @@ logger.error( "Missing toolchain factory for type: " + type + ". Possibly caused by misconfigured project." ); } - else if ( pers != null ) + else { - List<ToolchainModel> lst = pers.getToolchains(); + List<ToolchainModel> lst = effectiveToolchains.getToolchains(); if ( lst != null ) { for ( ToolchainModel toolchainModel : lst ) @@ -97,11 +97,9 @@ else if ( pers != null ) } } } - } - - for ( ToolchainFactory toolchainFactory : factories.values() ) - { - ToolchainPrivate tool = toolchainFactory.createDefaultToolchain(); + + // add default toolchain + ToolchainPrivate tool = fact.createDefaultToolchain(); if ( tool != null ) { toRet.add( tool ); diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/building/DefaultToolchainsBuildingResult.java b/maven-core/src/main/java/org/apache/maven/toolchain/building/DefaultToolchainsBuildingResult.java index b50473f..b72e5aa 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/building/DefaultToolchainsBuildingResult.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/building/DefaultToolchainsBuildingResult.java @@ -26,6 +26,7 @@ import org.apache.maven.toolchain.model.PersistedToolchains; /** + * Holds the result of the merged toolchains and holds the problems during this build, if any. * * @author Robert Scholte * @since 3.2.6 @@ -38,6 +39,12 @@ private List<Problem> problems; + /** + * Default constructor + * + * @param effectiveToolchains the merged toolchains, may not be {@code null} + * @param problems the problems while building the effectiveToolchains, if any. + */ public DefaultToolchainsBuildingResult( PersistedToolchains effectiveToolchains, List<Problem> problems ) { this.effectiveToolchains = effectiveToolchains;
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5716_2d0ec942.diff
bugs-dot-jar_data_MNG-2712_06090da4
--- BugID: MNG-2712 Summary: update policy 'daily' not honored Description: |- under certain circumstances, the '<updatePolicy>daily</updatePolicy>' isn't honored. This is the case where the remote metadata file doesn't exist, or contains <version>RELEASE/LATEST (which should never happen).. The timestamp used to compare for the update is 0L, because the local file doesn't exist. Then the remote file is retrieved, which also doesn't exist, and no metadatafile is created. The next time an up2date check is done, again against timestamp 0 for a non-existent file. This means that if you define a custom snapshot repo in settings.xml or a pom, and you have 500 transitive deps, the repo's that don't have that artifact are consulted 500 times for each mvn invocation. A build that normally takes about 20 seconds takes more than 10 minutes because of this bug. diff --git a/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java b/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java index 603dfea..d5a6460 100644 --- a/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java +++ b/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java @@ -113,16 +113,16 @@ public abstract class AbstractRepositoryMetadata { changed = metadata.merge( this.metadata ); } - + // beware meta-versions! String version = metadata.getVersion(); if ( version != null && ( Artifact.LATEST_VERSION.equals( version ) || Artifact.RELEASE_VERSION.equals( version ) ) ) { // meta-versions are not valid <version/> values...don't write them. - changed = false; + metadata.setVersion( null ); } - if ( changed ) + if ( changed || !metadataFile.exists() ) { Writer writer = null; try diff --git a/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java b/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java index c82d607..ddc23c0 100644 --- a/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java +++ b/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java @@ -78,6 +78,8 @@ public class DefaultRepositoryMetadataManager File file = new File( localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata( metadata, repository ) ); + + boolean checkForUpdates = policy.checkOutOfDate( new Date( file.lastModified() ) ) || !file.exists(); @@ -106,7 +108,7 @@ public class DefaultRepositoryMetadataManager { file.setLastModified( System.currentTimeMillis() ); } - else if ( !metadataIsEmpty ) + else { // this ensures that files are not continuously checked when they don't exist remotely try
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-2712_06090da4.diff
bugs-dot-jar_data_MNG-3131_f6f4ef5e
--- BugID: MNG-3131 Summary: Error message is misleading if a missing plugin parameter is of a type like List Description: |- Here is a sample output I got when I was working on the changes-plugin: {code} [INFO] One or more required plugin parameters are invalid/missing for 'changes:announcement-mail' [0] inside the definition for plugin: 'maven-changes-plugin'specify the following: <configuration> ... <smtpHost>VALUE</smtpHost> </configuration>. [1] inside the definition for plugin: 'maven-changes-plugin'specify the following: <configuration> ... <toAddresses>VALUE</toAddresses> </configuration>. {code} Notice the second parameter toAdresses. It is of the type List, so the correct configuration would be something like this {code} <configuration> ... <toAddresses> <toAddress>VALUE</toAddress> </toAddresses> </configuration>. {code} I haven't found where in the code base the handling of List/Map/Array parameters is. That code could probably be borrowed/reused in maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java which is the class responsible for formating the above messages. diff --git a/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java b/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java index 350349d..4027fcc 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/PluginParameterException.java @@ -23,6 +23,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Properties; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.Parameter; @@ -83,6 +84,7 @@ private static void decomposeParameterIntoUserInstructions( MojoDescriptor mojo, boolean isArray = param.getType().endsWith( "[]" ); boolean isCollection = false; boolean isMap = false; + boolean isProperties = false; if ( !isArray ) { try @@ -90,6 +92,7 @@ private static void decomposeParameterIntoUserInstructions( MojoDescriptor mojo, //assuming Type is available in current ClassLoader isCollection = Collection.class.isAssignableFrom( Class.forName( param.getType() ) ); isMap = Map.class.isAssignableFrom( Class.forName( param.getType() ) ); + isProperties = Properties.class.isAssignableFrom( Class.forName( param.getType() ) ); } catch ( ClassNotFoundException e ) { @@ -106,6 +109,13 @@ private static void decomposeParameterIntoUserInstructions( MojoDescriptor mojo, messageBuffer.append( '\n' ); messageBuffer.append( " <item>" ); } + else if ( isProperties ) + { + messageBuffer.append( '\n' ); + messageBuffer.append( " <property>\n" ); + messageBuffer.append( " <name>KEY</name>\n" ); + messageBuffer.append( " <value>" ); + } else if ( isMap ) { messageBuffer.append( '\n' ); @@ -116,7 +126,13 @@ else if ( isMap ) { messageBuffer.append( "</item>\n" ); messageBuffer.append( " " ); - } + } + else if ( isProperties ) + { + messageBuffer.append( "</value>\n" ); + messageBuffer.append( " </property>\n" ); + messageBuffer.append( " " ); + } else if ( isMap ) { messageBuffer.append( "</KEY>\n" );
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-3131_f6f4ef5e.diff
bugs-dot-jar_data_MNG-5209_ed651a4d
--- BugID: MNG-5209 Summary: MavenProject.getTestClasspathElements can return null elements Description: 'A broken {{MavenProject}} can return null values in certain lists, which seems incorrect (at least it is undocumented). Root cause of: http://netbeans.org/bugzilla/show_bug.cgi?id=205867' diff --git a/maven-core/src/main/java/org/apache/maven/project/MavenProject.java b/maven-core/src/main/java/org/apache/maven/project/MavenProject.java index 088289d..1e235f2 100644 --- a/maven-core/src/main/java/org/apache/maven/project/MavenProject.java +++ b/maven-core/src/main/java/org/apache/maven/project/MavenProject.java @@ -504,7 +504,11 @@ public class MavenProject { List<String> list = new ArrayList<String>( getArtifacts().size() + 1 ); - list.add( getBuild().getOutputDirectory() ); + String d = getBuild().getOutputDirectory(); + if ( d != null ) + { + list.add( d ); + } for ( Artifact a : getArtifacts() ) { @@ -580,9 +584,17 @@ public class MavenProject { List<String> list = new ArrayList<String>( getArtifacts().size() + 2 ); - list.add( getBuild().getTestOutputDirectory() ); + String d = getBuild().getTestOutputDirectory(); + if ( d != null ) + { + list.add( d ); + } - list.add( getBuild().getOutputDirectory() ); + d = getBuild().getOutputDirectory(); + if ( d != null ) + { + list.add( d ); + } for ( Artifact a : getArtifacts() ) { @@ -644,7 +656,11 @@ public class MavenProject { List<String> list = new ArrayList<String>( getArtifacts().size() + 1 ); - list.add( getBuild().getOutputDirectory() ); + String d = getBuild().getOutputDirectory(); + if ( d != null ) + { + list.add( d ); + } for ( Artifact a : getArtifacts() ) { @@ -717,7 +733,11 @@ public class MavenProject { List<String> list = new ArrayList<String>( getArtifacts().size() ); - list.add( getBuild().getOutputDirectory() ); + String d = getBuild().getOutputDirectory(); + if ( d != null ) + { + list.add( d ); + } for ( Artifact a : getArtifacts() ) {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5209_ed651a4d.diff
bugs-dot-jar_data_MNG-4518_f5ebc72d
--- BugID: MNG-4518 Summary: Profile activation based on JRE version misbehaves if java.version has build number Description: |- For this POM snippet {code:xml} <profiles> <profile> <id>test</id> <activation> <jdk>[1.6,)</jdk> </activation> </profile> </profiles> {code} running "mvn help:active-profiles -V" delivers: {noformat} >mvn help:active-profiles -V Apache Maven 2.2.1 (r801777; 2009-08-06 21:16:01+0200) Java version: 1.6.0_07 Java home: D:\Programme\Java\jdk-1.6.0_07\jre Default locale: de_DE, platform encoding: Cp1252 OS name: "windows xp" version: "5.1" arch: "x86" Family: "windows" [INFO] Scanning for projects... [INFO] Searching repository for plugin with prefix: 'help'. [INFO] ------------------------------------------------------------------------ [INFO] Building Maven Integration Test :: MNG- [INFO] task-segment: [help:active-profiles] (aggregator-style) [INFO] ------------------------------------------------------------------------ [INFO] [help:active-profiles {execution: default-cli}] [INFO] Active Profiles for Project 'org.apache.maven.its.mng:test:jar:0.1': There are no active profiles. {noformat} This is due to the version 1.6.0_07 which when parsed with Maven version rules is considered older than 1.6. diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java index 617ffa2..1ae90e1 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java @@ -108,20 +108,10 @@ public class JdkVersionProfileActivator List<String> valueTokens = new ArrayList<String>( Arrays.asList( value.split( "[\\.\\-\\_]" ) ) ); List<String> rangeValueTokens = new ArrayList<String>( Arrays.asList( rangeValue.value.split( "\\." ) ) ); - int max = Math.max( valueTokens.size(), rangeValueTokens.size() ); - addZeroTokens( valueTokens, max ); - addZeroTokens( rangeValueTokens, max ); + addZeroTokens( valueTokens, 3 ); + addZeroTokens( rangeValueTokens, 3 ); - if ( value.equals( rangeValue.getValue() ) ) - { - if ( !rangeValue.isClosed() ) - { - return isLeft ? -1 : 1; - } - return 0; - } - - for ( int i = 0; i < valueTokens.size() && i < rangeValueTokens.size(); i++ ) + for ( int i = 0; i < 3; i++ ) { int x = Integer.parseInt( valueTokens.get( i ) ); int y = Integer.parseInt( rangeValueTokens.get( i ) ); @@ -143,12 +133,9 @@ public class JdkVersionProfileActivator private static void addZeroTokens( List<String> tokens, int max ) { - if ( tokens.size() < max ) + while ( tokens.size() < max ) { - for ( int i = 0; i < ( max - tokens.size() ); i++ ) - { - tokens.add( "0" ); - } + tokens.add( "0" ); } }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4518_f5ebc72d.diff
bugs-dot-jar_data_MNG-3616_912a565f
--- BugID: MNG-3616 Summary: Null Pointer Exception when mirrorOf missing from mirror in settings.xml Description: "When attempting to generate any archetype from the mvn archetype:generate command I get a null pointer exception thrown if I have mirrors defined in my settings.xml file but fail to have the mirrorOf element set. \n\nThe stack trace for the archetype generation is:\n\nChoose a number: (1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/21/22/23/2\n4/25/26/27/28/29/30/31/32/33/34/35/36/37/38/39/40/41/42/43/44) 15: : 6\n[INFO] ------------------------------------------------------------------------\n[ERROR] BUILD FAILURE\n[INFO] ------------------------------------------------------------------------\n[INFO] : java.lang.NullPointerException\nnull\n[INFO] ------------------------------------------------------------------------\n[INFO] Trace\norg.apache.maven.BuildFailureException\nat org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(Defa\nultLifecycleExecutor.java:579)\nat org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandalone\nGoal(DefaultLifecycleExecutor.java:512)\nat org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(Defau\nltLifecycleExecutor.java:482)\nat org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHan\ndleFailures(DefaultLifecycleExecutor.java:330)\nat org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegmen\nts(DefaultLifecycleExecutor.java:227)\nat org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLi\nfecycleExecutor.java:142)\nat org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)\nat org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)\nat org.apache.maven.cli.MavenCli.main(MavenCli.java:287)\nat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\nat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.\njava:39)\nat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces\nsorImpl.java:25)\nat java.lang.reflect.Method.invoke(Method.java:585)\nat org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)\nat org.codehaus.classworlds.Launcher.launch(Launcher.java:255)\nat org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)\n\nat org.codehaus.classworlds.Launcher.main(Launcher.java:375)\nCaused by: org.apache.maven.plugin.MojoFailureException\nat org.apache.maven.archetype.mojos.CreateProjectFromArchetypeMojo.execu\nte(CreateProjectFromArchetypeMojo.java:202)\nat org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPlugi\nnManager.java:451)\nat org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(Defa\nultLifecycleExecutor.java:558)\n... 16 more\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 7 seconds\n[INFO] Finished at: Wed May 28 17:49:39 EST 2008\n[INFO] Final Memory: 8M/14M\n[INFO] ------------------------------------------------------------------------\n\nC:\\Documents and Settings\\frank\\My Documents\\Development\\Sandbox>mvn -v\nMaven version: 2.0.9\nJava version: 1.5.0_08\nOS name: \"windows xp\" version: \"5.1\" arch: \"x86\" Family: \"windows\"\n\nThe mirrored settings from the settings.xml file are:\n\n<mirrors>\n<mirror>\n<id>nexus-central</id>\n<url>http://maven.ho.bushlife.com.au:8081/nexus/content/groups/public</url>\n</mirror>\n</mirrors>\n\n\nAs a user you receive a null pointer exception because of something missing in the settings.xml file.\n\nAt the very least you should receive an error message indicating the problem. If you can have a situation where the mirrorOf setting is optional, then it should not be throwing a null pointer exception but handling it better.\n" diff --git a/maven-core/src/main/java/org/apache/maven/settings/validation/DefaultSettingsValidator.java b/maven-core/src/main/java/org/apache/maven/settings/validation/DefaultSettingsValidator.java index b44d8d9..0b6eaaf 100644 --- a/maven-core/src/main/java/org/apache/maven/settings/validation/DefaultSettingsValidator.java +++ b/maven-core/src/main/java/org/apache/maven/settings/validation/DefaultSettingsValidator.java @@ -21,12 +21,15 @@ package org.apache.maven.settings.validation; import java.util.List; +import org.apache.maven.settings.Mirror; import org.apache.maven.settings.Profile; import org.apache.maven.settings.Repository; +import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.settings.building.SettingsProblem; import org.apache.maven.settings.building.SettingsProblemCollector; import org.codehaus.plexus.component.annotations.Component; +import org.codehaus.plexus.util.StringUtils; /** * @author Milos Kleint @@ -36,16 +39,69 @@ public class DefaultSettingsValidator implements SettingsValidator { + private static final String ID_REGEX = "[A-Za-z0-9_\\-.]+"; + public void validate( Settings settings, SettingsProblemCollector problems ) { + if ( settings.isUsePluginRegistry() ) + { + addWarn( problems, "'usePluginRegistry' is deprecated and has no effect." ); + } + + List<String> pluginGroups = settings.getPluginGroups(); + + if ( pluginGroups != null ) + { + for ( int i = 0; i < pluginGroups.size(); i++ ) + { + String pluginGroup = pluginGroups.get( i ).trim(); + + if ( StringUtils.isBlank( pluginGroup ) ) + { + addError( problems, "'pluginGroups.pluginGroup[" + i + "]' must not be empty." ); + } + else if ( !pluginGroup.matches( ID_REGEX ) ) + { + addError( problems, "'pluginGroups.pluginGroup[" + i + + "]' must denote a valid group id and match the pattern " + ID_REGEX ); + } + } + } + + List<Server> servers = settings.getServers(); + + if ( servers != null ) + { + for ( int i = 0; i < servers.size(); i++ ) + { + Server server = servers.get( i ); + + validateStringNotEmpty( problems, "servers.server[" + i + "].id", server.getId(), null ); + } + } + + List<Mirror> mirrors = settings.getMirrors(); + + if ( mirrors != null ) + { + for ( Mirror mirror : mirrors ) + { + validateStringNotEmpty( problems, "mirrors.mirror.id", mirror.getId(), mirror.getUrl() ); + + validateStringNotEmpty( problems, "mirrors.mirror.url", mirror.getUrl(), mirror.getId() ); + + validateStringNotEmpty( problems, "mirrors.mirror.mirrorOf", mirror.getMirrorOf(), mirror.getId() ); + } + } + List<Profile> profiles = settings.getProfiles(); if ( profiles != null ) { - for ( Profile prof : profiles ) + for ( Profile profile : profiles ) { - validateRepositories( problems, prof.getRepositories(), "repositories.repository" ); - validateRepositories( problems, prof.getPluginRepositories(), "pluginRepositories.pluginRepository" ); + validateRepositories( problems, profile.getRepositories(), "repositories.repository" ); + validateRepositories( problems, profile.getPluginRepositories(), "pluginRepositories.pluginRepository" ); } } } @@ -54,9 +110,15 @@ public class DefaultSettingsValidator { for ( Repository repository : repositories ) { - validateStringNotEmpty( problems, prefix + ".id", repository.getId() ); + validateStringNotEmpty( problems, prefix + ".id", repository.getId(), repository.getUrl() ); + + validateStringNotEmpty( problems, prefix + ".url", repository.getUrl(), repository.getId() ); - validateStringNotEmpty( problems, prefix + ".url", repository.getUrl() ); + if ( "legacy".equals( repository.getLayout() ) ) + { + addWarn( problems, "'" + prefix + ".layout' for " + repository.getId() + + " uses the deprecated value 'legacy'." ); + } } } @@ -64,11 +126,6 @@ public class DefaultSettingsValidator // Field validation // ---------------------------------------------------------------------- - private boolean validateStringNotEmpty( SettingsProblemCollector problems, String fieldName, String string ) - { - return validateStringNotEmpty( problems, fieldName, string, null ); - } - /** * Asserts: * <p/> @@ -137,4 +194,9 @@ public class DefaultSettingsValidator problems.add( SettingsProblem.Severity.ERROR, msg, -1, -1, null ); } + private void addWarn( SettingsProblemCollector problems, String msg ) + { + problems.add( SettingsProblem.Severity.WARNING, msg, -1, -1, null ); + } + }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-3616_912a565f.diff
bugs-dot-jar_data_MNG-5742_6ab41ee8
--- BugID: MNG-5742 Summary: inconsistent classloading for extensions=true plugins Description: 'Maven creates two class realms for build extensions plugins. One realm is used to contribute core extensions and the other to execute plugins goals. The two realms have slightly different classpath, with extensions realm not "seeing" classes from other extensions and not resolving reactor dependencies. The two realms are mostly independent and have duplicate copies of components, including duplicate copies of singletons. This results in multiple invocation of singleton components in some cases. This also results inconsistent/unexpected component wiring. ' diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java index c815920..5704276 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java @@ -390,8 +390,6 @@ private void createPluginRealm( PluginDescriptor pluginDescriptor, MavenSession RepositorySystemSession repositorySession = session.getRepositorySession(); if ( plugin.isExtensions() ) { - // TODO discover components in #setupExtensionsRealm - ExtensionRealmCache.CacheRecord extensionRecord; try { @@ -406,6 +404,11 @@ private void createPluginRealm( PluginDescriptor pluginDescriptor, MavenSession pluginRealm = extensionRecord.realm; pluginArtifacts = extensionRecord.artifacts; + + for ( ComponentDescriptor<?> componentDescriptor : pluginDescriptor.getComponents() ) + { + componentDescriptor.setRealm( pluginRealm ); + } } else { @@ -877,6 +880,8 @@ public void releaseMojo( Object mojo, MojoExecution mojoExecution ) { ClassRealm extensionRealm = classRealmManager.createExtensionRealm( plugin, toAetherArtifacts( artifacts ) ); + // TODO figure out how to use the same PluginDescriptor when running mojos + PluginDescriptor pluginDescriptor = null; if ( plugin.isExtensions() && !artifacts.isEmpty() ) {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5742_6ab41ee8.diff
bugs-dot-jar_data_MNG-5212_712c4fff
--- BugID: MNG-5212 Summary: DefaultPluginDescriptorCache does not retain pluginDescriptor dependencies Description: PluginDescriptor dependencies is defined in META-INF/maven/plugin.xml, so there is no reason not to retain this field when storing and retrieving PluginDescriptor instances to and from descriptor cache. The attribute can be used in embedding scenarios and for command line builds to quickly determine if plugin has certain dependencies or not, without having to fully resolve plugin dependencies. I'll commit a fix with corresponding unit test shortly. diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java index 96b8274..8bb6909 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java @@ -96,6 +96,8 @@ public class DefaultPluginDescriptorCache clone.setId( original.getId() ); clone.setIsolatedRealm( original.isIsolatedRealm() ); clone.setSource( original.getSource() ); + + clone.setDependencies( original.getDependencies() ); } return clone;
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5212_712c4fff.diff
bugs-dot-jar_data_MNG-1856_faa5cf27
--- BugID: MNG-1856 Summary: legacy layout tag in a profile does not show up in child pom. Description: "the legacy layout tag in a profile does not show up in an inherited pom.\n\nGiven the following pom.xml:\n\n<project>\n <modelVersion>4.0.0</modelVersion>\n \ <groupId>xxx</groupId>\n <artifactId>yyy</artifactId>\n <version>1.0-SNAPSHOT</version>\n \ <packaging>pom</packaging>\n <profiles>\n <profile>\n <id>maven-1</id>\n \ <activation>\n <property>\n <name>maven1</name>\n </property>\n \ </activation>\n <distributionManagement>\n <repository>\n <id>maven-1-repo</id>\n \ <name>Maven1 Repository</name>\n <url>sftp://...</url>\n <layout>legacy</layout>\n \ </repository>\n </distributionManagement> \n </profile>\n </profiles>\n</project>\n\ngives for:\n\nmvn projecthelp:effective-pom -Dmaven1\n\nthe following result:\n\n...\n \ <distributionManagement>\n <repository>\n <id>maven-1-repo</id>\n <name>Maven1 Repository</name>\n <url>sftp://...</url>\n <layout>legacy</layout>\n \ </repository>\n </distributionManagement>\n</project>\n\nwhich is CORRECT, however if I inherit from this pom with the following pom.xml:\n\n<project>\n <parent>\n \ <groupId>xxx</groupId>\n <artifactId>yyy</artifactId>\n <version>1.0-SNAPSHOT</version>\n \ </parent>\n <modelVersion>4.0.0</modelVersion>\n <groupId>uuu</groupId>\n <artifactId>vvv</artifactId>\n \ <version>2.0-SNAPSHOT</version>\n</project>\n\ngives for:\n\nmvn projecthelp:effective-pom -Dmaven1\n\nthe following result:\n\n...\n <distributionManagement>\n <repository>\n \ <id>maven-1-repo</id>\n <name>Maven1 Repository</name>\n <url>sftp://...</url>\n \ </repository>\n </distributionManagement>\n</project>\n\nwhich is INCORRECT, the layout tag is missing.\n\nThis issue may be related to:\n\nhttp://jira.codehaus.org/browse/MNG-731\nhttp://jira.codehaus.org/browse/MNG-1756\n" diff --git a/maven-project/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java b/maven-project/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java index 2839c50..1d2268f 100644 --- a/maven-project/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java +++ b/maven-project/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java @@ -107,10 +107,6 @@ public class DefaultModelInheritanceAssembler } } - // ---------------------------------------------------------------------- - // Distribution - // ---------------------------------------------------------------------- - assembleDistributionInheritence( child, parent, childPathAdjustment, appendPaths ); // issueManagement @@ -177,8 +173,6 @@ public class DefaultModelInheritanceAssembler assembleDependencyManagementInheritance( child, parent ); - assembleDistributionManagementInheritance( child, parent ); - Properties props = new Properties(); props.putAll( parent.getProperties() ); props.putAll( child.getProperties() ); @@ -186,46 +180,6 @@ public class DefaultModelInheritanceAssembler child.setProperties( props ); } - private void assembleDistributionManagementInheritance( Model child, Model parent ) - { - DistributionManagement cDistMgmt = child.getDistributionManagement(); - DistributionManagement pDistMgmt = parent.getDistributionManagement(); - - if ( cDistMgmt == null ) - { - child.setDistributionManagement( pDistMgmt ); - } - else if ( pDistMgmt != null ) - { - if ( cDistMgmt.getRepository() == null ) - { - cDistMgmt.setRepository( pDistMgmt.getRepository() ); - } - - if ( cDistMgmt.getSnapshotRepository() == null ) - { - cDistMgmt.setSnapshotRepository( pDistMgmt.getSnapshotRepository() ); - } - - if ( StringUtils.isEmpty( cDistMgmt.getDownloadUrl() ) ) - { - cDistMgmt.setDownloadUrl( pDistMgmt.getDownloadUrl() ); - } - - if ( cDistMgmt.getRelocation() == null ) - { - cDistMgmt.setRelocation( pDistMgmt.getRelocation() ); - } - - if ( cDistMgmt.getSite() == null ) - { - cDistMgmt.setSite( pDistMgmt.getSite() ); - } - - // NOTE: We SHOULD NOT be inheriting status, since this is an assessment of the POM quality. - } - } - private void assembleDependencyManagementInheritance( Model child, Model parent ) { DependencyManagement parentDepMgmt = parent.getDependencyManagement(); @@ -486,17 +440,8 @@ public class DefaultModelInheritanceAssembler { if ( parentDistMgmt.getRepository() != null ) { - DeploymentRepository repository = new DeploymentRepository(); - + DeploymentRepository repository = copyDistributionRepository( parentDistMgmt.getRepository() ); childDistMgmt.setRepository( repository ); - - repository.setId( parentDistMgmt.getRepository().getId() ); - - repository.setName( parentDistMgmt.getRepository().getName() ); - - repository.setUrl( parentDistMgmt.getRepository().getUrl() ); - - repository.setUniqueVersion( parentDistMgmt.getRepository().isUniqueVersion() ); } } @@ -504,20 +449,37 @@ public class DefaultModelInheritanceAssembler { if ( parentDistMgmt.getSnapshotRepository() != null ) { - DeploymentRepository repository = new DeploymentRepository(); - + DeploymentRepository repository = + copyDistributionRepository( parentDistMgmt.getSnapshotRepository() ); childDistMgmt.setSnapshotRepository( repository ); + } + } + + if ( StringUtils.isEmpty( childDistMgmt.getDownloadUrl() ) ) + { + childDistMgmt.setDownloadUrl( parentDistMgmt.getDownloadUrl() ); + } - repository.setId( parentDistMgmt.getSnapshotRepository().getId() ); + // NOTE: We SHOULD NOT be inheriting status, since this is an assessment of the POM quality. + // NOTE: We SHOULD NOT be inheriting relocation, since this relates to a single POM + } + } - repository.setName( parentDistMgmt.getSnapshotRepository().getName() ); + private static DeploymentRepository copyDistributionRepository( DeploymentRepository parentRepository ) + { + DeploymentRepository repository = new DeploymentRepository(); - repository.setUrl( parentDistMgmt.getSnapshotRepository().getUrl() ); + repository.setId( parentRepository.getId() ); - repository.setUniqueVersion( parentDistMgmt.getSnapshotRepository().isUniqueVersion() ); - } - } - } + repository.setName( parentRepository.getName() ); + + repository.setUrl( parentRepository.getUrl() ); + + repository.setLayout( parentRepository.getLayout() ); + + repository.setUniqueVersion( parentRepository.isUniqueVersion() ); + + return repository; } protected String appendPath( String parentPath, String childPath, String pathAdjustment, boolean appendPaths )
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-1856_faa5cf27.diff
bugs-dot-jar_data_MNG-2221_cc859f5c
--- BugID: MNG-2221 Summary: Multiple Executions of Plugin at Difference Inhertiance levels causes plugin executions to run multiple times Description: |- Can occur in a variety of ways, but the attached test case shows a parent pom defining an antrun-execution, and then a child specifying another execution with a different id. Both executions run twice when running from the child. I believe this is the same as Kenney Westerhof's comment: http://jira.codehaus.org/browse/MNG-2054#action_62477 diff --git a/maven-project/src/main/java/org/apache/maven/project/ModelUtils.java b/maven-project/src/main/java/org/apache/maven/project/ModelUtils.java index 66527df..7e6de40 100644 --- a/maven-project/src/main/java/org/apache/maven/project/ModelUtils.java +++ b/maven-project/src/main/java/org/apache/maven/project/ModelUtils.java @@ -82,6 +82,11 @@ public final class ModelUtils String parentInherited = parentPlugin.getInherited(); + // only merge plugin definition from the parent if at least one + // of these is true: + // 1. we're not processing the plugins in an inheritance-based merge + // 2. the parent's <inherited/> flag is not set + // 3. the parent's <inherited/> flag is set to true if ( !handleAsInheritance || parentInherited == null || Boolean.valueOf( parentInherited ).booleanValue() ) { @@ -97,18 +102,21 @@ public final class ModelUtils mergePluginDefinitions( childPlugin, parentPlugin, handleAsInheritance ); } + // if we're processing this as an inheritance-based merge, and + // the parent's <inherited/> flag is not set, then we need to + // clear the inherited flag in the merge result. if ( handleAsInheritance && parentInherited == null ) { assembledPlugin.unsetInheritanceApplied(); } mergedPlugins.add(assembledPlugin); + + // fix for MNG-2221 (assembly cache was not being populated for later reference): + assembledPlugins.put( assembledPlugin.getKey(), assembledPlugin ); } } - // FIXME: not sure what's intended here, but this entire - // loop can be replaced by 'mergedPlugins.addAll( childPlugins.values() ); - // since assembledPlugins is never updated and remains empty. for ( Iterator it = childPlugins.values().iterator(); it.hasNext(); ) { Plugin childPlugin = (Plugin) it.next();
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-2221_cc859f5c.diff
bugs-dot-jar_data_MNG-5075_2eb419ed
--- BugID: MNG-5075 Summary: MavenProject.getParent throws undocumented ISE Description: |- http://bugzilla-attachments-197994.netbeans.org/bugzilla/attachment.cgi?id=107899 shows a stack trace encountered when calling {{MavenProject.getParent}} on a project with some errors (probably POMs missing in the local repository). This method has no Javadoc comment, so it is hard to know exactly what it is permitted/supposed to do, but {{hasParent}} implies that {{null}} is a valid return value, and there is no {{throws IllegalStateException}} clause. The attached patch brings the behavior in line with that signature. (I think I got the {{PlexusTestCase}} infrastructure working with all the required wiring but it may be possible to simplify the test case.) Cleaner might be to just declare {{getParent}} (and also {{hasParent}}?) to throw {{ProjectBuildingException}}, though this would be a source-incompatible change. (Only binary-incompatible for clients which are already catching {{IllegalStateException}}!) diff --git a/maven-core/src/main/java/org/apache/maven/project/MavenProject.java b/maven-core/src/main/java/org/apache/maven/project/MavenProject.java index d6f308f..91038b3 100644 --- a/maven-core/src/main/java/org/apache/maven/project/MavenProject.java +++ b/maven-core/src/main/java/org/apache/maven/project/MavenProject.java @@ -102,6 +102,8 @@ public static final String EMPTY_PROJECT_VERSION = "0"; + private static final MavenProject ERROR_BUILDING_PARENT = new MavenProject(); + private Model model; private MavenProject parent; @@ -343,6 +345,10 @@ public Model getModel() return model; } + /** + * Returns the project corresponding to a declared parent. + * @return the parent, or null if no parent is declared or there was an error building it + */ public MavenProject getParent() { if ( parent == null ) @@ -363,7 +369,11 @@ public MavenProject getParent() } catch ( ProjectBuildingException e ) { - throw new IllegalStateException( "Failed to build parent project for " + getId(), e ); + if ( logger != null ) + { + logger.error( "Failed to build parent project for " + getId(), e ); + } + parent = ERROR_BUILDING_PARENT; } } else if ( model.getParent() != null ) @@ -378,11 +388,15 @@ else if ( model.getParent() != null ) } catch ( ProjectBuildingException e ) { - throw new IllegalStateException( "Failed to build parent project for " + getId(), e ); + if ( logger != null ) + { + logger.error( "Failed to build parent project for " + getId(), e ); + } + parent = ERROR_BUILDING_PARENT; } } } - return parent; + return parent == ERROR_BUILDING_PARENT ? null : parent; } public void setParent( MavenProject parent )
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5075_2eb419ed.diff
bugs-dot-jar_data_MNG-1509_4e955c05
--- BugID: MNG-1509 Summary: Profile activation by os doesn't work Description: |+ Profile activation by os doesn't work. OperatingSystemProfileActivator is missing in components.xml. Implementation of OperatingSystemProfileActivator.isActive is wrong. diff --git a/maven-project/src/main/java/org/apache/maven/profiles/activation/OperatingSystemProfileActivator.java b/maven-project/src/main/java/org/apache/maven/profiles/activation/OperatingSystemProfileActivator.java index 72575fe..7b068e7 100644 --- a/maven-project/src/main/java/org/apache/maven/profiles/activation/OperatingSystemProfileActivator.java +++ b/maven-project/src/main/java/org/apache/maven/profiles/activation/OperatingSystemProfileActivator.java @@ -35,17 +35,28 @@ public class OperatingSystemProfileActivator { Activation activation = profile.getActivation(); ActivationOS os = activation.getOs(); - - boolean hasNonNull = ensureAtLeastOneNonNull( os ); - - boolean isFamily = determineFamilyMatch( os.getFamily() ); - boolean isName = determineNameMatch( os.getName() ); - boolean isArch = determineArchMatch( os.getArch() ); - boolean isVersion = determineVersionMatch( os.getVersion() ); - - return hasNonNull && isFamily && isName && isArch && isVersion; + + boolean result = ensureAtLeastOneNonNull( os ); + + if ( result && os.getFamily() != null ) + { + result = determineFamilyMatch( os.getFamily() ); + } + if ( result && os.getName() != null ) + { + result = determineNameMatch( os.getName() ); + } + if ( result && os.getArch() != null ) + { + result = determineArchMatch( os.getArch() ); + } + if ( result && os.getVersion() != null ) + { + result = determineVersionMatch( os.getVersion() ); + } + return result; } - + private boolean ensureAtLeastOneNonNull( ActivationOS os ) { return os.getArch() != null || os.getFamily() != null || os.getName() != null || os.getVersion() != null; @@ -107,9 +118,9 @@ public class OperatingSystemProfileActivator reverse = true; test = test.substring( 1 ); } - + boolean result = Os.isName( test ); - + if ( reverse ) { return !result;
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-1509_4e955c05.diff
bugs-dot-jar_data_MNG-5212_c53d95ce
--- BugID: MNG-5212 Summary: DefaultPluginDescriptorCache does not retain pluginDescriptor dependencies Description: PluginDescriptor dependencies is defined in META-INF/maven/plugin.xml, so there is no reason not to retain this field when storing and retrieving PluginDescriptor instances to and from descriptor cache. The attribute can be used in embedding scenarios and for command line builds to quickly determine if plugin has certain dependencies or not, without having to fully resolve plugin dependencies. I'll commit a fix with corresponding unit test shortly. diff --git a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java index 96b8274..8bb6909 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginDescriptorCache.java @@ -96,6 +96,8 @@ public class DefaultPluginDescriptorCache clone.setId( original.getId() ); clone.setIsolatedRealm( original.isIsolatedRealm() ); clone.setSource( original.getSource() ); + + clone.setDependencies( original.getDependencies() ); } return clone;
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5212_c53d95ce.diff
bugs-dot-jar_data_MNG-2408_b92af0e4
--- BugID: MNG-2408 Summary: Improve handling of "no plugin version found" error after intermittent errors Description: "If you follow the instructions at http://maven.apache.org/guides/getting-started/index.html#How%20do%20I%20make%20my%20first%20Maven%20project? to use the archetype plugin to create a new project skeleton, the suggested command line fails as below.\n\nIt seems there is a typo of some kind in the suggested command line, I am not familiar enough with maven 2 to know for sure.\n\nGraham-Leggetts-Computer:~/src/standard/alchemy/maven minfrin$ mvn archetype:create -DgroupId=za.co.standardbank.alchemy -DartifactId=alchemy-trader \ \n[INFO] Scanning for projects...\n[INFO] Searching repository for plugin with prefix: 'archetype'.\n[INFO] ------------------------------------------------------------------------\n[ERROR] BUILD ERROR\n[INFO] ------------------------------------------------------------------------\n[INFO] The plugin 'org.apache.maven.plugins:maven-archetype-plugin' does not exist or no valid version could be found\n[INFO] ------------------------------------------------------------------------\n[INFO] For more information, run Maven with the -e switch\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 1 second\n[INFO] Finished at: Tue Jun 27 09:43:14 SAST 2006\n[INFO] Final Memory: 1M/2M\n[INFO] ------------------------------------------------------------------------\n" diff --git a/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java b/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java index 3b09252..603dfea 100644 --- a/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java +++ b/maven-artifact-manager/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java @@ -113,6 +113,14 @@ public abstract class AbstractRepositoryMetadata { changed = metadata.merge( this.metadata ); } + + // beware meta-versions! + String version = metadata.getVersion(); + if ( version != null && ( Artifact.LATEST_VERSION.equals( version ) || Artifact.RELEASE_VERSION.equals( version ) ) ) + { + // meta-versions are not valid <version/> values...don't write them. + changed = false; + } if ( changed ) {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-2408_b92af0e4.diff
bugs-dot-jar_data_MNG-5655_96337372
--- BugID: MNG-5655 Summary: WeakMojoExecutionListener callbacks invoked multiple times in some cases Description: When the same WeakMojoExecutionListener instance is injected under multiple component Key's, the instance before/after execution callbacks are invoked multiple times. diff --git a/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScope.java b/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScope.java index fc8b1e6..d8a5f6c 100644 --- a/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScope.java +++ b/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScope.java @@ -19,6 +19,8 @@ * under the License. */ +import java.util.Collection; +import java.util.IdentityHashMap; import java.util.LinkedList; import java.util.Map; @@ -177,36 +179,42 @@ protected void configure() public void beforeMojoExecution( MojoExecutionEvent event ) throws MojoExecutionException { - for ( Object provided : getScopeState().provided.values() ) + for ( WeakMojoExecutionListener provided : getProvidedListeners() ) { - if ( provided instanceof WeakMojoExecutionListener ) - { - ( (WeakMojoExecutionListener) provided ).beforeMojoExecution( event ); - } + provided.beforeMojoExecution( event ); } } public void afterMojoExecutionSuccess( MojoExecutionEvent event ) throws MojoExecutionException { - for ( Object provided : getScopeState().provided.values() ) + for ( WeakMojoExecutionListener provided : getProvidedListeners() ) { - if ( provided instanceof WeakMojoExecutionListener ) - { - ( (WeakMojoExecutionListener) provided ).afterMojoExecutionSuccess( event ); - } + provided.afterMojoExecutionSuccess( event ); } } public void afterExecutionFailure( MojoExecutionEvent event ) { + for ( WeakMojoExecutionListener provided : getProvidedListeners() ) + { + provided.afterExecutionFailure( event ); + } + } + + private Collection<WeakMojoExecutionListener> getProvidedListeners() + { + // the same instance can be provided multiple times under different Key's + // deduplicate instances to avoid redundant beforeXXX/afterXXX callbacks + IdentityHashMap<WeakMojoExecutionListener, Object> listeners = + new IdentityHashMap<WeakMojoExecutionListener, Object>(); for ( Object provided : getScopeState().provided.values() ) { if ( provided instanceof WeakMojoExecutionListener ) { - ( (WeakMojoExecutionListener) provided ).afterExecutionFailure( event ); + listeners.put( (WeakMojoExecutionListener) provided, null ); } } + return listeners.keySet(); } - }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5655_96337372.diff
bugs-dot-jar_data_MNG-2281_f0fcef7e
--- BugID: MNG-2281 Summary: 1.0-beta-3 should be < 1.0-SNAPSHOT Description: diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java index 3f36455..cf617d6 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java @@ -145,7 +145,7 @@ public class ComparableVersion private static class StringItem implements Item { - private final static String[] QUALIFIERS = { "snapshot", "alpha", "beta", "milestone", "rc", "", "sp" }; + private final static String[] QUALIFIERS = { "alpha", "beta", "milestone", "rc", "snapshot", "", "sp" }; private final static List<String> _QUALIFIERS = Arrays.asList( QUALIFIERS );
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-2281_f0fcef7e.diff
bugs-dot-jar_data_MNG-1205_1bdeeccc
--- BugID: MNG-1205 Summary: dependency with scope:system & flag optional = true doesn't appear in the class path Description: |- Dependency with scope:system & flag optional = true doesn't appear in the class path Try to call m2 install or compiler:compile in the attached project. Compilation will fail ... best regards JuBu diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java index 8f26cc7..3daff67 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java @@ -82,7 +82,7 @@ public class DefaultArtifactCollector if ( node.filterTrail( filter ) ) { // If it was optional, we don't add it or its children, just allow the update of the version and scope - if ( !artifact.isOptional() ) + if ( node.isChildOfRootNode() || !artifact.isOptional() ) { artifact.setDependencyTrail( node.getDependencyTrail() ); @@ -224,7 +224,7 @@ public class DefaultArtifactCollector { ResolutionNode child = (ResolutionNode) i.next(); // We leave in optional ones, but don't pick up its dependencies - if ( !child.isResolved() && !child.getArtifact().isOptional() ) + if ( !child.isResolved() && ( !child.getArtifact().isOptional() || child.isChildOfRootNode() ) ) { Artifact artifact = child.getArtifact(); try diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java index ef47794..c3f1f66 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java @@ -146,6 +146,11 @@ public class ResolutionNode { return children != null; } + + public boolean isChildOfRootNode() + { + return parent != null && parent.parent == null; + } public Iterator getChildrenIterator() {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-1205_1bdeeccc.diff
bugs-dot-jar_data_MNG-3092_5ffd8903
--- BugID: MNG-3092 Summary: Resolution of version ranges with non-snapshot bounds can resolve to a snapshot version Description: |- Contrary to the 2.0 design docs: "Resolution of dependency ranges should not resolve to a snapshot (development version) unless it is included as an explicit boundary." -- from http://docs.codehaus.org/display/MAVEN/Dependency+Mediation+and+Conflict+Resolution#DependencyMediationandConflictResolution-Incorporating%7B%7BSNAPSHOT%7D%7Dversionsintothespecification The following is equates to true: VersionRange.createFromVersionSpec( "[1.0,1.1]" ).containsVersion( new DefaultArtifactVersion( "1.1-SNAPSHOT" ) ) The attached patch only allows snapshot versions to be contained in a range if they are equal to one of the boundaries. Note that this is a strict equality, so [1.0,1.2-SNAPSHOT] will not contain 1.1-SNAPSHOT. diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/Restriction.java b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/Restriction.java index a3a1b77..f8de2c9 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/Restriction.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/Restriction.java @@ -1,6 +1,5 @@ package org.apache.maven.artifact.versioning; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -20,6 +19,8 @@ package org.apache.maven.artifact.versioning; * under the License. */ +import org.apache.maven.artifact.Artifact; + /** * Describes a restriction in versioning. * @@ -71,9 +72,17 @@ public class Restriction public boolean containsVersion( ArtifactVersion version ) { + boolean snapshot = isSnapshot( version ); + if ( lowerBound != null ) { int comparison = lowerBound.compareTo( version ); + + if ( snapshot && comparison == 0 ) + { + return true; + } + if ( ( comparison == 0 ) && !lowerBoundInclusive ) { return false; @@ -86,6 +95,12 @@ public class Restriction if ( upperBound != null ) { int comparison = upperBound.compareTo( version ); + + if ( snapshot && comparison == 0 ) + { + return true; + } + if ( ( comparison == 0 ) && !upperBoundInclusive ) { return false; @@ -95,9 +110,20 @@ public class Restriction return false; } } + + if ( lowerBound != null || upperBound != null ) + { + return !snapshot; + } + return true; } + private boolean isSnapshot( ArtifactVersion version ) + { + return Artifact.SNAPSHOT_VERSION.equals( version.getQualifier() ); + } + @Override public int hashCode() {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-3092_5ffd8903.diff
bugs-dot-jar_data_MNG-4383_0f3d4d24
--- BugID: MNG-4383 Summary: Uninterpolated expressions should cause an error for dependency versions Description: "I declared a dependency as such:\n{noformat}<dependency>\n <groupId>org.slf4j</groupId>\n \ <artifactId>slf4j-api</artifactId>\n <version>${slf4j.version}</version>\n</dependency>{noformat} \n\nBut did not define the *slf4j.version* property. Obviously ${...} is an expression and if the expression is not resolved, why allow it? Here was the output:\n\n{noformat} Downloading: http://repo1.maven.org/maven2/org/slf4j/slf4j-api/${slf4j.version}/slf4j-api-${slf4j.version}.pom{noformat} \n\nIn terms of usability, an obvious expression should be interpolated. If it cannot, it should be a runtime error." diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java b/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java index c60c446..4e429a4 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java @@ -139,8 +139,7 @@ public class DefaultModelValidator validateStringNotEmpty( "version", problems, false, model.getVersion() ); - boolean warnOnBadBoolean = request.getValidationLevel() < ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0; - boolean warnOnBadDependencyScope = request.getValidationLevel() < ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0; + boolean warnOnly = request.getValidationLevel() < ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0; for ( Dependency d : model.getDependencies() ) { @@ -178,12 +177,15 @@ public class DefaultModelValidator if ( request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 ) { - validateBoolean( "dependencies.dependency.optional", problems, warnOnBadBoolean, d.getOptional(), + validateVersion( "dependencies.dependency.version", problems, warnOnly, d.getVersion(), + d.getManagementKey() ); + + validateBoolean( "dependencies.dependency.optional", problems, warnOnly, d.getOptional(), d.getManagementKey() ); /* * TODO: Extensions like Flex Mojos use custom scopes like "merged", "internal", "external", etc. In - * order to don't break backward-compat with those, only warn but don't error our. + * order to don't break backward-compat with those, only warn but don't error out. */ validateEnum( "dependencies.dependency.scope", problems, true, d.getScope(), d.getManagementKey(), "provided", "compile", "runtime", "test", "system" ); @@ -227,8 +229,8 @@ public class DefaultModelValidator if ( request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 ) { - validateBoolean( "dependencyManagement.dependencies.dependency.optional", problems, - warnOnBadBoolean, d.getOptional(), d.getManagementKey() ); + validateBoolean( "dependencyManagement.dependencies.dependency.optional", problems, warnOnly, + d.getOptional(), d.getManagementKey() ); } } } @@ -250,16 +252,16 @@ public class DefaultModelValidator validateStringNotEmpty( "build.plugins.plugin.version", problems, warnOnMissingPluginVersion, p.getVersion(), p.getKey() ); - validateBoolean( "build.plugins.plugin.inherited", problems, warnOnBadBoolean, p.getInherited(), + validateBoolean( "build.plugins.plugin.inherited", problems, warnOnly, p.getInherited(), p.getKey() ); - validateBoolean( "build.plugins.plugin.extensions", problems, warnOnBadBoolean, p.getExtensions(), + validateBoolean( "build.plugins.plugin.extensions", problems, warnOnly, p.getExtensions(), p.getKey() ); for ( Dependency d : p.getDependencies() ) { validateEnum( "build.plugins.plugin[" + p.getKey() + "].dependencies.dependency.scope", - problems, warnOnBadDependencyScope, d.getScope(), d.getManagementKey(), + problems, warnOnly, d.getScope(), d.getManagementKey(), "compile", "runtime", "system" ); } } @@ -578,11 +580,12 @@ public class DefaultModelValidator if ( sourceHint != null ) { - addViolation( problems, warning, "'" + fieldName + "' must be 'true' or 'false' for " + sourceHint ); + addViolation( problems, warning, "'" + fieldName + "' must be 'true' or 'false' for " + sourceHint + + " but is '" + string + "'." ); } else { - addViolation( problems, warning, "'" + fieldName + "' must be 'true' or 'false'." ); + addViolation( problems, warning, "'" + fieldName + "' must be 'true' or 'false' but is '" + string + "'." ); } return false; @@ -605,11 +608,39 @@ public class DefaultModelValidator if ( sourceHint != null ) { - addViolation( problems, warning, "'" + fieldName + "' must be one of " + values + " for " + sourceHint ); + addViolation( problems, warning, "'" + fieldName + "' must be one of " + values + " for " + sourceHint + + " but is '" + string + "'." ); + } + else + { + addViolation( problems, warning, "'" + fieldName + "' must be one of " + values + " but is '" + string + + "'." ); + } + + return false; + } + + private boolean validateVersion( String fieldName, ModelProblemCollector problems, boolean warning, String string, + String sourceHint ) + { + if ( string == null || string.length() <= 0 ) + { + return true; + } + + if ( !hasExpression( string ) ) + { + return true; + } + + if ( sourceHint != null ) + { + addViolation( problems, warning, "'" + fieldName + "' must be a valid version for " + sourceHint + + " but is '" + string + "'." ); } else { - addViolation( problems, warning, "'" + fieldName + "' must be one of " + values ); + addViolation( problems, warning, "'" + fieldName + "' must be a valid version but is '" + string + "'." ); } return false;
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4383_0f3d4d24.diff
bugs-dot-jar_data_MNG-4565_c6529932
--- BugID: MNG-4565 Summary: Requiring multiple profile activation conditions to be true does not work Description: | According to the documentation at http://www.sonatype.com/books/mvnref-book/reference/profiles-sect-activation.html a profile is activated when all activation conditions are met (which makes sense of course). But when I try to use this it does not work. It seems maven does an OR instead of an AND (which is not rearly as useful and is the opposite of what the documentation says at the previous link). For example, if I have one profile that is activated like this: {code:xml} <activation> <activeByDefault>false</activeByDefault> <os> <name>linux</name> </os> </activation>{code} and another profile that is activated like this: {code:xml} <activation> <activeByDefault>false</activeByDefault> <os> <name>linux</name> </os> <property> <name>release</name> <value>true</value> </property> </activation>{code} Then I would expect the second profile to only be activated if the OS is linux and the release property is defined. When I run 'mvn help:active-profiles' however, maven shows that both profiles are active even though the release property is not defined. diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/profile/DefaultProfileSelector.java b/maven-model-builder/src/main/java/org/apache/maven/model/profile/DefaultProfileSelector.java index c376c99..0aeed9d 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/profile/DefaultProfileSelector.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/profile/DefaultProfileSelector.java @@ -104,13 +104,19 @@ else if ( isActiveByDefault( profile ) ) private boolean isActive( Profile profile, ProfileActivationContext context, ModelProblemCollector problems ) { + boolean isActive = false; + for ( ProfileActivator activator : activators ) { + if ( activator.presentInConfig( profile, context, problems ) ) { + isActive = true; + } + } for ( ProfileActivator activator : activators ) { try { - if ( activator.isActive( profile, context, problems ) ) + if ( activator.presentInConfig( profile, context, problems ) ) { - return true; + isActive &= activator.isActive( profile, context, problems ); } } catch ( RuntimeException e ) @@ -122,7 +128,7 @@ private boolean isActive( Profile profile, ProfileActivationContext context, Mod return false; } } - return false; + return isActive; } private boolean isActiveByDefault( Profile profile ) diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/FileProfileActivator.java b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/FileProfileActivator.java index 07ba79b..b1d0442 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/FileProfileActivator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/FileProfileActivator.java @@ -167,4 +167,23 @@ else if ( path.contains( "${basedir}" ) ) return missing ? !fileExists : fileExists; } + @Override + public boolean presentInConfig( Profile profile, ProfileActivationContext context, ModelProblemCollector problems ) + { + Activation activation = profile.getActivation(); + + if ( activation == null ) + { + return false; + } + + ActivationFile file = activation.getFile(); + + if ( file == null ) + { + return false; + } + return true; + } + } diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java index 62b6cfb..10747de 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/JdkVersionProfileActivator.java @@ -83,6 +83,25 @@ else if ( isRange( jdk ) ) } } + @Override + public boolean presentInConfig( Profile profile, ProfileActivationContext context, ModelProblemCollector problems ) + { + Activation activation = profile.getActivation(); + + if ( activation == null ) + { + return false; + } + + String jdk = activation.getJdk(); + + if ( jdk == null ) + { + return false; + } + return true; + } + private static boolean isInRange( String value, List<RangeValue> range ) { int leftRelation = getRelationOrder( value, range.get( 0 ), true ); diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/OperatingSystemProfileActivator.java b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/OperatingSystemProfileActivator.java index 94d380c..b6d3f05 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/OperatingSystemProfileActivator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/OperatingSystemProfileActivator.java @@ -76,6 +76,25 @@ public boolean isActive( Profile profile, ProfileActivationContext context, Mode return active; } + @Override + public boolean presentInConfig( Profile profile, ProfileActivationContext context, ModelProblemCollector problems ) + { + Activation activation = profile.getActivation(); + + if ( activation == null ) + { + return false; + } + + ActivationOS os = activation.getOs(); + + if ( os == null ) + { + return false; + } + return true; + } + private boolean ensureAtLeastOneNonNull( ActivationOS os ) { return os.getArch() != null || os.getFamily() != null || os.getName() != null || os.getVersion() != null; diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/ProfileActivator.java b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/ProfileActivator.java index 142dddf..7094a3f 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/ProfileActivator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/ProfileActivator.java @@ -43,4 +43,17 @@ */ boolean isActive( Profile profile, ProfileActivationContext context, ModelProblemCollector problems ); + /** + * Determines whether specified activation method is present in configuration or not. It should help to have AND between + * activation conditions + * Need for solving http://jira.codehaus.org/browse/MNG-4565 + * @param profile The profile whose activation status should be determined, must not be {@code null}. + * @param context The environmental context used to determine the activation status of the profile, must not be + * {@code null}. + * @param problems The container used to collect problems (e.g. bad syntax) that were encountered, must not be + * {@code null}. + * @return {@code true} if the profile is active, {@code false} otherwise. + */ + boolean presentInConfig( Profile profile, ProfileActivationContext context, ModelProblemCollector problems ); + } diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/PropertyProfileActivator.java b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/PropertyProfileActivator.java index 374647f..e8e6e99 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/PropertyProfileActivator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/profile/activation/PropertyProfileActivator.java @@ -103,4 +103,23 @@ public boolean isActive( Profile profile, ProfileActivationContext context, Mode } } + @Override + public boolean presentInConfig( Profile profile, ProfileActivationContext context, ModelProblemCollector problems ) + { + Activation activation = profile.getActivation(); + + if ( activation == null ) + { + return false; + } + + ActivationProperty property = activation.getProperty(); + + if ( property == null ) + { + return false; + } + return true; + } + }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4565_c6529932.diff
bugs-dot-jar_data_MNG-3991_2169c4a3
--- BugID: MNG-3991 Summary: POM validator allows <scope>optional</scope> but it is not valid. Description: "In my project I did a mistake and I wrote\n{code}\n<dependency>\n\t<groupId>org.slf4j</groupId>\n\t<artifactId>slf4j-log4j12</artifactId>\n\t<version>1.5.0</version>\n\t<scope>optional</scope>\n</dependency>\n{code}\n\nbut in fact I intended to write\n{code}\n<dependency>\n\t<groupId>org.slf4j</groupId>\n\t<artifactId>slf4j-log4j12</artifactId>\n\t<version>1.5.0</version>\n\t<optional>true</optional>\n</dependency>\n{code}\n\nI'm very surprised that Maven doesn't detect such a mistake during the validate phase. Could it be possible to add a check to allow only valid scopes.\n\nThanks" diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java b/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java index 586141e..c60c446 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java @@ -181,7 +181,11 @@ public class DefaultModelValidator validateBoolean( "dependencies.dependency.optional", problems, warnOnBadBoolean, d.getOptional(), d.getManagementKey() ); - validateEnum( "dependencies.dependency.scope", problems, warnOnBadDependencyScope, d.getScope(), + /* + * TODO: Extensions like Flex Mojos use custom scopes like "merged", "internal", "external", etc. In + * order to don't break backward-compat with those, only warn but don't error our. + */ + validateEnum( "dependencies.dependency.scope", problems, true, d.getScope(), d.getManagementKey(), "provided", "compile", "runtime", "test", "system" ); } }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-3991_2169c4a3.diff
bugs-dot-jar_data_MNG-1999_ad38e46b
--- BugID: MNG-1999 Summary: Reporting inheritance does not work properly Description: |- I have a parent project and some subprojects. The parent project's pom has: <reporting> <excludeDefaults>true</excludeDefaults> </reporting> However, it does not get inherited to subprojects and so all default reports are generated for all subprojects. I'm not sure if this is a bug or a lack of feature but I would be good to have it. FYI, I'm speaking about here: http://svn.apache.org/viewcvs.cgi/directory/trunks/apacheds/ diff --git a/maven-project/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java b/maven-project/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java index 39b8488..2839c50 100644 --- a/maven-project/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java +++ b/maven-project/src/main/java/org/apache/maven/project/inheritance/DefaultModelInheritanceAssembler.java @@ -16,15 +16,6 @@ package org.apache.maven.project.inheritance; * limitations under the License. */ -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.TreeMap; - import org.apache.maven.model.Build; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; @@ -38,6 +29,15 @@ import org.apache.maven.model.Site; import org.apache.maven.project.ModelUtils; import org.codehaus.plexus.util.StringUtils; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.StringTokenizer; +import java.util.TreeMap; + /** * @author <a href="mailto:[email protected]">Jason van Zyl </a> * @version $Id: DefaultModelInheritanceAssembler.java,v 1.4 2004/08/23 20:24:54 @@ -275,6 +275,8 @@ public class DefaultModelInheritanceAssembler child.setReporting( childReporting ); } + childReporting.setExcludeDefaults( parentReporting.isExcludeDefaults() ); + if ( StringUtils.isEmpty( childReporting.getOutputDirectory() ) ) { childReporting.setOutputDirectory( parentReporting.getOutputDirectory() ); @@ -422,25 +424,28 @@ public class DefaultModelInheritanceAssembler if ( StringUtils.isEmpty( childScm.getConnection() ) && !StringUtils.isEmpty( parentScm.getConnection() ) ) { - childScm.setConnection( appendPath( parentScm.getConnection(), child.getArtifactId(), childPathAdjustment, appendPaths ) ); + childScm.setConnection( + appendPath( parentScm.getConnection(), child.getArtifactId(), childPathAdjustment, appendPaths ) ); } if ( StringUtils.isEmpty( childScm.getDeveloperConnection() ) && !StringUtils.isEmpty( parentScm.getDeveloperConnection() ) ) { childScm - .setDeveloperConnection( - appendPath( parentScm.getDeveloperConnection(), child.getArtifactId(), childPathAdjustment, appendPaths ) ); + .setDeveloperConnection( appendPath( parentScm.getDeveloperConnection(), child.getArtifactId(), + childPathAdjustment, appendPaths ) ); } if ( StringUtils.isEmpty( childScm.getUrl() ) && !StringUtils.isEmpty( parentScm.getUrl() ) ) { - childScm.setUrl( appendPath( parentScm.getUrl(), child.getArtifactId(), childPathAdjustment, appendPaths ) ); + childScm.setUrl( + appendPath( parentScm.getUrl(), child.getArtifactId(), childPathAdjustment, appendPaths ) ); } } } - private void assembleDistributionInheritence( Model child, Model parent, String childPathAdjustment, boolean appendPaths ) + private void assembleDistributionInheritence( Model child, Model parent, String childPathAdjustment, + boolean appendPaths ) { if ( parent.getDistributionManagement() != null ) { @@ -471,7 +476,8 @@ public class DefaultModelInheritanceAssembler if ( site.getUrl() != null ) { - site.setUrl( appendPath( site.getUrl(), child.getArtifactId(), childPathAdjustment, appendPaths ) ); + site.setUrl( + appendPath( site.getUrl(), child.getArtifactId(), childPathAdjustment, appendPaths ) ); } } } @@ -517,56 +523,56 @@ public class DefaultModelInheritanceAssembler protected String appendPath( String parentPath, String childPath, String pathAdjustment, boolean appendPaths ) { List pathFragments = new ArrayList(); - + String rootPath = parentPath; String protocol = null; int protocolIdx = rootPath.indexOf( "://" ); - + if ( protocolIdx > -1 ) { protocol = rootPath.substring( 0, protocolIdx + 3 ); rootPath = rootPath.substring( protocolIdx + 3 ); } - + pathFragments.add( rootPath ); - + if ( appendPaths ) { if ( pathAdjustment != null ) { pathFragments.add( pathAdjustment ); } - + pathFragments.add( childPath ); } - + StringBuffer cleanedPath = new StringBuffer(); - + if ( protocol != null ) { cleanedPath.append( protocol ); } - + if ( rootPath.startsWith( "/" ) ) { cleanedPath.append( '/' ); } - + String lastToken = null; String currentToken = null; - + for ( Iterator it = pathFragments.iterator(); it.hasNext(); ) { String pathFragment = (String) it.next(); - + StringTokenizer tokens = new StringTokenizer( pathFragment, "/" ); - - while( tokens.hasMoreTokens() ) + + while ( tokens.hasMoreTokens() ) { lastToken = currentToken; currentToken = tokens.nextToken(); - + if ( "..".equals( currentToken ) ) { // trim the previous path part off... @@ -579,12 +585,12 @@ public class DefaultModelInheritanceAssembler } } } - + if ( !childPath.endsWith( "/" ) && appendPaths ) { cleanedPath.setLength( cleanedPath.length() - 1 ); } - + return cleanedPath.toString(); }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-1999_ad38e46b.diff
bugs-dot-jar_data_MNG-4915_1c3abfba
--- BugID: MNG-4915 Summary: Versions in pom.xml are not checked for invalid characters Description: |+ It seems that the pom.xml is not checking if the version contains invalid characters. If I have following fragment inside pom: <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>>>3.5</version> </dependency> then Maven is trying to download JUnit version >>3.5 diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java b/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java index 33b2f26..8a2f634 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java @@ -764,39 +764,47 @@ public class DefaultModelValidator return true; } - if ( !hasExpression( string ) ) + if ( hasExpression( string ) ) { - return true; + addViolation( problems, severity, fieldName, sourceHint, + "must be a valid version but is '" + string + "'.", tracker ); + return false; } - addViolation( problems, severity, fieldName, sourceHint, "must be a valid version but is '" + string + "'.", - tracker ); + if ( !validateBannedCharacters( fieldName, problems, severity, string, sourceHint, tracker, + ILLEGAL_VERSION_CHARS ) ) + { + return false; + } - return false; + return true; } private boolean validatePluginVersion( String fieldName, ModelProblemCollector problems, String string, String sourceHint, InputLocationTracker tracker, ModelBuildingRequest request ) { - Severity errOn30 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 ); - if ( string == null ) { // NOTE: The check for missing plugin versions is handled directly by the model builder return true; } - if ( string.length() > 0 && !hasExpression( string ) && !"RELEASE".equals( string ) - && !"LATEST".equals( string ) ) + Severity errOn30 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 ); + + if ( !validateVersion( fieldName, problems, errOn30, string, sourceHint, tracker ) ) { - return true; + return false; } - addViolation( problems, errOn30, fieldName, sourceHint, "must be a valid version but is '" + string + "'.", - tracker ); + if ( string.length() <= 0 || "RELEASE".equals( string ) || "LATEST".equals( string ) ) + { + addViolation( problems, errOn30, fieldName, sourceHint, "must be a valid version but is '" + string + "'.", + tracker ); + return false; + } - return false; + return true; } private static void addViolation( ModelProblemCollector problems, Severity severity, String fieldName,
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4915_1c3abfba.diff
bugs-dot-jar_data_MNG-2931_d7422212
--- BugID: MNG-2931 Summary: DefaultArtifactCollector changes the version of the originatingArtifact if it's in the dependencyManagement with another version Description: "DefaultDependencyTreeBuilder\nhttps://svn.apache.org/repos/asf/maven/shared/trunk/maven-dependency-tree/src/main/java/org/apache/maven/shared/dependency/tree/DefaultDependencyTreeBuilder.java\n\ncalls collect like this\n\n collector.collect( project.getDependencyArtifacts(), project.getArtifact(), managedVersions, repository,\n project.getRemoteArtifactRepositories(), metadataSource, null,\n Collections.singletonList( listener ) );\n\nProblem: \nThis pom \nhttp://repo1.maven.org/maven2/org/codehaus/plexus/plexus-component-api/1.0-alpha-22/plexus-component-api-1.0-alpha-22.pom\nextends\nhttp://repo1.maven.org/maven2/org/codehaus/plexus/plexus-containers/1.0-alpha-22/plexus-containers-1.0-alpha-22.pom\nthat in dependencyManagement has org.codehaus.plexus:plexus-component-api:1.0-alpha-19\n\nso during collect project.getArtifact().getVersion() is changed to the managedVersion instead of the original one\n\nEither this is a bug or an exception should be thrown when originatingArtifact is in managedVersions\n\n" diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java index 47e7acf..9a923d8 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactCollector.java @@ -69,8 +69,7 @@ public class DefaultArtifactCollector root.addDependencies( artifacts, remoteRepositories, filter ); - ManagedVersionMap versionMap = (managedVersions != null && managedVersions instanceof ManagedVersionMap) ? - (ManagedVersionMap)managedVersions : new ManagedVersionMap(managedVersions); + ManagedVersionMap versionMap = getManagedVersionsMap( originatingArtifact, managedVersions ); recurse( root, resolvedArtifacts, versionMap, localRepository, remoteRepositories, source, filter, listeners ); @@ -107,6 +106,45 @@ public class DefaultArtifactCollector return result; } + /** + * Get the map of managed versions, removing the originating artifact if it is also in managed versions + * @param originatingArtifact artifact we are processing + * @param managedVersions original managed versions + */ + private ManagedVersionMap getManagedVersionsMap( Artifact originatingArtifact, Map managedVersions ) + { + ManagedVersionMap versionMap; + if ( managedVersions != null && managedVersions instanceof ManagedVersionMap ) + { + versionMap = (ManagedVersionMap) managedVersions; + } + else + { + versionMap = new ManagedVersionMap( managedVersions ); + } + + /* remove the originating artifact if it is also in managed versions to avoid being modified during resolution */ + Artifact managedOriginatingArtifact = (Artifact) versionMap.get( originatingArtifact.getDependencyConflictId() ); + if ( managedOriginatingArtifact != null ) + { + String managedVersion = managedOriginatingArtifact.getVersion(); + String version = originatingArtifact.getVersion(); + if ( !managedVersion.equals( version ) ) + { + // TODO we probably want to warn the user that he is building and artifact with a + // different version than in dependencyManagement + if ( managedVersions instanceof ManagedVersionMap ) + { + /* avoid modifying the managedVersions parameter creating a new map */ + versionMap = new ManagedVersionMap( managedVersions ); + } + versionMap.remove( originatingArtifact.getDependencyConflictId() ); + } + } + + return versionMap; + } + private void recurse( ResolutionNode node, Map resolvedArtifacts, ManagedVersionMap managedVersions, ArtifactRepository localRepository, List remoteRepositories, ArtifactMetadataSource source, ArtifactFilter filter, List listeners )
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-2931_d7422212.diff
bugs-dot-jar_data_MNG-4761_8cdb461f
--- BugID: MNG-4761 Summary: Plugin-level dependency scope causes some plugin classpaths to be incorrect Description: |- Plugin-level dependencies should use RUNTIME scope at all times. Using any other scope may alter the weighting given to the subgraph-choice algorithm used in transitive dependency resolution. Plugin-level dependencies use compile scope by default. When transitive resolution takes place, compile scope takes precedence over runtime scope, causing the transitive dependency sub-graph of the plugin-level dependency to be activated over those of the plugin itself. This happens even when the plugin's transitive dep is NEARER to the top level than the one brought in by that plugin-level dependency itself. The result is that when a dep that's farther away is chosen over a nearer one, it can then be disabled by Maven choosing to disable its parent dep (the one that brought it in) in another part of the transitive resolution process. This is a very subtle case where Maven is doing the wrong thing. The attached test case should make it clearer. diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver.java index 954616f..57374d2 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultPluginDependenciesResolver.java @@ -98,7 +98,10 @@ public class DefaultPluginDependenciesResolver Set<Artifact> overrideArtifacts = new LinkedHashSet<Artifact>(); for ( Dependency dependency : plugin.getDependencies() ) { - dependency.setScope( Artifact.SCOPE_RUNTIME ); + if ( !Artifact.SCOPE_SYSTEM.equals( dependency.getScope() ) ) + { + dependency.setScope( Artifact.SCOPE_RUNTIME ); + } overrideArtifacts.add( repositorySystem.createDependencyArtifact( dependency ) ); }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4761_8cdb461f.diff
bugs-dot-jar_data_MNG-4474_269c956e
--- BugID: MNG-4474 Summary: "[regression] Wagon manager does not respect instantiation strategy of wagons" Description: Calling {{WagonManager.getWagon()}} multiple times from the same thread (and with the same thread context class loader) will always return the same wagon instance, even if the wagon uses "per-lookup" instantiation. diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultWagonManager.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultWagonManager.java index 00e7f38..0b4f3ae 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultWagonManager.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultWagonManager.java @@ -46,6 +46,7 @@ import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.util.FileUtils; @@ -67,9 +68,6 @@ public class DefaultWagonManager @Requirement private PlexusContainer container; - @Requirement(role = Wagon.class) - private Map<String, Wagon> wagons; - @Requirement private UpdateCheckManager updateCheckManager; @@ -686,11 +684,16 @@ public class DefaultWagonManager } String hint = protocol.toLowerCase( java.util.Locale.ENGLISH ); - Wagon wagon = (Wagon) wagons.get( hint ); - if ( wagon == null ) + Wagon wagon; + try + { + wagon = container.lookup( Wagon.class, hint ); + } + catch ( ComponentLookupException e ) { - throw new UnsupportedProtocolException( "Cannot find wagon which supports the requested protocol: " + protocol ); + throw new UnsupportedProtocolException( "Cannot find wagon which supports the requested protocol: " + + protocol, e ); } return wagon;
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4474_269c956e.diff
bugs-dot-jar_data_MNG-4648_83389c34
--- BugID: MNG-4648 Summary: NullPointerException thrown from DefaultPluginRealmCache#pluginHashCode method if project-level plugin dependency misses version Description: |- As a user i would like to see better error reporting from DefaultPluginRealmCache#pluginHashCode method Currently it calculates hash value based on a dependency metadata, but if I omit version it fails with NullPointer exception. It would be more user friendly to validate metadata prior to calculating hash value and to display more meaningful error to the end user. Test scenario: - configure plugin and create dependencies - add dependency but DO NOT specify version - run maven such that plugin is invoked maven will fail without reporting which dependency doesn't have version diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java b/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java index fa262c8..bed7b47 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java @@ -253,12 +253,7 @@ public class DefaultModelValidator validateBoolean( "build.plugins.plugin.extensions", problems, errOn30, p.getExtensions(), p.getKey() ); - for ( Dependency d : p.getDependencies() ) - { - validateEnum( "build.plugins.plugin[" + p.getKey() + "].dependencies.dependency.scope", - problems, errOn30, d.getScope(), d.getManagementKey(), - "compile", "runtime", "system" ); - } + validateEffectivePluginDependencies( problems, p, request ); } validateResources( problems, build.getResources(), "build.resources.resource", request ); @@ -365,67 +360,21 @@ public class DefaultModelValidator } private void validateEffectiveDependencies( ModelProblemCollector problems, List<Dependency> dependencies, - boolean managed, ModelBuildingRequest request ) + boolean management, ModelBuildingRequest request ) { Severity errOn30 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 ); - String prefix = managed ? "dependencyManagement.dependencies.dependency." : "dependencies.dependency."; + String prefix = management ? "dependencyManagement.dependencies.dependency." : "dependencies.dependency."; for ( Dependency d : dependencies ) { - validateId( prefix + "artifactId", problems, d.getArtifactId(), d.getManagementKey() ); - - validateId( prefix + "groupId", problems, d.getGroupId(), d.getManagementKey() ); - - if ( !managed ) - { - validateStringNotEmpty( prefix + "type", problems, Severity.ERROR, d.getType(), d.getManagementKey() ); - - validateStringNotEmpty( prefix + "version", problems, Severity.ERROR, d.getVersion(), - d.getManagementKey() ); - } - - if ( "system".equals( d.getScope() ) ) - { - String systemPath = d.getSystemPath(); - - if ( StringUtils.isEmpty( systemPath ) ) - { - addViolation( problems, Severity.ERROR, prefix + "systemPath", d.getManagementKey(), "is missing." ); - } - else - { - File sysFile = new File( systemPath ); - if ( !sysFile.isAbsolute() ) - { - addViolation( problems, Severity.ERROR, prefix + "systemPath", d.getManagementKey(), - "must specify an absolute path but is " + systemPath ); - } - else if ( !sysFile.isFile() ) - { - String msg = "refers to a non-existing file " + sysFile.getAbsolutePath(); - systemPath = systemPath.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); - String jdkHome = - request.getSystemProperties().getProperty( "java.home", "" ) + File.separator + ".."; - if ( systemPath.startsWith( jdkHome ) ) - { - msg += ". Please verify that you run Maven using a JDK and not just a JRE."; - } - addViolation( problems, Severity.WARNING, prefix + "systemPath", d.getManagementKey(), msg ); - } - } - } - else if ( StringUtils.isNotEmpty( d.getSystemPath() ) ) - { - addViolation( problems, Severity.ERROR, prefix + "systemPath", d.getManagementKey(), "must be omitted." - + " This field may only be specified for a dependency with system scope." ); - } + validateEffectiveDependency( problems, d, management, prefix, request ); if ( request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 ) { validateBoolean( prefix + "optional", problems, errOn30, d.getOptional(), d.getManagementKey() ); - if ( !managed ) + if ( !management ) { validateVersion( prefix + "version", problems, errOn30, d.getVersion(), d.getManagementKey() ); @@ -440,6 +389,80 @@ public class DefaultModelValidator } } + private void validateEffectivePluginDependencies( ModelProblemCollector problems, Plugin plugin, + ModelBuildingRequest request ) + { + List<Dependency> dependencies = plugin.getDependencies(); + + if ( !dependencies.isEmpty() ) + { + String prefix = "build.plugins.plugin[" + plugin.getKey() + "].dependencies.dependency."; + + Severity errOn30 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 ); + + for ( Dependency d : dependencies ) + { + validateEffectiveDependency( problems, d, false, prefix, request ); + + validateVersion( prefix + "version", problems, errOn30, d.getVersion(), d.getManagementKey() ); + + validateEnum( prefix + "scope", problems, errOn30, d.getScope(), d.getManagementKey(), "compile", + "runtime", "system" ); + } + } + } + + private void validateEffectiveDependency( ModelProblemCollector problems, Dependency d, boolean management, + String prefix, ModelBuildingRequest request ) + { + validateId( prefix + "artifactId", problems, d.getArtifactId(), d.getManagementKey() ); + + validateId( prefix + "groupId", problems, d.getGroupId(), d.getManagementKey() ); + + if ( !management ) + { + validateStringNotEmpty( prefix + "type", problems, Severity.ERROR, d.getType(), d.getManagementKey() ); + + validateStringNotEmpty( prefix + "version", problems, Severity.ERROR, d.getVersion(), d.getManagementKey() ); + } + + if ( "system".equals( d.getScope() ) ) + { + String systemPath = d.getSystemPath(); + + if ( StringUtils.isEmpty( systemPath ) ) + { + addViolation( problems, Severity.ERROR, prefix + "systemPath", d.getManagementKey(), "is missing." ); + } + else + { + File sysFile = new File( systemPath ); + if ( !sysFile.isAbsolute() ) + { + addViolation( problems, Severity.ERROR, prefix + "systemPath", d.getManagementKey(), + "must specify an absolute path but is " + systemPath ); + } + else if ( !sysFile.isFile() ) + { + String msg = "refers to a non-existing file " + sysFile.getAbsolutePath(); + systemPath = systemPath.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); + String jdkHome = + request.getSystemProperties().getProperty( "java.home", "" ) + File.separator + ".."; + if ( systemPath.startsWith( jdkHome ) ) + { + msg += ". Please verify that you run Maven using a JDK and not just a JRE."; + } + addViolation( problems, Severity.WARNING, prefix + "systemPath", d.getManagementKey(), msg ); + } + } + } + else if ( StringUtils.isNotEmpty( d.getSystemPath() ) ) + { + addViolation( problems, Severity.ERROR, prefix + "systemPath", d.getManagementKey(), "must be omitted." + + " This field may only be specified for a dependency with system scope." ); + } + } + private void validateRepositories( ModelProblemCollector problems, List<Repository> repositories, String prefix, ModelBuildingRequest request ) {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4648_83389c34.diff
bugs-dot-jar_data_MNG-5687_3d2d8619
--- BugID: MNG-5687 Summary: Parallel Builds can build in wrong order Description: | Fixed JDK8 IT failure for MavenITmng3004ReactorFailureBehaviorMultithreadedTest#testitFailFastSingleThread It turns out the execution order of the modules in the build can be incorrect, in some cases severely incorrect. For parallel builds this can have all sorts of interesting side effects such as classpath appearing to be intermittently incorrect, missing jars/resources and similar. The -am options and -amd options may simply fail with the incorrect build order because expected dependencies have not been built and actual dependencies may not have been built. The underlying problem was that ProjectDependencyGraph#getDownstreamProjects and getUpstreamProjects did not actually obey the reactor build order as defined by ProjectDependencyGraph#getSortedProjects, even though the javadoc claims they should. This has only worked by accident on earlier JDK's and might not have worked at all (basically depends on Set iteration order being equal to insertion order). JDK8 has slightly different iteration order, which caused the IT failure. This problem may be the root cause of MNG-4996 and any other issue where the modules build in incorrect order. The bug affects: parallel builds command line -am (--also-make) option command line -amd (also-make-dependents) option On all java versions, although visibility might be somewhat different on different jdks. Added simple unit test that catches the problem. diff --git a/maven-core/src/main/java/org/apache/maven/DefaultProjectDependencyGraph.java b/maven-core/src/main/java/org/apache/maven/DefaultProjectDependencyGraph.java index 84d2cc5..4074e58 100644 --- a/maven-core/src/main/java/org/apache/maven/DefaultProjectDependencyGraph.java +++ b/maven-core/src/main/java/org/apache/maven/DefaultProjectDependencyGraph.java @@ -23,6 +23,7 @@ import java.util.Collection; import java.util.HashSet; import java.util.List; +import java.util.Set; import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.project.DuplicateProjectException; @@ -32,7 +33,7 @@ /** * Describes the inter-dependencies between projects in the reactor. - * + * * @author Benjamin Bentmann */ class DefaultProjectDependencyGraph @@ -43,12 +44,13 @@ /** * Creates a new project dependency graph based on the specified projects. - * + * * @param projects The projects to create the dependency graph with - * @throws DuplicateProjectException - * @throws CycleDetectedException + * @throws DuplicateProjectException + * @throws CycleDetectedException */ - public DefaultProjectDependencyGraph( Collection<MavenProject> projects ) throws CycleDetectedException, DuplicateProjectException + public DefaultProjectDependencyGraph( Collection<MavenProject> projects ) + throws CycleDetectedException, DuplicateProjectException { this.sorter = new ProjectSorter( projects ); } @@ -65,14 +67,14 @@ public DefaultProjectDependencyGraph( Collection<MavenProject> projects ) throws throw new IllegalArgumentException( "project missing" ); } - Collection<String> projectIds = new HashSet<String>(); + Set<String> projectIds = new HashSet<String>(); getDownstreamProjects( ProjectSorter.getId( project ), projectIds, transitive ); - return getProjects( projectIds ); + return getSortedProjects( projectIds ); } - private void getDownstreamProjects( String projectId, Collection<String> projectIds, boolean transitive ) + private void getDownstreamProjects( String projectId, Set<String> projectIds, boolean transitive ) { for ( String id : sorter.getDependents( projectId ) ) { @@ -90,11 +92,11 @@ private void getDownstreamProjects( String projectId, Collection<String> project throw new IllegalArgumentException( "project missing" ); } - Collection<String> projectIds = new HashSet<String>(); + Set<String> projectIds = new HashSet<String>(); getUpstreamProjects( ProjectSorter.getId( project ), projectIds, transitive ); - return getProjects( projectIds ); + return getSortedProjects( projectIds ); } private void getUpstreamProjects( String projectId, Collection<String> projectIds, boolean transitive ) @@ -108,21 +110,19 @@ private void getUpstreamProjects( String projectId, Collection<String> projectId } } - private List<MavenProject> getProjects( Collection<String> projectIds ) + private List<MavenProject> getSortedProjects( Set<String> projectIds ) { - List<MavenProject> projects = new ArrayList<MavenProject>( projectIds.size() ); + List<MavenProject> result = new ArrayList<MavenProject>( projectIds.size() ); - for ( String projectId : projectIds ) + for ( MavenProject mavenProject : sorter.getSortedProjects() ) { - MavenProject project = sorter.getProjectMap().get( projectId ); - - if ( project != null ) + if ( projectIds.contains( ProjectSorter.getId( mavenProject ) ) ) { - projects.add( project ); + result.add( mavenProject ); } } - return projects; + return result; } @Override
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5687_3d2d8619.diff
bugs-dot-jar_data_MNG-4695_bb39b480
--- BugID: MNG-4695 Summary: 'Missing Error during pom validation: "You cannot have two plugin executions with the same (or missing) <id/> elements."' Description: "Maven 2.2.1 gives an error \"You cannot have two plugin executions with the same (or missing) <id/> elements.\", if there are two executions for the same plugin without an id element. \nMaven 3.0 beta1 doesn't throw this usefull validation error. It uses the first configuration for both executions.\n\nA relatet issue, where this error has occured with an attached example: http://jira.codehaus.org/browse/MRPM-76\n" diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java b/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java index 4291443..73fb915 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/validation/DefaultModelValidator.java @@ -28,6 +28,7 @@ import java.util.Map; import java.util.Set; import org.apache.maven.model.Build; +import org.apache.maven.model.BuildBase; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; import org.apache.maven.model.DistributionManagement; @@ -103,12 +104,12 @@ public class DefaultModelValidator Build build = model.getBuild(); if ( build != null ) { - validateRawPlugins( problems, build.getPlugins(), false, request ); + validateRawPlugins( problems, build.getPlugins(), "build.plugins.plugin", request ); PluginManagement mngt = build.getPluginManagement(); if ( mngt != null ) { - validateRawPlugins( problems, mngt.getPlugins(), true, request ); + validateRawPlugins( problems, mngt.getPlugins(), "build.pluginManagement.plugins.plugin", request ); } } @@ -116,38 +117,49 @@ public class DefaultModelValidator for ( Profile profile : model.getProfiles() ) { + String prefix = "profiles.profile[" + profile.getId() + "]"; + if ( !profileIds.add( profile.getId() ) ) { addViolation( problems, errOn30, "profiles.profile.id", null, "must be unique but found duplicate profile with id " + profile.getId(), profile ); } - validateRawDependencies( problems, profile.getDependencies(), "profiles.profile[" + profile.getId() - + "].dependencies.dependency", request ); + validateRawDependencies( problems, profile.getDependencies(), prefix + ".dependencies.dependency", + request ); if ( profile.getDependencyManagement() != null ) { - validateRawDependencies( problems, profile.getDependencyManagement().getDependencies(), - "profiles.profile[" + profile.getId() - + "].dependencyManagement.dependencies.dependency", request ); + validateRawDependencies( problems, profile.getDependencyManagement().getDependencies(), prefix + + ".dependencyManagement.dependencies.dependency", request ); } - validateRepositories( problems, profile.getRepositories(), "profiles.profile[" + profile.getId() - + "].repositories.repository", request ); + validateRepositories( problems, profile.getRepositories(), prefix + ".repositories.repository", request ); + + validateRepositories( problems, profile.getPluginRepositories(), prefix + + ".pluginRepositories.pluginRepository", request ); + + BuildBase buildBase = profile.getBuild(); + if ( buildBase != null ) + { + validateRawPlugins( problems, buildBase.getPlugins(), prefix + ".plugins.plugin", request ); - validateRepositories( problems, profile.getPluginRepositories(), "profiles.profile[" + profile.getId() - + "].pluginRepositories.pluginRepository", request ); + PluginManagement mngt = buildBase.getPluginManagement(); + if ( mngt != null ) + { + validateRawPlugins( problems, mngt.getPlugins(), prefix + ".pluginManagement.plugins.plugin", + request ); + } + } } } } - private void validateRawPlugins( ModelProblemCollector problems, List<Plugin> plugins, boolean managed, + private void validateRawPlugins( ModelProblemCollector problems, List<Plugin> plugins, String prefix, ModelBuildingRequest request ) { Severity errOn31 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1 ); - String prefix = ( managed ? "build.pluginManagement." : "build." ) + "plugins.plugin."; - Map<String, Plugin> index = new HashMap<String, Plugin>(); for ( Plugin plugin : plugins ) @@ -158,7 +170,7 @@ public class DefaultModelValidator if ( existing != null ) { - addViolation( problems, errOn31, prefix + "(groupId:artifactId)", null, + addViolation( problems, errOn31, prefix + ".(groupId:artifactId)", null, "must be unique but found duplicate declaration of plugin " + key, plugin ); } else @@ -172,7 +184,7 @@ public class DefaultModelValidator { if ( !executionIds.add( exec.getId() ) ) { - addViolation( problems, Severity.ERROR, "build.plugins.plugin[" + plugin.getKey() + addViolation( problems, Severity.ERROR, prefix + "[" + plugin.getKey() + "].executions.execution.id", null, "must be unique but found duplicate execution with id " + exec.getId(), exec ); }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4695_bb39b480.diff
bugs-dot-jar_data_MNG-2174_778f044e
--- BugID: MNG-2174 Summary: "<pluginManagement><plugins><plugin><dependencies> do not propogate to child POM plugins (potentially scoped to only affecting child POM plugins that live within a <profile>)" Description: |+ <pluginManagement><plugins><plugin><dependencies> do not propogate to child POM plugins. Kenny believe this works OKAY if the childs are using the parent <pluginManagement> preconfigured plugins in their main <build> section however it does NOT work if the childs are trying to use those preconfigured plugins via their own <profiles>. Configuration propogates through okay but dependencies are missing and have to be respecified in the child POMs. diff --git a/maven-project/src/main/java/org/apache/maven/project/builder/PomClassicDomainModel.java b/maven-project/src/main/java/org/apache/maven/project/builder/PomClassicDomainModel.java index 5475819..5abb68c 100644 --- a/maven-project/src/main/java/org/apache/maven/project/builder/PomClassicDomainModel.java +++ b/maven-project/src/main/java/org/apache/maven/project/builder/PomClassicDomainModel.java @@ -306,6 +306,7 @@ public final class PomClassicDomainModel s.add(ProjectUri.Reporting.Plugins.Plugin.ReportSets.xUri); s.add(ProjectUri.Reporting.Plugins.Plugin.ReportSets.ReportSet.configuration); s.add(ProjectUri.Build.Plugins.Plugin.Executions.Execution.configuration); + s.add(ProjectUri.Profiles.Profile.Build.Plugins.Plugin.configuration);//TODO: More profile info modelProperties = ModelMarshaller.marshallXmlToModelProperties( getInputStream(), ProjectUri.baseUri, s ); } diff --git a/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultProjectBuilder.java b/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultProjectBuilder.java index c5604bb..085bc4d 100644 --- a/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultProjectBuilder.java +++ b/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultProjectBuilder.java @@ -213,14 +213,29 @@ public class DefaultProjectBuilder PomClassicDomainModel domainModel = new PomClassicDomainModel( pom ); domainModel.setProjectDirectory( pom.getParentFile() ); + List<DomainModel> domainModels = new ArrayList<DomainModel>(); + domainModels.add( domainModel ); ProfileContext profileContext = new ProfileContext(new DefaultModelDataSource(domainModel.getModelProperties(), PomTransformer.MODEL_CONTAINER_FACTORIES), activeProfileIds, properties); + Collection<ModelContainer> profileContainers = profileContext.getActiveProfiles(); - //get mixin - List<DomainModel> domainModels = new ArrayList<DomainModel>(); - domainModels.add( domainModel ); + for(ModelContainer mc : profileContainers) + { + List<ModelProperty> transformed = new ArrayList<ModelProperty>(); + transformed.add(new ModelProperty(ProjectUri.xUri, null)); + for(ModelProperty mp : mc.getProperties()) + { + if(mp.getUri().startsWith(ProjectUri.Profiles.Profile.xUri) && !mp.getUri().equals(ProjectUri.Profiles.Profile.id) + && !mp.getUri().startsWith(ProjectUri.Profiles.Profile.Activation.xUri) ) + { + transformed.add(new ModelProperty(mp.getUri().replace(ProjectUri.Profiles.Profile.xUri, ProjectUri.xUri), + mp.getResolvedValue())); + } + } + domainModels.add(new PomClassicDomainModel(transformed)); + } File parentFile = null; int lineageCount = 0;
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-2174_778f044e.diff
bugs-dot-jar_data_MNG-1797_5d99b35c
--- BugID: MNG-1797 Summary: Dependency excludes apply to every subsequent dependency, not just the one it is declared under. Description: "If you specify ANY dependency excludes, all dependencies after that one in the pom will also exclude what you specified. They appear to be cumulative on every dependency in that they bleed over into sibling dependencies. \nIt's easy to test if you add an exclusion to a random dependency. This exclusion should exclude a required transitive dependency that is included by a dependency lower in the list. \ You will find that the dependency lower in the list no longer includes the required dependency because it is using the filter you declared in the other dependency.\n" diff --git a/maven-project/src/main/java/org/apache/maven/profiles/DefaultProfileManager.java b/maven-project/src/main/java/org/apache/maven/profiles/DefaultProfileManager.java index 5f6534d..68acd29 100644 --- a/maven-project/src/main/java/org/apache/maven/profiles/DefaultProfileManager.java +++ b/maven-project/src/main/java/org/apache/maven/profiles/DefaultProfileManager.java @@ -66,13 +66,14 @@ public class DefaultProfileManager */ public DefaultProfileManager( PlexusContainer container, Properties props ) { - this( container, (Settings)null ); - if (props != null) { - systemProperties = props; - } + this( container, (Settings)null, props ); } + /** + * @deprecated without passing in the system properties, the SystemPropertiesProfileActivator will not work correctly + * in embedded envirnments. + */ public DefaultProfileManager( PlexusContainer container, Settings settings ) { this.container = container; @@ -80,6 +81,23 @@ public class DefaultProfileManager loadSettingsProfiles( settings ); } + /** + * the properties passed to the profile manager are the props that + * are passed to maven, possibly containing profile activator properties + * + */ + public DefaultProfileManager( PlexusContainer container, Settings settings, Properties props ) + { + this.container = container; + + loadSettingsProfiles( settings ); + + if ( props != null ) + { + systemProperties = props; + } + } + public Properties getSystemProperties() { return systemProperties; } diff --git a/maven-project/src/main/java/org/apache/maven/project/artifact/MavenMetadataSource.java b/maven-project/src/main/java/org/apache/maven/project/artifact/MavenMetadataSource.java index ffa3ac6..bde81f3 100644 --- a/maven-project/src/main/java/org/apache/maven/project/artifact/MavenMetadataSource.java +++ b/maven-project/src/main/java/org/apache/maven/project/artifact/MavenMetadataSource.java @@ -48,7 +48,6 @@ import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.ArrayList; import java.util.Collections; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; @@ -337,7 +336,9 @@ public class MavenMetadataSource artifact.setFile( new File( d.getSystemPath() ) ); } - if ( artifact != null && ( dependencyFilter == null || dependencyFilter.include( artifact ) ) ) + ArtifactFilter artifactFilter = dependencyFilter; + + if ( artifact != null && ( artifactFilter == null || artifactFilter.include( artifact ) ) ) { if ( d.getExclusions() != null && !d.getExclusions().isEmpty() ) { @@ -350,20 +351,20 @@ public class MavenMetadataSource ArtifactFilter newFilter = new ExcludesArtifactFilter( exclusions ); - if ( dependencyFilter != null ) + if ( artifactFilter != null ) { AndArtifactFilter filter = new AndArtifactFilter(); - filter.add( dependencyFilter ); + filter.add( artifactFilter ); filter.add( newFilter ); - dependencyFilter = filter; + artifactFilter = filter; } else { - dependencyFilter = newFilter; + artifactFilter = newFilter; } } - artifact.setDependencyFilter( dependencyFilter ); + artifact.setDependencyFilter( artifactFilter ); if ( project != null ) {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-1797_5d99b35c.diff
bugs-dot-jar_data_MNG-5613_bef7fac6
--- BugID: MNG-5613 Summary: NPE error when building a reactor with duplicated artifacts Description: "Using v3.2.1 when building a malformed project containing a duplicated groupId:artifactId I got this rather unhelpful error:\n\n{code}\n[ERROR] Internal error: java.lang.NullPointerException -> [Help 1]\norg.apache.maven.InternalErrorException: Internal error: java.lang.NullPointerException\n\tat org.apache.maven.DefaultMaven.execute(DefaultMaven.java:167)\n\tat org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)\n\tat org.apache.maven.cli.MavenCli.doMain(MavenCli.java:213)\n\tat org.apache.maven.cli.MavenCli.main(MavenCli.java:157)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:601)\n\tat org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)\n\tat org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)\n\tat org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)\n\tat org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)\nCaused by: java.lang.NullPointerException\n\tat org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:270)\n\tat org.apache.maven.DefaultMaven.execute(DefaultMaven.java:155)\n\t... 11 more\n{code}\n\nThe more helpful error should have been:\n{code}\norg.apache.maven.project.DuplicateProjectException: Project 'com.foo.bar:foo-bar:2.15.0' is duplicated in the reactor\n\tat org.apache.maven.project.ProjectSorter.<init>(ProjectSorter.java:93)\n\tat org.apache.maven.DefaultProjectDependencyGraph.<init>(DefaultProjectDependencyGraph.java:53)\n\tat org.apache.maven.DefaultMaven.createProjectDependencyGraph(DefaultMaven.java:819)\n\tat org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:268)\n\tat org.apache.maven.DefaultMaven.execute(DefaultMaven.java:155)\n\tat org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)\n\tat org.apache.maven.cli.MavenCli.doMain(MavenCli.java:213)\n\tat org.apache.maven.cli.MavenCli.main(MavenCli.java:157)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:601)\n\tat org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)\n\tat org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)\n\tat org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)\n\tat org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)\n{code}" diff --git a/maven-core/src/main/java/org/apache/maven/DefaultMaven.java b/maven-core/src/main/java/org/apache/maven/DefaultMaven.java index 6328819..ab47efd 100644 --- a/maven-core/src/main/java/org/apache/maven/DefaultMaven.java +++ b/maven-core/src/main/java/org/apache/maven/DefaultMaven.java @@ -267,13 +267,13 @@ private MavenExecutionResult doExecute( MavenExecutionRequest request ) // ProjectDependencyGraph projectDependencyGraph = createProjectDependencyGraph( projects, request, result, true ); - session.setProjects( projectDependencyGraph.getSortedProjects() ); - if ( result.hasExceptions() ) { return result; } + session.setProjects( projectDependencyGraph.getSortedProjects() ); + try { session.setProjectMap( getProjectMap( session.getProjects() ) );
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5613_bef7fac6.diff
bugs-dot-jar_data_MNG-5209_87884c7b
--- BugID: MNG-5209 Summary: MavenProject.getTestClasspathElements can return null elements Description: 'A broken {{MavenProject}} can return null values in certain lists, which seems incorrect (at least it is undocumented). Root cause of: http://netbeans.org/bugzilla/show_bug.cgi?id=205867' diff --git a/maven-core/src/main/java/org/apache/maven/project/MavenProject.java b/maven-core/src/main/java/org/apache/maven/project/MavenProject.java index 088289d..1e235f2 100644 --- a/maven-core/src/main/java/org/apache/maven/project/MavenProject.java +++ b/maven-core/src/main/java/org/apache/maven/project/MavenProject.java @@ -504,7 +504,11 @@ public class MavenProject { List<String> list = new ArrayList<String>( getArtifacts().size() + 1 ); - list.add( getBuild().getOutputDirectory() ); + String d = getBuild().getOutputDirectory(); + if ( d != null ) + { + list.add( d ); + } for ( Artifact a : getArtifacts() ) { @@ -580,9 +584,17 @@ public class MavenProject { List<String> list = new ArrayList<String>( getArtifacts().size() + 2 ); - list.add( getBuild().getTestOutputDirectory() ); + String d = getBuild().getTestOutputDirectory(); + if ( d != null ) + { + list.add( d ); + } - list.add( getBuild().getOutputDirectory() ); + d = getBuild().getOutputDirectory(); + if ( d != null ) + { + list.add( d ); + } for ( Artifact a : getArtifacts() ) { @@ -644,7 +656,11 @@ public class MavenProject { List<String> list = new ArrayList<String>( getArtifacts().size() + 1 ); - list.add( getBuild().getOutputDirectory() ); + String d = getBuild().getOutputDirectory(); + if ( d != null ) + { + list.add( d ); + } for ( Artifact a : getArtifacts() ) { @@ -717,7 +733,11 @@ public class MavenProject { List<String> list = new ArrayList<String>( getArtifacts().size() ); - list.add( getBuild().getOutputDirectory() ); + String d = getBuild().getOutputDirectory(); + if ( d != null ) + { + list.add( d ); + } for ( Artifact a : getArtifacts() ) {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5209_87884c7b.diff
bugs-dot-jar_data_MNG-4837_3fca2bb2
--- BugID: MNG-4837 Summary: Interpolation error due to cyclic expression for one of the POM coordinates gets needlessly repeated Description: |- This simple POM {code:xml} <project> <modelVersion>4.0.0</modelVersion> <groupId>${groupId}</groupId> <artifactId>test</artifactId> <version>0.1</version> <packaging>jar</packaging> <distributionManagement> <repository> <id>maven-core-it</id> <url>file:///${basedir}/repo</url> </repository> </distributionManagement> </project> {code} causes the following model errors: {noformat} [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] Resolving expression: '${groupId}': Detected the following recursive expression cycle: [groupId] -> [Help 2] [ERROR] 'groupId' with value '${groupId}' does not match a valid id pattern. @ line 25, column 12 {noformat} Note the excessive repetition of the groupId related cycle although this expression actually appears only once in the POM. diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/StringSearchModelInterpolator.java b/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/StringSearchModelInterpolator.java index 8f7085a..590f2da 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/StringSearchModelInterpolator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/StringSearchModelInterpolator.java @@ -324,6 +324,11 @@ public class StringSearchModelInterpolator private boolean isQualifiedForInterpolation( Field field, Class<?> fieldType ) { + if ( Map.class.equals( fieldType ) && "locations".equals( field.getName() ) ) + { + return false; + } + Boolean primitive = fieldIsPrimitiveByClass.get( fieldType ); if ( primitive == null ) {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4837_3fca2bb2.diff
bugs-dot-jar_data_MNG-5003_a7d9b689
--- BugID: MNG-5003 Summary: MavenPluginManager serves m2e partially initialized mojo descriptors in some cases Description: Not sure if this affect command line maven, but m2e sometimes gets MojoDescriptor instances with null classRealm and implementationClass. Looks like the problem has to do with incomplete plugin descriptor setup when after reused cached plugin realm. I'll try to provide a fix and corresponding unit test. diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java index 0c541b1..603e670 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java @@ -311,6 +311,10 @@ public class DefaultMavenPluginManager { pluginDescriptor.setClassRealm( cacheRecord.realm ); pluginDescriptor.setArtifacts( new ArrayList<Artifact>( cacheRecord.artifacts ) ); + for ( ComponentDescriptor<?> componentDescriptor : pluginDescriptor.getComponents() ) + { + componentDescriptor.setRealm( cacheRecord.realm ); + } } else {
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-5003_a7d9b689.diff
bugs-dot-jar_data_MNG-4529_03a383e3
--- BugID: MNG-4529 Summary: 'maven fails on IBM JDK 1.5.0 with exception IllegalAccessException: Field is final' Description: "On Windows XP, and IBM JDK 1.5.0, maven 2.2.1 fails with the exception IllegalAccessException: Field is final. (See the complete stacktrace is at the end)\n\nHow to duplicate:\n1. (IMPORTANT) Delete maven local repository at <user home>\\.m2\\repository directory completely!\n2. Unzip myapp.zip\n3. Run command \"mvn package -e\"\n\nMore info:\nThe exception will happen when maven trying to set value to some static final fields. Re-run the command will see another new exception (old exception will not happend again). If you try maven in debug mode (to debug it with Eclipse), the exception will NOT appear. The complete information about maven, JDK, etc. are in the attached file: ibm.output.txt. The other output file (sun.output.txt) is the successful result when running using Sun JDK 1.5.0\n\nRoot cause:\nIn StringSearchModelInterpolator.java of maven 2.2.1, there is a code snippet that tries to using Reflection to change values of fields (even if the fields are final)\n\nLine 175: \n fields[i].setAccessible( true );\nLine 189:\n fields[i].set( target, interpolated );\n\nIf fields[i] is a final field, on Sun JDK 1.5.0, the operation is successful but on IBM JDK 1.5.0, an exception will be thrown. \n\n\n\n================ Complete stacktrace ==========================\norg.apache.maven.lifecycle.LifecycleExecutionException: Unable to build project for plugin 'org.apache.maven.plugins:maven-compiler-plugin': Failed to interpolate field: public static final java.lang.String org.codehaus.plexus.util.xml.Xpp3Dom.CHILDREN_COMBINATION_MODE_ATTRIBUTE on class: org.codehaus.plexus.util.xml.Xpp3Dom for project unknown:maven-compiler-plugin at Artifact [org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2]\n\tat org.apache.maven.lifecycle.DefaultLifecycleExecutor.verifyPlugin(DefaultLifecycleExecutor.java:1557)\n\tat org.apache.maven.lifecycle.DefaultLifecycleExecutor.getMojoDescriptor(DefaultLifecycleExecutor.java:1851)\n\tat org.apache.maven.lifecycle.DefaultLifecycleExecutor.bindLifecycleForPackaging(DefaultLifecycleExecutor.java:1311)\n\tat org.apache.maven.lifecycle.DefaultLifecycleExecutor.constructLifecycleMappings(DefaultLifecycleExecutor.java:1275)\n\tat org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:534)\n\tat org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)\n\tat org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)\n\tat org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)\n\tat org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)\n\tat org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)\n\tat org.apache.maven.cli.MavenCli.main(MavenCli.java:362)\n\tat org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:615)\n\tat org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)\n\tat org.codehaus.classworlds.Launcher.launch(Launcher.java:255)\n\tat org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)\n\tat org.codehaus.classworlds.Launcher.main(Launcher.java:375)\nCaused by: org.apache.maven.plugin.InvalidPluginException: Unable to build project for plugin 'org.apache.maven.plugins:maven-compiler-plugin': Failed to interpolate field: public static final java.lang.String org.codehaus.plexus.util.xml.Xpp3Dom.CHILDREN_COMBINATION_MODE_ATTRIBUTE on class: org.codehaus.plexus.util.xml.Xpp3Dom for project unknown:maven-compiler-plugin at Artifact [org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2]\n\tat org.apache.maven.plugin.DefaultPluginManager.checkRequiredMavenVersion(DefaultPluginManager.java:293)\n\tat org.apache.maven.plugin.DefaultPluginManager.verifyVersionedPlugin(DefaultPluginManager.java:205)\n\tat org.apache.maven.plugin.DefaultPluginManager.verifyPlugin(DefaultPluginManager.java:184)\n\tat org.apache.maven.plugin.DefaultPluginManager.loadPluginDescriptor(DefaultPluginManager.java:1642)\n\tat org.apache.maven.lifecycle.DefaultLifecycleExecutor.verifyPlugin(DefaultLifecycleExecutor.java:1540)\n\t... 19 more\nCaused by: org.apache.maven.project.InvalidProjectModelException: Failed to interpolate field: public static final java.lang.String org.codehaus.plexus.util.xml.Xpp3Dom.CHILDREN_COMBINATION_MODE_ATTRIBUTE on class: org.codehaus.plexus.util.xml.Xpp3Dom for project unknown:maven-compiler-plugin at Artifact [org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2]\n\tat org.apache.maven.project.DefaultMavenProjectBuilder.buildInternal(DefaultMavenProjectBuilder.java:884)\n\tat org.apache.maven.project.DefaultMavenProjectBuilder.buildFromRepository(DefaultMavenProjectBuilder.java:255)\n\tat org.apache.maven.plugin.DefaultPluginManager.checkRequiredMavenVersion(DefaultPluginManager.java:277)\n\t... 23 more\nCaused by: org.apache.maven.project.interpolation.ModelInterpolationException: Failed to interpolate field: public static final java.lang.String org.codehaus.plexus.util.xml.Xpp3Dom.CHILDREN_COMBINATION_MODE_ATTRIBUTE on class: org.codehaus.plexus.util.xml.Xpp3Dom\n\tat org.apache.maven.project.interpolation.StringSearchModelInterpolator$InterpolateObjectAction.traverseObjectWithParents(StringSearchModelInterpolator.java:318)\n\tat org.apache.maven.project.interpolation.StringSearchModelInterpolator$InterpolateObjectAction.run(StringSearchModelInterpolator.java:135)\n\tat org.apache.maven.project.interpolation.StringSearchModelInterpolator$InterpolateObjectAction.run(StringSearchModelInterpolator.java:102)\n\tat java.security.AccessController.doPrivileged(AccessController.java:192)\n\tat org.apache.maven.project.interpolation.StringSearchModelInterpolator.interpolateObject(StringSearchModelInterpolator.java:80)\n\tat org.apache.maven.project.interpolation.StringSearchModelInterpolator.interpolate(StringSearchModelInterpolator.java:62)\n\tat org.apache.maven.project.DefaultMavenProjectBuilder.processProjectLogic(DefaultMavenProjectBuilder.java:990)\n\tat org.apache.maven.project.DefaultMavenProjectBuilder.buildInternal(DefaultMavenProjectBuilder.java:880)\n\t... 25 more\nCaused by: java.lang.IllegalAccessException: Field is final\n\tat sun.reflect.UnsafeQualifiedStaticObjectFieldAccessorImpl.set(UnsafeQualifiedStaticObjectFieldAccessorImpl.java:77)\n\tat java.lang.reflect.Field.set(Field.java:684)\n\tat org.apache.maven.project.interpolation.StringSearchModelInterpolator$InterpolateObjectAction.traverseObjectWithParents(StringSearchModelInterpolator.java:189)\n\t... 32 more\n" diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/StringSearchModelInterpolator.java b/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/StringSearchModelInterpolator.java index 712508d..6ff36b4 100644 --- a/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/StringSearchModelInterpolator.java +++ b/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/StringSearchModelInterpolator.java @@ -32,6 +32,7 @@ import org.codehaus.plexus.interpolation.ValueSource; import java.io.File; import java.lang.reflect.Array; import java.lang.reflect.Field; +import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; @@ -329,6 +330,11 @@ public class StringSearchModelInterpolator return false; } + if ( Modifier.isFinal( field.getModifiers() ) ) + { + return false; + } + return true; }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4529_03a383e3.diff
bugs-dot-jar_data_MNG-4918_691a03a7
--- BugID: MNG-4918 Summary: MavenProject#clone() doubles active profiles Description: "The error occured in our Project with more than 60 submodules and aggregating JavaDoc. Due to the forking of the LifeCycle many clones of the MavenProject object seem to be performed. Since MavenProject#clone doubles the entries in the list of active profiles we start with one active profile and after a few dozen clones the list of active profiles exceeds 10.000.000 elements. This will than kill the VM by OOME. \n\nmavenProject.getActiveProfiles().size() == 1 \nmavenProject.clone().getActiveProfiles().size() == 2 \nmavenProject.clone().clone().getActiveProfiles().size() == 4\nand so on " diff --git a/maven-core/src/main/java/org/apache/maven/project/MavenProject.java b/maven-core/src/main/java/org/apache/maven/project/MavenProject.java index 8a7d64b..de3c278 100644 --- a/maven-core/src/main/java/org/apache/maven/project/MavenProject.java +++ b/maven-core/src/main/java/org/apache/maven/project/MavenProject.java @@ -1407,7 +1407,7 @@ public class MavenProject public void setActiveProfiles( List<Profile> activeProfiles ) { - this.activeProfiles.addAll( activeProfiles ); + this.activeProfiles = activeProfiles; } public List<Profile> getActiveProfiles()
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4918_691a03a7.diff
bugs-dot-jar_data_MNG-4933_469d0096
--- BugID: MNG-4933 Summary: With a resource directory as . maven raise an java.lang.StringIndexOutOfBoundsException:217 Description: |- I exexute a release:prepare-with-pom I debug this execution and I found when the directory is equal to basedir.getPath() an exception is raised. And I have this definition in my pom.xml <resource> <directory>.</directory> <includes> <include>plugin.xml</include> <include>plugin.properties</include> <include>icons/**</include> </includes> </resource> Trace: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.1.1:prepare-with-pom (default-cli) on project servicelayer: Execution default-cli of goal org.apache.maven.plugins:maven-release-plugin:2.1.1:prepare-with-pom failed: String index out of range: -1 -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.1.1:prepare-with-pom (default-cli) on project servicelayer: Execution default-cli of goal org.apache.maven.plugins:maven-release-plugin:2.1.1:prepare-with-pom failed: String index out of range: -1 at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:211) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:140) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:316) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:153) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:451) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:188) at org.apache.maven.cli.MavenCli.main(MavenCli.java:134) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352) Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-cli of goal org.apache.maven.plugins:maven-release-plugin:2.1.1:prepare-with-pom failed: String index out of range: -1 at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:116) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:195) ... 19 more Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1937) at java.lang.String.substring(String.java:1904) at org.apache.maven.project.path.DefaultPathTranslator.unalignFromBaseDirectory(DefaultPathTranslator.java:217) at org.apache.maven.project.path.DefaultPathTranslator.unalignFromBaseDirectory(DefaultPathTranslator.java:181) at org.apache.maven.shared.release.phase.GenerateReleasePomsPhase.createReleaseModel(GenerateReleasePomsPhase.java:274) at org.apache.maven.shared.release.phase.GenerateReleasePomsPhase.generateReleasePom(GenerateReleasePomsPhase.java:141) at org.apache.maven.shared.release.phase.GenerateReleasePomsPhase.generateReleasePoms(GenerateReleasePomsPhase.java:129) at org.apache.maven.shared.release.phase.GenerateReleasePomsPhase.execute(GenerateReleasePomsPhase.java:105) at org.apache.maven.shared.release.phase.GenerateReleasePomsPhase.execute(GenerateReleasePomsPhase.java:92) at org.apache.maven.shared.release.DefaultReleaseManager.prepare(DefaultReleaseManager.java:203) at org.apache.maven.shared.release.DefaultReleaseManager.prepare(DefaultReleaseManager.java:140) at org.apache.maven.shared.release.DefaultReleaseManager.prepare(DefaultReleaseManager.java:103) at org.apache.maven.plugins.release.PrepareReleaseMojo.prepareRelease(PrepareReleaseMojo.java:279) at org.apache.maven.plugins.release.PrepareWithPomReleaseMojo.execute(PrepareWithPomReleaseMojo.java:47) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:107) ... 20 more [ERROR] [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] diff --git a/maven-compat/src/main/java/org/apache/maven/project/path/DefaultPathTranslator.java b/maven-compat/src/main/java/org/apache/maven/project/path/DefaultPathTranslator.java index c9ec15d..020b652 100644 --- a/maven-compat/src/main/java/org/apache/maven/project/path/DefaultPathTranslator.java +++ b/maven-compat/src/main/java/org/apache/maven/project/path/DefaultPathTranslator.java @@ -38,6 +38,11 @@ public class DefaultPathTranslator public void alignToBaseDirectory( Model model, File basedir ) { + if ( basedir == null ) + { + return; + } + Build build = model.getBuild(); if ( build != null ) @@ -83,6 +88,11 @@ public class DefaultPathTranslator public String alignToBaseDirectory( String path, File basedir ) { + if ( basedir == null ) + { + return path; + } + if ( path == null ) { return null; @@ -166,6 +176,11 @@ public class DefaultPathTranslator public void unalignFromBaseDirectory( Model model, File basedir ) { + if ( basedir == null ) + { + return; + } + Build build = model.getBuild(); if ( build != null ) @@ -209,14 +224,37 @@ public class DefaultPathTranslator } } - public String unalignFromBaseDirectory( String directory, File basedir ) + public String unalignFromBaseDirectory( String path, File basedir ) { - String path = basedir.getPath(); - if ( directory.startsWith( path ) ) + if ( basedir == null ) + { + return path; + } + + if ( path == null ) { - directory = directory.substring( path.length() + 1 ).replace( '\\', '/' ); + return null; } - return directory; + + path = path.trim(); + + String base = basedir.getAbsolutePath(); + if ( path.startsWith( base ) ) + { + path = chopLeadingFileSeparator( path.substring( base.length() ) ); + } + + if ( path.length() <= 0 ) + { + path = "."; + } + + if ( !new File( path ).isAbsolute() ) + { + path = path.replace( '\\', '/' ); + } + + return path; } }
bugs-dot-jar/maven_extracted_diff/developer-patch_bugs-dot-jar_MNG-4933_469d0096.diff
bugs-dot-jar_data_WICKET-5565_44f4782a
--- BugID: WICKET-5565 Summary: PackageMapper - Could not resolve class Description: "It seems that the PackageMapper try to resolve much more than it is supposed to do, for instance if I've 2 pages test1/TestPage1 and test2/TestPage2 then it tries to resolve test2/TestPage1 when I reach the page1... \n\nWARN - WicketObjects \ - Could not resolve class [com.mycompany.test2.TestPage1]\njava.lang.ClassNotFoundException: com.mycompany.test2.TestPage1\n at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)\n \ at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)\n \ at java.lang.Class.forName0(Native Method)\n at java.lang.Class.forName(Class.java:270)\n \ at org.apache.wicket.application.AbstractClassResolver.resolveClass(AbstractClassResolver.java:108)\n \ at org.apache.wicket.core.util.lang.WicketObjects.resolveClass(WicketObjects.java:71)\n \ at org.apache.wicket.core.request.mapper.AbstractComponentMapper.getPageClass(AbstractComponentMapper.java:134)\n \ at org.apache.wicket.core.request.mapper.PackageMapper.parseRequest(PackageMapper.java:152)\n \ at org.apache.wicket.core.request.mapper.AbstractBookmarkableMapper.mapRequest(AbstractBookmarkableMapper.java:322)\n \ at org.apache.wicket.request.mapper.CompoundRequestMapper.mapRequest(CompoundRequestMapper.java:152)\n \ at org.apache.wicket.request.cycle.RequestCycle.resolveRequestHandler(RequestCycle.java:189)\n \ at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:219)\n \ at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:293)\n \ at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:261)\n \ at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:203)\n \ at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:284)" diff --git a/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java b/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java index ad15d6d..2037356 100644 --- a/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java +++ b/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java @@ -225,7 +225,13 @@ public class PackageMapper extends AbstractBookmarkableMapper @Override public int getCompatibilityScore(Request request) { - // always return 0 here so that the mounts have higher priority - return 0; + if (urlStartsWith(request.getUrl(), mountSegments)) + { + return mountSegments.length; + } + else + { + return 0; + } } }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5565_44f4782a.diff
bugs-dot-jar_data_WICKET-4696_f5f802c5
--- BugID: WICKET-4696 Summary: NumberTextField doesn't accept values <=0 for Double and Float Description: |- The org.apache.wicket.util.lang.Numbers class defines the method : public static Number getMinValue(Class<? extends Number> numberType) This method return the MatchingNumberTypeClass.MIN_VALUE. But for Double.MIN_VALUE and Float.MIN_VALUE return the smallest positive number, not the smallest negative number like for the other number classes. One side effect is that by default you can't enter a negative value, or a 0 in a NumberTextField<Double> or NumberTextField<Float>. diff --git a/wicket-util/src/main/java/org/apache/wicket/util/lang/Numbers.java b/wicket-util/src/main/java/org/apache/wicket/util/lang/Numbers.java index f4e7858..260d8d1 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/lang/Numbers.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/lang/Numbers.java @@ -38,8 +38,8 @@ public final class Numbers * * @param numberType * the type of the number for which the minimum value will be returned - * @return the minimum value of the numberType or {@value Double#MIN_VALUE} if the numberType - * itself is either {@code null} or has no minimum value + * @return the minimum value of the numberType or Double if the numberType itself is either + * {@code null} or has no minimum value */ public static Number getMinValue(Class<? extends Number> numberType) { @@ -54,11 +54,11 @@ public final class Numbers } else if (Float.class == numberType || float.class == numberType) { - result = Float.MIN_VALUE; + result = -Float.MAX_VALUE; } else if (Double.class == numberType || double.class == numberType) { - result = Double.MIN_VALUE; + result = -Double.MAX_VALUE; } else if (Byte.class == numberType || byte.class == numberType) { @@ -70,8 +70,8 @@ public final class Numbers } else { // null of any other Number - LOG.debug("'{}' has no minimum value. Falling back to Double.MIN_VALUE.", numberType); - result = Double.MIN_VALUE; + LOG.debug("'{}' has no minimum value. Falling back to Double.", numberType); + result = -Double.MAX_VALUE; } return result;
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4696_f5f802c5.diff
bugs-dot-jar_data_WICKET-5560_aa82ccfc
--- BugID: WICKET-5560 Summary: A 404 error occurs when using a CryptoMapper Description: "Under certain prerequisites a 404 error occurs.\n\nThe prerequisites are:\n- A _CryptoMapper_ is used as _RequestMapper_\n- _SecuritySettings.enforceMounts_ is set to true\n- Class _SomePage_ is *not* annotated with _@MountPath_\n\nReason:\nIn _BookmarkableMapper.parseRequest_ (called indirectly by _CryptoMapper.mapRequest_) the method _matches_ returns _false_,\nas _reverseUrl_ is the *encrypted URL* (_rootRequestMapper_ is a _CryptoMapper_) but _BookmarkableMapper.matches_ expects a *decrypted URL*.\n\n_BookmarkableMapper_ - lines 132 ff.:\n{code}\nUrl reverseUrl = application.getRootRequestMapper().mapHandler(\n\tnew RenderPageRequestHandler(new PageProvider(pageClass)));\nif (!matches(request.cloneWithUrl(reverseUrl)))\n{\n\treturn null;\n}\n{code}\n\t\nAs a result _BookmarkableMapper.mapRequest_ and hence _CryptoMapper.mapRequest_ returns _null_ resulting in a 404 error.\n" diff --git a/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/BookmarkableMapper.java b/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/BookmarkableMapper.java index 60764fa..bf7e64b 100644 --- a/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/BookmarkableMapper.java +++ b/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/BookmarkableMapper.java @@ -19,11 +19,11 @@ package org.apache.wicket.core.request.mapper; import java.util.List; import org.apache.wicket.Application; -import org.apache.wicket.core.request.handler.PageProvider; -import org.apache.wicket.core.request.handler.RenderPageRequestHandler; +import org.apache.wicket.request.IRequestMapper; import org.apache.wicket.request.Request; import org.apache.wicket.request.Url; import org.apache.wicket.request.component.IRequestablePage; +import org.apache.wicket.request.mapper.ICompoundRequestMapper; import org.apache.wicket.request.mapper.info.PageComponentInfo; import org.apache.wicket.request.mapper.parameter.IPageParametersEncoder; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -118,9 +118,7 @@ public class BookmarkableMapper extends AbstractBookmarkableMapper if (!pageClass.equals(application.getHomePage())) { // WICKET-5094 only enforce mount if page is mounted - Url reverseUrl = application.getRootRequestMapper().mapHandler( - new RenderPageRequestHandler(new PageProvider(pageClass))); - if (!matches(request.cloneWithUrl(reverseUrl))) + if (isPageMounted(pageClass, application)) { return null; } @@ -138,6 +136,27 @@ public class BookmarkableMapper extends AbstractBookmarkableMapper return null; } + private boolean isPageMounted(Class<? extends IRequestablePage> pageClass, + Application application) + { + ICompoundRequestMapper applicationMappers = application.getRootRequestMapperAsCompound(); + + for (IRequestMapper requestMapper : applicationMappers) + { + if(requestMapper instanceof AbstractBookmarkableMapper && requestMapper != this) + { + AbstractBookmarkableMapper mapper = (AbstractBookmarkableMapper) requestMapper; + + if(mapper.checkPageClass(pageClass)) + { + return true; + } + } + } + + return false; + } + @Override protected boolean pageMustHaveBeenCreatedBookmarkable() { diff --git a/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java b/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java index 4f0f107..ff13a62 100644 --- a/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java +++ b/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java @@ -221,4 +221,11 @@ public class PackageMapper extends AbstractBookmarkableMapper { return false; } + + @Override + protected boolean checkPageClass(Class<? extends IRequestablePage> pageClass) + { + PackageName pageClassPackageName = PackageName.forClass(pageClass); + return packageName.equals(pageClassPackageName); + } }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5560_aa82ccfc.diff
bugs-dot-jar_data_WICKET-3413_499a9c6b
--- BugID: WICKET-3413 Summary: FLAG_INHERITABLE_MODEL and default model change Description: "The issue is about correctness of Component#setDefaultModel (Component#setModelImpl) method behavior. I expect that the flag FLAG_INHERITABLE_MODEL should be checked there and turned off in case if new model is not a IComponentInheritedModel. \n\nLet check the next code:\npublic MyPanel(String id) {\n super(id);\n ...\n form.setModel(new CompoundPropertyModel(this));\n DropDownChoice ddc = new DropDownChoice(\"variant\", Arrays.ofList(...)) { // p1\n @Override\n protected void onInitialize() {\n super.onInitialize();\n setModel(new DefaultingWrapModel(getModel(), Model.of(\"default value\")); // p2\n }\n };\n ddc.setNullValid(false);\n \ ddc.setRequired(true);\n form.add(ddc);\n ...\n}\n\nIn the (p1) the DDC will initialize with CompoundPropertyModel and the FLAG_INHERITABLE_MODEL will be turned on soon by the first invocation of FormComponent#getModel().\n\n In the (p2) we wrap the DDC model with the model which provide the default value (DefaultingWrapModel implements IWrapModel). So we change the model, but the FLAG_INHERITABLE_MODEL is still turned on. On the Component#detach() event, the method Component#setModelImpl(null) will be invoked for the ddc and the DefaultingWrapModel instance will be lost:\n\n\t\t// reset the model to null when the current model is a IWrapModel and\n\t\t// the model that created it/wrapped in it is a IComponentInheritedModel\n\t\t// The model will be created next time.\n\t\tif (getFlag(FLAG_INHERITABLE_MODEL))\n\t\t{\n\t\t\tsetModelImpl(null);\n\t\t\tsetFlag(FLAG_INHERITABLE_MODEL, false);\n\t\t}\n\nI think that such behavior is unexpected.\n\nhttp://apache-wicket.1842946.n4.nabble.com/1-4-15-FLAG-INHERITABLE-MODEL-and-default-model-change-td3252093.html" diff --git a/wicket-core/src/main/java/org/apache/wicket/Component.java b/wicket-core/src/main/java/org/apache/wicket/Component.java index f94cf41..7a3df6a 100644 --- a/wicket-core/src/main/java/org/apache/wicket/Component.java +++ b/wicket-core/src/main/java/org/apache/wicket/Component.java @@ -2956,6 +2956,12 @@ public abstract class Component if (model != null) { data_set(0, model); + // WICKET-3413 reset 'inherited model' flag if model changed + // and a new one is not IComponentInheritedModel + if (getFlag(FLAG_INHERITABLE_MODEL) && !(model instanceof IComponentInheritedModel)) + { + setFlag(FLAG_INHERITABLE_MODEL, false); + } } else {
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-3413_499a9c6b.diff
bugs-dot-jar_data_WICKET-4185_5fd03973
--- BugID: WICKET-4185 Summary: ListenerInterfaceRequestHandler should not assume existence of a page Description: ListenerInterfaceRequestHandler should not assume a page instance is always available in isPageInstanceCreated. This handler can also be used for links on bookmarkable pages. The attached patch fixes this. diff --git a/wicket-core/src/main/java/org/apache/wicket/request/handler/ListenerInterfaceRequestHandler.java b/wicket-core/src/main/java/org/apache/wicket/request/handler/ListenerInterfaceRequestHandler.java index a4b5817..0c497d5 100644 --- a/wicket-core/src/main/java/org/apache/wicket/request/handler/ListenerInterfaceRequestHandler.java +++ b/wicket-core/src/main/java/org/apache/wicket/request/handler/ListenerInterfaceRequestHandler.java @@ -249,8 +249,16 @@ public class ListenerInterfaceRequestHandler public final boolean isPageInstanceCreated() { - // this request handler always operates on a created page instance - return true; + // FIXME wicket.next remove the workaround for page providers that don't implement the + // interface + if (!(pageComponentProvider instanceof IIntrospectablePageProvider)) + { + LOG.warn( + "{} used by this application does not implement {}, the request handler is falling back on using incorrect behavior", + IPageProvider.class, IIntrospectablePageProvider.class); + return !pageComponentProvider.isNewPageInstance(); + } + return ((IIntrospectablePageProvider)pageComponentProvider).hasPageInstance(); } public final String getComponentPath()
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4185_5fd03973.diff
bugs-dot-jar_data_WICKET-5698_f45ce896
--- BugID: WICKET-5698 Summary: WebApplication#unmount() unmounts the whole compound mapper if some of its inner ones matches Description: "From dev@ mailing lists: http://markmail.org/message/wmdgbrhvrvaeygvr\n\nWebApplication.unmount() calls getRootRequestMapperAsCompound(), and \ncalls unmount() on that.\n\ngetRootRequestMapperAsCompound() checks if the root request mapper is a \ncompound, if not, wraps it in a compound, sets the compound as root and \nreturns the compound.\n\nCompoundRequestMapper.unmount() identifies which of the mappers added \ndirectly to the compound handle the url, and removes them.\n\nThe problem:\nIf the original root mapper was a single wrapper, or layer of wrappers, \nwith the actual mounted mapper wrapped some levels down, then the whole \nwrapper is removed, not just the specific MountedMapper that is wrapped. \nThis has the effect of removing every single mapper, leaving root mapper \nas an empty compound.\n\nI would like to attempt to provide a patch to fix this, but would like \nguidance on the approach. I have come up with three approaches:\n\n1. Introduce interface IWrappedRequestMapper. This will be an interface \nwhich has one method: IRequestMapper getWrappedRequestMapper(). We can \nthen have all wrapper mappers implement this and work down the tree to \nfind the correct MountedMapper (wicket 6) to remove.\n\n2. Have WebApplication hold a reference to a specific \nCompoundRequestMapper, and have all mount()/unmount() operations add and \nremove from this mapper. This compound would need to be added to the \ndefault list during init. This makes it complicated to work out how to \ndo things like have CryptoMapper not apply to mounted pages.\n\n3. Add method unmount() to IRequestMapper, so that wrappers can \ndelegate. This obviously can only be done in wicket 7, but we're making \nmounting a problem of every single request mapper, when not even \nApplication cares about mounting." diff --git a/wicket-request/src/main/java/org/apache/wicket/request/mapper/CompoundRequestMapper.java b/wicket-request/src/main/java/org/apache/wicket/request/mapper/CompoundRequestMapper.java index bbd6277..94635b3 100644 --- a/wicket-request/src/main/java/org/apache/wicket/request/mapper/CompoundRequestMapper.java +++ b/wicket-request/src/main/java/org/apache/wicket/request/mapper/CompoundRequestMapper.java @@ -251,7 +251,12 @@ public class CompoundRequestMapper implements ICompoundRequestMapper for (IRequestMapper mapper : this) { - if (mapper.mapRequest(request) != null) + if (mapper instanceof ICompoundRequestMapper) + { + ICompoundRequestMapper inner = (ICompoundRequestMapper) mapper; + inner.unmount(path); + } + else if (mapper.mapRequest(request) != null) { remove(mapper); }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5698_f45ce896.diff
bugs-dot-jar_data_WICKET-4572_dfc56674
--- BugID: WICKET-4572 Summary: 'DiskDataStore returns the wrong page when the page disk space is full ' Description: |- If the configured file size for the session data is overflowed (see org.apache.wicket.settings.IStoreSettings#setMaxSizePerSession(Bytes)) then Wicket may return wrong page data (bytes) for a expired page. The problem is in org.apache.wicket.pageStore.PageWindowManager#idToWindowIndex which may have several page ids (the keys) pointing to the same window index (values). diff --git a/wicket-core/src/main/java/org/apache/wicket/pageStore/PageWindowManager.java b/wicket-core/src/main/java/org/apache/wicket/pageStore/PageWindowManager.java index 0f2faa6..03887bb 100644 --- a/wicket-core/src/main/java/org/apache/wicket/pageStore/PageWindowManager.java +++ b/wicket-core/src/main/java/org/apache/wicket/pageStore/PageWindowManager.java @@ -64,6 +64,11 @@ public class PageWindowManager implements Serializable */ private IntHashMap<Integer> idToWindowIndex = null; + /** + * Inversed index of #idToWindowIndex + */ + private IntHashMap<Integer> windowIndexToPageId = null; + /** index of last added page */ private int indexPointer = -1; @@ -84,7 +89,13 @@ public class PageWindowManager implements Serializable { if (idToWindowIndex != null && pageId != -1 && windowIndex != -1) { + Integer oldPageId = windowIndexToPageId.remove(windowIndex); + if (oldPageId != null) + { + idToWindowIndex.remove(oldPageId); + } idToWindowIndex.put(pageId, windowIndex); + windowIndexToPageId.put(windowIndex, pageId); } } @@ -94,7 +105,11 @@ public class PageWindowManager implements Serializable */ private void removeWindowIndex(int pageId) { - idToWindowIndex.remove(pageId); + Integer windowIndex = idToWindowIndex.remove(pageId); + if (windowIndex != null) + { + windowIndexToPageId.remove(windowIndex); + } } /** @@ -104,6 +119,8 @@ public class PageWindowManager implements Serializable { idToWindowIndex = null; idToWindowIndex = new IntHashMap<Integer>(); + windowIndexToPageId = null; + windowIndexToPageId = new IntHashMap<Integer>(); for (int i = 0; i < windows.size(); ++i) { PageWindowInternal window = windows.get(i); @@ -195,6 +212,7 @@ public class PageWindowManager implements Serializable } idToWindowIndex = null; + windowIndexToPageId = null; } /** @@ -213,6 +231,7 @@ public class PageWindowManager implements Serializable windows.remove(index + 1); idToWindowIndex = null; // reset index + windowIndexToPageId = null; } } @@ -364,7 +383,7 @@ public class PageWindowManager implements Serializable } // if we are not going to reuse a page window (because it's not on - // indexPointor position or because we didn't find it), increment the + // indexPointer position or because we didn't find it), increment the // indexPointer if (index == -1 || index != indexPointer) {
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4572_dfc56674.diff
bugs-dot-jar_data_WICKET-4119_bb7a6995
--- BugID: WICKET-4119 Summary: FileResourceStream returns unknown content type Description: |- See http://apache-wicket.1842946.n4.nabble.com/PackageResourceReference-and-Doctype-in-Markup-file-tp3889467p3889587.html The response for FileResourceStreams returns an unknown content type for css- and image-files. Correct content types should be "text/css" and "image/png" (see also attached quickstart). diff --git a/wicket-core/src/main/java/org/apache/wicket/protocol/http/mock/MockServletContext.java b/wicket-core/src/main/java/org/apache/wicket/protocol/http/mock/MockServletContext.java index 42a8996..392e921 100755 --- a/wicket-core/src/main/java/org/apache/wicket/protocol/http/mock/MockServletContext.java +++ b/wicket-core/src/main/java/org/apache/wicket/protocol/http/mock/MockServletContext.java @@ -107,7 +107,7 @@ public class MockServletContext implements ServletContext mimeTypes.put("htm", "text/html"); mimeTypes.put("css", "text/css"); mimeTypes.put("xml", "text/xml"); - mimeTypes.put("js", "text/plain"); + mimeTypes.put("js", "text/javascript"); mimeTypes.put("gif", "image/gif"); mimeTypes.put("jpg", "image/jpeg"); mimeTypes.put("png", "image/png"); diff --git a/wicket-core/src/main/java/org/apache/wicket/request/resource/ByteArrayResource.java b/wicket-core/src/main/java/org/apache/wicket/request/resource/ByteArrayResource.java index d156c11..d11cab8 100644 --- a/wicket-core/src/main/java/org/apache/wicket/request/resource/ByteArrayResource.java +++ b/wicket-core/src/main/java/org/apache/wicket/request/resource/ByteArrayResource.java @@ -16,6 +16,8 @@ */ package org.apache.wicket.request.resource; +import java.net.URLConnection; + import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.util.time.Time; @@ -95,6 +97,22 @@ public class ByteArrayResource extends AbstractResource { final ResourceResponse response = new ResourceResponse(); + String contentType = this.contentType; + + if (contentType == null) + { + if (filename != null) + { + contentType = URLConnection.getFileNameMap().getContentTypeFor(filename); + } + + if (contentType == null) + { + contentType = "application/octet-stream"; + } + } + + response.setContentType(contentType); response.setLastModified(lastModified); diff --git a/wicket-core/src/main/java/org/apache/wicket/request/resource/PackageResource.java b/wicket-core/src/main/java/org/apache/wicket/request/resource/PackageResource.java index 449c344..a4ce0fe 100644 --- a/wicket-core/src/main/java/org/apache/wicket/request/resource/PackageResource.java +++ b/wicket-core/src/main/java/org/apache/wicket/request/resource/PackageResource.java @@ -252,11 +252,15 @@ public class PackageResource extends AbstractResource implements IStaticCacheabl return sendResourceError(resourceResponse, HttpServletResponse.SC_NOT_FOUND, "Unable to find resource"); - String contentType = resourceStream.getContentType(); - if (contentType == null && Application.exists()) + final String contentType; + if (Application.exists()) { contentType = Application.get().getMimeType(path); } + else + { + contentType = resourceStream.getContentType(); + } // set Content-Type (may be null) resourceResponse.setContentType(contentType); diff --git a/wicket-core/src/main/java/org/apache/wicket/request/resource/ResourceStreamResource.java b/wicket-core/src/main/java/org/apache/wicket/request/resource/ResourceStreamResource.java index e9d25f0..e83257a 100644 --- a/wicket-core/src/main/java/org/apache/wicket/request/resource/ResourceStreamResource.java +++ b/wicket-core/src/main/java/org/apache/wicket/request/resource/ResourceStreamResource.java @@ -123,11 +123,15 @@ public class ResourceStreamResource extends AbstractResource } data.setFileName(fileName); - String contentType = stream.getContentType(); - if (contentType == null && fileName != null && Application.exists()) + final String contentType; + if (fileName != null && Application.exists()) { contentType = Application.get().getMimeType(fileName); } + else + { + contentType = stream.getContentType(); + } data.setContentType(contentType); data.setTextEncoding(textEncoding);
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4119_bb7a6995.diff
bugs-dot-jar_data_WICKET-4841_ce172da8
--- BugID: WICKET-4841 Summary: Return error code 400 when an Ajax request has no base url set in header/request parameters. Description: "Hello,\n\ncurrently we've got a problem with faked ajax requests. these ajax \nrequests misses some parameters, but the wicket-ajax header flag is set. \nSo ServletWebRequest throws an exception:\n\njava.lang.IllegalStateException: Current ajax request is missing the base url header or parameter\n at org.apache.wicket.util.lang.Checks.notNull(Checks.java:38)\n \ at org.apache.wicket.protocol.http.servlet.ServletWebRequest.getClientUrl(ServletWebRequest.java:171)\n \ at org.apache.wicket.request.UrlRenderer.<init>(UrlRenderer.java:59)\n\n\nThese faked requests are so massive, that our application is no longer \nmonitorable. Our workaround rejects these requests via apache config. \n\nInstead of logging an exception, in deployment mode wicket should log a warning and reject the request" diff --git a/wicket-core/src/main/java/org/apache/wicket/protocol/http/servlet/ServletWebRequest.java b/wicket-core/src/main/java/org/apache/wicket/protocol/http/servlet/ServletWebRequest.java index 02ffe67..8e41aef 100644 --- a/wicket-core/src/main/java/org/apache/wicket/protocol/http/servlet/ServletWebRequest.java +++ b/wicket-core/src/main/java/org/apache/wicket/protocol/http/servlet/ServletWebRequest.java @@ -30,6 +30,7 @@ import java.util.Set; import javax.servlet.ServletRequest; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.apache.wicket.protocol.http.RequestUtils; import org.apache.wicket.request.IRequestParameters; @@ -37,9 +38,9 @@ import org.apache.wicket.request.IWritableRequestParameters; import org.apache.wicket.request.Url; import org.apache.wicket.request.UrlUtils; import org.apache.wicket.request.http.WebRequest; +import org.apache.wicket.request.http.flow.AbortWithHttpErrorCodeException; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.lang.Bytes; -import org.apache.wicket.util.lang.Checks; import org.apache.wicket.util.string.PrependingStringBuffer; import org.apache.wicket.util.string.StringValue; import org.apache.wicket.util.string.Strings; @@ -168,7 +169,11 @@ public class ServletWebRequest extends WebRequest base = getRequestParameters().getParameterValue(PARAM_AJAX_BASE_URL).toString(null); } - Checks.notNull(base, "Current ajax request is missing the base url header or parameter"); + if (base == null) + { + throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_BAD_REQUEST, + "Current ajax request is missing the base url header or parameter"); + } return setParameters(Url.parse(base, getCharset())); }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4841_ce172da8.diff
bugs-dot-jar_data_WICKET-5656_f539c18c
--- BugID: WICKET-5656 Summary: PropertyResolver does not scan for NotNull in annotation tree Description: |- When annotating a field of a bean with e.g. org.hibernate.validator.constraints.NotEmpty, this implies javax.validation.constraints.NotNull, but PropertyValidator only checks for the annotations immediately on the filed not the tree of annotations. As a result Wicket does not mark the field as required in the UI, which it should. Also PropertyResolver.findNotNullConstraints() is not even protected, so cannot be patched in a simple way. So as a solution I suggest changing findNotNullConstraints() to be protected and rather be something like findConstraints(filter), or findConstraints(clazz), and then in that method method recursively invoking getComposingConstraints to get all constraints, but collecting only those of interest. Possibly some care needs to be taken to prevent infinite recursion where constraints are composed of each other (if that compiles). diff --git a/wicket-bean-validation/src/main/java/org/apache/wicket/bean/validation/PropertyValidator.java b/wicket-bean-validation/src/main/java/org/apache/wicket/bean/validation/PropertyValidator.java index e8e6376..a2486c7 100644 --- a/wicket-bean-validation/src/main/java/org/apache/wicket/bean/validation/PropertyValidator.java +++ b/wicket-bean-validation/src/main/java/org/apache/wicket/bean/validation/PropertyValidator.java @@ -10,6 +10,7 @@ import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validator; import javax.validation.constraints.NotNull; +import javax.validation.groups.Default; import javax.validation.metadata.ConstraintDescriptor; import org.apache.wicket.Component; @@ -100,11 +101,10 @@ public class PropertyValidator<T> extends Behavior implements IValidator<T> if (property_ == null) { throw new IllegalStateException( - "Could not resolve Property from component: " + - component + - ". Either specify the Property in the constructor or use a model that works in combination with a " + - IPropertyResolver.class.getSimpleName() + - " to resolve the Property automatically"); + "Could not resolve Property from component: " + component + + ". Either specify the Property in the constructor or use a model that works in combination with a " + + IPropertyResolver.class.getSimpleName() + + " to resolve the Property automatically"); } } return property_; @@ -126,14 +126,15 @@ public class PropertyValidator<T> extends Behavior implements IValidator<T> if (this.component != null) { throw new IllegalStateException( // - "This validator has already been added to component: " + this.component + - ". This validator does not support reusing instances, please create a new one"); + "This validator has already been added to component: " + + this.component + + ". This validator does not support reusing instances, please create a new one"); } if (!(component instanceof FormComponent)) { - throw new IllegalStateException(getClass().getSimpleName() + - " can only be added to FormComponents"); + throw new IllegalStateException(getClass().getSimpleName() + + " can only be added to FormComponents"); } // TODO add a validation key that appends the type so we can have @@ -208,7 +209,7 @@ public class PropertyValidator<T> extends Behavior implements IValidator<T> for (NotNull constraint : constraints) { - if (constraint.groups().length == 0 && validatorGroups.isEmpty()) + if (canApplyToDefaultGroup(constraint) && validatorGroups.isEmpty()) { return true; } @@ -225,6 +226,14 @@ public class PropertyValidator<T> extends Behavior implements IValidator<T> return false; } + private boolean canApplyToDefaultGroup(NotNull constraint) + { + List<Class<?>> groups = Arrays.asList(constraint.groups()); + //the constraint can be applied to default group either if its group array is empty + //or if it contains javax.validation.groups.Default + return groups.size() == 0 || groups.contains(Default.class); + } + @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void onComponentTag(Component component, ComponentTag tag)
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5656_f539c18c.diff
bugs-dot-jar_data_WICKET-4014_e60bac5f
--- BugID: WICKET-4014 Summary: Wicket 1.5 Form Post Action and Link Get discard Page Class Information Description: | Page expiry is a very annoying and perplexing event especially if users stay logged in via remember-me cookie. It is therefore not a fancy enhancement but an essential business requirement to not drop the user out of context after session expiry. Only stateless pages can fully achieve this, but it is not always desirable to go fully stateless, especially while a recovery solution already exists. In 1.4, this appears to be automatic with BookmarkablePageRequestTargetUrlCodingStrategy - without any additional coding. The solution is well known - keep as much state in the client as required to recover the page class, and possibly even its page parameters, and to not destroy this information. The two attached testcases show two possible methods of page fallback recovery (one with AJAX, one without) that already work behind the scenes. Of course it is easy with AJAX, to just force a page reload, but this is not discussed here. AJAX just serves to demonstrate how easy the principle actually is. In most cases the user could successfully reload the page but Wicket 1.5 can't create a response because it has forgotten the class of the expired page. In 1.4, it is possible to recover the class of an expired page via its mount path. This feature is lost in 1.5. To get this functionality back in a more streamlined fashion, I am additionaly proposing in a separate jira issue 4013 to store page class and page parameters in PageExpiredException. Meanwhile, the focus of this issue is to request whatever means to not overwrite the path of a page in a form post action or get request, and to get the page class back as in 1.4 by whatever means. The two attached testcases may be helpful for expermintation. The 1.4 tescase demonstrates how the scheme works, unfortunately I could not fill the blanks in the 1.5 testcase. In 1.4, a form tag is rendered as: <form wicket:id="form" action="?wicket:interface=:0:form::IFormSubmitListener::" This is requested as: /testForm.0?wicket:interface=:0:form::IFormSubmitListener:: and the page class can be recovered from the mount path "testForm" as in mount(new HybridUrlCodingStrategy("testForm", TestPageForm.class)); an anchor tag is rendered as: <a href="?wicket:interface=:0:linkSwitch::ILinkListener::" This is requested as: /testLink.0?wicket:interface=:0:linkSwitch::ILinkListener:: and the page class can be recovered from the mount path "test" as in mount(new HybridUrlCodingStrategy("testLink", TestPageLink.class)); In 1.5, a form tag is rendered as: <form wicket:id="form" action="wicket/page?0-2.IFormSubmitListener-form" This is requested requested as: /wicket/page?0-1.IFormSubmitListener-form This overwrites the mount path "testForm" as in mountPage("testForm", TestPageForm.class); Consequently the server cannot discover the page class an anchor tag is rendered as: <a href="wicket/page?0-1.ILinkListener-linkSwitch" This is requested requested as: /wicket/page?0-1.ILinkListener-linkSwitch This overwrites the mount path "testLink" as in mountPage("testLink", TestPageLink.class); Consequently the server cannot discover the page class diff --git a/wicket-core/src/main/java/org/apache/wicket/request/mapper/MountedMapper.java b/wicket-core/src/main/java/org/apache/wicket/request/mapper/MountedMapper.java index 1c5d039..04fe4e8 100644 --- a/wicket-core/src/main/java/org/apache/wicket/request/mapper/MountedMapper.java +++ b/wicket-core/src/main/java/org/apache/wicket/request/mapper/MountedMapper.java @@ -19,10 +19,15 @@ package org.apache.wicket.request.mapper; import java.util.ArrayList; import java.util.List; +import org.apache.wicket.RequestListenerInterface; +import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.Request; import org.apache.wicket.request.Url; import org.apache.wicket.request.component.IRequestablePage; +import org.apache.wicket.request.handler.ListenerInterfaceRequestHandler; +import org.apache.wicket.request.mapper.info.ComponentInfo; import org.apache.wicket.request.mapper.info.PageComponentInfo; +import org.apache.wicket.request.mapper.info.PageInfo; import org.apache.wicket.request.mapper.parameter.IPageParametersEncoder; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.mapper.parameter.PageParametersEncoder; @@ -354,6 +359,41 @@ public class MountedMapper extends AbstractBookmarkableMapper return new PageParameters(); } + @Override + public Url mapHandler(IRequestHandler requestHandler) + { + Url url = super.mapHandler(requestHandler); + + if (url == null && requestHandler instanceof ListenerInterfaceRequestHandler) + { + ListenerInterfaceRequestHandler handler = (ListenerInterfaceRequestHandler)requestHandler; + IRequestablePage page = handler.getPage(); + Class<? extends IRequestablePage> pageClass = page.getClass(); + if (checkPageClass(pageClass)) + { + String componentPath = handler.getComponentPath(); + RequestListenerInterface listenerInterface = handler.getListenerInterface(); + + Integer renderCount = null; + if (listenerInterface.isIncludeRenderCount()) + { + renderCount = page.getRenderCount(); + } + + PageInfo pageInfo = new PageInfo(page.getPageId()); + ComponentInfo componentInfo = new ComponentInfo(renderCount, + requestListenerInterfaceToString(listenerInterface), componentPath, + handler.getBehaviorIndex()); + PageComponentInfo pageComponentInfo = new PageComponentInfo(pageInfo, componentInfo); + UrlInfo urlInfo = new UrlInfo(pageComponentInfo, page.getClass(), + handler.getPageParameters()); + url = buildUrl(urlInfo); + } + } + + return url; + } + /** * @see org.apache.wicket.request.mapper.AbstractBookmarkableMapper#buildUrl(org.apache.wicket.request.mapper.AbstractBookmarkableMapper.UrlInfo) */
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4014_e60bac5f.diff
bugs-dot-jar_data_WICKET-5853_b80f6640
--- BugID: WICKET-5853 Summary: LongConverter converts some values greater than Long.MAX_VALUE Description: |- Currently it's possible to submit some values via Long Textfield<Long> that are greater than Long.MAX_VALUE. This will produce converted input and model update with value of Long.MAX_VALUE I'm not sure what the behavior should be - imho throwing ConversionException seems fair as the input isn't a valid Long. The reason seems to be precision loss during Double.valueOf(input) execution while converting, and then comparing to Long.MAX_VALUE using Long.doubleValue() in *AbstractNumberConverter*, which by casting leads to to the same precision loss and the numbers are seemingly equal during comparison of ranges. Maybe using BigDecimals for parsing could help here. The quickstart is available at [https://github.com/zeratul021/wicket-number-conversion]. For the fastest demonstration I extended Wicket's _longConversion()_ test-case in *ConvertersTest*: [https://github.com/zeratul021/wicket-number-conversion/blob/master/src/test/java/com/github/zeratul021/wicketnumberconversion/ConvertersTest.java#L300] diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractDecimalConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractDecimalConverter.java index 09485fa..f16ad92 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractDecimalConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractDecimalConverter.java @@ -16,14 +16,11 @@ */ package org.apache.wicket.util.convert.converter; -import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; /** - * Base class for all number converters. + * Base class for all converters of decimal numbers. * * @author Jonathan Locke * @param <N> @@ -32,25 +29,6 @@ public abstract class AbstractDecimalConverter<N extends Number> extends Abstrac { private static final long serialVersionUID = 1L; - /** The date format to use */ - private final Map<Locale, NumberFormat> numberFormats = new ConcurrentHashMap<>(); - - /** - * @param locale - * @return Returns the numberFormat. - */ - @Override - public NumberFormat getNumberFormat(final Locale locale) - { - NumberFormat numberFormat = numberFormats.get(locale); - if (numberFormat == null) - { - numberFormat = newNumberFormat(locale); - setNumberFormat(locale, numberFormat); - } - return (NumberFormat)numberFormat.clone(); - } - /** * Creates a new {@link NumberFormat} for the given locale. The instance is later cached and is * accessible through {@link #getNumberFormat(Locale)} @@ -58,24 +36,9 @@ public abstract class AbstractDecimalConverter<N extends Number> extends Abstrac * @param locale * @return number format */ + @Override protected NumberFormat newNumberFormat(final Locale locale) { return NumberFormat.getInstance(locale); } - - /** - * @param locale - * The Locale that was used for this NumberFormat - * @param numberFormat - * The numberFormat to set. - */ - public final void setNumberFormat(final Locale locale, final NumberFormat numberFormat) - { - if (numberFormat instanceof DecimalFormat) - { - ((DecimalFormat)numberFormat).setParseBigDecimal(true); - } - - numberFormats.put(locale, numberFormat); - } } diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractIntegerConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractIntegerConverter.java index 88639c0..0499814 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractIntegerConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractIntegerConverter.java @@ -18,10 +18,9 @@ package org.apache.wicket.util.convert.converter; import java.text.NumberFormat; import java.util.Locale; -import java.util.concurrent.ConcurrentHashMap; /** - * Base class for all number converters. + * Base class for all converters of integer numbers. * * @author Jonathan Locke * @param <I> @@ -30,29 +29,12 @@ public abstract class AbstractIntegerConverter<I extends Number> extends Abstrac { private static final long serialVersionUID = 1L; - /** The date format to use */ - private final ConcurrentHashMap<Locale, NumberFormat> numberFormats = new ConcurrentHashMap<>(); - - /** - * @param locale - * The locale - * @return Returns the numberFormat. - */ @Override - public NumberFormat getNumberFormat(final Locale locale) + protected NumberFormat newNumberFormat(Locale locale) { - NumberFormat numberFormat = numberFormats.get(locale); - if (numberFormat == null) - { - numberFormat = NumberFormat.getIntegerInstance(locale); - numberFormat.setParseIntegerOnly(true); - numberFormat.setGroupingUsed(false); - NumberFormat tmpNumberFormat = numberFormats.putIfAbsent(locale, numberFormat); - if (tmpNumberFormat != null) - { - numberFormat = tmpNumberFormat; - } - } - return (NumberFormat)numberFormat.clone(); + NumberFormat numberFormat = NumberFormat.getIntegerInstance(locale); + numberFormat.setParseIntegerOnly(true); + numberFormat.setGroupingUsed(false); + return numberFormat; } } diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractNumberConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractNumberConverter.java index 5c448c0..da3df42 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractNumberConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/AbstractNumberConverter.java @@ -16,8 +16,11 @@ */ package org.apache.wicket.util.convert.converter; +import java.math.BigDecimal; +import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; +import java.util.concurrent.ConcurrentHashMap; import org.apache.wicket.util.convert.ConversionException; @@ -32,11 +35,45 @@ public abstract class AbstractNumberConverter<N extends Number> extends Abstract { private static final long serialVersionUID = 1L; + /** The date format to use */ + private final ConcurrentHashMap<Locale, NumberFormat> numberFormats = new ConcurrentHashMap<>(); + /** * @param locale + * The locale * @return Returns the numberFormat. */ - public abstract NumberFormat getNumberFormat(Locale locale); + public NumberFormat getNumberFormat(final Locale locale) + { + NumberFormat numberFormat = numberFormats.get(locale); + if (numberFormat == null) + { + numberFormat = newNumberFormat(locale); + + if (numberFormat instanceof DecimalFormat) + { + // always try to parse BigDecimals + ((DecimalFormat)numberFormat).setParseBigDecimal(true); + } + + NumberFormat tmpNumberFormat = numberFormats.putIfAbsent(locale, numberFormat); + if (tmpNumberFormat != null) + { + numberFormat = tmpNumberFormat; + } + } + // return a clone because NumberFormat.get..Instance use a pool + return (NumberFormat)numberFormat.clone(); + } + + /** + * Creates a new {@link NumberFormat} for the given locale. The instance is later cached and is + * accessible through {@link #getNumberFormat(Locale)} + * + * @param locale + * @return number format + */ + protected abstract NumberFormat newNumberFormat(final Locale locale); /** * Parses a value as a String and returns a Number. @@ -44,15 +81,15 @@ public abstract class AbstractNumberConverter<N extends Number> extends Abstract * @param value * The object to parse (after converting with toString()) * @param min - * The minimum allowed value + * The minimum allowed value or {@code null} if none * @param max - * The maximum allowed value + * The maximum allowed value or {@code null} if none * @param locale * @return The number * @throws ConversionException * if value is unparsable or out of range */ - protected N parse(Object value, final double min, final double max, Locale locale) + protected BigDecimal parse(Object value, final BigDecimal min, final BigDecimal max, Locale locale) { if (locale == null) { @@ -78,19 +115,30 @@ public abstract class AbstractNumberConverter<N extends Number> extends Abstract return null; } - if (number.doubleValue() < min) + BigDecimal bigDecimal; + if (number instanceof BigDecimal) + { + bigDecimal = (BigDecimal)number; + } + else + { + // should occur rarely, see #getNumberFormat(Locale) + bigDecimal = new BigDecimal(number.toString()); + } + + if (min != null && bigDecimal.compareTo(min) < 0) { - throw newConversionException("Value cannot be less than " + min, value, locale).setFormat( - numberFormat); + throw newConversionException("Value cannot be less than " + min, value, locale) + .setFormat(numberFormat); } - if (number.doubleValue() > max) + if (max != null && bigDecimal.compareTo(max) > 0) { - throw newConversionException("Value cannot be greater than " + max, value, locale).setFormat( - numberFormat); + throw newConversionException("Value cannot be greater than " + max, value, locale) + .setFormat(numberFormat); } - return number; + return bigDecimal; } @Override diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/BigDecimalConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/BigDecimalConverter.java index dd6e0ba..162a6de 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/BigDecimalConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/BigDecimalConverter.java @@ -44,33 +44,6 @@ public class BigDecimalConverter extends AbstractDecimalConverter<BigDecimal> return null; } - final Number number = parse(value, -Double.MAX_VALUE, Double.MAX_VALUE, locale); - - if (number instanceof BigDecimal) - { - return (BigDecimal)number; - } - else if (number instanceof Double) - { - // See link why the String is preferred for doubles - // http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigDecimal.html#BigDecimal%28double%29 - return new BigDecimal(Double.toString(number.doubleValue())); - } - else if (number instanceof Long) - { - return new BigDecimal(number.longValue()); - } - else if (number instanceof Float) - { - return new BigDecimal(number.floatValue()); - } - else if (number instanceof Integer) - { - return new BigDecimal(number.intValue()); - } - else - { - return new BigDecimal(value); - } + return parse(value, null, null, locale); } } diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/BigIntegerConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/BigIntegerConverter.java index 22077be..5da0034 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/BigIntegerConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/BigIntegerConverter.java @@ -16,6 +16,7 @@ */ package org.apache.wicket.util.convert.converter; +import java.math.BigDecimal; import java.math.BigInteger; import java.util.Locale; @@ -44,23 +45,13 @@ public class BigIntegerConverter extends AbstractIntegerConverter<BigInteger> return null; } - final Number number = parse(value, -Double.MAX_VALUE, Double.MAX_VALUE, locale); + final BigDecimal number = parse(value, null, null, locale); - if (number instanceof BigInteger) + if (number == null) { - return (BigInteger)number; - } - else if (number instanceof Long) - { - return BigInteger.valueOf(number.longValue()); - } - else if (number instanceof Integer) - { - return BigInteger.valueOf(number.intValue()); - } - else - { - return new BigInteger(value); + return null; } + + return new BigInteger(number.toString()); } } diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ByteConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ByteConverter.java index 8c351e4..8850165 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ByteConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ByteConverter.java @@ -16,6 +16,7 @@ */ package org.apache.wicket.util.convert.converter; +import java.math.BigDecimal; import java.util.Locale; import org.apache.wicket.util.convert.IConverter; @@ -31,6 +32,9 @@ public class ByteConverter extends AbstractIntegerConverter<Byte> { private static final long serialVersionUID = 1L; + private static final BigDecimal MIN_VALUE = new BigDecimal(Byte.MIN_VALUE); + private static final BigDecimal MAX_VALUE = new BigDecimal(Byte.MAX_VALUE); + /** * The singleton instance for a byte converter */ @@ -42,7 +46,7 @@ public class ByteConverter extends AbstractIntegerConverter<Byte> @Override public Byte convertToObject(final String value, final Locale locale) { - final Number number = parse(value, Byte.MIN_VALUE, Byte.MAX_VALUE, locale); + final BigDecimal number = parse(value, MIN_VALUE, MAX_VALUE, locale); if (number == null) { diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/DoubleConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/DoubleConverter.java index fbf5862..ce2ca99 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/DoubleConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/DoubleConverter.java @@ -16,6 +16,7 @@ */ package org.apache.wicket.util.convert.converter; +import java.math.BigDecimal; import java.util.Locale; import org.apache.wicket.util.convert.IConverter; @@ -31,6 +32,11 @@ public class DoubleConverter extends AbstractDecimalConverter<Double> { private static final long serialVersionUID = 1L; + // Double.MIN is the smallest nonzero positive number, not the largest + // negative number + private static final BigDecimal MIN_VALUE = new BigDecimal(-Double.MAX_VALUE); + private static final BigDecimal MAX_VALUE = new BigDecimal(Double.MAX_VALUE); + /** * The singleton instance for a double converter */ @@ -42,9 +48,7 @@ public class DoubleConverter extends AbstractDecimalConverter<Double> @Override public Double convertToObject(final String value, final Locale locale) { - final Number number = parse(value, -Double.MAX_VALUE, Double.MAX_VALUE, locale); - // Double.MIN is the smallest nonzero positive number, not the largest - // negative number + final BigDecimal number = parse(value, MIN_VALUE, MAX_VALUE, locale); if (number == null) { diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/FloatConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/FloatConverter.java index bc1562a..c4b2b79 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/FloatConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/FloatConverter.java @@ -16,6 +16,7 @@ */ package org.apache.wicket.util.convert.converter; +import java.math.BigDecimal; import java.util.Locale; import org.apache.wicket.util.convert.IConverter; @@ -31,6 +32,11 @@ public class FloatConverter extends AbstractDecimalConverter<Float> { private static final long serialVersionUID = 1L; + // Float.MIN is the smallest nonzero positive number, not the largest + // negative number + private static final BigDecimal MIN_VALUE = new BigDecimal(-Float.MAX_VALUE); + private static final BigDecimal MAX_VALUE = new BigDecimal(Float.MAX_VALUE); + /** * The singleton instance for a float converter */ @@ -42,7 +48,7 @@ public class FloatConverter extends AbstractDecimalConverter<Float> @Override public Float convertToObject(final String value, final Locale locale) { - final Number number = parse(value, -Float.MAX_VALUE, Float.MAX_VALUE, locale); + final BigDecimal number = parse(value, MIN_VALUE, MAX_VALUE, locale); if (number == null) { diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/IntegerConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/IntegerConverter.java index 8fd1edf..5055d4a 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/IntegerConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/IntegerConverter.java @@ -16,6 +16,7 @@ */ package org.apache.wicket.util.convert.converter; +import java.math.BigDecimal; import java.util.Locale; import org.apache.wicket.util.convert.IConverter; @@ -31,6 +32,9 @@ public class IntegerConverter extends AbstractIntegerConverter<Integer> { private static final long serialVersionUID = 1L; + private static final BigDecimal MIN_VALUE = new BigDecimal(Integer.MIN_VALUE); + private static final BigDecimal MAX_VALUE = new BigDecimal(Integer.MAX_VALUE); + /** * The singleton instance for a integer converter */ @@ -42,7 +46,7 @@ public class IntegerConverter extends AbstractIntegerConverter<Integer> @Override public Integer convertToObject(final String value, final Locale locale) { - final Number number = parse(value, Integer.MIN_VALUE, Integer.MAX_VALUE, locale); + final BigDecimal number = parse(value, MIN_VALUE, MAX_VALUE, locale); if (number == null) { diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/LongConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/LongConverter.java index 67401b2..0cf8db6 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/LongConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/LongConverter.java @@ -16,6 +16,7 @@ */ package org.apache.wicket.util.convert.converter; +import java.math.BigDecimal; import java.util.Locale; import org.apache.wicket.util.convert.IConverter; @@ -31,6 +32,9 @@ public class LongConverter extends AbstractIntegerConverter<Long> { private static final long serialVersionUID = 1L; + private static final BigDecimal MIN_VALUE = new BigDecimal(Long.MIN_VALUE); + private static final BigDecimal MAX_VALUE = new BigDecimal(Long.MAX_VALUE); + /** * The singleton instance for a long converter */ @@ -42,7 +46,7 @@ public class LongConverter extends AbstractIntegerConverter<Long> @Override public Long convertToObject(final String value, final Locale locale) { - final Number number = parse(value, Long.MIN_VALUE, Long.MAX_VALUE, locale); + final BigDecimal number = parse(value, MIN_VALUE, MAX_VALUE, locale); if (number == null) { diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ShortConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ShortConverter.java index 4d2a2fa..30aa1b7 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ShortConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ShortConverter.java @@ -16,6 +16,7 @@ */ package org.apache.wicket.util.convert.converter; +import java.math.BigDecimal; import java.util.Locale; import org.apache.wicket.util.convert.IConverter; @@ -31,6 +32,9 @@ public class ShortConverter extends AbstractIntegerConverter<Short> { private static final long serialVersionUID = 1L; + private static final BigDecimal MIN_VALUE = new BigDecimal(Short.MIN_VALUE); + private static final BigDecimal MAX_VALUE = new BigDecimal(Short.MAX_VALUE); + /** * The singleton instance for a short converter */ @@ -42,7 +46,7 @@ public class ShortConverter extends AbstractIntegerConverter<Short> @Override public Short convertToObject(final String value, final Locale locale) { - final Number number = parse(value, Short.MIN_VALUE, Short.MAX_VALUE, locale); + final BigDecimal number = parse(value, MIN_VALUE, MAX_VALUE, locale); if (number == null) { diff --git a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ZeroPaddingIntegerConverter.java b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ZeroPaddingIntegerConverter.java index 84c4f62..181be0b 100644 --- a/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ZeroPaddingIntegerConverter.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/convert/converter/ZeroPaddingIntegerConverter.java @@ -24,8 +24,10 @@ import java.util.Locale; * @author Eelco Hillenius * @author Jonathan Locke * @author Al Maw + * + * @deprecated use an {@link IntegerConverter} with suitable format string instead */ -public class ZeroPaddingIntegerConverter extends AbstractIntegerConverter<Integer> +public class ZeroPaddingIntegerConverter extends IntegerConverter { private static final long serialVersionUID = 1L; @@ -58,29 +60,4 @@ public class ZeroPaddingIntegerConverter extends AbstractIntegerConverter<Intege return result; } - - /** - * @see org.apache.wicket.util.convert.IConverter#convertToObject(java.lang.String,Locale) - */ - @Override - public Integer convertToObject(final String value, final Locale locale) - { - final Number number = parse(value, Integer.MIN_VALUE, Integer.MAX_VALUE, locale); - - if (number == null) - { - return null; - } - - return number.intValue(); - } - - /** - * @see org.apache.wicket.util.convert.converter.AbstractConverter#getTargetType() - */ - @Override - protected Class<Integer> getTargetType() - { - return Integer.class; - } } \ No newline at end of file
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5853_b80f6640.diff
bugs-dot-jar_data_WICKET-5572_cd414fa5
--- BugID: WICKET-5572 Summary: Dequeueing problem when there is TransparentWebMarkupContainer around <wicket:child/> Description: |- While testing 7.0.0-M1 release I've found an issue with wicket-bootstrap's sample application. Here is a minified version of it that reproduces the problem. The two important things are: - a TransparentWebMarkupContainer (TWMC) is attached to <html> tag in the base page - the sub page is requested It appears that dequeueing logic cannot find the closing tag of the TWMC and thinks that </wicket:child> is the closing tag. diff --git a/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java b/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java index 30293fb..55e3184 100644 --- a/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java +++ b/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java @@ -2178,9 +2178,13 @@ public abstract class MarkupContainer extends Component implements Iterable<Comp { return DequeueTagAction.SKIP; } + else if (wicketTag.isChildTag()) + { + return DequeueTagAction.DEQUEUE; + } else { - return null; // dont know + return null; // don't know } } return DequeueTagAction.DEQUEUE;
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5572_cd414fa5.diff
bugs-dot-jar_data_WICKET-5251_3d2393c7
--- BugID: WICKET-5251 Summary: Minified name resolves incorrectly if default resource reference is used Description: "In PackageResourceReference.\n\nWhen a default reference to a minified resource is used (i.e. the resource wasn't mounted) the resource reference name includes '.min'. \n\nWhen trying to resolve the minified name, another '.min' is appended, resulting in the minified name resolving to 'html5.min.min.js'. \n\nAs a result, the PackageResourceReference concludes that the resource was not minified, and adds compression." diff --git a/wicket-core/src/main/java/org/apache/wicket/request/resource/PackageResourceReference.java b/wicket-core/src/main/java/org/apache/wicket/request/resource/PackageResourceReference.java index cc72731..710eef2 100644 --- a/wicket-core/src/main/java/org/apache/wicket/request/resource/PackageResourceReference.java +++ b/wicket-core/src/main/java/org/apache/wicket/request/resource/PackageResourceReference.java @@ -207,7 +207,14 @@ public class PackageResourceReference extends ResourceReference if (idxOfExtension > -1) { String extension = name.substring(idxOfExtension); - minifiedName = name.substring(0, name.length() - extension.length() + 1) + "min" + extension; + final String baseName = name.substring(0, name.length() - extension.length() + 1); + if (!".min".equals(extension) && !baseName.endsWith(".min.")) + { + minifiedName = baseName + "min" + extension; + } else + { + minifiedName = name; + } } else { minifiedName = name + ".min";
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5251_3d2393c7.diff
bugs-dot-jar_data_WICKET-5060_8e6a6ec5
--- BugID: WICKET-5060 Summary: Fragment and Component with same id fail with misleading exception Description: |- A page having a component from inherited markup *and* fragment with the *same* id fails with misleading exception message. Exception message: The component(s) below failed to render. Possible reasons could be that: 1) you have added a component in code but forgot to reference it in the markup (thus the component will never be rendered), 2) if your components were added in a parent container then make sure the markup for the child container includes them in <wicket:extend> ... and list of component id's from fragment multiplied by amount of rows in DataTable Cause: The markup of the component is used by the fragment. diff --git a/wicket-core/src/main/java/org/apache/wicket/markup/html/panel/FragmentMarkupSourcingStrategy.java b/wicket-core/src/main/java/org/apache/wicket/markup/html/panel/FragmentMarkupSourcingStrategy.java index ac47e37..400ea8d 100644 --- a/wicket-core/src/main/java/org/apache/wicket/markup/html/panel/FragmentMarkupSourcingStrategy.java +++ b/wicket-core/src/main/java/org/apache/wicket/markup/html/panel/FragmentMarkupSourcingStrategy.java @@ -152,7 +152,7 @@ public class FragmentMarkupSourcingStrategy extends AbstractMarkupSourcingStrate { throw new MarkupNotFoundException("Markup found for Fragment '" + markupId + "' in providing markup container " + getMarkupProvider(container) - + " is not a fragment tag"); + + " is not a <wicket:fragment> tag"); } }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5060_8e6a6ec5.diff
bugs-dot-jar_data_WICKET-4121_8967eb2b
--- BugID: WICKET-4121 Summary: WizardStep$FormValidatorWrapper.isActiveStep(WizardStep.java) causes NullPointerException Description: |- Using the Wizard with a nested WizardModel (see RecursiveWizardModel implementation at the attached quickstart application) causes a NullPointerException. I was able to run the same test application with wicket 1.4.18 without any problems. Caused by: java.lang.NullPointerException at org.apache.wicket.extensions.wizard.WizardStep$FormValidatorWrapper.isActiveStep(WizardStep.java:145) at org.apache.wicket.extensions.wizard.WizardStep$FormValidatorWrapper.getDependentFormComponents(WizardStep.java:109) at org.apache.wicket.markup.html.form.validation.FormValidatorAdapter.getDependentFormComponents(FormValidatorAdapter.java:47) at org.apache.wicket.markup.html.form.Form.validateFormValidator(Form.java:1782) at org.apache.wicket.markup.html.form.Form.validateFormValidators(Form.java:1828) at org.apache.wicket.markup.html.form.Form.validate(Form.java:1706) at org.apache.wicket.markup.html.form.Form.process(Form.java:773) at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:728) at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:670) diff --git a/wicket-extensions/src/main/java/org/apache/wicket/extensions/wizard/Wizard.java b/wicket-extensions/src/main/java/org/apache/wicket/extensions/wizard/Wizard.java index b6ebad4..3bad8db 100644 --- a/wicket-extensions/src/main/java/org/apache/wicket/extensions/wizard/Wizard.java +++ b/wicket-extensions/src/main/java/org/apache/wicket/extensions/wizard/Wizard.java @@ -16,8 +16,6 @@ */ package org.apache.wicket.extensions.wizard; -import java.util.Iterator; - import org.apache.wicket.Component; import org.apache.wicket.feedback.ContainerFeedbackMessageFilter; import org.apache.wicket.markup.html.IHeaderResponse; @@ -276,15 +274,6 @@ public class Wizard extends Panel implements IWizardModelListener, IWizard wizardModel.addListener(this); - Iterator<IWizardStep> stepsIterator = wizardModel.stepIterator(); - if (stepsIterator != null) - { - while (stepsIterator.hasNext()) - { - (stepsIterator.next()).init(wizardModel); - } - } - // reset model to prepare for action wizardModel.reset(); } diff --git a/wicket-extensions/src/main/java/org/apache/wicket/extensions/wizard/WizardModel.java b/wicket-extensions/src/main/java/org/apache/wicket/extensions/wizard/WizardModel.java index c66d352..69c973f 100644 --- a/wicket-extensions/src/main/java/org/apache/wicket/extensions/wizard/WizardModel.java +++ b/wicket-extensions/src/main/java/org/apache/wicket/extensions/wizard/WizardModel.java @@ -217,6 +217,12 @@ public class WizardModel extends AbstractWizardModel { history.clear(); activeStep = null; + + for (IWizardStep step : steps) + { + step.init(this); + } + setActiveStep(findNextVisibleStep()); }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4121_8967eb2b.diff
bugs-dot-jar_data_WICKET-3644_ab1856db
--- BugID: WICKET-3644 Summary: RequestCycleListenerCollection.onException should not throw an exception when multiple listeners handle the exception Description: When multiple listeners handle the exception, RequestCycleListenerCollection should simple take the first handler. The current approach makes it impossible to add a listener that handles all exceptions and later add listeners for specific exceptions. Simply removing the 'if (handlers.size() > 1)' should suffice. diff --git a/wicket-core/src/main/java/org/apache/wicket/request/cycle/RequestCycleListenerCollection.java b/wicket-core/src/main/java/org/apache/wicket/request/cycle/RequestCycleListenerCollection.java index 7422820..821b883 100644 --- a/wicket-core/src/main/java/org/apache/wicket/request/cycle/RequestCycleListenerCollection.java +++ b/wicket-core/src/main/java/org/apache/wicket/request/cycle/RequestCycleListenerCollection.java @@ -19,14 +19,13 @@ package org.apache.wicket.request.cycle; import java.util.ArrayList; import java.util.List; -import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.util.listener.ListenerCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * Special, Wicket internal composite {@link IRequestCycleListener} that */ public class RequestCycleListenerCollection extends ListenerCollection<IRequestCycleListener> implements @@ -57,6 +56,13 @@ public class RequestCycleListenerCollection extends ListenerCollection<IRequestC }); } + /** + * Notifies all registered listeners of the exception and calls the first handler that was + * returned by the listeners. + * + * @see org.apache.wicket.request.cycle.IRequestCycleListener#onException(org.apache.wicket.request.cycle.RequestCycle, + * java.lang.Exception) + */ public IRequestHandler onException(final RequestCycle cycle, final Exception ex) { final List<IRequestHandler> handlers = new ArrayList<IRequestHandler>(); @@ -77,14 +83,12 @@ public class RequestCycleListenerCollection extends ListenerCollection<IRequestC { return null; } - if (handlers.size() > 1) { - throw new WicketRuntimeException( - "More than one request cycle listener returned a request handler while handling the exception.", - ex); + logger.debug( + "{} exception handlers available for exception {}, using the first handler", + handlers.size(), ex); } - return handlers.get(0); }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-3644_ab1856db.diff
bugs-dot-jar_data_WICKET-5147_184e51e9
--- BugID: WICKET-5147 Summary: WicketTester MockHttpRequest.getCookies very slow / OutOfMemory Description: "\nWe have an extensive set of WicketTester tests. Recently, the wicket RELEASE in the maven repository changed to 6.7.0. After the new version, our tests got very slow.\n\nWhen profiling, I discovered that the MockHttpRequest.getCookies() was taking up a lot of time. Also, tests failed because of OutOfMemory exceptions. My guess is that somehow a lot of objects are created at such speeds that the GC cannot clean them\n\nI will investigate further, but switching back to 6.6.0 solved the issue. \n\n[Edit]\nThe tests are run with TestNG and using 'mvn test'" diff --git a/wicket-core/src/main/java/org/apache/wicket/DefaultExceptionMapper.java b/wicket-core/src/main/java/org/apache/wicket/DefaultExceptionMapper.java index eea361d..81829d0 100644 --- a/wicket-core/src/main/java/org/apache/wicket/DefaultExceptionMapper.java +++ b/wicket-core/src/main/java/org/apache/wicket/DefaultExceptionMapper.java @@ -56,7 +56,7 @@ public class DefaultExceptionMapper implements IExceptionMapper Response response = RequestCycle.get().getResponse(); if (response instanceof WebResponse) { - // we don't wan't to cache an exceptional reply in the browser + // we don't want to cache an exceptional reply in the browser ((WebResponse)response).disableCaching(); } return internalMap(e); @@ -92,7 +92,7 @@ public class DefaultExceptionMapper implements IExceptionMapper if (e instanceof StalePageException) { - // If the page was stale, just rerender it + // If the page was stale, just re-render it // (the url should always be updated by an redirect in that case) return new RenderPageRequestHandler(new PageProvider(((StalePageException)e).getPage())); } @@ -167,7 +167,6 @@ public class DefaultExceptionMapper implements IExceptionMapper private boolean isProcessingAjaxRequest() { - RequestCycle rc = RequestCycle.get(); Request request = rc.getRequest(); if (request instanceof WebRequest) diff --git a/wicket-core/src/main/java/org/apache/wicket/Page.java b/wicket-core/src/main/java/org/apache/wicket/Page.java index 1467798..86c0472 100644 --- a/wicket-core/src/main/java/org/apache/wicket/Page.java +++ b/wicket-core/src/main/java/org/apache/wicket/Page.java @@ -450,6 +450,8 @@ public abstract class Page extends MarkupContainer implements IRedirectListener, if (stateless == null) { + internalInitialize(); + if (isStateless() == false) { stateless = Boolean.FALSE; diff --git a/wicket-core/src/main/java/org/apache/wicket/page/AbstractPageManager.java b/wicket-core/src/main/java/org/apache/wicket/page/AbstractPageManager.java index 263bb62..da259e4 100644 --- a/wicket-core/src/main/java/org/apache/wicket/page/AbstractPageManager.java +++ b/wicket-core/src/main/java/org/apache/wicket/page/AbstractPageManager.java @@ -127,10 +127,6 @@ public abstract class AbstractPageManager implements IPageManager @Override public void touchPage(IManageablePage page) { - if (!page.isPageStateless()) - { - getContext().bind(); - } getRequestAdapter().touch(page); } } diff --git a/wicket-core/src/main/java/org/apache/wicket/protocol/http/WicketFilter.java b/wicket-core/src/main/java/org/apache/wicket/protocol/http/WicketFilter.java index be577f3..f40a0c9 100644 --- a/wicket-core/src/main/java/org/apache/wicket/protocol/http/WicketFilter.java +++ b/wicket-core/src/main/java/org/apache/wicket/protocol/http/WicketFilter.java @@ -431,6 +431,23 @@ public class WicketFilter implements Filter ThreadContext.detach(); } } + catch (Exception e) + { + // #destroy() might not be called by the web container when #init() fails, + // so destroy now + log.warn("initialization failed, destroying now"); + + try + { + destroy(); + } + catch (Exception destroyException) + { + log.warn("Unable to destroy after initialization failure", destroyException); + } + + throw new ServletException(e); + } finally { if (newClassLoader != previousClassLoader) @@ -578,7 +595,14 @@ public class WicketFilter implements Filter if (applicationFactory != null) { - applicationFactory.destroy(this); + try + { + applicationFactory.destroy(this); + } + finally + { + applicationFactory = null; + } } } @@ -781,7 +805,7 @@ public class WicketFilter implements Filter * level "/" then an empty string should be used instead. * * @param filterPath - * @return + * @return canonic filter path */ static String canonicaliseFilterPath(String filterPath) { diff --git a/wicket-core/src/main/java/org/apache/wicket/request/cycle/PageRequestHandlerTracker.java b/wicket-core/src/main/java/org/apache/wicket/request/cycle/PageRequestHandlerTracker.java index caa5a6d..b2390a6 100644 --- a/wicket-core/src/main/java/org/apache/wicket/request/cycle/PageRequestHandlerTracker.java +++ b/wicket-core/src/main/java/org/apache/wicket/request/cycle/PageRequestHandlerTracker.java @@ -59,6 +59,13 @@ public class PageRequestHandlerTracker extends AbstractRequestCycleListener registerLastHandler(cycle,handler); } + @Override + public void onExceptionRequestHandlerResolved(RequestCycle cycle, IRequestHandler handler, Exception exception) + { + super.onExceptionRequestHandlerResolved(cycle, handler, exception); + registerLastHandler(cycle,handler); + } + /** * Registers pagerequesthandler when it's resolved ,keeps up with the most recent handler resolved *
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5147_184e51e9.diff
bugs-dot-jar_data_WICKET-3253_71b6e905
--- BugID: WICKET-3253 Summary: NPE with nested property models Description: |- After updated from 1.4.8 to 1.4.14 I got this bug. The problem is with nested property models where the "top" model has a null model object that is bound to a TextField. You get a NPE when the page is rendered. There is a quick workaround by overriding getOjbectClass() on the property model. I provide a running example of the problem. diff --git a/wicket/src/main/java/org/apache/wicket/model/AbstractPropertyModel.java b/wicket/src/main/java/org/apache/wicket/model/AbstractPropertyModel.java index b95679c..6df54fa 100644 --- a/wicket/src/main/java/org/apache/wicket/model/AbstractPropertyModel.java +++ b/wicket/src/main/java/org/apache/wicket/model/AbstractPropertyModel.java @@ -247,8 +247,11 @@ public abstract class AbstractPropertyModel<T> { try { - return PropertyResolver.getPropertyClass(expression, - ((IObjectClassAwareModel<?>)this.target).getObjectClass()); + Class<?> targetClass = ((IObjectClassAwareModel<?>)this.target).getObjectClass(); + if (targetClass != null) + { + return PropertyResolver.getPropertyClass(expression, targetClass); + } } catch (WicketRuntimeException e) {
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-3253_71b6e905.diff
bugs-dot-jar_data_WICKET-5484_ecdfc124
--- BugID: WICKET-5484 Summary: WebPageRenderer must not render full page in Ajax requests Description: |- WebPageRenderer renders the full page when WebRequest#shouldPreserveClientUrl() is true or RedirectStrategy.NEVER_REDIRECT is configured. For Ajax request this means that wicket-ajax-js will not be able to parse the HTML response. diff --git a/wicket-core/src/main/java/org/apache/wicket/request/handler/render/WebPageRenderer.java b/wicket-core/src/main/java/org/apache/wicket/request/handler/render/WebPageRenderer.java index 4b95e32..8c99c13 100644 --- a/wicket-core/src/main/java/org/apache/wicket/request/handler/render/WebPageRenderer.java +++ b/wicket-core/src/main/java/org/apache/wicket/request/handler/render/WebPageRenderer.java @@ -332,10 +332,16 @@ public class WebPageRenderer extends PageRenderer protected boolean shouldRenderPageAndWriteResponse(RequestCycle cycle, Url currentUrl, Url targetUrl) { + // WICKET-5484 never render and write for Ajax requests + if (isAjax(cycle)) + { + return false; + } + return neverRedirect(getRedirectPolicy()) - || (!isAjax(cycle) && ((isOnePassRender() && notForcedRedirect(getRedirectPolicy())) || (targetUrl + || ((isOnePassRender() && notForcedRedirect(getRedirectPolicy())) || (targetUrl .equals(currentUrl) && notNewAndNotStatelessPage(isNewPageInstance(), - isPageStateless())))) || (targetUrl.equals(currentUrl) && isRedirectToRender()) + isPageStateless()))) || (targetUrl.equals(currentUrl) && isRedirectToRender()) || shouldPreserveClientUrl(cycle); }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5484_ecdfc124.diff
bugs-dot-jar_data_WICKET-2368_fae1601b
--- BugID: WICKET-2368 Summary: Page.checkRendering fails after setting BorderBodyContainer visiblity to false Description: "After toggling visibility of the BorderBodyContainer to false the Page.checkRendering method fails in line 1157, claiming an iterator IllegalStateException. This happens because iterator.remove() is called twice for a child component in the border component, if the body is not visible.\n\nMy Code:\n\npublic class TogglePanel extends Border {\n\tprivate boolean expanded = true;\n\n\tpublic TogglePanel(String id, IModel<String> titleModel) {\n\t\tsuper(id, titleModel);\n\n\t\tLink link = new Link(\"title\") {\n\n\t\t\t@Override\n\t\t\tpublic void onClick() {\n\t\t\t\texpanded = !expanded;\n\t\t\t\tgetBodyContainer().setVisible(expanded);\n\t\t\t}\n\t\t};\n\t\tlink.add(new Label(\"titleLabel\", titleModel));\n\n\t\tadd(link);\n\t}\n\n}\n\nMarkup:\n\n<wicket:border>\n\t<h3 class=\"collapse\" wicket:id=\"title\">\n\t\t<span class=\"label\" wicket:id=\"titleLabel\">Panel Title</span>\n\t\t<a class=\"foldicon\">&nbsp;</a>\n\t</h3>\n\t<wicket:body />\n</wicket:border>\n\n" diff --git a/wicket/src/main/java/org/apache/wicket/Page.java b/wicket/src/main/java/org/apache/wicket/Page.java index 756036f..7ec9bc2 100644 --- a/wicket/src/main/java/org/apache/wicket/Page.java +++ b/wicket/src/main/java/org/apache/wicket/Page.java @@ -688,7 +688,7 @@ public abstract class Page extends MarkupContainer implements IRedirectListener, try { - if (getClass().getConstructor(new Class[] {}) != null) + if (getClass().getConstructor(new Class[] { }) != null) { bookmarkable = Boolean.TRUE; } @@ -1067,7 +1067,7 @@ public abstract class Page extends MarkupContainer implements IRedirectListener, // If component never rendered if (renderedComponents == null || !renderedComponents.contains(component)) { - // If auto component ... + // If not an auto component ... if (!component.isAuto() && component.isVisibleInHierarchy()) { // Increase number of unrendered components @@ -1106,8 +1106,7 @@ public abstract class Page extends MarkupContainer implements IRedirectListener, renderedComponents = null; Iterator<Component> iterator = unrenderedComponents.iterator(); - - while (iterator.hasNext()) + outerWhile : while (iterator.hasNext()) { Component component = iterator.next(); // Now first test if the component has a sibling that is a transparent resolver. @@ -1129,7 +1128,7 @@ public abstract class Page extends MarkupContainer implements IRedirectListener, "Component {} wasn't rendered but most likely it has a transparent parent: {}", component, sibling); iterator.remove(); - break; + continue outerWhile; } } } @@ -1139,7 +1138,6 @@ public abstract class Page extends MarkupContainer implements IRedirectListener, Border border = component.findParent(Border.class); if (border != null && !border.getBodyContainer().isVisibleInHierarchy()) { - // Suppose: // // <div wicket:id="border"><div wicket:id="label"></div> suppose
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-2368_fae1601b.diff
bugs-dot-jar_data_WICKET-4184_a0150366
--- BugID: WICKET-4184 Summary: AppendingStringBuffer.insert infinite loop Description: "When trying to insert a StringBuffer into an AppendingStringBuffer, the method \n\npublic AppendingStringBuffer insert(final int offset, final Object obj)\n\nwill call itself repeatedly generating an infinite loop.\n\nThe fix would be to call toString() method if the object is a StringBuffer\n\n\npublic AppendingStringBuffer insert(final int offset, final Object obj)\n\t{\n\t\tif (obj instanceof AppendingStringBuffer)\n\t\t{\n\t\t\tAppendingStringBuffer asb = (AppendingStringBuffer)obj;\n\t\t\treturn insert(offset, asb.value, 0, asb.count);\n\t\t}\n\t\telse if (obj instanceof StringBuffer)\n\t\t{\n\t\t\t//return insert(offset, obj);\n return insert(offset, obj.toString());\n\n\t\t}\n\t\treturn insert(offset, String.valueOf(obj));\n\t}\n" diff --git a/wicket-util/src/main/java/org/apache/wicket/util/string/AppendingStringBuffer.java b/wicket-util/src/main/java/org/apache/wicket/util/string/AppendingStringBuffer.java index a8abb5f..19e69a6 100755 --- a/wicket-util/src/main/java/org/apache/wicket/util/string/AppendingStringBuffer.java +++ b/wicket-util/src/main/java/org/apache/wicket/util/string/AppendingStringBuffer.java @@ -37,6 +37,7 @@ public final class AppendingStringBuffer implements java.io.Serializable, CharSe private static final AppendingStringBuffer NULL = new AppendingStringBuffer("null"); private static final StringBuilder SB_NULL = new StringBuilder("null"); + private static final StringBuffer SBF_NULL = new StringBuffer("null"); /** * The value is used for character storage. @@ -947,7 +948,11 @@ public final class AppendingStringBuffer implements java.io.Serializable, CharSe } else if (obj instanceof StringBuffer) { - return insert(offset, obj); + return insert(offset, (StringBuffer)obj); + } + else if (obj instanceof StringBuilder) + { + return insert(offset, (StringBuilder)obj); } return insert(offset, String.valueOf(obj)); } @@ -1010,9 +1015,9 @@ public final class AppendingStringBuffer implements java.io.Serializable, CharSe /** * Inserts the string into this string buffer. * <p> - * The characters of the <code>String</code> argument are inserted, in order, into this string - * buffer at the indicated offset, moving up any characters originally above that position and - * increasing the length of this string buffer by the length of the argument. If + * The characters of the <code>StringBuilder</code> argument are inserted, in order, into this + * string buffer at the indicated offset, moving up any characters originally above that + * position and increasing the length of this string buffer by the length of the argument. If * <code>str</code> is <code>null</code>, then the four characters <code>"null"</code> are * inserted into this string buffer. * <p> @@ -1063,6 +1068,61 @@ public final class AppendingStringBuffer implements java.io.Serializable, CharSe } /** + * Inserts the string into this string buffer. + * <p> + * The characters of the <code>StringBuffer</code> argument are inserted, in order, into this + * string buffer at the indicated offset, moving up any characters originally above that + * position and increasing the length of this string buffer by the length of the argument. If + * <code>str</code> is <code>null</code>, then the four characters <code>"null"</code> are + * inserted into this string buffer. + * <p> + * The character at index <i>k</i> in the new character sequence is equal to: + * <ul> + * <li>the character at index <i>k</i> in the old character sequence, if <i>k</i> is less than + * <code>offset</code> + * <li>the character at index <i>k</i><code>-offset</code> in the argument <code>str</code>, if + * <i>k</i> is not less than <code>offset</code> but is less than + * <code>offset+str.length()</code> + * <li>the character at index <i>k</i><code>-str.length()</code> in the old character sequence, + * if <i>k</i> is not less than <code>offset+str.length()</code> + * </ul> + * <p> + * The offset argument must be greater than or equal to <code>0</code>, and less than or equal + * to the length of this string buffer. + * + * @param offset + * the offset. + * @param str + * a string. + * @return a reference to this <code>AppendingStringBuffer</code> object. + * @exception StringIndexOutOfBoundsException + * if the offset is invalid. + * @see java.lang.StringBuffer#length() + */ + public AppendingStringBuffer insert(final int offset, StringBuffer str) + { + if ((offset < 0) || (offset > count)) + { + throw new StringIndexOutOfBoundsException(); + } + + if (str == null) + { + str = SBF_NULL; + } + int len = str.length(); + int newcount = count + len; + if (newcount > value.length) + { + expandCapacity(newcount); + } + System.arraycopy(value, offset, value, offset + len, count - offset); + str.getChars(0, len, value, offset); + count = newcount; + return this; + } + + /** * Inserts the string representation of the <code>char</code> array argument into this string * buffer. * <p>
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4184_a0150366.diff
bugs-dot-jar_data_WICKET-16_6c5083b4
--- BugID: WICKET-16 Summary: missing base64/ URL encoding Description: "yesterday i showed the concept of omponents to a friend and stumled into something i dont understand and think it might be a bug. \n \nI have a small panelcompoment that holds a searchform (textfield + submit) nothing special here, the code behind looks like: \n \n @Override\n public void onSubmit() \n {\n \ String suchFeld = getSuchfeld();\n if(suchFeld.length()>0)\n \ {\n PageParameters params = new PageParameters();\n params.add(\"finde\",suchFeld);\n \ setResponsePage(Suche.class,params);\n }\n else\n \ {\n setResponsePage(getPage().getClass());\n } \ \n }\n \nthe component is put into a \"BasePage\":\n \n public BasePage() {\n .... \n add(bar);\n add(new SuchPanel(\"SuchPanel\"));\n \ .....\n}\n \nwich is then extended by the real page:\n \npublic class Foo extends BasePage{\n \n /** Creates a new instance of Zigarren */\n public Foo() {\n }\n \nwich works all fine, however if the class name contains non ascii letters\n(e.g: ö ä ü etc.) it gives me a bug if nothing is entered into the search and the part\n \npublic class Zubehör extends BasePage{\n \n /** Creates a new instance of Zubehör */\n public Zubehör() {\n }\n \n\"setResponsePage(getPage().getClass());\" comes to action, the trouble is that the page might have the URL:\n?wicket:bookmarkablePage=:de.pages.Zubeh%C3%B6r\nbut the form tries to go to : \nwicket:bookmarkablePage=:de.pages.Zubeh%F6r\n \nwich results in a CODE 404 in the App Server \n" diff --git a/wicket/src/main/java/wicket/protocol/http/request/WebRequestCodingStrategy.java b/wicket/src/main/java/wicket/protocol/http/request/WebRequestCodingStrategy.java index 7d45266..93d5d96 100644 --- a/wicket/src/main/java/wicket/protocol/http/request/WebRequestCodingStrategy.java +++ b/wicket/src/main/java/wicket/protocol/http/request/WebRequestCodingStrategy.java @@ -563,7 +563,25 @@ public class WebRequestCodingStrategy implements IRequestCodingStrategy, IReques // Add <page-map-name>:<bookmarkable-page-class> - url.append(pageMapName + Component.PATH_SEPARATOR + pageClass.getName()); + String pageClassName = pageClass.getName(); + /* + * Encode the url so it is correct even for class names containing + * non ASCII characters, like ä, æ, ø, å etc. + * + * The reason for this is that when redirecting to these + * bookmarkable pages, we need to have the url encoded correctly + * because we can't rely on the browser to interpret the unencoded + * url correctly. + */ + try + { + pageClassName = URLEncoder.encode(pageClassName, "UTF-8"); + } + catch (UnsupportedEncodingException e) + { + throw new RuntimeException(e); + } + url.append(pageMapName + Component.PATH_SEPARATOR + pageClassName); } // Get page parameters
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-16_6c5083b4.diff
bugs-dot-jar_data_WICKET-4520_b91154ea
--- BugID: WICKET-4520 Summary: Inline enclosure doesn't work if wicket:message attribute is used on the same tag Description: "Markup like:\n\n <div wicket:enclosure=\"child\" wicket:message=\"title:something\">\n\t \ <div>Inner div\n\t\t <span wicket:id=\"child\">Blah</span>\n\t </div>\n \ </div>\n\ndoesn't work (Inner div is visible, no matter whether 'child' is visible or not) because the auto component created for wicket:message breaks somehow wicket:enclosure.\n" diff --git a/wicket-core/src/main/java/org/apache/wicket/Application.java b/wicket-core/src/main/java/org/apache/wicket/Application.java index 6cd4445..98078ea 100644 --- a/wicket-core/src/main/java/org/apache/wicket/Application.java +++ b/wicket-core/src/main/java/org/apache/wicket/Application.java @@ -685,11 +685,11 @@ public abstract class Application implements UnboundListener, IEventSink pageSettings.addComponentResolver(new HtmlHeaderResolver()); pageSettings.addComponentResolver(new WicketLinkTagHandler()); pageSettings.addComponentResolver(new WicketMessageResolver()); - pageSettings.addComponentResolver(new WicketMessageTagHandler()); pageSettings.addComponentResolver(new FragmentResolver()); pageSettings.addComponentResolver(new RelativePathPrefixHandler()); pageSettings.addComponentResolver(new EnclosureHandler()); pageSettings.addComponentResolver(new InlineEnclosureHandler()); + pageSettings.addComponentResolver(new WicketMessageTagHandler()); pageSettings.addComponentResolver(new WicketContainerResolver()); // Install button image resource factory diff --git a/wicket-core/src/main/java/org/apache/wicket/markup/MarkupParser.java b/wicket-core/src/main/java/org/apache/wicket/markup/MarkupParser.java index d84383f..4720314 100644 --- a/wicket-core/src/main/java/org/apache/wicket/markup/MarkupParser.java +++ b/wicket-core/src/main/java/org/apache/wicket/markup/MarkupParser.java @@ -150,6 +150,7 @@ public class MarkupParser extends AbstractMarkupParser filters.add(new WicketLinkTagHandler()); filters.add(new AutoLabelTagHandler()); filters.add(new WicketNamespaceHandler(markupResourceStream)); + filters.add(new WicketMessageTagHandler(markupResourceStream)); // Provided the wicket component requesting the markup is known ... if ((markupResourceStream != null) && (markupResourceStream.getResource() != null)) @@ -157,8 +158,6 @@ public class MarkupParser extends AbstractMarkupParser final ContainerInfo containerInfo = markupResourceStream.getContainerInfo(); if (containerInfo != null) { - filters.add(new WicketMessageTagHandler(markupResourceStream)); - // Pages require additional handlers if (Page.class.isAssignableFrom(containerInfo.getContainerClass())) { diff --git a/wicket-core/src/main/java/org/apache/wicket/markup/parser/filter/InlineEnclosureHandler.java b/wicket-core/src/main/java/org/apache/wicket/markup/parser/filter/InlineEnclosureHandler.java index ab7e609..06a193a 100644 --- a/wicket-core/src/main/java/org/apache/wicket/markup/parser/filter/InlineEnclosureHandler.java +++ b/wicket-core/src/main/java/org/apache/wicket/markup/parser/filter/InlineEnclosureHandler.java @@ -43,7 +43,6 @@ import org.apache.wicket.util.string.Strings; * enclosure is identified by the 'child' attribute value which must be equal to the relative child * id path. * - * @see EnclosureResolver * @see InlineEnclosure * * @author Joonas Hamalainen @@ -96,7 +95,7 @@ public final class InlineEnclosureHandler extends AbstractMarkupFilter tag.toString(), tag.getPos()); } - // if it doesn't have a wicket-id already, than assign one now. + // if it doesn't have a wicket-id already, then assign one now. if (Strings.isEmpty(tag.getId())) { if (Strings.isEmpty(htmlId)) @@ -129,7 +128,7 @@ public final class InlineEnclosureHandler extends AbstractMarkupFilter // Are we within an enclosure? else if ((enclosures != null) && (enclosures.size() > 0)) { - // In case the enclosure tag did not provide a child component id, than assign the + // In case the enclosure tag did not provide a child component id, then assign the // first ComponentTag's id found as the controlling child to the enclosure. if (tag.isOpen() && (tag.getId() != null) && !(tag instanceof WicketTag) && !tag.isAutoComponentTag()) diff --git a/wicket-core/src/main/java/org/apache/wicket/markup/parser/filter/WicketMessageTagHandler.java b/wicket-core/src/main/java/org/apache/wicket/markup/parser/filter/WicketMessageTagHandler.java index acda0a6..5044128 100644 --- a/wicket-core/src/main/java/org/apache/wicket/markup/parser/filter/WicketMessageTagHandler.java +++ b/wicket-core/src/main/java/org/apache/wicket/markup/parser/filter/WicketMessageTagHandler.java @@ -83,7 +83,7 @@ public final class WicketMessageTagHandler extends AbstractMarkupFilter final String wicketMessageAttribute = tag.getAttributes().getString( getWicketMessageAttrName()); - if ((wicketMessageAttribute != null) && (wicketMessageAttribute.trim().length() > 0)) + if (Strings.isEmpty(wicketMessageAttribute) == false) { // check if this tag is raw markup if (tag.getId() == null) @@ -165,7 +165,7 @@ public final class WicketMessageTagHandler extends AbstractMarkupFilter // localize any raw markup that has wicket:message attrs if ((tag != null) && (tag.getId().startsWith(WICKET_MESSAGE_CONTAINER_ID))) { - Component wc = null; + Component wc; int autoIndex = container.getPage().getAutoIndex(); String id = WICKET_MESSAGE_CONTAINER_ID + autoIndex;
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4520_b91154ea.diff
bugs-dot-jar_data_WICKET-4365_1485a856
--- BugID: WICKET-4365 Summary: Form components' name/value are encoded in stateless form's action url Description: |- Stateless forms aren't working well as you can see on wicket examples: http://www.wicket-library.com/wicket-examples/stateless/foo The first time you submit, (for example, the value 10), everything works as supposed to. If you now change the value (to 11 for example) and submit the form, the value wicket shows is 10. I think the problem is stateless forms are generating an action URL with submitted values on query string, and when you resubmit the form, this values on query string replace the POST(or GET) values. diff --git a/wicket-core/src/main/java/org/apache/wicket/markup/html/form/Form.java b/wicket-core/src/main/java/org/apache/wicket/markup/html/form/Form.java index a0f3654..46dbefc 100644 --- a/wicket-core/src/main/java/org/apache/wicket/markup/html/form/Form.java +++ b/wicket-core/src/main/java/org/apache/wicket/markup/html/form/Form.java @@ -796,10 +796,6 @@ public class Form<T> extends WebMarkupContainer implements IFormSubmitListener */ public void process(IFormSubmitter submittingComponent) { - // save the page in case the component is removed during submit - final Page page = getPage(); - String hiddenFieldId = getHiddenFieldId(); - if (!isEnabledInHierarchy() || !isVisibleInHierarchy()) { // since process() can be called outside of the default form workflow, an additional diff --git a/wicket-core/src/main/java/org/apache/wicket/markup/html/form/StatelessForm.java b/wicket-core/src/main/java/org/apache/wicket/markup/html/form/StatelessForm.java index 034519c..2442556 100644 --- a/wicket-core/src/main/java/org/apache/wicket/markup/html/form/StatelessForm.java +++ b/wicket-core/src/main/java/org/apache/wicket/markup/html/form/StatelessForm.java @@ -17,6 +17,9 @@ package org.apache.wicket.markup.html.form; import org.apache.wicket.model.IModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.util.visit.IVisit; +import org.apache.wicket.util.visit.IVisitor; /** * This StatelessForm is the same as a normal form but with the statelesshint default to true. The @@ -72,4 +75,33 @@ public class StatelessForm<T> extends Form<T> { return urlFor(IFormSubmitListener.INTERFACE, getPage().getPageParameters()); } + + /** + * Remove the page parameters for all form component otherwise they get appended to action URL + * + * {@inheritDoc} + */ + @Override + public void process(IFormSubmitter submittingComponent) + { + super.process(submittingComponent); + + final PageParameters parameters = getPage().getPageParameters(); + if (parameters != null) + { + visitFormComponents(new IVisitor<FormComponent<?>, Void>() + { + public void component(final FormComponent<?> formComponent, final IVisit<Void> visit) + { + parameters.remove(formComponent.getInputName()); + } + }); + parameters.remove(getHiddenFieldId()); + if (submittingComponent instanceof AbstractSubmitLink) + { + AbstractSubmitLink submitLink = (AbstractSubmitLink)submittingComponent; + parameters.remove(submitLink.getInputName()); + } + } + } }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4365_1485a856.diff
bugs-dot-jar_data_WICKET-5500_825da305
--- BugID: WICKET-5500 Summary: Ignore the path parameters when reading the page class Description: "http://localhost:8080/linkomatic/wicket/bookmarkable/org.apache.wicket.examples.linkomatic.Page3;myjsessionid=123456 leads to :\n\nWARN - AbstractRepeater - Child component of repeater org.apache.wicket.markup.repeater.RepeatingView:area has a non-safe child id of page1. Safe child ids must be composed of digits only.\nWARN \ - WicketObjects - Could not resolve class [org.apache.wicket.examples.linkomatic.Page3;blass=koko]\njava.lang.ClassNotFoundException: org/apache/wicket/examples/linkomatic/Page3;blass=koko\n\tat java.lang.Class.forName0(Native Method)\n\tat java.lang.Class.forName(Class.java:264)\n\tat org.apache.wicket.application.AbstractClassResolver.resolveClass(AbstractClassResolver.java:108)\n\tat org.apache.wicket.core.util.lang.WicketObjects.resolveClass(WicketObjects.java:72)\n\tat org.apache.wicket.core.request.mapper.AbstractComponentMapper.getPageClass(AbstractComponentMapper.java:139)\n\tat org.apache.wicket.core.request.mapper.BookmarkableMapper.parseRequest(BookmarkableMapper.java:118)\n\tat org.apache.wicket.core.request.mapper.AbstractBookmarkableMapper.mapRequest(AbstractBookmarkableMapper.java:292)\n\tat org.apache.wicket.request.mapper.CompoundRequestMapper.mapRequest(CompoundRequestMapper.java:152)\n\tat org.apache.wicket.request.cycle.RequestCycle.resolveRequestHandler(RequestCycle.java:190)\n...\n\nSuch request at the moment works only if the the path parameter name is 'jsessionid'" diff --git a/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/AbstractComponentMapper.java b/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/AbstractComponentMapper.java index b1480ee..efd77c6 100644 --- a/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/AbstractComponentMapper.java +++ b/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/AbstractComponentMapper.java @@ -130,9 +130,28 @@ public abstract class AbstractComponentMapper extends AbstractMapper implements */ protected Class<? extends IRequestablePage> getPageClass(String name) { - Args.notEmpty(name, "name"); + String cleanedClassName = cleanClassName(name); + return WicketObjects.resolveClass(cleanedClassName); + } + + /** + * Cleans the class name from any extra information that may be there. + * + * @param className + * The raw class name parsed from the url + * @return The cleaned class name + */ + protected String cleanClassName(String className) + { + Args.notEmpty(className, "className"); + + if (Strings.indexOf(className, ';') > -1) + { + // remove any path parameters set manually by the user. WICKET-5500 + className = Strings.beforeFirst(className, ';'); + } - return WicketObjects.resolveClass(name); + return className; } /** diff --git a/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java b/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java index 41c6696..ad15d6d 100644 --- a/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java +++ b/wicket-core/src/main/java/org/apache/wicket/core/request/mapper/PackageMapper.java @@ -139,7 +139,8 @@ public class PackageMapper extends AbstractBookmarkableMapper PageComponentInfo info = getPageComponentInfo(url); // load the page class - String className = url.getSegments().get(mountSegments.length); + String name = url.getSegments().get(mountSegments.length); + String className = cleanClassName(name); if (isValidClassName(className) == false) {
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5500_825da305.diff
bugs-dot-jar_data_WICKET-5711_5837817c
--- BugID: WICKET-5711 Summary: OnChangeAjaxBehavior should listen for both 'inputchange' and 'change' events for TextField and TextArea Description: |- WICKET-5603 introduced a regression that a TextField using OnChangeAjaxBehavior doesn't work anymore when used as date picker, or Select2. The problem is that usually extensions like DatePicker and Select2 will fire 'change' event when they update the text input. OnChangeAjaxBehavior should use both 'inputchange" and "change" events for TextField and TextArea components. diff --git a/wicket-core/src/main/java/org/apache/wicket/ajax/form/OnChangeAjaxBehavior.java b/wicket-core/src/main/java/org/apache/wicket/ajax/form/OnChangeAjaxBehavior.java index f363cd8..27c229c 100644 --- a/wicket-core/src/main/java/org/apache/wicket/ajax/form/OnChangeAjaxBehavior.java +++ b/wicket-core/src/main/java/org/apache/wicket/ajax/form/OnChangeAjaxBehavior.java @@ -47,7 +47,8 @@ public abstract class OnChangeAjaxBehavior extends AjaxFormComponentUpdatingBeha * for text input form component depending on the browser. * 'change' is used as a fallback for all other form component types. */ - public static final String EVENT_INPUTCHANGE = "inputchange"; + public static final String EVENT_NAME = "inputchange change"; + public static final String EVENT_CHANGE = "change"; /** @@ -55,23 +56,19 @@ public abstract class OnChangeAjaxBehavior extends AjaxFormComponentUpdatingBeha */ public OnChangeAjaxBehavior() { - super(EVENT_INPUTCHANGE + " " + EVENT_CHANGE); + super(EVENT_NAME); } @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); - + Component component = getComponent(); - - //textfiels and textareas will trigger this behavior with event 'inputchange' - //while all the other components will use 'change' - if (component instanceof TextField || component instanceof TextArea) - { - attributes.setEventNames(EVENT_INPUTCHANGE); - } - else + + // textfiels and textareas will trigger this behavior with either 'inputchange' or 'change' events + // all the other components will use just 'change' + if (!(component instanceof TextField || component instanceof TextArea)) { attributes.setEventNames(EVENT_CHANGE); }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5711_5837817c.diff
bugs-dot-jar_data_WICKET-5603_240ab3c3
--- BugID: WICKET-5603 Summary: OnChangeAjaxBehavior attached to DropDownChoice produces two Ajax requests in Chrome v35 Description: "I have a DropDownChoice with attached OnChangeAjaxBehavior, like this:\n{code:borderStyle=solid}\nnew DropDownChoice<>(\"dd\", new Model<>(), Arrays.asList( \"First\", \"Second\"))\n \ .add( new OnChangeAjaxBehavior() {\n @Override\n protected void onUpdate(AjaxRequestTarget target) {\n System.out.println( \"update\" );\n }\n});\n{code}\n\nWhen selecting any of drop down options, two Ajax requests being generated.\nIt behaves OK in IE, FF and Chrome v34, only Chrome v35 is affected \n " diff --git a/wicket-core/src/main/java/org/apache/wicket/ajax/form/OnChangeAjaxBehavior.java b/wicket-core/src/main/java/org/apache/wicket/ajax/form/OnChangeAjaxBehavior.java index 965ae56..863eded 100644 --- a/wicket-core/src/main/java/org/apache/wicket/ajax/form/OnChangeAjaxBehavior.java +++ b/wicket-core/src/main/java/org/apache/wicket/ajax/form/OnChangeAjaxBehavior.java @@ -16,7 +16,11 @@ */ package org.apache.wicket.ajax.form; +import org.apache.wicket.Component; +import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; import org.apache.wicket.markup.html.form.FormComponent; +import org.apache.wicket.markup.html.form.TextArea; +import org.apache.wicket.markup.html.form.TextField; /** * A behavior that updates the hosting {@link FormComponent} via Ajax when value of the component is @@ -42,14 +46,33 @@ public abstract class OnChangeAjaxBehavior extends AjaxFormComponentUpdatingBeha * for text input form component depending on the browser. * 'change' is used as a fallback for all other form component types. */ - public static final String EVENT_NAME = "inputchange change"; + public static final String EVENT_INPUTCHANGE = "inputchange"; + public static final String EVENT_CHANGE = "change"; /** * Constructor. */ public OnChangeAjaxBehavior() { - super(EVENT_NAME); + super(EVENT_INPUTCHANGE + " " + EVENT_CHANGE); } + @Override + protected void updateAjaxAttributes(AjaxRequestAttributes attributes) + { + super.updateAjaxAttributes(attributes); + + Component component = getComponent(); + + //textfiels and textareas will trigger this behavior with event 'inputchange' + //while all the other components will use 'change' + if (component instanceof TextField || component instanceof TextArea) + { + attributes.setEventNames(EVENT_INPUTCHANGE); + } + else + { + attributes.setEventNames(EVENT_CHANGE); + } + } }
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-5603_240ab3c3.diff
bugs-dot-jar_data_WICKET-3280_295e73bd
--- BugID: WICKET-3280 Summary: IResponseFilter doesn't work in 1.5 Description: In current 1.5-SNAPSHOT there are no callers of org.apache.wicket.settings.IRequestCycleSettings.getResponseFilters() and thus filters are never executed. diff --git a/wicket/src/main/java/org/apache/wicket/ajax/AjaxRequestTarget.java b/wicket/src/main/java/org/apache/wicket/ajax/AjaxRequestTarget.java index 84ff3f0..c1ff4a5 100644 --- a/wicket/src/main/java/org/apache/wicket/ajax/AjaxRequestTarget.java +++ b/wicket/src/main/java/org/apache/wicket/ajax/AjaxRequestTarget.java @@ -51,6 +51,8 @@ import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.resource.ResourceReference; +import org.apache.wicket.response.StringResponse; +import org.apache.wicket.response.filter.IResponseFilter; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.string.AppendingStringBuffer; import org.apache.wicket.util.string.Strings; @@ -603,43 +605,18 @@ public class AjaxRequestTarget implements IPageRequestHandler // Make sure it is not cached by a client response.disableCaching(); - response.write("<?xml version=\"1.0\" encoding=\""); - response.write(encoding); - response.write("\"?>"); - response.write("<ajax-response>"); - - // invoke onbeforerespond event on listeners - fireOnBeforeRespondListeners(); - - // normal behavior - Iterator<CharSequence> it = prependJavaScripts.iterator(); - while (it.hasNext()) - { - CharSequence js = it.next(); - respondInvocation(response, js); - } - - // process added components - respondComponents(response); - - fireOnAfterRespondListeners(response); - - // execute the dom ready javascripts as first javascripts - // after component replacement - it = domReadyJavaScripts.iterator(); - while (it.hasNext()) + try { - CharSequence js = it.next(); - respondInvocation(response, js); + final StringResponse bodyResponse = new StringResponse(); + contructResponseBody(bodyResponse, encoding); + invokeResponseFilters(bodyResponse); + response.write(bodyResponse.getBuffer()); } - it = appendJavaScripts.iterator(); - while (it.hasNext()) + finally { - CharSequence js = it.next(); - respondInvocation(response, js); + // restore the original response + RequestCycle.get().setResponse(response); } - - response.write("</ajax-response>"); } finally { @@ -648,6 +625,80 @@ public class AjaxRequestTarget implements IPageRequestHandler } /** + * Collects the response body (without the headers) so that it can be pre-processed before + * written down to the original response. + * + * @param bodyResponse + * the buffering response + * @param encoding + * the encoding that should be used to encode the body + */ + private void contructResponseBody(final Response bodyResponse, final String encoding) + { + bodyResponse.write("<?xml version=\"1.0\" encoding=\""); + bodyResponse.write(encoding); + bodyResponse.write("\"?>"); + bodyResponse.write("<ajax-response>"); + + // invoke onbeforerespond event on listeners + fireOnBeforeRespondListeners(); + + // normal behavior + Iterator<CharSequence> it = prependJavaScripts.iterator(); + while (it.hasNext()) + { + CharSequence js = it.next(); + respondInvocation(bodyResponse, js); + } + + // process added components + respondComponents(bodyResponse); + + fireOnAfterRespondListeners(bodyResponse); + + // execute the dom ready javascripts as first javascripts + // after component replacement + it = domReadyJavaScripts.iterator(); + while (it.hasNext()) + { + CharSequence js = it.next(); + respondInvocation(bodyResponse, js); + } + it = appendJavaScripts.iterator(); + while (it.hasNext()) + { + CharSequence js = it.next(); + respondInvocation(bodyResponse, js); + } + + bodyResponse.write("</ajax-response>"); + } + + /** + * Runs the configured {@link IResponseFilter}s over the constructed Ajax response + * + * @param contentResponse + * the Ajax {@link Response} body + */ + private void invokeResponseFilters(final StringResponse contentResponse) + { + AppendingStringBuffer responseBuffer = new AppendingStringBuffer( + contentResponse.getBuffer()); + + List<IResponseFilter> responseFilters = Application.get() + .getRequestCycleSettings() + .getResponseFilters(); + + if (responseFilters != null) + { + for (IResponseFilter filter : responseFilters) + { + filter.filter(responseBuffer); + } + } + } + + /** * */ private void fireOnBeforeRespondListeners() @@ -667,7 +718,7 @@ public class AjaxRequestTarget implements IPageRequestHandler * * @param response */ - private void fireOnAfterRespondListeners(final WebResponse response) + private void fireOnAfterRespondListeners(final Response response) { // invoke onafterresponse event on listeners if (listeners != null) @@ -697,7 +748,7 @@ public class AjaxRequestTarget implements IPageRequestHandler * * @param response */ - private void respondComponents(WebResponse response) + private void respondComponents(Response response) { // TODO: We might need to call prepareRender on all components upfront diff --git a/wicket/src/main/java/org/apache/wicket/protocol/http/BufferedWebResponse.java b/wicket/src/main/java/org/apache/wicket/protocol/http/BufferedWebResponse.java index 113e442..1c9debe 100644 --- a/wicket/src/main/java/org/apache/wicket/protocol/http/BufferedWebResponse.java +++ b/wicket/src/main/java/org/apache/wicket/protocol/http/BufferedWebResponse.java @@ -24,10 +24,13 @@ import java.util.List; import javax.servlet.http.Cookie; +import org.apache.wicket.Application; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.request.Response; import org.apache.wicket.request.http.WebResponse; +import org.apache.wicket.response.filter.IResponseFilter; import org.apache.wicket.util.lang.Args; +import org.apache.wicket.util.string.AppendingStringBuffer; /** * Subclass of {@link WebResponse} that buffers the actions and performs those on another response. @@ -117,6 +120,20 @@ public class BufferedWebResponse extends WebResponse implements IMetaDataBufferi @Override protected void invoke(WebResponse response) { + + AppendingStringBuffer responseBuffer = new AppendingStringBuffer(builder); + + List<IResponseFilter> responseFilters = Application.get() + .getRequestCycleSettings() + .getResponseFilters(); + + if (responseFilters != null) + { + for (IResponseFilter filter : responseFilters) + { + filter.filter(responseBuffer); + } + } response.write(builder); } }; @@ -534,4 +551,5 @@ public class BufferedWebResponse extends WebResponse implements IMetaDataBufferi { return charSequenceAction.builder.toString(); } + } diff --git a/wicket/src/main/java/org/apache/wicket/response/filter/IResponseFilter.java b/wicket/src/main/java/org/apache/wicket/response/filter/IResponseFilter.java index e2f76cc..c106782 100644 --- a/wicket/src/main/java/org/apache/wicket/response/filter/IResponseFilter.java +++ b/wicket/src/main/java/org/apache/wicket/response/filter/IResponseFilter.java @@ -21,7 +21,7 @@ import org.apache.wicket.util.string.AppendingStringBuffer; /** * A response filter can be added to the * {@link org.apache.wicket.settings.IRequestCycleSettings#addResponseFilter(IResponseFilter)} - * object The will be called from the Buffered Response objects right before they would send it to + * object. This will be called from the Buffered Response objects right before they would send it to * the real responses. You have to use the * {@link org.apache.wicket.settings.IRequestCycleSettings#setBufferResponse(boolean)}(to true which * is the default) for this filtering to work.
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-3280_295e73bd.diff
bugs-dot-jar_data_WICKET-4072_7d5b8645
--- BugID: WICKET-4072 Summary: Form Input example fails when changing the language Description: "Trying to change the language of http://localhost:8080/forminput example fails with:\n\n\nCaused by: java.lang.ArrayIndexOutOfBoundsException: -1\n\tat java.util.ArrayList.remove(ArrayList.java:390)\n\tat org.apache.wicket.request.Url.resolveRelative(Url.java:884)\n\tat org.apache.wicket.markup.html.form.Form.dispatchEvent(Form.java:1028)\n\tat org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:699)\n\tat org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:670)\n\t... 37 more\n" diff --git a/wicket-request/src/main/java/org/apache/wicket/request/Url.java b/wicket-request/src/main/java/org/apache/wicket/request/Url.java index 2c3289b..6950de2 100755 --- a/wicket-request/src/main/java/org/apache/wicket/request/Url.java +++ b/wicket-request/src/main/java/org/apache/wicket/request/Url.java @@ -106,7 +106,7 @@ public final class Url implements Serializable * Parses the given URL string. * * @param url - * absolute or relative url with query string + * absolute or relative url with query string * @return Url object */ public static Url parse(final String url) @@ -118,7 +118,7 @@ public final class Url implements Serializable * Parses the given URL string. * * @param url - * absolute or relative url with query string + * absolute or relative url with query string * @param charset * @return Url object */ @@ -147,7 +147,7 @@ public final class Url implements Serializable absoluteUrl = url.substring(0, queryAt); queryString = url.substring(queryAt + 1); } - + // get absolute / relative part of url String relativeUrl; @@ -157,12 +157,12 @@ public final class Url implements Serializable if (protocolAt != -1) { result.protocol = absoluteUrl.substring(0, protocolAt).toLowerCase(Locale.US); - + final String afterProto = absoluteUrl.substring(protocolAt + 3); final String hostAndPort; final int relativeAt = afterProto.indexOf('/'); - + if (relativeAt == -1) { relativeUrl = ""; @@ -236,7 +236,7 @@ public final class Url implements Serializable * get default port number for protocol * * @param protocol - * name of protocol + * name of protocol * @return default port for protocol or <code>null</code> if unknown */ private static Integer getDefaultPortForProtocol(String protocol) @@ -311,7 +311,7 @@ public final class Url implements Serializable */ public Url(final List<String> segments, final Charset charset) { - this(segments, Collections.<QueryParameter>emptyList(), charset); + this(segments, Collections.<QueryParameter> emptyList(), charset); } /** @@ -592,8 +592,8 @@ public final class Url implements Serializable } /** - * render full representation of url (including protocol, host and port) - * into string representation + * render full representation of url (including protocol, host and port) into string + * representation */ public String toAbsoluteString() { @@ -601,8 +601,8 @@ public final class Url implements Serializable } /** - * render full representation of url (including protocol, host and port) - * into string representation + * render full representation of url (including protocol, host and port) into string + * representation * * @param charset * @@ -613,13 +613,13 @@ public final class Url implements Serializable StringBuilder result = new StringBuilder(); // output scheme://host:port if specified - if(protocol != null && Strings.isEmpty(host) == false) + if (protocol != null && Strings.isEmpty(host) == false) { result.append(protocol); result.append("://"); result.append(host); - - if(port != null && port.equals(getDefaultPortForProtocol(protocol)) == false) + + if (port != null && port.equals(getDefaultPortForProtocol(protocol)) == false) { result.append(':'); result.append(port); @@ -627,7 +627,7 @@ public final class Url implements Serializable } // append relative part result.append(this.toString()); - + // return url string return result.toString(); } @@ -880,9 +880,11 @@ public final class Url implements Serializable */ public void resolveRelative(final Url relative) { - // strip the first non-folder segment - getSegments().remove(getSegments().size() - 1); - + if (getSegments().size() > 0) + { + // strip the first non-folder segment + getSegments().remove(getSegments().size() - 1); + } // remove all './' (current folder) from the relative url if (!relative.getSegments().isEmpty() && ".".equals(relative.getSegments().get(0))) { @@ -963,13 +965,13 @@ public final class Url implements Serializable { this.host = host; } - + /** - * return path for current url in given encoding + * return path for current url in given encoding * * @param charset - * character set for encoding - * + * character set for encoding + * * @return path string */ public String getPath(Charset charset) @@ -992,7 +994,7 @@ public final class Url implements Serializable } /** - * return path for current url in original encoding + * return path for current url in original encoding * * @return path string */ @@ -1005,7 +1007,7 @@ public final class Url implements Serializable * return query string part of url in given encoding * * @param charset - * character set for encoding + * character set for encoding * * @return query string */
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4072_7d5b8645.diff
bugs-dot-jar_data_WICKET-4616_dd1df04b
--- BugID: WICKET-4616 Summary: onError call order doesn't match onSubmit Description: onError in Forms and Buttons should be called in the same order as onSubmit (i.e. post-order). diff --git a/wicket-core/src/main/java/org/apache/wicket/markup/html/form/Form.java b/wicket-core/src/main/java/org/apache/wicket/markup/html/form/Form.java index 35ac561..53898a6 100644 --- a/wicket-core/src/main/java/org/apache/wicket/markup/html/form/Form.java +++ b/wicket-core/src/main/java/org/apache/wicket/markup/html/form/Form.java @@ -928,18 +928,19 @@ public class Form<T> extends WebMarkupContainer implements IFormSubmitListener */ protected void callOnError(IFormSubmitter submitter) { + final Form<?> processingForm = findFormToProcess(submitter); + if (submitter != null) { submitter.onError(); } - onError(); - // call onError on nested forms - visitChildren(Form.class, new IVisitor<Component, Void>() + + // invoke Form#onSubmit(..) going from innermost to outermost + Visits.visitPostOrder(processingForm, new IVisitor<Form<?>, Void>() { @Override - public void component(final Component component, final IVisit<Void> visit) + public void component(Form<?> form, IVisit<Void> visit) { - final Form<?> form = (Form<?>)component; if (!form.isEnabledInHierarchy() || !form.isVisibleInHierarchy()) { visit.dontGoDeeper(); @@ -950,7 +951,7 @@ public class Form<T> extends WebMarkupContainer implements IFormSubmitListener form.onError(); } } - }); + }, new ClassVisitFilter(Form.class)); } @@ -1208,8 +1209,8 @@ public class Form<T> extends WebMarkupContainer implements IFormSubmitListener * processing to clients. * <p> * This implementation first finds out whether the form processing was triggered by a nested - * IFormSubmittingComponent of this form. If that is the case, that component's onSubmit is - * called first. + * IFormSubmittingComponent of this form. If that is the case, that component's + * onSubmitBefore/AfterForm methods are called appropriately.. * </p> * <p> * Regardless of whether a submitting component was found, the form's onSubmit method is called @@ -1225,7 +1226,6 @@ public class Form<T> extends WebMarkupContainer implements IFormSubmitListener { final Form<?> processingForm = findFormToProcess(submittingComponent); - // process submitting component (if specified) if (submittingComponent != null) {
bugs-dot-jar/wicket_extracted_diff/developer-patch_bugs-dot-jar_WICKET-4616_dd1df04b.diff