diff --git a/src/main/java/org/jruby/rack/AbstractRackDispatcher.java b/src/main/java/org/jruby/rack/AbstractRackDispatcher.java index 155ffb09b..3c70a6f82 100644 --- a/src/main/java/org/jruby/rack/AbstractRackDispatcher.java +++ b/src/main/java/org/jruby/rack/AbstractRackDispatcher.java @@ -9,6 +9,8 @@ import java.io.IOException; +import static org.jruby.rack.RackLogger.Level.*; + /** * * @author nicksieger @@ -46,10 +48,10 @@ protected void handleException( final RackResponseEnvironment response) throws IOException { if ( response.isCommitted() ) { - context.log(RackLogger.ERROR, "couldn't handle exception (response is committed)", e); + context.log(ERROR, "couldn't handle exception (response is committed)", e); return; } - context.log(RackLogger.INFO, "resetting rack response due exception: " + e); + context.log(INFO, "resetting rack response due exception: " + e); response.reset(); afterException(request, e, response); diff --git a/src/main/java/org/jruby/rack/DefaultErrorApplication.java b/src/main/java/org/jruby/rack/DefaultErrorApplication.java index ed98c0ba8..777bf4ea8 100644 --- a/src/main/java/org/jruby/rack/DefaultErrorApplication.java +++ b/src/main/java/org/jruby/rack/DefaultErrorApplication.java @@ -33,6 +33,8 @@ import org.jruby.Ruby; +import static org.jruby.rack.RackLogger.Level.*; + /** * Default error application if the Rack error application can not be setup or * "jruby.rack.error" handling is turned off (set to false). @@ -117,7 +119,7 @@ public String getBody() { body = buildErrorBody(); } catch (Exception e) { - log(RackLogger.INFO, "failed building error body", e); + log(INFO, "failed building error body", e); body = getError() == null ? "" : getError().toString(); } } @@ -149,11 +151,11 @@ public void respond(RackResponseEnvironment response) { defaultRespond(this, response); } catch (IOException e) { - log(RackLogger.WARN, "could not write response body", e); + log(WARN, "could not write response body", e); } } - private void log(String level, String message, Throwable e) { + private void log(RackLogger.Level level, String message, Throwable e) { if ( context != null ) context.log(level, message, e); } diff --git a/src/main/java/org/jruby/rack/DefaultRackApplicationFactory.java b/src/main/java/org/jruby/rack/DefaultRackApplicationFactory.java index f0771c30f..7b4887e35 100644 --- a/src/main/java/org/jruby/rack/DefaultRackApplicationFactory.java +++ b/src/main/java/org/jruby/rack/DefaultRackApplicationFactory.java @@ -11,8 +11,6 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.util.Map; @@ -99,11 +97,7 @@ public void init(final RackContext rackContext) { */ @Override public RackApplication newApplication() { - return createApplication(new ApplicationObjectFactory() { - public IRubyObject create(Ruby runtime) { - return createApplicationObject(runtime); - } - }); + return createApplication(this::createApplicationObject); } /** @@ -209,13 +203,7 @@ public RackApplication newErrorApplication() { return new DefaultErrorApplication(rackContext); } try { - RackApplication app = createErrorApplication( - new ApplicationObjectFactory() { - public IRubyObject create(Ruby runtime) { - return createErrorApplicationObject(runtime); - } - } - ); + RackApplication app = createErrorApplication(this::createErrorApplicationObject); app.init(); return app; } @@ -250,7 +238,7 @@ protected IRubyObject createRackServletWrapper(Ruby runtime, String rackup, Stri ); } - static interface ApplicationObjectFactory { + interface ApplicationObjectFactory { IRubyObject create(Ruby runtime) ; } @@ -267,21 +255,7 @@ protected RubyInstanceConfig initRuntimeConfig(final RubyInstanceConfig config) // Don't affect the container and sibling web apps when ENV changes are // made inside the Ruby app ... // There are quite a such things made in a typical Bundler based app. - try { // config.setUpdateNativeENVEnabled(false) using reflection : - final Method setUpdateNativeENVEnabled = - config.getClass().getMethod("setUpdateNativeENVEnabled", Boolean.TYPE); - setUpdateNativeENVEnabled.invoke(config, false); - } - catch (NoSuchMethodException e) { // ignore method has been added in JRuby 1.6.7 - rackContext.log(DEBUG, "envronment changes made inside one app " + - "might affect another, consider updating JRuby if this is an issue"); - } - catch (IllegalAccessException e) { - rackContext.log(WARN, "failed to disable updating native environment", e); - } - catch (InvocationTargetException e) { - throw new RackException(e.getTargetException()); - } + config.setUpdateNativeENVEnabled(false); final Map newEnv = rackConfig.getRuntimeEnvironment(); if ( newEnv != null ) { @@ -297,7 +271,6 @@ protected RubyInstanceConfig initRuntimeConfig(final RubyInstanceConfig config) else { // allow to work (backwards) "compatibly" with previous `ENV.clear` // RUBYOPT was processed since it happens on config.processArguments - @SuppressWarnings("unchecked") final Map env = config.getEnvironment(); if ( env != null && env.containsKey("RUBYOPT") ) { newEnv.put( "RUBYOPT", env.get("RUBYOPT") ); @@ -355,9 +328,7 @@ protected void loadJRubyRack(final Ruby runtime) { public void initRuntime(final Ruby runtime) { loadJRubyRack(runtime); // set $servlet_context : - runtime.getGlobalVariables().set( - "$servlet_context", JavaUtil.convertJavaToRuby(runtime, rackContext) - ); + runtime.getGlobalVariables().set("$servlet_context", JavaUtil.convertJavaToRuby(runtime, rackContext)); // load our (servlet) Rack handler : runtime.evalScriptlet("require 'rack/handler/servlet'"); @@ -411,9 +382,6 @@ public String checkAndSetRackVersion(final Ruby runtime) { rackContext.log(DEBUG, "could not read 'rack.version' magic comment from rackup", e); } - if ( rackVersion == null ) { - // NOTE: try matching a `require 'bundler/setup'` line ... maybe not ?! - } if ( rackVersion != null ) { runtime.evalScriptlet("require 'rubygems'"); @@ -462,10 +430,22 @@ public void destroy() { runtime.tearDown(false); } + private void captureMessage(final RaiseException re) { + try { + IRubyObject rubyException = re.getException(); + ThreadContext context = rubyException.getRuntime().getCurrentContext(); + // JRuby-Rack internals (@see jruby/rack/capture.rb) : + rubyException.callMethod(context, "capture"); + rubyException.callMethod(context, "store"); + } + catch (Exception e) { + rackContext.log(INFO, "failed to capture exception message", e); + // won't be able to capture anything + } + } } private RackApplication createErrorApplication(final ApplicationObjectFactory appFactory) { - // final Ruby runtime = newRuntime(); return new ErrorApplicationImpl(appFactory); } @@ -482,29 +462,13 @@ public void init() { } - private void captureMessage(final RaiseException re) { - try { - IRubyObject rubyException = re.getException(); - ThreadContext context = rubyException.getRuntime().getCurrentContext(); - // JRuby-Rack internals (@see jruby/rack/capture.rb) : - rubyException.callMethod(context, "capture"); - rubyException.callMethod(context, "store"); - } - catch (Exception e) { - rackContext.log(INFO, "failed to capture exception message", e); - // won't be able to capture anything - } - } - private String findConfigRuPathInSubDirectories(final String path, int level) { - @SuppressWarnings("unchecked") final Set entries = rackContext.getResourcePaths(path); if (entries != null) { String config_ru = path + "config.ru"; if ( entries.contains(config_ru) ) { return config_ru; } - if (level > 0) { level--; for ( String subpath : entries ) { @@ -526,11 +490,9 @@ private static String getContextLoaderScript(final String name, final boolean si InputStream is = contextLoader.getResourceAsStream(name); return IOHelpers.inputStreamToString(is); } - catch (IOException e) { - if ( silent ) return null; throw e; - } - catch (RuntimeException e) { - if ( silent ) return null; throw e; + catch (IOException|RuntimeException e) { + if ( silent ) return null; + throw e; } } @@ -565,7 +527,7 @@ private String resolveRackupScript() throws RackInitializationException { } catch (IOException ex) { /* won't happen */ } - rackContext.log(RackLogger.ERROR, "failed to read rackup from '"+ rackup + "' (" + e + ")"); + rackContext.log(ERROR, "failed to read rackup from '"+ rackup + "' (" + e + ")"); throw new RackInitializationException("failed to read rackup input", e); } } diff --git a/src/main/java/org/jruby/rack/DefaultRackConfig.java b/src/main/java/org/jruby/rack/DefaultRackConfig.java index 197c970d5..5667a7851 100644 --- a/src/main/java/org/jruby/rack/DefaultRackConfig.java +++ b/src/main/java/org/jruby/rack/DefaultRackConfig.java @@ -253,18 +253,11 @@ public Map getRuntimeEnvironment() { if ( env == null ) env = getProperty("jruby.runtime.environment"); final Object envFlag = toStrictBoolean(env, null); if ( envFlag != null ) { - boolean keep = ((Boolean) envFlag).booleanValue(); // jruby.runtime.env = true keep as is (return null) // jruby.runtime.env = false clear env (return empty) - //return keep ? null : new HashMap(); - if ( keep ) { - return new HashMap(System.getenv()); - } - else { - return new HashMap(); - } + return (Boolean) envFlag ? new HashMap<>(System.getenv()) : new HashMap<>(); } - if ( isIgnoreEnvironment() ) return new HashMap(); + if ( isIgnoreEnvironment() ) return new HashMap<>(); // TODO maybe support custom value 'servlet' to use init params ? return toStringMap(env); } @@ -289,14 +282,14 @@ public boolean isThrowInitException() { static boolean isThrowInitException(RackConfig config) { Boolean error = config.getBooleanProperty("jruby.rack.error"); - if ( error != null && ! error.booleanValue() ) { - return true; // jruby.rack.error = false + if ( error != null && error.booleanValue() ) { + return false; // jruby.rack.error = true } - error = config.getBooleanProperty("jruby.rack.exception"); - if ( error != null && ! error.booleanValue() ) { - return true; // jruby.rack.exception = false + error = config.getBooleanProperty(RackEnvironment.EXCEPTION); + if ( error != null && error.booleanValue() ) { + return false; // jruby.rack.exception = true } - return false; + return true; } @Override @@ -421,7 +414,7 @@ private Map toStringMap(final String env) { } private static Map getLoggerTypes() { - final Map loggerTypes = new HashMap(8); + final Map loggerTypes = new HashMap<>(8); loggerTypes.put("commons_logging", "org.jruby.rack.logging.CommonsLoggingLogger"); loggerTypes.put("clogging", "org.jruby.rack.logging.CommonsLoggingLogger"); loggerTypes.put("slf4j", "org.jruby.rack.logging.Slf4jLogger"); diff --git a/src/main/java/org/jruby/rack/DefaultRackDispatcher.java b/src/main/java/org/jruby/rack/DefaultRackDispatcher.java index 79624b267..611f672c0 100644 --- a/src/main/java/org/jruby/rack/DefaultRackDispatcher.java +++ b/src/main/java/org/jruby/rack/DefaultRackDispatcher.java @@ -11,6 +11,8 @@ import org.jruby.rack.servlet.ServletRackContext; +import static org.jruby.rack.RackLogger.Level.*; + /** * Dispatcher suited for use in a servlet container * @author nick @@ -50,10 +52,10 @@ protected void afterException( } catch (final RuntimeException re) { // allow the error app to re-throw Ruby/JRuby-Rack exceptions : - if (re instanceof RackException) throw (RackException) re; + if (re instanceof RackException) throw re; //if (e instanceof RaiseException) throw (RaiseException) e; // TODO seems redundant maybe we should let the container decide ?! - context.log(RackLogger.ERROR, "error app failed to handle exception: " + e, re); + context.log(ERROR, "error app failed to handle exception: " + e, re); Integer errorCode = getErrorApplicationFailureStatusCode(); if ( errorCode != null && errorCode.intValue() > 0 ) { response.sendError(errorCode); diff --git a/src/main/java/org/jruby/rack/RackException.java b/src/main/java/org/jruby/rack/RackException.java index d4aaacb59..c55e16865 100644 --- a/src/main/java/org/jruby/rack/RackException.java +++ b/src/main/java/org/jruby/rack/RackException.java @@ -13,7 +13,6 @@ * * @author kares */ -@SuppressWarnings("serial") public class RackException extends RuntimeException { public RackException(String message) { @@ -57,9 +56,7 @@ static String exceptionMessage(final RaiseException e) { st.append(b.toString()); return st.toString(); } - else { - return null; - } + return null; } } diff --git a/src/main/java/org/jruby/rack/RackLogger.java b/src/main/java/org/jruby/rack/RackLogger.java index 6e41100ca..91c6b1119 100644 --- a/src/main/java/org/jruby/rack/RackLogger.java +++ b/src/main/java/org/jruby/rack/RackLogger.java @@ -12,10 +12,6 @@ * @author nicksieger */ public interface RackLogger { - - void log(String message) ; - void log(String message, Throwable ex) ; - //void debug(String message) ; //void debug(String message, Throwable e) ; @@ -37,44 +33,27 @@ enum Level { void log(Level level, String message) ; void log(Level level, String message, Throwable ex) ; - @Deprecated final String DEBUG = Level.DEBUG.name(); - @Deprecated final String INFO = Level.INFO.name(); - @Deprecated final String WARN = Level.WARN.name(); - @Deprecated final String ERROR = Level.ERROR.name(); + default void log(String message) { + log(Level.INFO, message); + } - void log(String level, String message) ; - void log(String level, String message, Throwable ex) ; + default void log(String message, Throwable ex) { + log(Level.ERROR, message, ex); + } - abstract class Base implements RackLogger { + default void log(String level, String message) { + log(Level.valueOf(level), message); + } - public abstract Level getLevel() ; + default void log(String level, String message, Throwable ex) { + log(Level.valueOf(level), message, ex); + } + abstract class Base implements RackLogger { + public abstract Level getLevel() ; public void setLevel(Level level) { /* noop */ } public boolean isFormatting() { return false; } - public void setFormatting(boolean flag) { /* noop */ } - - @Override - public void log(String message) { - log(Level.INFO, message); - } - - @Override - public void log(String message, Throwable ex) { - log(Level.ERROR, message, ex); - } - - @Override - public void log(String level, String message) { - log(Level.valueOf(level), message); - } - - @Override - public void log(String level, String message, Throwable ex) { - log(Level.valueOf(level), message, ex); - } - } - } diff --git a/src/main/java/org/jruby/rack/RackServletContextListener.java b/src/main/java/org/jruby/rack/RackServletContextListener.java index ace26b20c..cf16d34d6 100644 --- a/src/main/java/org/jruby/rack/RackServletContextListener.java +++ b/src/main/java/org/jruby/rack/RackServletContextListener.java @@ -16,6 +16,7 @@ import org.jruby.rack.servlet.ServletRackContext; import static org.jruby.rack.DefaultRackConfig.isThrowInitException; +import static org.jruby.rack.RackLogger.Level.*; /** * Web application lifecycle listener. @@ -49,7 +50,7 @@ public void contextInitialized(final ServletContextEvent event) { try { factory.init(rackContext); } - catch (RuntimeException e) { + catch (Exception e) { handleInitializationException(e, factory, rackContext); } } @@ -68,11 +69,8 @@ public void contextDestroyed(final ServletContextEvent event) { protected RackApplicationFactory newApplicationFactory(RackConfig config) { if (factory != null) return factory; // only != null while testing - final RackApplicationFactory factory = new DefaultRackApplicationFactory(); - final Integer maxRuntimes = config.getMaximumRuntimes(); - // for backwards compatibility when runtime mix/max values not specified - // we assume a single shared (threadsafe) runtime to be used : - if ( maxRuntimes == null || maxRuntimes.intValue() == 1 ) { + final RackApplicationFactory factory = getRealRackApplicationFactoryImpl(); + if (useSharedApplication((config))) { return new SharedRackApplicationFactory(factory); } else { @@ -81,12 +79,20 @@ protected RackApplicationFactory newApplicationFactory(RackConfig config) { new PoolingRackApplicationFactory(factory) ; } } - + + private static boolean useSharedApplication(final RackConfig config) { + final Integer maxRuntimes = config.getMaximumRuntimes(); + return maxRuntimes == null || maxRuntimes == 1; + } + + protected RackApplicationFactory getRealRackApplicationFactoryImpl() { + return new DefaultRackApplicationFactory(); + } + protected void handleInitializationException( final Exception e, final RackApplicationFactory factory, final ServletRackContext rackContext) { - // TODO for backwards compat we do not throw (by default) but should : if ( isThrowInitException(rackContext.getConfig()) ) { if (e instanceof RuntimeException) { throw (RuntimeException) e; @@ -94,7 +100,7 @@ protected void handleInitializationException( throw RackInitializationException.wrap(e); } // NOTE: factory should have already logged the error ... - rackContext.log(RackLogger.ERROR, "initialization failed", e); + rackContext.log(ERROR, "initialization failed", e); } - + } diff --git a/src/main/java/org/jruby/rack/ext/Logger.java b/src/main/java/org/jruby/rack/ext/Logger.java index 318e6945c..d8c5b728a 100644 --- a/src/main/java/org/jruby/rack/ext/Logger.java +++ b/src/main/java/org/jruby/rack/ext/Logger.java @@ -109,11 +109,8 @@ private void initialize(final IRubyObject context) { if ( context instanceof RackLogger ) { this.logger = (RackLogger) context; } - else if ( context instanceof RackContext ) { - this.logger = ((RackContext) context).getConfig().getLogger(); - } else { - this.logger = (RackLogger) context.toJava(RackLogger.class); + this.logger = context.toJava(RackLogger.class); } } @@ -285,8 +282,7 @@ public IRubyObject debug(final ThreadContext context, // See #add. // @JRubyMethod(name = "info") - public IRubyObject info(final ThreadContext context, - final IRubyObject msg, final Block block) { + public IRubyObject info(final ThreadContext context, final IRubyObject msg, final Block block) { return context.runtime.newBoolean( add(INFO, context, msg, block) ); } @@ -299,8 +295,7 @@ public IRubyObject info(final ThreadContext context, final Block block) { // Log a +WARN+ message. // @JRubyMethod(name = "warn") - public IRubyObject warn(final ThreadContext context, - final IRubyObject msg, final Block block) { + public IRubyObject warn(final ThreadContext context, final IRubyObject msg, final Block block) { return context.runtime.newBoolean( add(WARN, context, msg, block) ); } @@ -313,8 +308,7 @@ public IRubyObject warn(final ThreadContext context, final Block block) { // Log a +ERROR+ message. // @JRubyMethod(name = "error") - public IRubyObject error(final ThreadContext context, - final IRubyObject msg, final Block block) { + public IRubyObject error(final ThreadContext context, final IRubyObject msg, final Block block) { return context.runtime.newBoolean( add(ERROR, context, msg, block) ); } @@ -327,8 +321,7 @@ public IRubyObject error(final ThreadContext context, final Block block) { // Log a +FATAL+ message. // @JRubyMethod(name = "fatal") - public IRubyObject fatal(final ThreadContext context, - final IRubyObject msg, final Block block) { + public IRubyObject fatal(final ThreadContext context, final IRubyObject msg, final Block block) { return context.runtime.newBoolean( add(FATAL, context, msg, block) ); } @@ -342,9 +335,7 @@ public IRubyObject fatal(final ThreadContext context, final Block block) { // This will be printed no matter what the logger's level is. // @JRubyMethod(name = "unknown") - public IRubyObject unknown(final ThreadContext context, - final IRubyObject msg, final Block block) { - // NOTE possibly - "somehow" support UNKNOWN in RackLogger ?! + public IRubyObject unknown(final ThreadContext context, final IRubyObject msg, final Block block) { return context.runtime.newBoolean( add(UNKNOWN, context, msg, block) ); } @@ -375,10 +366,8 @@ public IRubyObject add(final ThreadContext context, // def add(severity, message = nil, progname = nil, &block) @JRubyMethod(name = "add") - public IRubyObject add(final ThreadContext context, - final IRubyObject severity, final IRubyObject msg, - final IRubyObject progname, final Block block) { - // NOTE possibly - "somehow" support UNKNOWN in RackLogger ?! + public IRubyObject add(final ThreadContext context, final IRubyObject severity, + final IRubyObject msg, final IRubyObject progname, final Block block) { return context.runtime.newBoolean( add(UNKNOWN, context, msg, block) ); } @@ -431,8 +420,7 @@ public IRubyObject append(final ThreadContext context, final IRubyObject msg) { // private @JRubyMethod(visibility = Visibility.PRIVATE, required = 4) - public IRubyObject format_message(final ThreadContext context, - final IRubyObject[] args) { + public IRubyObject format_message(final ThreadContext context, final IRubyObject[] args) { if ( formatter instanceof RubyProc ) { return ((RubyProc) formatter).call(context, args); } @@ -440,8 +428,8 @@ public IRubyObject format_message(final ThreadContext context, } private IRubyObject format_message(final ThreadContext context, - final int severityVal, final long datetimeMillis, - final IRubyObject progname, final IRubyObject msg) { + final int severityVal, final long datetimeMillis, + final IRubyObject progname, final IRubyObject msg) { final IRubyObject severity = RubyString.newStringShared(context.runtime, formatSeverity(severityVal)); final RubyTime datetime = RubyTime.newTime(context.runtime, datetimeMillis); @@ -493,9 +481,9 @@ private static String formatSeverity(final int severity) { // RackLogger @Override - public Object toJava(Class target) { + public T toJava(Class target) { // NOTE: maybe this is not a good idea ?! - if ( RackLogger.class == target ) return logger; + if ( RackLogger.class == target ) return (T) logger; return super.toJava(target); } @@ -563,14 +551,12 @@ public IRubyObject silence(final ThreadContext context, final Block block) { } @JRubyMethod(name = "silence", required = 1) - public IRubyObject silence(final ThreadContext context, - final IRubyObject temp_level, final Block block) { + public IRubyObject silence(final ThreadContext context, final IRubyObject temp_level, final Block block) { final int tempLevel = (int) temp_level.convertToInteger("to_i").getLongValue(); return doSilence(tempLevel, context, block); } - private IRubyObject doSilence(final int tempLevel, - final ThreadContext context, final Block block) { + private IRubyObject doSilence(final int tempLevel, final ThreadContext context, final Block block) { if ( silencer ) { try { // not implemented - on purpose! return block.yield(context, this); @@ -607,7 +593,7 @@ protected ServletLog(Ruby runtime, RubyClass metaClass) { super(runtime, metaClass); } - @JRubyMethod(required = 0, optional = 1) + @JRubyMethod(optional = 1) public IRubyObject initialize(final ThreadContext context, final IRubyObject[] args) { final IRubyObject rackContext; if ( args != null && args.length > 0 ) rackContext = args[0]; @@ -623,17 +609,16 @@ public IRubyObject initialize(final ThreadContext context, final IRubyObject[] a } else { try { - RackLogger logger = (RackLogger) rackContext.toJava(RackLogger.class); - this.context = logger; + this.context = rackContext.toJava(RackLogger.class); } catch (RaiseException e) { // TypeError final IRubyObject error = e.getException(); - if ( error == null && ! context.runtime.getTypeError().isInstance(error) ) { + if ( error == null || ! context.runtime.getTypeError().isInstance(error) ) { throw e; } // support passing in a ServletContext instance (for convenience) : try { - ServletContext servletContext = (ServletContext) rackContext.toJava(ServletContext.class); + ServletContext servletContext = rackContext.toJava(ServletContext.class); this.context = new ServletContextLogger(servletContext); } catch (RaiseException fail) { diff --git a/src/main/java/org/jruby/rack/ext/RackLibrary.java b/src/main/java/org/jruby/rack/ext/RackLibrary.java index 07e4faa0e..54aa6e0b0 100644 --- a/src/main/java/org/jruby/rack/ext/RackLibrary.java +++ b/src/main/java/org/jruby/rack/ext/RackLibrary.java @@ -36,7 +36,6 @@ */ public class RackLibrary implements Library, BasicLibraryService { - @SuppressWarnings("deprecation") public static void load(final Ruby runtime) { final RubyModule _JRuby = runtime.getOrCreateModule("JRuby"); final RubyModule _JRuby_Rack = _JRuby.defineModuleUnder("Rack"); diff --git a/src/main/java/org/jruby/rack/rails/RailsServletContextListener.java b/src/main/java/org/jruby/rack/rails/RailsServletContextListener.java index acaee55fd..ec978002c 100644 --- a/src/main/java/org/jruby/rack/rails/RailsServletContextListener.java +++ b/src/main/java/org/jruby/rack/rails/RailsServletContextListener.java @@ -7,11 +7,7 @@ package org.jruby.rack.rails; -import org.jruby.rack.SerialPoolingRackApplicationFactory; -import org.jruby.rack.SharedRackApplicationFactory; -import org.jruby.rack.PoolingRackApplicationFactory; import org.jruby.rack.RackApplicationFactory; -import org.jruby.rack.RackConfig; import org.jruby.rack.RackServletContextListener; /** @@ -19,20 +15,9 @@ * @author nicksieger */ public class RailsServletContextListener extends RackServletContextListener { - + @Override - protected RackApplicationFactory newApplicationFactory(RackConfig config) { - final RackApplicationFactory factory = new RailsRackApplicationFactory(); - final Integer maxRuntimes = config.getMaximumRuntimes(); - // TODO maybe after Rails 4 is out switch to shared by default as well ! - if ( maxRuntimes != null && maxRuntimes.intValue() == 1 ) { - return new SharedRackApplicationFactory(factory); - } - else { - return config.isSerialInitialization() ? - new SerialPoolingRackApplicationFactory(factory) : - new PoolingRackApplicationFactory(factory) ; - } + protected RackApplicationFactory getRealRackApplicationFactoryImpl() { + return new RailsRackApplicationFactory(); } - } diff --git a/src/main/java/org/jruby/rack/servlet/DefaultServletRackContext.java b/src/main/java/org/jruby/rack/servlet/DefaultServletRackContext.java index 5c2f05bef..457c2ea3d 100644 --- a/src/main/java/org/jruby/rack/servlet/DefaultServletRackContext.java +++ b/src/main/java/org/jruby/rack/servlet/DefaultServletRackContext.java @@ -35,7 +35,6 @@ * * @author nicksieger */ -@SuppressWarnings("rawtypes") public class DefaultServletRackContext implements ServletRackContext { private final RackConfig config; diff --git a/src/main/java/org/jruby/rack/servlet/ServletRackContext.java b/src/main/java/org/jruby/rack/servlet/ServletRackContext.java index 3b721e3b9..bb67a3358 100644 --- a/src/main/java/org/jruby/rack/servlet/ServletRackContext.java +++ b/src/main/java/org/jruby/rack/servlet/ServletRackContext.java @@ -21,6 +21,13 @@ public interface ServletRackContext extends RackContext, ServletContext { RackApplicationFactory getRackFactory(); - // ServletContext getRealContext(); // TODO support this in 1.2 + @Override + default void log(String message) { + RackContext.super.log(message); + } + @Override + default void log(String message, Throwable ex) { + RackContext.super.log(message, ex); + } } diff --git a/src/main/ruby/jruby/rack/booter.rb b/src/main/ruby/jruby/rack/booter.rb index 2d359d267..02501600e 100644 --- a/src/main/ruby/jruby/rack/booter.rb +++ b/src/main/ruby/jruby/rack/booter.rb @@ -85,10 +85,6 @@ def gem_path=(path); layout.gem_path = path end def public_path; layout.public_path end def public_path=(path); layout.public_path = path end - # @deprecated use {JRuby::Rack#logger} instead - # @return [Logger] - def logger; JRuby::Rack.logger; end - # Boot-up this booter, preparing the environment for the application. def boot! adjust_gem_path @@ -157,7 +153,7 @@ def env_gem_path # @note called during {#boot!} def export_global_settings - JRuby::Rack.send(:instance_variable_set, :@booter, self) # TODO + JRuby::Rack.instance_variable_set(:@booter, self) # NOTE: unused for now JRuby::Rack.app_path = layout.app_path JRuby::Rack.public_path = layout.public_path end @@ -183,7 +179,7 @@ def load_settings_from_init_rb stream = url.openStream stream.to_io.read rescue Exception => e - logger.info "failed to read from '#{url.toString}' (#{e.message})" + JRuby::Rack.logger.info "failed to read from '#{url.toString}' (#{e.message})" next ensure stream.close rescue nil diff --git a/src/main/ruby/jruby/rack/rails/environment.rb b/src/main/ruby/jruby/rack/rails/environment.rb deleted file mode 100644 index 3d4764ac6..000000000 --- a/src/main/ruby/jruby/rack/rails/environment.rb +++ /dev/null @@ -1,36 +0,0 @@ -#-- -# Copyright (c) 2010-2012 Engine Yard, Inc. -# Copyright (c) 2007-2009 Sun Microsystems, Inc. -# This source code is available under the MIT license. -# See the file LICENSE.txt for details. -#++ - -require 'jruby/rack/rails_booter' - -# Rails 3.x specific booter behavior. -# @see JRuby::Rack::Railtie -module JRuby::Rack::RailsBooter::RailsEnvironment - - # @return [Rails::Application] the (loaded) application instance - def to_app - # backward "compatibility" calling #to_app without a #load_environment - load_environment - ::Rails.application - end - - # Loads the Rails environment (*config/environment.rb*). - def load_environment - require expand_path('config/boot.rb') - require 'jruby/rack/rails/railtie' - require expand_path('config/environment.rb') - require 'jruby/rack/rails/extensions' - end - - protected - - # The public root is set in {JRuby::Rack::Railtie}. - def set_public_root - # no-op here - end - -end \ No newline at end of file diff --git a/src/main/ruby/jruby/rack/rails/railtie.rb b/src/main/ruby/jruby/rack/rails/railtie.rb index 567a8817e..69f2cc6a2 100644 --- a/src/main/ruby/jruby/rack/rails/railtie.rb +++ b/src/main/ruby/jruby/rack/rails/railtie.rb @@ -14,47 +14,30 @@ module JRuby::Rack class Railtie < ::Rails::Railtie config.before_configuration do |app| - paths = app.config.paths; public = JRuby::Rack.public_path - if paths.respond_to?(:'[]') && paths.respond_to?(:keys) - # Rails 3.1/3.2/4.x: paths["app/controllers"] style + public = JRuby::Rack.public_path + if public # nil if /public does not exist + paths = app.config.paths old_public = Pathname.new(paths['public'].to_a.first) javascripts = Pathname.new(paths['public/javascripts'].to_a.first) stylesheets = Pathname.new(paths['public/stylesheets'].to_a.first) paths['public'] = public.to_s; public = Pathname.new(public) paths['public/javascripts'] = public.join(javascripts.relative_path_from(old_public)).to_s paths['public/stylesheets'] = public.join(stylesheets.relative_path_from(old_public)).to_s - else - # Rails 3.0: old paths.app.controllers style - old_public = Pathname.new(paths.public.to_a.first) - javascripts = Pathname.new(paths.public.javascripts.to_a.first) - stylesheets = Pathname.new(paths.public.stylesheets.to_a.first) - paths.public = public.to_s; public = Pathname.new(public) - paths.public.javascripts = public.join(javascripts.relative_path_from(old_public)).to_s - paths.public.stylesheets = public.join(stylesheets.relative_path_from(old_public)).to_s - end if public # nil if /public does not exist + end end # TODO prefix initializers with 'jruby_rack.' !? initializer 'set_servlet_logger', :before => :initialize_logger do |app| app.config.logger ||= begin - config = app.config; logger = JRuby::Rack.logger + logger = JRuby::Rack.logger + config = app.config log_level = config.log_level || :info logger.level = logger.class.const_get(log_level.to_s.upcase) - log_formatter = config.log_formatter if config.respond_to?(:log_formatter) # >= 4.0 + log_formatter = config.log_formatter if config.respond_to?(:log_formatter) logger.formatter = log_formatter if log_formatter && logger.respond_to?(:formatter=) - if defined?(ActiveSupport::TaggedLogging) - if ActiveSupport::TaggedLogging.is_a?(Class) # Rails 3.2 - logger = ActiveSupport::TaggedLogging.new(logger) - else # Rails 4.0 - # extends the logger as well as it's logger.formatter instance : - # NOTE: good idea to keep or should we use a clone as Rails.logger ? - #dup_logger = logger.dup - #dup_logger.formatter = logger.formatter.dup - logger = ActiveSupport::TaggedLogging.new(logger) - end - end - logger + require 'active_support/tagged_logging' unless defined?(ActiveSupport::TaggedLogging) + ActiveSupport::TaggedLogging.new(logger) # returns a logger.clone end end diff --git a/src/main/ruby/jruby/rack/rails_booter.rb b/src/main/ruby/jruby/rack/rails_booter.rb index ead442f21..e4ba53013 100644 --- a/src/main/ruby/jruby/rack/rails_booter.rb +++ b/src/main/ruby/jruby/rack/rails_booter.rb @@ -26,12 +26,22 @@ def boot! super ENV['RAILS_ROOT'] = app_path ENV['RAILS_ENV'] = rails_env + self + end - require 'jruby/rack/rails/environment' - extend RailsEnvironment + # @return [Rails::Application] the (loaded) application instance + def to_app + # backward "compatibility" calling #to_app without a #load_environment + load_environment + ::Rails.application + end - set_public_root - self + # Loads the Rails environment (*config/environment.rb*). + def load_environment + require expand_path('config/boot.rb') + require 'jruby/rack/rails/railtie' + require expand_path('config/environment.rb') + require 'jruby/rack/rails/extensions' end protected @@ -42,12 +52,6 @@ def set_relative_url_root end end - # @see JRuby::Rack::RailsBooter::Rails2Environment#set_public_root - # @see JRuby::Rack::RailsBooter::Rails3Environment#set_public_root - def set_public_root - # no-op by default - leave as it is - end - # @deprecated no longer used, replaced with {#run_boot_hooks} def load_extensions # no-op diff --git a/src/main/ruby/rack/handler/servlet/default_env.rb b/src/main/ruby/rack/handler/servlet/default_env.rb index 3ef24ffd8..bf6786be4 100644 --- a/src/main/ruby/rack/handler/servlet/default_env.rb +++ b/src/main/ruby/rack/handler/servlet/default_env.rb @@ -20,9 +20,9 @@ class Servlet class DefaultEnv < Hash # The environment must be an instance of Hash ! BUILTINS = %w(rack.version rack.input rack.errors rack.url_scheme - rack.multithread rack.multiprocess rack.run_once + rack.multithread rack.multiprocess rack.run_once rack.hijack? java.servlet_request java.servlet_response java.servlet_context - jruby.rack.version jruby.rack.jruby.version jruby.rack.rack.release). + jruby.rack.version). map!(&:freeze) VARIABLES = %w(CONTENT_TYPE CONTENT_LENGTH PATH_INFO QUERY_STRING @@ -235,6 +235,7 @@ def load_builtin(env, key) when 'rack.multithread' then env[key] = true when 'rack.multiprocess' then env[key] = false when 'rack.run_once' then env[key] = false + when 'rack.hijack?' then env[key] = false when 'rack.input' then env[key] = @servlet_env ? JRuby::Rack::Input.new(@servlet_env) : nil when 'rack.errors' then context = rack_context @@ -248,8 +249,6 @@ def load_builtin(env, key) when 'java.servlet_context' then env[key] = servlet_context when 'jruby.rack.context' then env[key] = rack_context when 'jruby.rack.version' then env[key] = JRuby::Rack::VERSION - when 'jruby.rack.jruby.version' then env[key] = JRUBY_VERSION - when 'jruby.rack.rack.release' then env[key] = ::Rack.release else nil end diff --git a/src/spec/ruby/jruby/rack/app_layout_spec.rb b/src/spec/ruby/jruby/rack/app_layout_spec.rb index 20a1ebec4..dc9b2d966 100644 --- a/src/spec/ruby/jruby/rack/app_layout_spec.rb +++ b/src/spec/ruby/jruby/rack/app_layout_spec.rb @@ -218,7 +218,7 @@ it_behaves_like "FileSystemLayout" it "sets app uri from a rails.root context param" do - base = File.join File.dirname(__FILE__), '../../rails3x' + base = File.join File.dirname(__FILE__), '../../rails' @rack_context.should_receive(:getInitParameter).with("rails.root").and_return base expect( layout.app_uri ).to eq base expect( layout.app_path ).to eq File.expand_path(base) diff --git a/src/spec/ruby/jruby/rack/booter_spec.rb b/src/spec/ruby/jruby/rack/booter_spec.rb index 0a8c4e3af..516210bd3 100644 --- a/src/spec/ruby/jruby/rack/booter_spec.rb +++ b/src/spec/ruby/jruby/rack/booter_spec.rb @@ -10,11 +10,14 @@ describe JRuby::Rack::Booter do - let(:booter) do - JRuby::Rack::Booter.new JRuby::Rack.context = @rack_context - end + let(:context) { JRuby::Rack.context = @rack_context } + + let(:booter) { JRuby::Rack::Booter.new(context) } - after(:all) { JRuby::Rack.context = nil } + after(:all) do + JRuby::Rack.context = nil + JRuby::Rack.instance_variable_set(:@booter, nil) if JRuby::Rack.instance_variable_get(:@booter) + end before do @rack_env = ENV['RACK_ENV'] @@ -155,14 +158,6 @@ ENV['GEM_PATH'].should == "/blah/gems" end - it "creates a logger that writes messages to the servlet context (by default)" do - booter.boot! - @rack_context.stub(:isEnabled).and_return true - level = org.jruby.rack.RackLogger::Level::DEBUG - @rack_context.should_receive(:log).with(level, 'Hello-JRuby!') - booter.logger.debug 'Hello-JRuby!' - end - before { $loaded_init_rb = nil } it "loads and executes ruby code in META-INF/init.rb if it exists" do diff --git a/src/spec/ruby/jruby/rack/integration_spec.rb b/src/spec/ruby/jruby/rack/integration_spec.rb index acd546fb3..9a94037f8 100644 --- a/src/spec/ruby/jruby/rack/integration_spec.rb +++ b/src/spec/ruby/jruby/rack/integration_spec.rb @@ -87,14 +87,16 @@ let(:servlet_context) { new_servlet_context(base_path) } - it "initializes (pooling by default)" do + it "initializes pooling when min/max set" do + servlet_context.addInitParameter('jruby.min.runtimes', '1') + servlet_context.addInitParameter('jruby.max.runtimes', '2') + listener = org.jruby.rack.rails.RailsServletContextListener.new listener.contextInitialized javax.servlet.ServletContextEvent.new(servlet_context) rack_factory = servlet_context.getAttribute("rack.factory") rack_factory.should be_a(RackApplicationFactory) rack_factory.should be_a(PoolingRackApplicationFactory) - rack_factory.should respond_to(:realFactory) rack_factory.realFactory.should be_a(RailsRackApplicationFactory) servlet_context.getAttribute("rack.context").should be_a(RackContext) @@ -103,7 +105,19 @@ rack_factory.getApplication.should be_a(DefaultRackApplication) end - it "initializes threadsafe!" do + it "initializes shared (thread-safe) by default" do + listener = org.jruby.rack.rails.RailsServletContextListener.new + listener.contextInitialized javax.servlet.ServletContextEvent.new(servlet_context) + + rack_factory = servlet_context.getAttribute("rack.factory") + rack_factory.should be_a(RackApplicationFactory) + rack_factory.should be_a(SharedRackApplicationFactory) + rack_factory.realFactory.should be_a(RailsRackApplicationFactory) + + rack_factory.getApplication.should be_a(DefaultRackApplication) + end + + it "initializes shared (thread-safe) whem max runtimes is 1" do servlet_context.addInitParameter('jruby.max.runtimes', '1') listener = org.jruby.rack.rails.RailsServletContextListener.new diff --git a/src/spec/ruby/jruby/rack/logger_spec.rb b/src/spec/ruby/jruby/rack/logger_spec.rb index 2453307fc..2d9d6d478 100644 --- a/src/spec/ruby/jruby/rack/logger_spec.rb +++ b/src/spec/ruby/jruby/rack/logger_spec.rb @@ -116,17 +116,18 @@ end describe JRuby::Rack::ServletLog do + let(:servlet_context_logger) do + org.jruby.rack.logging.ServletContextLogger.new(servlet_context) + end it "writes messages to the servlet context" do - JRuby::Rack.context = rack_context = double('context') + JRuby::Rack.context = servlet_context_logger servlet_log = JRuby::Rack.send(:servlet_log) - rack_context.should_receive(:log).with(/hello/) servlet_log.write "hello" - rack_context.should_receive(:log).with(/hoja!/) + expect(real_logger.logged_content).to match(/hello/) servlet_log.puts "hoja!hoj" + expect(real_logger.logged_content).to match(/hoja!/) servlet_log.close end - end - end \ No newline at end of file diff --git a/src/spec/ruby/jruby/rack/rails_booter_spec.rb b/src/spec/ruby/jruby/rack/rails_booter_spec.rb index e8b23945d..040b1020e 100644 --- a/src/spec/ruby/jruby/rack/rails_booter_spec.rb +++ b/src/spec/ruby/jruby/rack/rails_booter_spec.rb @@ -99,17 +99,10 @@ rails_booter.public_path.should == "." end - it "uses JRuby-Rack's logger by default" do - booter.boot! - expect( booter.logger ).to_not be nil - expect( booter.logger ).to be JRuby::Rack.logger - booter.logger.info 'hello-there' - end - - RAILS_ROOT_DIR = File.expand_path("../../../rails3x", __FILE__) + RAILS_ROOT_DIR = File.expand_path("../../../rails", __FILE__) # NOTE: specs currently only test with a stubbed Rails::Railtie - describe "Rails 3.x", :lib => :stub do + describe "Rails (stubbed)", :lib => :stub do before :all do $LOAD_PATH.unshift File.join(RAILS_ROOT_DIR, 'stub') # for require 'rails/railtie' @@ -173,6 +166,21 @@ describe "logger" do + before(:all) do + @active_support = defined? ::ActiveSupport + @tagged_logging = active_support && ActiveSupport::TaggedLogging rescue false + end + + after(:all) do + if @tagged_logging == false + if @active_support + ActiveSupport.send :remove_const, :TaggedLogging + else + Object.send :remove_const, :ActiveSupport rescue nil + end + end + end + before do @app = double "app" @app.stub(:config).and_return @config = double("config") @@ -187,17 +195,17 @@ def logger=(logger); @logger = logger; end log_initializer[1].should == [{:before => :initialize_logger}] end - it "gets set as config.logger" do + it "gets set as config.logger (wrapped with tagged logging)" do logger = JRuby::Rack::Logger.new STDERR @config.stub(:log_level).and_return(:info) @config.stub(:log_formatter).and_return(nil) JRuby::Rack.should_receive(:logger).and_return(logger) - #logger.class.should_receive(:const_get).with('INFO').and_return(nil) - #logger.should_receive(:level=).with(nil) log_initializer.last.call(@app) - @app.config.logger.should be(logger) + rails_logger = @app.config.logger + # ActiveSupport::TaggedLogging.new clones the original logger instance + expect(rails_logger).to be_a(JRuby::Rack::Logger) end it "has a configurable log level" do @@ -206,38 +214,10 @@ def logger; @logger; end def logger=(logger); @logger = logger; end end @config.stub(:log_formatter).and_return(nil) - @config.should_receive(:log_level).and_return(:debug) + @config.should_receive(:log_level).and_return(:error) log_initializer.last.call(@app) ## - @app.config.logger.level.should be(JRuby::Rack::Logger::DEBUG) - end - - it "is wrapped in tagged logging" do # Rails 3.2 - active_support = defined? ::ActiveSupport - tagged_logging = active_support && ActiveSupport::TaggedLogging rescue nil - begin - klass = Class.new do # TaggedLogging stub - def initialize(logger); @logger = logger end - end - module ::ActiveSupport; end - ::ActiveSupport.const_set(:TaggedLogging, klass) - @config.stub(:log_level).and_return(nil) - @config.stub(:log_formatter).and_return(nil) - - log_initializer.last.call(@app) - @app.config.logger.should be_a(klass) - @app.config.logger.instance_variable_get(:@logger).should be_a(JRuby::Rack::Logger) - ensure - if tagged_logging.nil? - if active_support - ActiveSupport.send :remove_const, :TaggedLogging - else - Object.send :remove_const, :ActiveSupport rescue nil - end - else - ActiveSupport.const_set(:TaggedLogging, tagged_logging) - end - end + @app.config.logger.level.should be(JRuby::Rack::Logger::ERROR) end private diff --git a/src/spec/ruby/rack/embed/context_spec.rb b/src/spec/ruby/rack/embed/context_spec.rb index 1f7b1c69b..ab7d1eb43 100644 --- a/src/spec/ruby/rack/embed/context_spec.rb +++ b/src/spec/ruby/rack/embed/context_spec.rb @@ -17,7 +17,7 @@ end it "outputs log messages with level and new line to stdout" do - info = org.jruby.rack.embed.Context::INFO + info = org.jruby.rack.RackLogger::Level::INFO context.log info, "this is logging at its best" captured.should == "INFO: this is logging at its best\n" end diff --git a/src/spec/ruby/rack/servlet_context_listener_spec.rb b/src/spec/ruby/rack/servlet_context_listener_spec.rb index 4de971e71..b2df1708a 100644 --- a/src/spec/ruby/rack/servlet_context_listener_spec.rb +++ b/src/spec/ruby/rack/servlet_context_listener_spec.rb @@ -33,20 +33,19 @@ @listener.contextInitialized servlet_context_event end - it "logs an error if initialization failed" do - @factory.should_receive(:init).and_raise org.jruby.rack.RackInitializationException, "help" - @servlet_context.should_receive(:log) do |level, message, error| - level == 'ERROR' && message =~ /initialization failed/ && error.message == 'help' - end - @listener.contextInitialized servlet_context_event + it "throws an error if initialization failed" do + @servlet_context = org.springframework.mock.web.MockServletContext.new + @factory.should_receive(:init).and_raise org.jruby.rack.RackInitializationException.new("help") + + expect { @listener.contextInitialized(servlet_context_event) }.to raise_error(org.jruby.rack.RackInitializationException) end - it "throws an error if initialization failed (and jruby.rack.error = false)" do + it "does not throw if initialization failed (and jruby.rack.error = true)" do @servlet_context = org.springframework.mock.web.MockServletContext.new - @servlet_context.add_init_parameter 'jruby.rack.error', 'false' + @servlet_context.addInitParameter 'jruby.rack.error', 'true' @factory.should_receive(:init).and_raise org.jruby.rack.RackInitializationException.new("help") - expect { @listener.contextInitialized servlet_context_event }.to raise_error(org.jruby.rack.RackInitializationException) + expect { @listener.contextInitialized(servlet_context_event) }.to_not raise_error end end @@ -114,13 +113,20 @@ lambda { RailsServletContextListener.new }.should_not raise_error end - it "pools runtimes by default" do + it "shares a runtime by default" do factory = RailsServletContextListener.new. send(:newApplicationFactory, @rack_config) - factory.should be_a(org.jruby.rack.PoolingRackApplicationFactory) + factory.should be_a(org.jruby.rack.SharedRackApplicationFactory) end it "pools runtimes when max > 1" do + @rack_config.stub(:getMaximumRuntimes).and_return(2) + factory = RailsServletContextListener.new. + send(:newApplicationFactory, @rack_config) + factory.should be_a(org.jruby.rack.PoolingRackApplicationFactory) + end + + it "pools runtimes when max > 1 and serial initialization" do @rack_config.stub(:getMaximumRuntimes).and_return(3) @rack_config.stub(:isSerialInitialization).and_return(true) factory = RailsServletContextListener.new. diff --git a/src/spec/ruby/rails3x/config/application.rb b/src/spec/ruby/rails/config/application.rb similarity index 100% rename from src/spec/ruby/rails3x/config/application.rb rename to src/spec/ruby/rails/config/application.rb diff --git a/src/spec/ruby/rails3x/config/boot.rb b/src/spec/ruby/rails/config/boot.rb similarity index 100% rename from src/spec/ruby/rails3x/config/boot.rb rename to src/spec/ruby/rails/config/boot.rb diff --git a/src/spec/ruby/rails3x/config/environment.rb b/src/spec/ruby/rails/config/environment.rb similarity index 100% rename from src/spec/ruby/rails3x/config/environment.rb rename to src/spec/ruby/rails/config/environment.rb diff --git a/src/spec/ruby/rails3x/public/.gitkeep b/src/spec/ruby/rails/public/.gitkeep similarity index 100% rename from src/spec/ruby/rails3x/public/.gitkeep rename to src/spec/ruby/rails/public/.gitkeep diff --git a/src/spec/ruby/rails3x/stub/action_controller.rb b/src/spec/ruby/rails/stub/action_controller.rb similarity index 100% rename from src/spec/ruby/rails3x/stub/action_controller.rb rename to src/spec/ruby/rails/stub/action_controller.rb diff --git a/src/spec/ruby/rails3x/stub/active_support.rb b/src/spec/ruby/rails/stub/active_support.rb similarity index 100% rename from src/spec/ruby/rails3x/stub/active_support.rb rename to src/spec/ruby/rails/stub/active_support.rb diff --git a/src/spec/ruby/rails/stub/active_support/logger.rb b/src/spec/ruby/rails/stub/active_support/logger.rb new file mode 100644 index 000000000..fe7995b27 --- /dev/null +++ b/src/spec/ruby/rails/stub/active_support/logger.rb @@ -0,0 +1,88 @@ +# frozen_string_literal: true + +# require "active_support/logger_silence" +# require "active_support/logger_thread_safe_level" +require "logger" + +module ActiveSupport + class Logger < ::Logger + # include LoggerSilence + + # Returns true if the logger destination matches one of the sources + # + # logger = Logger.new(STDOUT) + # ActiveSupport::Logger.logger_outputs_to?(logger, STDOUT) + # # => true + def self.logger_outputs_to?(logger, *sources) + logdev = logger.instance_variable_get(:@logdev) + logger_source = logdev.dev if logdev.respond_to?(:dev) + sources.any? { |source| source == logger_source } + end + + # Broadcasts logs to multiple loggers. + def self.broadcast(logger) # :nodoc: + Module.new do + define_method(:add) do |*args, &block| + logger.add(*args, &block) + super(*args, &block) + end + + define_method(:<<) do |x| + logger << x + super(x) + end + + define_method(:close) do + logger.close + super() + end + + define_method(:progname=) do |name| + logger.progname = name + super(name) + end + + define_method(:formatter=) do |formatter| + logger.formatter = formatter + super(formatter) + end + + define_method(:level=) do |level| + logger.level = level + super(level) + end + + define_method(:local_level=) do |level| + logger.local_level = level if logger.respond_to?(:local_level=) + super(level) if respond_to?(:local_level=) + end + + define_method(:silence) do |level = Logger::ERROR, &block| + if logger.respond_to?(:silence) + logger.silence(level) do + if defined?(super) + super(level, &block) + else + block.call(self) + end + end + else + if defined?(super) + super(level, &block) + else + block.call(self) + end + end + end + end + end + + # Simple formatter which only displays the message. + class SimpleFormatter < ::Logger::Formatter + # This method is invoked when a log event occurs + def call(severity, timestamp, progname, msg) + "#{String === msg ? msg : msg.inspect}\n" + end + end + end +end diff --git a/src/spec/ruby/rails/stub/active_support/tagged_logging.rb b/src/spec/ruby/rails/stub/active_support/tagged_logging.rb new file mode 100644 index 000000000..5501de2d4 --- /dev/null +++ b/src/spec/ruby/rails/stub/active_support/tagged_logging.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require "active_support/logger" + +module ActiveSupport + # Wraps any standard Logger object to provide tagging capabilities. + # + # May be called with a block: + # + # logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT)) + # logger.tagged('BCX') { logger.info 'Stuff' } # Logs "[BCX] Stuff" + # logger.tagged('BCX', "Jason") { logger.info 'Stuff' } # Logs "[BCX] [Jason] Stuff" + # logger.tagged('BCX') { logger.tagged('Jason') { logger.info 'Stuff' } } # Logs "[BCX] [Jason] Stuff" + # + # If called without a block, a new logger will be returned with applied tags: + # + # logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT)) + # logger.tagged("BCX").info "Stuff" # Logs "[BCX] Stuff" + # logger.tagged("BCX", "Jason").info "Stuff" # Logs "[BCX] [Jason] Stuff" + # logger.tagged("BCX").tagged("Jason").info "Stuff" # Logs "[BCX] [Jason] Stuff" + # + # This is used by the default Rails.logger as configured by Railties to make + # it easy to stamp log lines with subdomains, request ids, and anything else + # to aid debugging of multi-user production applications. + module TaggedLogging + module Formatter # :nodoc: + # This method is invoked when a log event occurs. + def call(severity, timestamp, progname, msg) + super(severity, timestamp, progname, "#{tags_text}#{msg}") + end + end + + def self.new(logger) + logger = logger.clone + + if logger.formatter + logger.formatter = logger.formatter.dup + else + # Ensure we set a default formatter so we aren't extending nil! + logger.formatter = ActiveSupport::Logger::SimpleFormatter.new + end + + logger.formatter.extend Formatter + logger.extend(self) + end + end +end \ No newline at end of file diff --git a/src/spec/ruby/rails3x/stub/rails/railtie.rb b/src/spec/ruby/rails/stub/rails/railtie.rb similarity index 100% rename from src/spec/ruby/rails3x/stub/rails/railtie.rb rename to src/spec/ruby/rails/stub/rails/railtie.rb diff --git a/src/spec/ruby/spec_helper.rb b/src/spec/ruby/spec_helper.rb index e28a01cf9..a09660de1 100644 --- a/src/spec/ruby/spec_helper.rb +++ b/src/spec/ruby/spec_helper.rb @@ -21,8 +21,8 @@ require 'rspec' -require 'jruby'; ext_class = org.jruby.rack.ext.RackLibrary -JRuby.runtime.loadExtension 'JRuby::Rack', ext_class.new, true +require 'jruby' # we rely on JRuby.runtime in a few places +JRuby::Util.load_ext('org.jruby.rack.ext.RackLibrary') module SharedHelpers @@ -170,7 +170,7 @@ def should_not_eval_as_nil(code, runtime = @runtime) # alias rescue LoadError end -# current 'library' environment (based on appraisals) e.g. :rails32 +# current 'library' environment (based on appraisals) e.g. :rails72 CURRENT_LIB = defined?(Rails::VERSION) ? :"rails#{Rails::VERSION::MAJOR}#{Rails::VERSION::MINOR}" : :stub