) getHeaderNames.invoke( getResponse() );
- }
- catch (NoSuchMethodException e) { return null; }
- catch (IllegalAccessException e) { return null; }
- catch (InvocationTargetException e) { return null; }
- }
-
}
diff --git a/src/main/ruby/jruby/rack/chunked.rb b/src/main/ruby/jruby/rack/chunked.rb
index 0cdaf454..74c79b85 100644
--- a/src/main/ruby/jruby/rack/chunked.rb
+++ b/src/main/ruby/jruby/rack/chunked.rb
@@ -20,16 +20,4 @@ def each(&block)
@body.each(&block) # no-chunking on servlets
end
-end if defined? Rack::Chunked::Body
-
-unless defined? Rack::Chunked::Body # Rack 1.1
-
- Rack::Chunked.class_eval do
-
- def each(&block)
- @body.each(&block) # no-chunking on servlets
- end
-
- end
-
end
\ No newline at end of file
diff --git a/src/main/ruby/jruby/rack/helpers.rb b/src/main/ruby/jruby/rack/helpers.rb
index b19512f2..b5e2028c 100644
--- a/src/main/ruby/jruby/rack/helpers.rb
+++ b/src/main/ruby/jruby/rack/helpers.rb
@@ -134,7 +134,7 @@ def resolve_constant(camel_cased_name, context = Object)
require underscore(camel_cased_name)
retry
rescue LoadError => le
- e.message << " (#{le.message})"
+ e.message = "#{e.message} (#{le.message})"
end unless required
raise e
end
diff --git a/src/main/ruby/jruby/rack/rails/railtie.rb b/src/main/ruby/jruby/rack/rails/railtie.rb
index 1ef002ab..567a8817 100644
--- a/src/main/ruby/jruby/rack/rails/railtie.rb
+++ b/src/main/ruby/jruby/rack/rails/railtie.rb
@@ -6,6 +6,7 @@
# See the file LICENSE.txt for details.
#++
+require 'active_support'
require 'rails/railtie'
require 'pathname'
diff --git a/src/main/ruby/jruby/rack/session_store.rb b/src/main/ruby/jruby/rack/session_store.rb
index 860d6bc8..9aeb3f47 100644
--- a/src/main/ruby/jruby/rack/session_store.rb
+++ b/src/main/ruby/jruby/rack/session_store.rb
@@ -10,74 +10,38 @@
module JRuby::Rack
module Session
- if defined?(::Rack::Session::Abstract::SessionHash) # Rack 1.3+
+ class SessionHash < ::Rack::Session::Abstract::SessionHash
- # as of rails 3.1.x the rack session hash implementation is used
- # rather than the custom rails AbstractStore::SessionHash class
- class SessionHash < ::Rack::Session::Abstract::SessionHash; end
-
- # 1.5.0 removed SessionHash http://github.com/rack/rack/commit/83a270d64820
- OptionsHash = if defined?(::Rack::Session::Abstract::OptionsHash)
- ::Rack::Session::Abstract::OptionsHash
- else nil
+ def enabled? # Rails 7.0 added a need for this in Sessions, and forgot to make it optional within flash middleware
+ true
end
- elsif defined?(ActionDispatch::Session::AbstractStore) # Rails 3.0
-
- require 'active_support/core_ext/hash' # non-loaded SessionHash dependency
-
- class SessionHash < ActionDispatch::Session::AbstractStore::SessionHash; end
-
- OptionsHash = ActionDispatch::Session::AbstractStore::OptionsHash
-
- else # a fallback for (old) Rails 2.3
-
- class SessionHash < ActionController::Session::AbstractStore::SessionHash; end
-
- OptionsHash = ActionController::Session::AbstractStore::OptionsHash
-
- end
-
- SessionHash.class_eval do
-
# Allows direct delegation to servlet session methods when session is active
def method_missing(method, *args, &block)
- servlet_session = store.get_servlet_session(@env)
+ servlet_session = @store.get_servlet_session(@req.env)
if servlet_session && servlet_session.respond_to?(method)
servlet_session.send(method, *args, &block)
else
super
end
end
-
- private
- def store
- @store ||= defined?(@store) ? @store : @by # Rack 1.5 renamed @by
- end
-
end
# Rack based SessionStore implementation but compatible with (older) AbstractStore.
class SessionStore < ::Rack::Session::Abstract::ID
- ENV_SESSION_KEY = defined?(::Rack::Session::Abstract::ENV_SESSION_KEY) ?
- ::Rack::Session::Abstract::ENV_SESSION_KEY : 'rack.session'.freeze
-
- ENV_SESSION_OPTIONS_KEY = defined?(::Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY) ?
- ::Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY : 'rack.session.options'.freeze
-
ENV_SERVLET_SESSION_KEY = 'java.servlet_session'.freeze
-
RAILS_SESSION_KEY = "__current_rails_session".freeze
def initialize(app, options={})
super(app, options.merge!(:cookie_only => false, :defer => true))
end
- def context(env, app = @app) # adapt Rack 1.1/1.2 to be compatible with 1.3+
- prepare_session(env)
- status, headers, body = app.call(env)
- commit_session(env, status, headers, body)
+ def context(env, app = @app)
+ req = make_request env
+ prepare_session(req)
+ status, headers, body = app.call(req.env)
+ commit_session(req, status, headers, body)
end
# (public) servlet specific methods :
@@ -107,7 +71,9 @@ def get_servlet_session(env, create = false)
private # Rack::Session::Abstract::ID overrides :
- def session_class; ::JRuby::Rack::Session::SessionHash; end # Rack 1.5
+ def session_class
+ ::JRuby::Rack::Session::SessionHash
+ end
def initialize_sid
nil # dummy method - not usable with servlet API
@@ -117,20 +83,9 @@ def generate_sid(secure = @sid_secure)
nil # dummy method - no session id generation with servlet API
end
- def prepare_session(env) # exist since Rack 1.3
- session_was = env[ENV_SESSION_KEY]
- env[ENV_SESSION_KEY] = session_class.new(self, env)
- if options_hash = ::JRuby::Rack::Session::OptionsHash
- env[ENV_SESSION_OPTIONS_KEY] = options_hash.new(self, env, @default_options)
- else
- env[ENV_SESSION_OPTIONS_KEY] = @default_options.dup
- end
- env[ENV_SESSION_KEY].merge! session_was if session_was
- end
-
- def load_session(env, session_id = nil) # session_id arg for get_session alias
+ def load_session(req) # session_id arg for get_session alias
session_id, session = false, {}
- if servlet_session = get_servlet_session(env)
+ if servlet_session = get_servlet_session(req.env)
begin
session_id = servlet_session.getId
servlet_session.synchronized do
@@ -152,33 +107,27 @@ def load_session(env, session_id = nil) # session_id arg for get_session alias
end
[ session_id, session ]
end
- alias :get_session :load_session # for AbstractStore::SessionHash compatibility
- def extract_session_id(env)
- servlet_session = get_servlet_session(env)
+ def extract_session_id(req)
+ servlet_session = get_servlet_session(req.env)
servlet_session.getId rescue nil if servlet_session
end
- def current_session_id(env)
- env[ENV_SESSION_OPTIONS_KEY][:id] # 1.5.0: env[ENV_SESSION_KEY].id
- end if ::JRuby::Rack::Session::OptionsHash
-
- def session_exists?(env)
- value = current_session_id(env)
+ def session_exists?(req)
+ value = current_session_id(req)
value && ! value.empty?
end
- alias :exists? :session_exists? # for AbstractStore::SessionHash compatibility
def loaded_session?(session)
! session.is_a?(::JRuby::Rack::Session::SessionHash) || session.loaded?
end
- def commit_session(env, status, headers, body)
- session = env[ENV_SESSION_KEY]
- options = env[ENV_SESSION_OPTIONS_KEY]
+ def commit_session(req, status, headers, body)
+ session = req.env[::Rack::RACK_SESSION]
+ options = req.env[::Rack::RACK_SESSION_OPTIONS]
if options[:drop] || options[:renew]
- destroy_session(env, options[:id], options)
+ destroy_session(req.env, options[:id], options)
end
return [status, headers, body] if options[:drop] || options[:skip]
@@ -186,8 +135,8 @@ def commit_session(env, status, headers, body)
if loaded_session?(session)
session_id = session.respond_to?(:id=) ? session.id : options[:id]
session_data = session.to_hash.delete_if { |_,v| v.nil? }
- unless set_session(env, session_id, session_data, options)
- env["rack.errors"].puts("WARNING #{self.class.name} failed to save session. Content dropped.")
+ unless set_session(req.env, session_id, session_data, options)
+ req.env["rack.errors"].puts("WARNING #{self.class.name} failed to save session. Content dropped.")
end
end
@@ -245,7 +194,6 @@ def destroy_session(env, session_id = nil, options = nil)
rescue java.lang.IllegalStateException # if session already invalid
nil
end
- alias :destroy :destroy_session # for AbstractStore::SessionHash compatibility
end
diff --git a/src/spec/java/org/jruby/rack/mock/DelegatingServletInputStream.java b/src/spec/java/org/jruby/rack/mock/DelegatingServletInputStream.java
deleted file mode 100644
index d8694c00..00000000
--- a/src/spec/java/org/jruby/rack/mock/DelegatingServletInputStream.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2002-2013 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jruby.rack.mock;
-
-import java.io.IOException;
-import java.io.InputStream;
-import javax.servlet.ServletInputStream;
-
-/**
- * Delegating implementation of {@link javax.servlet.ServletInputStream}.
- *
- * Used by {@link MockHttpServletRequest}; typically not directly
- * used for testing application controllers.
- *
- * @author Juergen Hoeller
- * @since 1.0.2
- * @see MockHttpServletRequest
- */
-public class DelegatingServletInputStream extends ServletInputStream {
-
- private final InputStream sourceStream;
-
-
- /**
- * Create a DelegatingServletInputStream for the given source stream.
- * @param sourceStream the source stream (never null
)
- */
- public DelegatingServletInputStream(InputStream sourceStream) {
- this.sourceStream = sourceStream;
- }
-
- /**
- * Return the underlying source stream (never null
).
- */
- public final InputStream getSourceStream() {
- return this.sourceStream;
- }
-
-
- public int read() throws IOException {
- return this.sourceStream.read();
- }
-
- public void close() throws IOException {
- super.close();
- this.sourceStream.close();
- }
-
-}
diff --git a/src/spec/java/org/jruby/rack/mock/DelegatingServletOutputStream.java b/src/spec/java/org/jruby/rack/mock/DelegatingServletOutputStream.java
deleted file mode 100644
index e4c5feb7..00000000
--- a/src/spec/java/org/jruby/rack/mock/DelegatingServletOutputStream.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2002-2013 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jruby.rack.mock;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import javax.servlet.ServletOutputStream;
-
-/**
- * Delegating implementation of {@link javax.servlet.ServletOutputStream}.
- *
- *
Used by {@link MockHttpServletResponse}; typically not directly
- * used for testing application controllers.
- *
- * @author Juergen Hoeller
- * @since 1.0.2
- * @see MockHttpServletResponse
- */
-public class DelegatingServletOutputStream extends ServletOutputStream {
-
- private final OutputStream targetStream;
-
- /**
- * Create a DelegatingServletOutputStream for the given target stream.
- * @param targetStream the target stream (never null
)
- */
- public DelegatingServletOutputStream(OutputStream targetStream) {
- this.targetStream = targetStream;
- }
-
- /**
- * Return the underlying target stream (never null
).
- */
- public final OutputStream getTargetStream() {
- return this.targetStream;
- }
-
- public void write(int b) throws IOException {
- this.targetStream.write(b);
- }
-
- @Override
- public void flush() throws IOException {
- super.flush();
- this.targetStream.flush();
- }
-
- @Override
- public void close() throws IOException {
- super.close();
- this.targetStream.close();
- }
-
-}
diff --git a/src/spec/java/org/jruby/rack/mock/HeaderValueHolder.java b/src/spec/java/org/jruby/rack/mock/HeaderValueHolder.java
deleted file mode 100644
index 1565e618..00000000
--- a/src/spec/java/org/jruby/rack/mock/HeaderValueHolder.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright 2002-2013 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jruby.rack.mock;
-
-import java.lang.reflect.Array;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Internal helper class that serves as value holder for request headers.
- *
- * @author Juergen Hoeller
- * @author Rick Evans
- */
-class HeaderValueHolder {
-
- private final List values = new LinkedList();
-
- public void setValue(Object value) {
- this.values.clear();
- this.values.add(value);
- }
-
- public void addValue(Object value) {
- this.values.add(value);
- }
-
- public void addValues(Collection> values) {
- this.values.addAll(values);
- }
-
- public void addValueArray(Object values) {
- mergeArrayIntoCollection(values, this.values);
- }
-
- public List getValues() {
- return Collections.unmodifiableList(this.values);
- }
-
- public List getStringValues() {
- List stringList = new ArrayList(this.values.size());
- for (Object value : this.values) {
- stringList.add(value.toString());
- }
- return Collections.unmodifiableList(stringList);
- }
-
- public Object getValue() {
- return (!this.values.isEmpty() ? this.values.get(0) : null);
- }
-
- public String getStringValue() {
- return (!this.values.isEmpty() ? this.values.get(0).toString() : null);
- }
-
-
- /**
- * Find a HeaderValueHolder by name, ignoring casing.
- * @param headers the Map of header names to HeaderValueHolders
- * @param name the name of the desired header
- * @return the corresponding HeaderValueHolder,
- * or null
if none found
- */
- public static HeaderValueHolder getByName(Map headers, String name) {
- for (String headerName : headers.keySet()) {
- if (headerName.equalsIgnoreCase(name)) {
- return headers.get(headerName);
- }
- }
- return null;
- }
-
- /**
- * Merge the given array into the given Collection.
- * @param array the array to merge (may be null
)
- * @param collection the target Collection to merge the array into
- */
- @SuppressWarnings({"unchecked","rawtypes"})
- private static void mergeArrayIntoCollection(Object array, Collection collection) {
- if (collection == null) {
- throw new IllegalArgumentException("Collection must not be null");
- }
- Object[] arr = toObjectArray(array);
- for (Object elem : arr) {
- collection.add(elem);
- }
- }
-
- /**
- * Convert the given array (which may be a primitive array) to an
- * object array (if necessary of primitive wrapper objects).
- * A null
source value will be converted to an
- * empty Object array.
- * @param source the (potentially primitive) array
- * @return the corresponding object array (never null
)
- * @throws IllegalArgumentException if the parameter is not an array
- */
- private static Object[] toObjectArray(Object source) {
- if (source instanceof Object[]) {
- return (Object[]) source;
- }
- if (source == null) {
- return new Object[0];
- }
- if (!source.getClass().isArray()) {
- throw new IllegalArgumentException("Source is not an array: " + source);
- }
- int length = Array.getLength(source);
- if (length == 0) {
- return new Object[0];
- }
- Class> wrapperType = Array.get(source, 0).getClass();
- Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
- for (int i = 0; i < length; i++) {
- newArray[i] = Array.get(source, i);
- }
- return newArray;
- }
-
-}
diff --git a/src/spec/java/org/jruby/rack/mock/LinkedCaseInsensitiveMap.java b/src/spec/java/org/jruby/rack/mock/LinkedCaseInsensitiveMap.java
deleted file mode 100644
index ad45d067..00000000
--- a/src/spec/java/org/jruby/rack/mock/LinkedCaseInsensitiveMap.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright 2002-2013 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jruby.rack.mock;
-
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * {@link LinkedHashMap} variant that stores String keys in a case-insensitive
- * manner, for example for key-based access in a results table.
- *
- *
Preserves the original order as well as the original casing of keys,
- * while allowing for contains, get and remove calls with any case of key.
- *
- *
Does not support null
keys.
- *
- * @author Juergen Hoeller
- */
-@SuppressWarnings("serial")
-class LinkedCaseInsensitiveMap extends LinkedHashMap {
-
- private final Map caseInsensitiveKeys;
-
- private final Locale locale;
-
-
- /**
- * Create a new LinkedCaseInsensitiveMap for the default Locale.
- * @see java.lang.String#toLowerCase()
- */
- public LinkedCaseInsensitiveMap() {
- this(null);
- }
-
- /**
- * Create a new LinkedCaseInsensitiveMap that stores lower-case keys
- * according to the given Locale.
- * @param locale the Locale to use for lower-case conversion
- * @see java.lang.String#toLowerCase(java.util.Locale)
- */
- public LinkedCaseInsensitiveMap(Locale locale) {
- super();
- this.caseInsensitiveKeys = new HashMap();
- this.locale = (locale != null ? locale : Locale.getDefault());
- }
-
- /**
- * Create a new LinkedCaseInsensitiveMap that wraps a {@link LinkedHashMap}
- * with the given initial capacity and stores lower-case keys according
- * to the default Locale.
- * @param initialCapacity the initial capacity
- * @see java.lang.String#toLowerCase()
- */
- public LinkedCaseInsensitiveMap(int initialCapacity) {
- this(initialCapacity, null);
- }
-
- /**
- * Create a new LinkedCaseInsensitiveMap that wraps a {@link LinkedHashMap}
- * with the given initial capacity and stores lower-case keys according
- * to the given Locale.
- * @param initialCapacity the initial capacity
- * @param locale the Locale to use for lower-case conversion
- * @see java.lang.String#toLowerCase(java.util.Locale)
- */
- public LinkedCaseInsensitiveMap(int initialCapacity, Locale locale) {
- super(initialCapacity);
- this.caseInsensitiveKeys = new HashMap(initialCapacity);
- this.locale = (locale != null ? locale : Locale.getDefault());
- }
-
-
- @Override
- public V put(String key, V value) {
- this.caseInsensitiveKeys.put(convertKey(key), key);
- return super.put(key, value);
- }
-
- @Override
- public boolean containsKey(Object key) {
- return (key instanceof String && this.caseInsensitiveKeys.containsKey(convertKey((String) key)));
- }
-
- @Override
- public V get(Object key) {
- if (key instanceof String) {
- return super.get(this.caseInsensitiveKeys.get(convertKey((String) key)));
- }
- else {
- return null;
- }
- }
-
- @Override
- public V remove(Object key) {
- if (key instanceof String ) {
- return super.remove(this.caseInsensitiveKeys.remove(convertKey((String) key)));
- }
- else {
- return null;
- }
- }
-
- @Override
- public void clear() {
- this.caseInsensitiveKeys.clear();
- super.clear();
- }
-
-
- /**
- * Convert the given key to a case-insensitive key.
- * The default implementation converts the key
- * to lower-case according to this Map's Locale.
- * @param key the user-specified key
- * @return the key to use for storing
- * @see java.lang.String#toLowerCase(java.util.Locale)
- */
- protected String convertKey(String key) {
- return key.toLowerCase(this.locale);
- }
-
-}
\ No newline at end of file
diff --git a/src/spec/java/org/jruby/rack/mock/MockAsyncContext.java b/src/spec/java/org/jruby/rack/mock/MockAsyncContext.java
deleted file mode 100644
index ab291817..00000000
--- a/src/spec/java/org/jruby/rack/mock/MockAsyncContext.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright 2002-2013 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.jruby.rack.mock;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import javax.servlet.AsyncContext;
-import javax.servlet.AsyncEvent;
-import javax.servlet.AsyncListener;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-//import org.springframework.beans.BeanUtils;
-//import org.springframework.web.util.WebUtils;
-
-/**
- * Mock implementation of the {@link AsyncContext} interface.
- *
- * @author Rossen Stoyanchev
- */
-public class MockAsyncContext implements AsyncContext {
-
- private final HttpServletRequest request;
-
- private final HttpServletResponse response;
-
- private final List listeners = new ArrayList();
-
- private String dispatchedPath;
-
- private long timeout = 10 * 1000L; // 10 seconds is Tomcat's default
-
- private final List dispatchHandlers = new ArrayList();
-
-
- public MockAsyncContext(ServletRequest request, ServletResponse response) {
- this.request = (HttpServletRequest) request;
- this.response = (HttpServletResponse) response;
- }
-
-
- public void addDispatchHandler(Runnable handler) {
- this.dispatchHandlers.add(handler);
- }
-
- @Override
- public ServletRequest getRequest() {
- return this.request;
- }
-
- @Override
- public ServletResponse getResponse() {
- return this.response;
- }
-
- @Override
- public boolean hasOriginalRequestAndResponse() {
- return (this.request instanceof MockHttpServletRequest) && (this.response instanceof MockHttpServletResponse);
- }
-
- @Override
- public void dispatch() {
- dispatch(this.request.getRequestURI());
- }
-
- @Override
- public void dispatch(String path) {
- dispatch(null, path);
- }
-
- @Override
- public void dispatch(ServletContext context, String path) {
- this.dispatchedPath = path;
- for (Runnable r : this.dispatchHandlers) {
- r.run();
- }
- }
-
- public String getDispatchedPath() {
- return this.dispatchedPath;
- }
-
- @Override
- public void complete() {
- MockHttpServletRequest mockRequest = WebUtils.getNativeRequest(request, MockHttpServletRequest.class);
- if (mockRequest != null) {
- mockRequest.setAsyncStarted(false);
- }
- for (AsyncListener listener : this.listeners) {
- try {
- listener.onComplete(new AsyncEvent(this, this.request, this.response));
- }
- catch (IOException e) {
- throw new IllegalStateException("AsyncListener failure", e);
- }
- }
- }
-
- @Override
- public void start(Runnable runnable) {
- runnable.run();
- }
-
- @Override
- public void addListener(AsyncListener listener) {
- this.listeners.add(listener);
- }
-
- @Override
- public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) {
- this.listeners.add(listener);
- }
-
- public List getListeners() {
- return this.listeners;
- }
-
- @Override
- public T createListener(Class clazz) throws ServletException {
- return instantiate(clazz); // BeanUtils.instantiateClass(clazz);
- }
-
- @Override
- public void setTimeout(long timeout) {
- this.timeout = timeout;
- }
-
- @Override
- public long getTimeout() {
- return this.timeout;
- }
-
- private static T instantiate(Class clazz) throws IllegalArgumentException {
- if (clazz.isInterface()) {
- throw new IllegalArgumentException(clazz + " is an interface");
- }
- try {
- return clazz.newInstance();
- }
- catch (InstantiationException ex) {
- throw new IllegalArgumentException(clazz + " is it an abstract class?", ex);
- }
- catch (IllegalAccessException ex) {
- throw new IllegalArgumentException(clazz + " constructor accessible?", ex);
- }
- }
-
-}
diff --git a/src/spec/java/org/jruby/rack/mock/MockHttpServletRequest.java b/src/spec/java/org/jruby/rack/mock/MockHttpServletRequest.java
deleted file mode 100644
index c3be6d4a..00000000
--- a/src/spec/java/org/jruby/rack/mock/MockHttpServletRequest.java
+++ /dev/null
@@ -1,1018 +0,0 @@
-/*
- * Copyright 2002-2013 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jruby.rack.mock;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.UnsupportedEncodingException;
-import java.security.Principal;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-import java.util.Vector;
-
-import javax.servlet.AsyncContext;
-import javax.servlet.DispatcherType;
-import javax.servlet.RequestDispatcher;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletInputStream;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-import javax.servlet.http.Part;
-
-/**
- * Mock implementation of the {@link javax.servlet.http.HttpServletRequest} interface.
- *
- * As of Spring 4.0, this set of mocks is designed on a Servlet 3.0 baseline.
- *
- * @author Juergen Hoeller
- * @author Rod Johnson
- * @author Rick Evans
- * @author Mark Fisher
- * @author Chris Beams
- * @author Sam Brannen
- */
-public class MockHttpServletRequest implements HttpServletRequest {
-
- /**
- * The default protocol: 'http'.
- */
- public static final String DEFAULT_PROTOCOL = "http";
-
- /**
- * The default server address: '127.0.0.1'.
- */
- public static final String DEFAULT_SERVER_ADDR = "127.0.0.1";
-
- /**
- * The default server name: 'localhost'.
- */
- public static final String DEFAULT_SERVER_NAME = "localhost";
-
- /**
- * The default server port: '80'.
- */
- public static final int DEFAULT_SERVER_PORT = 80;
-
- /**
- * The default remote address: '127.0.0.1'.
- */
- public static final String DEFAULT_REMOTE_ADDR = "127.0.0.1";
-
- /**
- * The default remote host: 'localhost'.
- */
- public static final String DEFAULT_REMOTE_HOST = "localhost";
-
- private boolean active = true;
-
-
- // ---------------------------------------------------------------------
- // ServletRequest properties
- // ---------------------------------------------------------------------
-
- private final Map attributes = new LinkedHashMap();
-
- private String characterEncoding;
-
- private byte[] content;
-
- private String contentType;
-
- private ServletInputStream inputStream;
- private BufferedReader reader;
-
- private final Map parameters = new LinkedHashMap(16);
-
- private String protocol = DEFAULT_PROTOCOL;
-
- private String scheme = DEFAULT_PROTOCOL;
-
- private String serverName = DEFAULT_SERVER_NAME;
-
- private int serverPort = DEFAULT_SERVER_PORT;
-
- private String remoteAddr = DEFAULT_REMOTE_ADDR;
-
- private String remoteHost = DEFAULT_REMOTE_HOST;
-
- /** List of locales in descending order */
- private final List locales = new LinkedList();
-
- private boolean secure = false;
-
- private final ServletContext servletContext;
-
- private int remotePort = DEFAULT_SERVER_PORT;
-
- private String localName = DEFAULT_SERVER_NAME;
-
- private String localAddr = DEFAULT_SERVER_ADDR;
-
- private int localPort = DEFAULT_SERVER_PORT;
-
- private boolean asyncStarted = false;
-
- private boolean asyncSupported = false;
-
- private MockAsyncContext asyncContext;
-
- private DispatcherType dispatcherType = DispatcherType.REQUEST;
-
- // ---------------------------------------------------------------------
- // HttpServletRequest properties
- // ---------------------------------------------------------------------
-
- private String authType;
-
- private Cookie[] cookies;
-
- private final Map headers = new LinkedCaseInsensitiveMap();
-
- private String method;
-
- private String pathInfo;
-
- private String contextPath = "";
-
- private String queryString;
-
- private String remoteUser;
-
- private final Set userRoles = new HashSet();
-
- private Principal userPrincipal;
-
- private String requestedSessionId;
-
- private String requestURI;
-
- private String servletPath = "";
-
- private HttpSession session;
-
- private boolean requestedSessionIdValid = true;
-
- private boolean requestedSessionIdFromCookie = true;
-
- private boolean requestedSessionIdFromURL = false;
-
- private final Map parts = new LinkedHashMap();
-
-
- // ---------------------------------------------------------------------
- // Constructors
- // ---------------------------------------------------------------------
-
- /**
- * Create a new MockHttpServletRequest with a default
- * {@link MockServletContext}.
- * @see MockServletContext
- */
- public MockHttpServletRequest() {
- this(null, "", "");
- }
-
- /**
- * Create a new MockHttpServletRequest with a default
- * {@link MockServletContext}.
- * @param method the request method (may be null
)
- * @param requestURI the request URI (may be null
)
- * @see #setMethod
- * @see #setRequestURI
- * @see MockServletContext
- */
- public MockHttpServletRequest(String method, String requestURI) {
- this(null, method, requestURI);
- }
-
- /**
- * Create a new MockHttpServletRequest.
- * @param servletContext the ServletContext that the request runs in (may be
- * null
to use a default MockServletContext)
- * @see MockServletContext
- */
- public MockHttpServletRequest(ServletContext servletContext) {
- this(servletContext, "", "");
- }
-
- /**
- * Create a new MockHttpServletRequest.
- * @param servletContext the ServletContext that the request runs in (may be
- * null
to use a default MockServletContext)
- * @param method the request method (may be null
)
- * @param requestURI the request URI (may be null
)
- * @see #setMethod
- * @see #setRequestURI
- * @see MockServletContext
- */
- public MockHttpServletRequest(ServletContext servletContext, String method, String requestURI) {
- this.servletContext = servletContext;
- this.method = method;
- this.requestURI = requestURI;
- this.locales.add(Locale.ENGLISH);
- }
-
-
- // ---------------------------------------------------------------------
- // Lifecycle methods
- // ---------------------------------------------------------------------
-
- /**
- * Return the ServletContext that this request is associated with. (Not
- * available in the standard HttpServletRequest interface for some reason.)
- */
- @Override
- public ServletContext getServletContext() {
- return this.servletContext;
- }
-
- /**
- * Return whether this request is still active (that is, not completed yet).
- */
- public boolean isActive() {
- return this.active;
- }
-
- /**
- * Mark this request as completed, keeping its state.
- */
- public void close() {
- this.active = false;
- }
-
- /**
- * Invalidate this request, clearing its state.
- */
- public void invalidate() {
- close();
- clearAttributes();
- }
-
- /**
- * Check whether this request is still active (that is, not completed yet),
- * throwing an IllegalStateException if not active anymore.
- */
- protected void checkActive() throws IllegalStateException {
- if (!this.active) {
- throw new IllegalStateException("Request is not active anymore");
- }
- }
-
-
- // ---------------------------------------------------------------------
- // ServletRequest interface
- // ---------------------------------------------------------------------
-
- @Override
- public Object getAttribute(String name) {
- checkActive();
- return this.attributes.get(name);
- }
-
- @Override
- public Enumeration getAttributeNames() {
- checkActive();
- return new Vector(this.attributes.keySet()).elements();
- }
-
- @Override
- public String getCharacterEncoding() {
- return this.characterEncoding;
- }
-
- @Override
- public void setCharacterEncoding(String characterEncoding) {
- this.characterEncoding = characterEncoding;
- }
-
- public void setContent(byte[] content) {
- this.content = content;
- }
-
- @Override
- public int getContentLength() {
- return (this.content != null ? this.content.length : -1);
- }
-
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
-
- @Override
- public String getContentType() {
- return this.contentType;
- }
-
- @Override
- public ServletInputStream getInputStream() throws IllegalStateException {
- // NOTE: make sure it behaves like a real ServletRequest :
- if (this.reader != null) {
- throw new IllegalStateException("getReader() method has already been called for this request");
- }
- if (this.inputStream != null) return this.inputStream;
-
- if (this.content != null) {
- return this.inputStream = new DelegatingServletInputStream(new ByteArrayInputStream(this.content));
- }
- else {
- return null;
- }
- }
-
- public void resetInputStream() {
- this.inputStream = null;
- }
-
- /**
- * Set a single value for the specified HTTP parameter.
- *
- * If there are already one or more values registered for the given
- * parameter name, they will be replaced.
- */
- public void setParameter(String name, String value) {
- setParameter(name, new String[] { value });
- }
-
- /**
- * Set an array of values for the specified HTTP parameter.
- *
- * If there are already one or more values registered for the given
- * parameter name, they will be replaced.
- */
- public void setParameter(String name, String[] values) {
- this.parameters.put(name, values);
- }
-
- /**
- * Sets all provided parameters replacing any existing
- * values for the provided parameter names. To add without replacing
- * existing values, use {@link #addParameters(java.util.Map)}.
- */
- @SuppressWarnings("rawtypes")
- public void setParameters(Map params) {
- for (Object key : params.keySet()) {
- Object value = params.get(key);
- if (value instanceof String) {
- this.setParameter((String) key, (String) value);
- }
- else if (value instanceof String[]) {
- this.setParameter((String) key, (String[]) value);
- }
- else {
- throw new IllegalArgumentException("Parameter map value must be single value " + " or array of type ["
- + String.class.getName() + "]");
- }
- }
- }
-
- /**
- * Add a single value for the specified HTTP parameter.
- *
- * If there are already one or more values registered for the given
- * parameter name, the given value will be added to the end of the list.
- */
- public void addParameter(String name, String value) {
- addParameter(name, new String[] { value });
- }
-
- /**
- * Add an array of values for the specified HTTP parameter.
- *
- * If there are already one or more values registered for the given
- * parameter name, the given values will be added to the end of the list.
- */
- public void addParameter(String name, String[] values) {
- String[] oldArr = this.parameters.get(name);
- if (oldArr != null) {
- String[] newArr = new String[oldArr.length + values.length];
- System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
- System.arraycopy(values, 0, newArr, oldArr.length, values.length);
- this.parameters.put(name, newArr);
- }
- else {
- this.parameters.put(name, values);
- }
- }
-
- /**
- * Adds all provided parameters without replacing any
- * existing values. To replace existing values, use
- * {@link #setParameters(java.util.Map)}.
- */
- @SuppressWarnings("rawtypes")
- public void addParameters(Map params) {
- for (Object key : params.keySet()) {
- Object value = params.get(key);
- if (value instanceof String) {
- this.addParameter((String) key, (String) value);
- }
- else if (value instanceof String[]) {
- this.addParameter((String) key, (String[]) value);
- }
- else {
- throw new IllegalArgumentException("Parameter map value must be single value " + " or array of type ["
- + String.class.getName() + "]");
- }
- }
- }
-
- /**
- * Remove already registered values for the specified HTTP parameter, if
- * any.
- */
- public void removeParameter(String name) {
- this.parameters.remove(name);
- }
-
- /**
- * Removes all existing parameters.
- */
- public void removeAllParameters() {
- this.parameters.clear();
- }
-
- @Override
- public String getParameter(String name) {
- String[] arr = this.parameters.get(name);
- return (arr != null && arr.length > 0 ? arr[0] : null);
- }
-
- @Override
- public Enumeration getParameterNames() {
- return Collections.enumeration(this.parameters.keySet());
- }
-
- @Override
- public String[] getParameterValues(String name) {
- return this.parameters.get(name);
- }
-
- @Override
- public Map getParameterMap() {
- return Collections.unmodifiableMap(this.parameters);
- }
-
- public void setProtocol(String protocol) {
- this.protocol = protocol;
- }
-
- @Override
- public String getProtocol() {
- return this.protocol;
- }
-
- public void setScheme(String scheme) {
- this.scheme = scheme;
- }
-
- @Override
- public String getScheme() {
- return this.scheme;
- }
-
- public void setServerName(String serverName) {
- this.serverName = serverName;
- }
-
- @Override
- public String getServerName() {
- return this.serverName;
- }
-
- public void setServerPort(int serverPort) {
- this.serverPort = serverPort;
- }
-
- @Override
- public int getServerPort() {
- return this.serverPort;
- }
-
- @Override
- public BufferedReader getReader() throws UnsupportedEncodingException {
- // NOTE: make sure it behaves like a real ServletRequest :
- if (this.inputStream != null) {
- throw new IllegalStateException("getInputStream() method has already been called for this request");
- }
- if (this.reader != null) return this.reader;
-
- if (this.content != null) {
- InputStream sourceStream = new ByteArrayInputStream(this.content);
- Reader sourceReader = (this.characterEncoding != null) ? new InputStreamReader(sourceStream,
- this.characterEncoding) : new InputStreamReader(sourceStream);
- return this.reader = new BufferedReader(sourceReader);
- }
- else {
- return null;
- }
- }
-
- public void setRemoteAddr(String remoteAddr) {
- this.remoteAddr = remoteAddr;
- }
-
- @Override
- public String getRemoteAddr() {
- return this.remoteAddr;
- }
-
- public void setRemoteHost(String remoteHost) {
- this.remoteHost = remoteHost;
- }
-
- @Override
- public String getRemoteHost() {
- return this.remoteHost;
- }
-
- @Override
- public void setAttribute(String name, Object value) {
- checkActive();
- if (value != null) {
- this.attributes.put(name, value);
- }
- else {
- this.attributes.remove(name);
- }
- }
-
- @Override
- public void removeAttribute(String name) {
- checkActive();
- this.attributes.remove(name);
- }
-
- /**
- * Clear all of this request's attributes.
- */
- public void clearAttributes() {
- this.attributes.clear();
- }
-
- /**
- * Add a new preferred locale, before any existing locales.
- */
- public void addPreferredLocale(Locale locale) {
- this.locales.add(0, locale);
- }
-
- @Override
- public Locale getLocale() {
- return this.locales.get(0);
- }
-
- @Override
- public Enumeration getLocales() {
- return Collections.enumeration(this.locales);
- }
-
- public void setSecure(boolean secure) {
- this.secure = secure;
- }
-
- @Override
- public boolean isSecure() {
- return this.secure;
- }
-
- @Override
- public RequestDispatcher getRequestDispatcher(String path) {
- return new MockRequestDispatcher(path);
- }
-
- @Override @Deprecated
- public String getRealPath(String path) {
- return this.servletContext.getRealPath(path);
- }
-
- public void setRemotePort(int remotePort) {
- this.remotePort = remotePort;
- }
-
- @Override
- public int getRemotePort() {
- return this.remotePort;
- }
-
- public void setLocalName(String localName) {
- this.localName = localName;
- }
-
- @Override
- public String getLocalName() {
- return this.localName;
- }
-
- public void setLocalAddr(String localAddr) {
- this.localAddr = localAddr;
- }
-
- @Override
- public String getLocalAddr() {
- return this.localAddr;
- }
-
- public void setLocalPort(int localPort) {
- this.localPort = localPort;
- }
-
- @Override
- public int getLocalPort() {
- return this.localPort;
- }
-
-
- // ---------------------------------------------------------------------
- // HttpServletRequest interface
- // ---------------------------------------------------------------------
-
- public void setAuthType(String authType) {
- this.authType = authType;
- }
-
- @Override
- public String getAuthType() {
- return this.authType;
- }
-
- /**
- * Return the set of Cookies received with this Request.
- */
- @Override
- public Cookie[] getCookies() {
- return cookies;
- }
-
- /**
- * Set the set of cookies received with this Request.
- */
- public void setCookies(Cookie... cookies) {
- this.cookies = cookies;
- }
-
- /**
- * Add a header entry for the given name.
- * If there was no entry for that header name before, the value will be used
- * as-is. In case of an existing entry, a String array will be created,
- * adding the given value (more specifically, its toString representation)
- * as further element.
- *
Multiple values can only be stored as list of Strings, following the
- * Servlet spec (see getHeaders
accessor). As alternative to
- * repeated addHeader
calls for individual elements, you can
- * use a single call with an entire array or Collection of values as
- * parameter.
- * @see #getHeaderNames
- * @see #getHeader
- * @see #getHeaders
- * @see #getDateHeader
- * @see #getIntHeader
- */
- @SuppressWarnings("rawtypes")
- public void addHeader(String name, Object value) {
- HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
- if (header == null) {
- header = new HeaderValueHolder();
- this.headers.put(name, header);
- }
- if (value instanceof Collection) {
- header.addValues((Collection) value);
- }
- else if (value.getClass().isArray()) {
- header.addValueArray(value);
- }
- else {
- header.addValue(value);
- }
- }
-
- @Override
- public long getDateHeader(String name) {
- HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
- Object value = (header != null ? header.getValue() : null);
- if (value instanceof Date) {
- return ((Date) value).getTime();
- }
- else if (value instanceof Number) {
- return ((Number) value).longValue();
- }
- else if (value != null) {
- throw new IllegalArgumentException("Value for header '" + name + "' is neither a Date nor a Number: "
- + value);
- }
- else {
- return -1L;
- }
- }
-
- @Override
- public int getIntHeader(String name) {
- HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
- Object value = (header != null ? header.getValue() : null);
- if (value instanceof Number) {
- return ((Number) value).intValue();
- }
- else if (value instanceof String) {
- return Integer.parseInt((String) value);
- }
- else if (value != null) {
- throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value);
- }
- else {
- return -1;
- }
- }
-
- @Override
- public String getHeader(String name) {
- HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
- return (header != null ? header.getStringValue() : null);
- }
-
- @Override
- public Enumeration getHeaders(String name) {
- HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
- return Collections.enumeration(header != null ? header.getStringValues() : new LinkedList());
- }
-
- @Override
- public Enumeration getHeaderNames() {
- return Collections.enumeration(this.headers.keySet());
- }
-
- public void setMethod(String method) {
- this.method = method;
- }
-
- @Override
- public String getMethod() {
- return this.method;
- }
-
- public void setPathInfo(String pathInfo) {
- this.pathInfo = pathInfo;
- }
-
- @Override
- public String getPathInfo() {
- return this.pathInfo;
- }
-
- @Override
- public String getPathTranslated() {
- return (this.pathInfo != null ? getRealPath(this.pathInfo) : null);
- }
-
- public void setContextPath(String contextPath) {
- this.contextPath = contextPath;
- }
-
- @Override
- public String getContextPath() {
- return this.contextPath;
- }
-
- public void setQueryString(String queryString) {
- this.queryString = queryString;
- }
-
- @Override
- public String getQueryString() {
- return this.queryString;
- }
-
- public void setRemoteUser(String remoteUser) {
- this.remoteUser = remoteUser;
- }
-
- @Override
- public String getRemoteUser() {
- return this.remoteUser;
- }
-
- public void addUserRole(String role) {
- this.userRoles.add(role);
- }
-
- @Override
- public boolean isUserInRole(String role) {
- return this.userRoles.contains(role);
- }
-
- public void setUserPrincipal(Principal userPrincipal) {
- this.userPrincipal = userPrincipal;
- }
-
- @Override
- public Principal getUserPrincipal() {
- return this.userPrincipal;
- }
-
- public void setRequestedSessionId(String requestedSessionId) {
- this.requestedSessionId = requestedSessionId;
- }
-
- @Override
- public String getRequestedSessionId() {
- return this.requestedSessionId;
- }
-
- public void setRequestURI(String requestURI) {
- this.requestURI = requestURI;
- }
-
- @Override
- public String getRequestURI() {
- return this.requestURI;
- }
-
- @Override
- public StringBuffer getRequestURL() {
- StringBuffer url = new StringBuffer(this.scheme);
- url.append("://").append(this.serverName).append(':').append(this.serverPort);
- url.append(getRequestURI());
- return url;
- }
-
- public void setServletPath(String servletPath) {
- this.servletPath = servletPath;
- }
-
- @Override
- public String getServletPath() {
- return this.servletPath;
- }
-
- public void setSession(HttpSession session) {
- this.session = session;
- if (session instanceof MockHttpSession) {
- MockHttpSession mockSession = ((MockHttpSession) session);
- mockSession.access();
- }
- }
-
- @Override
- public HttpSession getSession(boolean create) {
- checkActive();
- // Reset session if invalidated.
- if (this.session instanceof MockHttpSession && ((MockHttpSession) this.session).isInvalid()) {
- this.session = null;
- }
- // Create new session if necessary.
- if (this.session == null && create) {
- this.session = new MockHttpSession(this.servletContext);
- }
- return this.session;
- }
-
- @Override
- public HttpSession getSession() {
- return getSession(true);
- }
-
- public void setRequestedSessionIdValid(boolean requestedSessionIdValid) {
- this.requestedSessionIdValid = requestedSessionIdValid;
- }
-
- @Override
- public boolean isRequestedSessionIdValid() {
- return this.requestedSessionIdValid;
- }
-
- public void setRequestedSessionIdFromCookie(boolean requestedSessionIdFromCookie) {
- this.requestedSessionIdFromCookie = requestedSessionIdFromCookie;
- }
-
- @Override
- public boolean isRequestedSessionIdFromCookie() {
- return this.requestedSessionIdFromCookie;
- }
-
- public void setRequestedSessionIdFromURL(boolean requestedSessionIdFromURL) {
- this.requestedSessionIdFromURL = requestedSessionIdFromURL;
- }
-
- @Override
- public boolean isRequestedSessionIdFromURL() {
- return this.requestedSessionIdFromURL;
- }
-
- @Override @Deprecated
- public boolean isRequestedSessionIdFromUrl() {
- return isRequestedSessionIdFromURL();
- }
-
- @Override
- public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void login(String username, String password) throws ServletException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void logout() throws ServletException {
- this.userPrincipal = null;
- this.remoteUser = null;
- this.authType = null;
- }
-
- public void addPart(Part part) {
- this.parts.put(part.getName(), part);
- }
-
- @Override
- public Part getPart(String name) throws IOException, IllegalStateException, ServletException {
- return this.parts.get(name);
- }
-
- @Override
- public Collection getParts() throws IOException, IllegalStateException, ServletException {
- return this.parts.values();
- }
-
- @Override
- public AsyncContext startAsync() {
- return startAsync(this, null);
- }
-
- @Override
- public AsyncContext startAsync(ServletRequest request, ServletResponse response) {
- if (!this.asyncSupported) {
- throw new IllegalStateException("Async not supported");
- }
- this.asyncStarted = true;
- this.asyncContext = new MockAsyncContext(request, response);
- return this.asyncContext;
- }
-
- public void setAsyncStarted(boolean asyncStarted) {
- this.asyncStarted = asyncStarted;
- }
-
- @Override
- public boolean isAsyncStarted() {
- return this.asyncStarted;
- }
-
- public void setAsyncSupported(boolean asyncSupported) {
- this.asyncSupported = asyncSupported;
- }
-
- @Override
- public boolean isAsyncSupported() {
- return this.asyncSupported;
- }
-
- public void setAsyncContext(MockAsyncContext asyncContext) {
- this.asyncContext = asyncContext;
- }
-
- @Override
- public AsyncContext getAsyncContext() {
- return this.asyncContext;
- }
-
- public void setDispatcherType(DispatcherType dispatcherType) {
- this.dispatcherType = dispatcherType;
- }
-
- @Override
- public DispatcherType getDispatcherType() {
- return this.dispatcherType;
- }
-
-}
diff --git a/src/spec/java/org/jruby/rack/mock/MockHttpServletResponse.java b/src/spec/java/org/jruby/rack/mock/MockHttpServletResponse.java
deleted file mode 100644
index 286a7fc0..00000000
--- a/src/spec/java/org/jruby/rack/mock/MockHttpServletResponse.java
+++ /dev/null
@@ -1,555 +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.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jruby.rack.mock;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.io.UnsupportedEncodingException;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * Mock implementation of the {@link javax.servlet.http.HttpServletResponse} interface.
- *
- * Compatible with Servlet 2.5 as well as Servlet 3.0.
- *
- * @author Juergen Hoeller
- * @author Rod Johnson
- */
-public class MockHttpServletResponse implements HttpServletResponse {
-
- private static final String CHARSET_PREFIX = "charset=";
-
-
- //---------------------------------------------------------------------
- // ServletResponse properties
- //---------------------------------------------------------------------
-
- private boolean outputStreamAccessAllowed = true;
-
- private boolean writerAccessAllowed = true;
-
- private String characterEncoding = "ISO-8859-1";
-
- private final ByteArrayOutputStream content = new ByteArrayOutputStream();
-
- private final ServletOutputStream outputStream = new ResponseServletOutputStream(this.content);
-
- private PrintWriter writer;
-
- private int contentLength = 0;
-
- private String contentType;
-
- private int bufferSize = 4096;
-
- private boolean committed;
-
- private Locale locale = Locale.getDefault();
-
-
- //---------------------------------------------------------------------
- // HttpServletResponse properties
- //---------------------------------------------------------------------
-
- private final List cookies = new ArrayList();
-
- private final Map headers = new LinkedCaseInsensitiveMap();
-
- private int status = HttpServletResponse.SC_OK;
-
- private String errorMessage;
-
- private String redirectedUrl;
-
- private String forwardedUrl;
-
- private final List includedUrls = new ArrayList();
-
-
- //---------------------------------------------------------------------
- // ServletResponse interface
- //---------------------------------------------------------------------
-
- /**
- * Set whether {@link #getOutputStream()} access is allowed.
- * Default is true
.
- */
- public void setOutputStreamAccessAllowed(boolean outputStreamAccessAllowed) {
- this.outputStreamAccessAllowed = outputStreamAccessAllowed;
- }
-
- /**
- * Return whether {@link #getOutputStream()} access is allowed.
- */
- public boolean isOutputStreamAccessAllowed() {
- return this.outputStreamAccessAllowed;
- }
-
- /**
- * Set whether {@link #getWriter()} access is allowed.
- *
Default is true
.
- */
- public void setWriterAccessAllowed(boolean writerAccessAllowed) {
- this.writerAccessAllowed = writerAccessAllowed;
- }
-
- /**
- * Return whether {@link #getOutputStream()} access is allowed.
- */
- public boolean isWriterAccessAllowed() {
- return this.writerAccessAllowed;
- }
-
- public void setCharacterEncoding(String characterEncoding) {
- this.characterEncoding = characterEncoding;
- }
-
- public String getCharacterEncoding() {
- return this.characterEncoding;
- }
-
- public ServletOutputStream getOutputStream() {
- if (!this.outputStreamAccessAllowed) {
- throw new IllegalStateException("OutputStream access not allowed");
- }
- return this.outputStream;
- }
-
- public PrintWriter getWriter() throws UnsupportedEncodingException {
- if (!this.writerAccessAllowed) {
- throw new IllegalStateException("Writer access not allowed");
- }
- if (this.writer == null) {
- Writer targetWriter = (this.characterEncoding != null ?
- new OutputStreamWriter(this.content, this.characterEncoding) : new OutputStreamWriter(this.content));
- this.writer = new ResponsePrintWriter(targetWriter);
- }
- return this.writer;
- }
-
- public byte[] getContentAsByteArray() {
- flushBuffer();
- return this.content.toByteArray();
- }
-
- public String getContentAsString() throws UnsupportedEncodingException {
- flushBuffer();
- return (this.characterEncoding != null) ?
- this.content.toString(this.characterEncoding) : this.content.toString();
- }
-
- public void setContentLength(int contentLength) {
- this.contentLength = contentLength;
- }
-
- public int getContentLength() {
- return this.contentLength;
- }
-
- public void setContentType(String contentType) {
- this.contentType = contentType;
- if (contentType != null) {
- int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX);
- if (charsetIndex != -1) {
- String encoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length());
- setCharacterEncoding(encoding);
- }
- }
- }
-
- public String getContentType() {
- return this.contentType;
- }
-
- public void setBufferSize(int bufferSize) {
- this.bufferSize = bufferSize;
- }
-
- public int getBufferSize() {
- return this.bufferSize;
- }
-
- public void flushBuffer() {
- setCommitted(true);
- }
-
- public void resetBuffer() {
- if (isCommitted()) {
- throw new IllegalStateException("Cannot reset buffer - response is already committed");
- }
- this.content.reset();
- }
-
- private void setCommittedIfBufferSizeExceeded() {
- int bufSize = getBufferSize();
- if (bufSize > 0 && this.content.size() > bufSize) {
- setCommitted(true);
- }
- }
-
- public void setCommitted(boolean committed) {
- this.committed = committed;
- }
-
- public boolean isCommitted() {
- return this.committed;
- }
-
- public void reset() {
- resetBuffer();
- this.characterEncoding = null;
- this.contentLength = 0;
- this.contentType = null;
- this.locale = null;
- this.cookies.clear();
- this.headers.clear();
- this.status = HttpServletResponse.SC_OK;
- this.errorMessage = null;
- }
-
- public void setLocale(Locale locale) {
- this.locale = locale;
- }
-
- public Locale getLocale() {
- return this.locale;
- }
-
-
- //---------------------------------------------------------------------
- // HttpServletResponse interface
- //---------------------------------------------------------------------
-
- public void addCookie(Cookie cookie) {
- this.cookies.add(cookie);
- }
-
- public Cookie[] getCookies() {
- return this.cookies.toArray(new Cookie[this.cookies.size()]);
- }
-
- public Cookie getCookie(String name) {
- for (Cookie cookie : this.cookies) {
- if (name.equals(cookie.getName())) {
- return cookie;
- }
- }
- return null;
- }
-
- public boolean containsHeader(String name) {
- return (HeaderValueHolder.getByName(this.headers, name) != null);
- }
-
- /**
- * Return the names of all specified headers as a Set of Strings.
- *
As of Servlet 3.0, this method is also defined HttpServletResponse.
- * @return the Set
of header name Strings
, or an empty Set
if none
- */
- public Set getHeaderNames() {
- return this.headers.keySet();
- }
-
- /**
- * Return the primary value for the given header as a String, if any.
- * Will return the first value in case of multiple values.
- * As of Servlet 3.0, this method is also defined HttpServletResponse.
- * As of Spring 3.1, it returns a stringified value for Servlet 3.0 compatibility.
- * Consider using {@link #getHeaderValue(String)} for raw Object access.
- * @param name the name of the header
- * @return the associated header value, or null if none
- */
- public String getHeader(String name) {
- HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
- return (header != null ? header.getStringValue() : null);
- }
-
- /**
- * Return all values for the given header as a List of Strings.
- * As of Servlet 3.0, this method is also defined HttpServletResponse.
- * As of Spring 3.1, it returns a List of stringified values for Servlet 3.0 compatibility.
- * Consider using {@link #getHeaderValues(String)} for raw Object access.
- * @param name the name of the header
- * @return the associated header values, or an empty List if none
- */
- public List getHeaders(String name) {
- HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
- if (header != null) {
- return header.getStringValues();
- }
- else {
- return Collections.emptyList();
- }
- }
-
- /**
- * Return the primary value for the given header, if any.
- * Will return the first value in case of multiple values.
- * @param name the name of the header
- * @return the associated header value, or null if none
- */
- public Object getHeaderValue(String name) {
- HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
- return (header != null ? header.getValue() : null);
- }
-
- /**
- * Return all values for the given header as a List of value objects.
- * @param name the name of the header
- * @return the associated header values, or an empty List if none
- */
- public List getHeaderValues(String name) {
- HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
- if (header != null) {
- return header.getValues();
- }
- else {
- return Collections.emptyList();
- }
- }
-
- /**
- * The default implementation returns the given URL String as-is.
- * Can be overridden in subclasses, appending a session id or the like.
- */
- public String encodeURL(String url) {
- return url;
- }
-
- /**
- * The default implementation delegates to {@link #encodeURL},
- * returning the given URL String as-is.
- *
Can be overridden in subclasses, appending a session id or the like
- * in a redirect-specific fashion. For general URL encoding rules,
- * override the common {@link #encodeURL} method instead, appyling
- * to redirect URLs as well as to general URLs.
- */
- public String encodeRedirectURL(String url) {
- return encodeURL(url);
- }
-
- public String encodeUrl(String url) {
- return encodeURL(url);
- }
-
- public String encodeRedirectUrl(String url) {
- return encodeRedirectURL(url);
- }
-
- public void sendError(int status, String errorMessage) throws IOException {
- if (isCommitted()) {
- throw new IllegalStateException("Cannot set error status - response is already committed");
- }
- this.status = status;
- this.errorMessage = errorMessage;
- setCommitted(true);
- }
-
- public void sendError(int status) throws IOException {
- if (isCommitted()) {
- throw new IllegalStateException("Cannot set error status - response is already committed");
- }
- this.status = status;
- setCommitted(true);
- }
-
- public void sendRedirect(String url) throws IOException {
- if (isCommitted()) {
- throw new IllegalStateException("Cannot send redirect - response is already committed");
- }
- this.redirectedUrl = url;
- setCommitted(true);
- }
-
- public String getRedirectedUrl() {
- return this.redirectedUrl;
- }
-
- public void setDateHeader(String name, long value) {
- setHeaderValue(name, value);
- }
-
- public void addDateHeader(String name, long value) {
- addHeaderValue(name, value);
- }
-
- public void setHeader(String name, String value) {
- setHeaderValue(name, value);
- }
-
- public void addHeader(String name, String value) {
- addHeaderValue(name, value);
- }
-
- public void setIntHeader(String name, int value) {
- setHeaderValue(name, value);
- }
-
- public void addIntHeader(String name, int value) {
- addHeaderValue(name, value);
- }
-
- private void setHeaderValue(String name, Object value) {
- doAddHeaderValue(name, value, true);
- }
-
- private void addHeaderValue(String name, Object value) {
- doAddHeaderValue(name, value, false);
- }
-
- private void doAddHeaderValue(String name, Object value, boolean replace) {
- HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
- if (header == null) {
- header = new HeaderValueHolder();
- this.headers.put(name, header);
- }
- if (replace) {
- header.setValue(value);
- }
- else {
- header.addValue(value);
- }
- }
-
- public void setStatus(int status) {
- this.status = status;
- }
-
- public void setStatus(int status, String errorMessage) {
- this.status = status;
- this.errorMessage = errorMessage;
- }
-
- public int getStatus() {
- return this.status;
- }
-
- public String getErrorMessage() {
- return this.errorMessage;
- }
-
-
- //---------------------------------------------------------------------
- // Methods for MockRequestDispatcher
- //---------------------------------------------------------------------
-
- public void setForwardedUrl(String forwardedUrl) {
- this.forwardedUrl = forwardedUrl;
- }
-
- public String getForwardedUrl() {
- return this.forwardedUrl;
- }
-
- public void setIncludedUrl(String includedUrl) {
- this.includedUrls.clear();
- if (includedUrl != null) {
- this.includedUrls.add(includedUrl);
- }
- }
-
- public String getIncludedUrl() {
- int count = this.includedUrls.size();
- if (count > 1) {
- throw new IllegalStateException(
- "More than 1 URL included - check getIncludedUrls instead: " + this.includedUrls);
- }
- return (count == 1 ? this.includedUrls.get(0) : null);
- }
-
- public void addIncludedUrl(String includedUrl) {
- this.includedUrls.add(includedUrl);
- }
-
- public List getIncludedUrls() {
- return this.includedUrls;
- }
-
-
- /**
- * Inner class that adapts the ServletOutputStream to mark the
- * response as committed once the buffer size is exceeded.
- */
- private class ResponseServletOutputStream extends DelegatingServletOutputStream {
-
- public ResponseServletOutputStream(OutputStream out) {
- super(out);
- }
-
- public void write(int b) throws IOException {
- super.write(b);
- super.flush();
- setCommittedIfBufferSizeExceeded();
- }
-
- public void flush() throws IOException {
- super.flush();
- setCommitted(true);
- }
- }
-
-
- /**
- * Inner class that adapts the PrintWriter to mark the
- * response as committed once the buffer size is exceeded.
- */
- private class ResponsePrintWriter extends PrintWriter {
-
- public ResponsePrintWriter(Writer out) {
- super(out, true);
- }
-
- public void write(char buf[], int off, int len) {
- super.write(buf, off, len);
- super.flush();
- setCommittedIfBufferSizeExceeded();
- }
-
- public void write(String s, int off, int len) {
- super.write(s, off, len);
- super.flush();
- setCommittedIfBufferSizeExceeded();
- }
-
- public void write(int c) {
- super.write(c);
- super.flush();
- setCommittedIfBufferSizeExceeded();
- }
-
- public void flush() {
- super.flush();
- setCommitted(true);
- }
- }
-
-}
diff --git a/src/spec/java/org/jruby/rack/mock/MockHttpSession.java b/src/spec/java/org/jruby/rack/mock/MockHttpSession.java
deleted file mode 100644
index 9435e257..00000000
--- a/src/spec/java/org/jruby/rack/mock/MockHttpSession.java
+++ /dev/null
@@ -1,270 +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.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jruby.rack.mock;
-
-import java.io.Serializable;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Vector;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpSession;
-import javax.servlet.http.HttpSessionBindingEvent;
-import javax.servlet.http.HttpSessionBindingListener;
-import javax.servlet.http.HttpSessionContext;
-
-/**
- * Mock implementation of the {@link javax.servlet.http.HttpSession} interface.
- *
- * Compatible with Servlet 2.5 as well as Servlet 3.0.
- *
- * @author Juergen Hoeller
- * @author Rod Johnson
- * @author Mark Fisher
- */
-@SuppressWarnings("deprecation")
-public class MockHttpSession implements HttpSession {
-
- private static int nextId = 1;
-
- private String id;
-
- private final long creationTime = System.currentTimeMillis();
-
- private int maxInactiveInterval;
-
- private long lastAccessedTime = System.currentTimeMillis();
-
- private final ServletContext servletContext;
-
- private final Map attributes = new LinkedHashMap();
-
- private boolean invalid = false;
-
- private boolean isNew = true;
-
-
- /**
- * Create a new MockHttpSession with a default {@link MockServletContext}.
- *
- * @see MockServletContext
- */
- public MockHttpSession() {
- this(null);
- }
-
- /**
- * Create a new MockHttpSession.
- *
- * @param servletContext the ServletContext that the session runs in
- */
- public MockHttpSession(ServletContext servletContext) {
- this(servletContext, null);
- }
-
- /**
- * Create a new MockHttpSession.
- *
- * @param servletContext the ServletContext that the session runs in
- * @param id a unique identifier for this session
- */
- public MockHttpSession(ServletContext servletContext, String id) {
- this.servletContext = servletContext;
- this.id = (id != null ? id : Integer.toString(nextId++));
- }
-
- public long getCreationTime() throws IllegalStateException {
- checkInvalid("getCreationTime()");
- return this.creationTime;
- }
-
- public String getId() {
- return this.id;
- }
-
- void setId(String id) {
- this.id = id;
- }
-
- public void access() {
- this.lastAccessedTime = System.currentTimeMillis();
- this.isNew = false;
- }
-
- public long getLastAccessedTime() throws IllegalStateException {
- checkInvalid("getLastAccessedTime()");
- return this.lastAccessedTime;
- }
-
- public ServletContext getServletContext() {
- return this.servletContext;
- }
-
- public void setMaxInactiveInterval(int interval) {
- this.maxInactiveInterval = interval;
- }
-
- public int getMaxInactiveInterval() {
- return this.maxInactiveInterval;
- }
-
- public HttpSessionContext getSessionContext() {
- throw new UnsupportedOperationException("getSessionContext");
- }
-
- public Object getAttribute(String name) throws IllegalStateException {
- checkInvalid("getAttribute("+ name +")");
- return this.attributes.get(name);
- }
-
- public Object getValue(String name) {
- return getAttribute(name);
- }
-
- public Enumeration getAttributeNames() throws IllegalStateException {
- checkInvalid("getAttributeNames()");
- return new Vector(this.attributes.keySet()).elements();
- }
-
- public String[] getValueNames() throws IllegalStateException {
- checkInvalid("getValueNames()");
- return this.attributes.keySet().toArray(new String[this.attributes.size()]);
- }
-
- public void setAttribute(String name, Object value) throws IllegalStateException {
- checkInvalid("setAttribute("+ name + ")");
- if (value != null) {
- this.attributes.put(name, value);
- if (value instanceof HttpSessionBindingListener) {
- ((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value));
- }
- }
- else {
- removeAttribute(name);
- }
- }
-
- public void putValue(String name, Object value) {
- setAttribute(name, value);
- }
-
- public void removeAttribute(String name) throws IllegalStateException {
- checkInvalid("removeAttribute("+ name + ")");
- Object value = this.attributes.remove(name);
- if (value instanceof HttpSessionBindingListener) {
- ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
- }
- }
-
- public void removeValue(String name) {
- removeAttribute(name);
- }
-
- /**
- * Clear all of this session's attributes.
- */
- public void clearAttributes() {
- for (Iterator> it = this.attributes.entrySet().iterator(); it.hasNext();) {
- Map.Entry entry = it.next();
- String name = entry.getKey();
- Object value = entry.getValue();
- it.remove();
- if (value instanceof HttpSessionBindingListener) {
- ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
- }
- }
- }
-
- public void invalidate() throws IllegalStateException {
- checkInvalid("invalidate()");
- this.invalid = true;
- clearAttributes();
- }
-
- public boolean isInvalid() {
- return this.invalid;
- }
-
- public void setNew(boolean value) {
- this.isNew = value;
- }
-
- public boolean isNew() throws IllegalStateException {
- checkInvalid("isNew()");
- return this.isNew;
- }
-
- /**
- * Serialize the attributes of this session into an object that can be
- * turned into a byte array with standard Java serialization.
- *
- * @return a representation of this session's serialized state
- */
- public Serializable serializeState() {
- HashMap state = new HashMap();
- for (Iterator> it = this.attributes.entrySet().iterator(); it.hasNext();) {
- Map.Entry entry = it.next();
- String name = entry.getKey();
- Object value = entry.getValue();
- it.remove();
- if (value instanceof Serializable) {
- state.put(name, (Serializable) value);
- }
- else {
- // Not serializable... Servlet containers usually automatically
- // unbind the attribute in this case.
- if (value instanceof HttpSessionBindingListener) {
- ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
- }
- }
- }
- return state;
- }
-
- /**
- * Deserialize the attributes of this session from a state object created by
- * {@link #serializeState()}.
- *
- * @param state a representation of this session's serialized state
- */
- @SuppressWarnings("unchecked")
- public void deserializeState(Serializable state) {
- this.attributes.putAll((Map) state);
- }
-
- @Override
- public String toString() {
- return getClass().getName() + "@" + Integer.toHexString(hashCode()) + this.attributes;
- }
-
- Map getAttributes() {
- return attributes;
- }
-
- private void checkInvalid(String method) throws IllegalStateException {
- if ( invalid == true ) {
- if ( method == null ) method = "";
- throw new IllegalStateException(method + ": session already invalidated");
- }
- }
-
-}
diff --git a/src/spec/java/org/jruby/rack/mock/MockRequestDispatcher.java b/src/spec/java/org/jruby/rack/mock/MockRequestDispatcher.java
deleted file mode 100644
index 3a1c79dd..00000000
--- a/src/spec/java/org/jruby/rack/mock/MockRequestDispatcher.java
+++ /dev/null
@@ -1,75 +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.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jruby.rack.mock;
-
-import javax.servlet.RequestDispatcher;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletResponseWrapper;
-
-/**
- * Mock implementation of the {@link javax.servlet.RequestDispatcher} interface.
- *
- * Used for testing the web framework; typically not necessary for
- * testing application controllers.
- *
- * @author Rod Johnson
- * @author Juergen Hoeller
- */
-public class MockRequestDispatcher implements RequestDispatcher {
-
- private final String url;
-
-
- /**
- * Create a new MockRequestDispatcher for the given URL.
- * @param url the URL to dispatch to.
- */
- public MockRequestDispatcher(String url) {
- this.url = url;
- }
-
-
- public void forward(ServletRequest request, ServletResponse response) {
- if (response.isCommitted()) {
- throw new IllegalStateException("Cannot perform forward - response is already committed");
- }
- getMockHttpServletResponse(response).setForwardedUrl(this.url);
- }
-
- public void include(ServletRequest request, ServletResponse response) {
- getMockHttpServletResponse(response).addIncludedUrl(this.url);
- }
-
- /**
- * Obtain the underlying MockHttpServletResponse,
- * unwrapping {@link HttpServletResponseWrapper} decorators if necessary.
- */
- protected MockHttpServletResponse getMockHttpServletResponse(ServletResponse response) {
- if (response instanceof MockHttpServletResponse) {
- return (MockHttpServletResponse) response;
- }
- if (response instanceof HttpServletResponseWrapper) {
- return getMockHttpServletResponse(((HttpServletResponseWrapper) response).getResponse());
- }
- throw new IllegalArgumentException("MockRequestDispatcher requires MockHttpServletResponse");
- }
-
-}
diff --git a/src/spec/java/org/jruby/rack/mock/MockServletConfig.java b/src/spec/java/org/jruby/rack/mock/MockServletConfig.java
deleted file mode 100644
index 3dc31489..00000000
--- a/src/spec/java/org/jruby/rack/mock/MockServletConfig.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright 2002-2009 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jruby.rack.mock;
-
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-
-/**
- * Mock implementation of the {@link javax.servlet.ServletConfig} interface.
- *
- *
Used for testing the web framework; typically not necessary for
- * testing application controllers.
- *
- * @author Rod Johnson
- * @author Juergen Hoeller
- * @since 1.0.2
- */
-public class MockServletConfig implements ServletConfig {
-
- private final ServletContext servletContext;
-
- private final String servletName;
-
- private final Map initParameters = new LinkedHashMap();
-
-
- /**
- * Create a new MockServletConfig with a default {@link MockServletContext}.
- */
- public MockServletConfig() {
- this(null, "");
- }
-
- /**
- * Create a new MockServletConfig with a default {@link MockServletContext}.
- * @param servletName the name of the servlet
- */
- public MockServletConfig(String servletName) {
- this(null, servletName);
- }
-
- /**
- * Create a new MockServletConfig.
- * @param servletContext the ServletContext that the servlet runs in
- */
- public MockServletConfig(ServletContext servletContext) {
- this(servletContext, "");
- }
-
- /**
- * Create a new MockServletConfig.
- * @param servletContext the ServletContext that the servlet runs in
- * @param servletName the name of the servlet
- */
- public MockServletConfig(ServletContext servletContext, String servletName) {
- this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
- this.servletName = servletName;
- }
-
-
- public String getServletName() {
- return this.servletName;
- }
-
- public ServletContext getServletContext() {
- return this.servletContext;
- }
-
- public void addInitParameter(String name, String value) {
- if (name == null) {
- throw new IllegalArgumentException("parameter name must not be null");
- }
- this.initParameters.put(name, value);
- }
-
- public String getInitParameter(String name) {
- if (name == null) {
- throw new IllegalArgumentException("parameter name must not be null");
- }
- return this.initParameters.get(name);
- }
-
- public Enumeration getInitParameterNames() {
- return Collections.enumeration(this.initParameters.keySet());
- }
-
-}
diff --git a/src/spec/java/org/jruby/rack/mock/MockServletContext.java b/src/spec/java/org/jruby/rack/mock/MockServletContext.java
deleted file mode 100644
index 79c54da0..00000000
--- a/src/spec/java/org/jruby/rack/mock/MockServletContext.java
+++ /dev/null
@@ -1,633 +0,0 @@
-/*
- * Copyright 2002-2013 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jruby.rack.mock;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.Enumeration;
-import java.util.EventListener;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.Map;
-import java.util.Set;
-import javax.servlet.Filter;
-import javax.servlet.FilterRegistration;
-import javax.servlet.RequestDispatcher;
-import javax.servlet.Servlet;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRegistration;
-import javax.servlet.SessionCookieConfig;
-import javax.servlet.SessionTrackingMode;
-import javax.servlet.descriptor.JspConfigDescriptor;
-
-import org.springframework.core.io.DefaultResourceLoader;
-import org.springframework.core.io.Resource;
-import org.springframework.core.io.ResourceLoader;
-
-import org.jruby.rack.RackLogger;
-import static org.jruby.rack.RackLogger.*;
-
-/**
- * Mock implementation of the {@link javax.servlet.ServletContext} interface.
- *
- * As of Spring 4.0, this set of mocks is designed on a Servlet 3.0 baseline.
- *
- *
Compatible with Servlet 3.0 but can be configured to expose a specific version
- * through {@link #setMajorVersion}/{@link #setMinorVersion}; default is 3.0.
- * Note that Servlet 3.0 support is limited: servlet, filter and listener
- * registration methods are not supported; neither is JSP configuration.
- * We generally do not recommend to unit-test your ServletContainerInitializers and
- * WebApplicationInitializers which is where those registration methods would be used.
- *
- *
Used for testing the Spring web framework; only rarely necessary for testing
- * application controllers. As long as application components don't explicitly
- * access the {@code ServletContext}, {@code ClassPathXmlApplicationContext} or
- * {@code FileSystemXmlApplicationContext} can be used to load the context files
- * for testing, even for {@code DispatcherServlet} context definitions.
- *
- *
For setting up a full {@code WebApplicationContext} in a test environment,
- * you can use {@code AnnotationConfigWebApplicationContext},
- * {@code XmlWebApplicationContext}, or {@code GenericWebApplicationContext},
- * passing in an appropriate {@code MockServletContext} instance. You might want
- * to configure your {@code MockServletContext} with a {@code FileSystemResourceLoader}
- * in that case to ensure that resource paths are interpreted as relative filesystem
- * locations.
- *
- *
A common setup is to point your JVM working directory to the root of your
- * web application directory, in combination with filesystem-based resource loading.
- * This allows to load the context files as used in the web application, with
- * relative paths getting interpreted correctly. Such a setup will work with both
- * {@code FileSystemXmlApplicationContext} (which will load straight from the
- * filesystem) and {@code XmlWebApplicationContext} with an underlying
- * {@code MockServletContext} (as long as the {@code MockServletContext} has been
- * configured with a {@code FileSystemResourceLoader}).
- *
- * @author Rod Johnson
- * @author Juergen Hoeller
- * @author Sam Brannen
- */
-public class MockServletContext implements ServletContext {
-
- private static final String TEMP_DIR_SYSTEM_PROPERTY = "java.io.tmpdir";
-
- private static final String TEMP_DIR_CONTEXT_ATTRIBUTE = "javax.servlet.context.tempdir";
-
- private final ResourceLoader resourceLoader;
-
- private final String resourceBasePath;
-
- private String contextPath = "";
-
- private int majorVersion = 3;
- private int minorVersion = 0;
-
- private int effectiveMajorVersion = 3;
- private int effectiveMinorVersion = 0;
-
- private final Map contexts = new HashMap();
- private final Map initParameters = new LinkedHashMap();
- private final Map attributes = new LinkedHashMap();
-
- private String servletContextName = "MockServletContext";
- //private String defaultServletName = "default";
-
- //final Map namedRequestDispatchers = new HashMap();
-
- private final Set declaredRoles = new HashSet();
-
- private Set sessionTrackingModes;
-
- private Object sessionCookieConfig; // SessionCookieConfig
-
- private RackLogger logger = new NullLogger();
-
- /**
- * Create a new MockServletContext, using no base path and a
- * DefaultResourceLoader (i.e. the classpath root as WAR root).
- * @see org.springframework.core.io.DefaultResourceLoader
- */
- public MockServletContext() {
- this("", null);
- }
-
- /**
- * Create a new MockServletContext, using a DefaultResourceLoader.
- * @param resourceBasePath the WAR root directory (should not end with a slash)
- * @see org.springframework.core.io.DefaultResourceLoader
- */
- public MockServletContext(String resourceBasePath) {
- this(resourceBasePath, null);
- }
-
- /**
- * Create a new MockServletContext, using the specified ResourceLoader
- * and no base path.
- * @param resourceLoader the ResourceLoader to use (or null for the default)
- */
- MockServletContext(ResourceLoader resourceLoader) {
- this("", resourceLoader);
- }
-
- /**
- * Create a new MockServletContext.
- * @param resourceBasePath the WAR root directory (should not end with a slash)
- * @param resourceLoader the ResourceLoader to use (or null for the default)
- */
- MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
- this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
- this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");
-
- // Use JVM temp dir as ServletContext temp dir.
- String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
- if (tempDir != null) {
- this.attributes.put(TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
- }
- }
-
-
- /**
- * Build a full resource location for the given path,
- * prepending the resource base path of this MockServletContext.
- * @param path the path as specified
- * @return the full resource path
- */
- protected String getResourceLocation(String path) {
- if (!path.startsWith("/")) {
- path = "/" + path;
- }
- return this.resourceBasePath + path;
- }
-
- private static class NullLogger extends RackLogger.Base {
-
- @Override
- public void log(String message) { /* NOOP */ }
-
- @Override
- public void log(String message, Throwable ex) { /* NOOP */ }
-
- @Override
- public boolean isEnabled(Level level) { return false; }
-
- @Override
- public void log(Level level, String message) { /* NOOP */ }
-
- @Override
- public void log(Level level, String message, Throwable ex) { /* NOOP */ }
-
- @Override
- public Level getLevel() { return null; }
-
- }
-
- public void setContextPath(String contextPath) {
- this.contextPath = (contextPath != null ? contextPath : "");
- }
-
- @Override // Servlet API 2.5
- public String getContextPath() {
- return this.contextPath;
- }
-
- public void registerContext(String contextPath, ServletContext context) {
- this.contexts.put(contextPath, context);
- }
-
- @Override
- public ServletContext getContext(String contextPath) {
- if (this.contextPath.equals(contextPath)) {
- return this;
- }
- return this.contexts.get(contextPath);
- }
-
- public void setMajorVersion(int majorVersion) {
- this.majorVersion = majorVersion;
- }
-
- @Override
- public int getMajorVersion() {
- return this.majorVersion;
- }
-
- public void setMinorVersion(int minorVersion) {
- this.minorVersion = minorVersion;
- }
-
- @Override
- public int getMinorVersion() {
- return this.minorVersion;
- }
-
- public void setEffectiveMajorVersion(int effectiveMajorVersion) {
- this.effectiveMajorVersion = effectiveMajorVersion;
- }
-
- @Override
-
- public int getEffectiveMajorVersion() {
- return this.effectiveMajorVersion;
- }
-
- public void setEffectiveMinorVersion(int effectiveMinorVersion) {
- this.effectiveMinorVersion = effectiveMinorVersion;
- }
-
- @Override
- public int getEffectiveMinorVersion() {
- return this.effectiveMinorVersion;
- }
-
- @Override
- public String getMimeType(String filePath) {
- try {
- Path path = Paths.get(filePath);
- return Files.probeContentType(path);
- } catch (IOException e) {
- return "application/octet-stream"; // default MIME type
- }
- }
-
- @Override
- public Set getResourcePaths(String path) {
- String actualPath = (path.endsWith("/") ? path : path + "/");
- Resource resource = this.resourceLoader.getResource(getResourceLocation(actualPath));
- try {
- File file = resource.getFile();
- String[] fileList = file.list();
- if (fileList == null || fileList.length == 0) {
- return null;
- }
- Set resourcePaths = new LinkedHashSet(fileList.length);
- for (String fileEntry : fileList) {
- String resultPath = actualPath + fileEntry;
- if (resource.createRelative(fileEntry).getFile().isDirectory()) {
- resultPath += "/";
- }
- resourcePaths.add(resultPath);
- }
- return resourcePaths;
- }
- catch (IOException ex) {
- logger.log(WARN, "Couldn't get resource paths for " + resource, ex);
- return null;
- }
- }
-
- @Override
- public URL getResource(String path) throws MalformedURLException {
- Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
- if (!resource.exists()) {
- return null;
- }
- try {
- return resource.getURL();
- }
- catch (MalformedURLException ex) {
- throw ex;
- }
- catch (IOException ex) {
- logger.log(WARN, "Couldn't get URL for " + resource, ex);
- return null;
- }
- }
-
- @Override
- public InputStream getResourceAsStream(String path) {
- Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
- if (!resource.exists()) {
- return null;
- }
- try {
- return resource.getInputStream();
- }
- catch (IOException ex) {
- logger.log(WARN, "Couldn't open InputStream for " + resource, ex);
- return null;
- }
- }
-
- @Override
- public RequestDispatcher getRequestDispatcher(String path) {
- if (!path.startsWith("/")) {
- throw new IllegalArgumentException("RequestDispatcher path at ServletContext level must start with '/'");
- }
- return new MockRequestDispatcher(path);
- }
-
- @Override
- public RequestDispatcher getNamedDispatcher(String path) {
- return null;
- }
-
- @Override @SuppressWarnings("deprecation")
- public Servlet getServlet(String name) {
- return null;
- }
-
- @Override
- public Enumeration getServlets() {
- return Collections.enumeration(new HashSet());
- }
-
- @Override @SuppressWarnings("deprecation")
- public Enumeration getServletNames() {
- return Collections.enumeration(new HashSet());
- }
-
- @Override
- public void log(String message) {
- logger.log(message);
- }
-
- @Override @SuppressWarnings("deprecation")
- public void log(Exception ex, String message) {
- logger.log(message, ex);
- }
-
- @Override
- public void log(String message, Throwable ex) {
- logger.log(message, ex);
- }
-
- public RackLogger getLogger() {
- return (logger instanceof NullLogger) ? null : logger;
- }
-
- public void setLogger(RackLogger logger) {
- this.logger = logger == null ? new NullLogger() : logger;
- }
-
- @Override
- public String getRealPath(String path) {
- Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
- try {
- return resource.getFile().getAbsolutePath();
- }
- catch (IOException ex) {
- logger.log(WARN, "Couldn't determine real path of resource " + resource, ex);
- return null;
- }
- }
-
- @Override
- public String getServerInfo() {
- return "MockServletContext";
- }
-
- @Override
- public String getInitParameter(String name) {
- if (name == null) {
- throw new IllegalArgumentException("parameter name must not be null");
- }
- return this.initParameters.get(name);
- }
-
- public void addInitParameter(String name, String value) {
- if (name == null) {
- throw new IllegalArgumentException("parameter name must not be null");
- }
- this.initParameters.put(name, value);
- }
-
- @Override
- public Enumeration getInitParameterNames() {
- return Collections.enumeration(this.initParameters.keySet());
- }
-
- @Override
- public Object getAttribute(String name) {
- if (name == null) {
- throw new IllegalArgumentException("attribute name must not be null");
- }
- return this.attributes.get(name);
- }
-
- @Override
- public Enumeration getAttributeNames() {
- return Collections.enumeration(this.attributes.keySet());
- }
-
- @Override
- public void setAttribute(String name, Object value) {
- if (name == null) {
- throw new IllegalArgumentException("attribute name must not be null");
- }
- if (value != null) {
- this.attributes.put(name, value);
- }
- else {
- this.attributes.remove(name);
- }
- }
-
- @Override
- public void removeAttribute(String name) {
- if (name == null) {
- throw new IllegalArgumentException("attribute name must not be null");
- }
- this.attributes.remove(name);
- }
-
- public void setServletContextName(String servletContextName) {
- this.servletContextName = servletContextName;
- }
-
- @Override
- public String getServletContextName() {
- return this.servletContextName;
- }
-
- //---------------------------------------------------------------------
- // Methods introduced in Servlet 3.0
- //---------------------------------------------------------------------
-
- @Override
- public ClassLoader getClassLoader() {
- // return ClassUtils.getDefaultClassLoader();
- ClassLoader cl = null;
- try {
- cl = Thread.currentThread().getContextClassLoader();
- }
- catch (Exception ex) {
- // Cannot access thread context ClassLoader - falling back...
- }
- if (cl == null) {
- // No thread context class loader -> use class loader of this class.
- cl = MockServletContext.class.getClassLoader();
- if (cl == null) {
- // getClassLoader() returning null indicates the bootstrap ClassLoader
- try {
- cl = ClassLoader.getSystemClassLoader();
- }
- catch (Exception ex) {
- // Cannot access system ClassLoader - oh well, maybe the caller can live with null...
- }
- }
- }
- return cl;
- }
-
- @Override
- public void declareRoles(String... roleNames) {
- // Assert.notNull(roleNames, "Role names array must not be null");
- for (String roleName : roleNames) {
- // Assert.hasLength(roleName, "Role name must not be empty");
- this.declaredRoles.add(roleName);
- }
- }
-
- public Set getDeclaredRoles() {
- return Collections.unmodifiableSet(this.declaredRoles);
- }
-
- @Override
- public boolean setInitParameter(String name, String value) {
- // Assert.notNull(name, "Parameter name must not be null");
- if (this.initParameters.containsKey(name)) {
- return false;
- }
- this.initParameters.put(name, value);
- return true;
- }
-
- @Override
- public void setSessionTrackingModes(Set sessionTrackingModes)
- throws IllegalStateException, IllegalArgumentException {
- this.sessionTrackingModes = sessionTrackingModes;
- }
-
- @Override
- public Set getDefaultSessionTrackingModes() {
- return EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL, SessionTrackingMode.SSL);
- }
-
- @Override
- public Set getEffectiveSessionTrackingModes() {
- return (this.sessionTrackingModes != null ?
- Collections.unmodifiableSet(this.sessionTrackingModes) : getDefaultSessionTrackingModes());
- }
-
- @Override
- public SessionCookieConfig getSessionCookieConfig() {
- if (sessionCookieConfig == null) {
- sessionCookieConfig = new MockSessionCookieConfig();
- }
- return (SessionCookieConfig) sessionCookieConfig;
- }
-
- //---------------------------------------------------------------------
- // Unsupported Servlet 3.0 registration methods
- //---------------------------------------------------------------------
-
- @Override
- public JspConfigDescriptor getJspConfigDescriptor() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public ServletRegistration.Dynamic addServlet(String servletName, String className) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public ServletRegistration.Dynamic addServlet(String servletName, Class extends Servlet> servletClass) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public T createServlet(Class c) throws ServletException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public ServletRegistration getServletRegistration(String servletName) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Map getServletRegistrations() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public FilterRegistration.Dynamic addFilter(String filterName, String className) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public FilterRegistration.Dynamic addFilter(String filterName, Class extends Filter> filterClass) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public T createFilter(Class c) throws ServletException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public FilterRegistration getFilterRegistration(String filterName) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Map getFilterRegistrations() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void addListener(Class extends EventListener> listenerClass) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void addListener(String className) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void addListener(T t) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public T createListener(Class c) throws ServletException {
- throw new UnsupportedOperationException();
- }
-
-}
diff --git a/src/spec/java/org/jruby/rack/mock/MockSessionCookieConfig.java b/src/spec/java/org/jruby/rack/mock/MockSessionCookieConfig.java
deleted file mode 100644
index 55e4fc0b..00000000
--- a/src/spec/java/org/jruby/rack/mock/MockSessionCookieConfig.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright 2002-2013 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.jruby.rack.mock;
-
-import javax.servlet.SessionCookieConfig;
-
-/**
- * Mock implementation of the {@link javax.servlet.SessionCookieConfig} interface.
- *
- * @author Juergen Hoeller
- * @since 4.0
- * @see javax.servlet.ServletContext#getSessionCookieConfig()
- */
-public class MockSessionCookieConfig implements SessionCookieConfig {
-
- private String name;
-
- private String domain;
-
- private String path;
-
- private String comment;
-
- private boolean httpOnly;
-
- private boolean secure;
-
- private int maxAge;
-
-
- @Override
- public void setName(String name) {
- this.name = name;
- }
-
- @Override
- public String getName() {
- return this.name;
- }
-
- @Override
- public void setDomain(String domain) {
- this.domain = domain;
- }
-
- @Override
- public String getDomain() {
- return this.domain;
- }
-
- @Override
- public void setPath(String path) {
- this.path = path;
- }
-
- @Override
- public String getPath() {
- return this.path;
- }
-
- @Override
- public void setComment(String comment) {
- this.comment = comment;
- }
-
- @Override
- public String getComment() {
- return this.comment;
- }
-
- @Override
- public void setHttpOnly(boolean httpOnly) {
- this.httpOnly = httpOnly;
- }
-
- @Override
- public boolean isHttpOnly() {
- return this.httpOnly;
- }
-
- @Override
- public void setSecure(boolean secure) {
- this.secure = secure;
- }
-
- @Override
- public boolean isSecure() {
- return this.secure;
- }
-
- @Override
- public void setMaxAge(int maxAge) {
- this.maxAge = maxAge;
- }
-
- @Override
- public int getMaxAge() {
- return this.maxAge;
- }
-
-}
-
diff --git a/src/spec/java/org/jruby/rack/mock/RackLoggingMockServletContext.java b/src/spec/java/org/jruby/rack/mock/RackLoggingMockServletContext.java
new file mode 100644
index 00000000..4e4d2438
--- /dev/null
+++ b/src/spec/java/org/jruby/rack/mock/RackLoggingMockServletContext.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2002-2013 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jruby.rack.mock;
+
+import org.jruby.rack.RackLogger;
+
+public class RackLoggingMockServletContext extends org.springframework.mock.web.MockServletContext {
+ private RackLogger logger = new NullLogger();
+
+ public RackLoggingMockServletContext() {
+ }
+
+ public RackLoggingMockServletContext(String resourceBasePath) {
+ super(resourceBasePath);
+ }
+
+ private static class NullLogger extends RackLogger.Base {
+
+ @Override
+ public void log(String message) { /* NOOP */ }
+
+ @Override
+ public void log(String message, Throwable ex) { /* NOOP */ }
+
+ @Override
+ public boolean isEnabled(Level level) {
+ return false;
+ }
+
+ @Override
+ public void log(Level level, String message) { /* NOOP */ }
+
+ @Override
+ public void log(Level level, String message, Throwable ex) { /* NOOP */ }
+
+ @Override
+ public Level getLevel() {
+ return null;
+ }
+
+ }
+
+ @Override
+ public void log(String message) {
+ logger.log(message);
+ }
+
+ @Override
+ @SuppressWarnings("deprecation")
+ public void log(Exception ex, String message) {
+ logger.log(message, ex);
+ }
+
+ @Override
+ public void log(String message, Throwable ex) {
+ logger.log(message, ex);
+ }
+
+ public RackLogger getLogger() {
+ return (logger instanceof NullLogger) ? null : logger;
+ }
+
+ public void setLogger(RackLogger logger) {
+ this.logger = logger == null ? new NullLogger() : logger;
+ }
+}
diff --git a/src/spec/java/org/jruby/rack/mock/WebUtils.java b/src/spec/java/org/jruby/rack/mock/WebUtils.java
deleted file mode 100644
index cafd326e..00000000
--- a/src/spec/java/org/jruby/rack/mock/WebUtils.java
+++ /dev/null
@@ -1,738 +0,0 @@
-/*
- * Copyright 2002-2014 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.jruby.rack.mock;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.util.Enumeration;
-import java.util.Map;
-import java.util.StringTokenizer;
-import java.util.TreeMap;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletRequestWrapper;
-import javax.servlet.ServletResponse;
-import javax.servlet.ServletResponseWrapper;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.springframework.util.Assert;
-import org.springframework.util.LinkedMultiValueMap;
-import org.springframework.util.MultiValueMap;
-import org.springframework.util.StringUtils;
-
-/**
- * Miscellaneous utilities for web applications.
- * Used by various framework classes.
- *
- * @author Rod Johnson
- * @author Juergen Hoeller
- */
-abstract class WebUtils {
-
- /**
- * Standard Servlet 2.3+ spec request attributes for include URI and paths.
- * If included via a RequestDispatcher, the current resource will see the
- * originating request. Its own URI and paths are exposed as request attributes.
- */
- public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri";
- public static final String INCLUDE_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.include.context_path";
- public static final String INCLUDE_SERVLET_PATH_ATTRIBUTE = "javax.servlet.include.servlet_path";
- public static final String INCLUDE_PATH_INFO_ATTRIBUTE = "javax.servlet.include.path_info";
- public static final String INCLUDE_QUERY_STRING_ATTRIBUTE = "javax.servlet.include.query_string";
-
- /**
- * Standard Servlet 2.4+ spec request attributes for forward URI and paths.
- *
If forwarded to via a RequestDispatcher, the current resource will see its
- * own URI and paths. The originating URI and paths are exposed as request attributes.
- */
- public static final String FORWARD_REQUEST_URI_ATTRIBUTE = "javax.servlet.forward.request_uri";
- public static final String FORWARD_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.forward.context_path";
- public static final String FORWARD_SERVLET_PATH_ATTRIBUTE = "javax.servlet.forward.servlet_path";
- public static final String FORWARD_PATH_INFO_ATTRIBUTE = "javax.servlet.forward.path_info";
- public static final String FORWARD_QUERY_STRING_ATTRIBUTE = "javax.servlet.forward.query_string";
-
- /**
- * Standard Servlet 2.3+ spec request attributes for error pages.
- *
To be exposed to JSPs that are marked as error pages, when forwarding
- * to them directly rather than through the servlet container's error page
- * resolution mechanism.
- */
- public static final String ERROR_STATUS_CODE_ATTRIBUTE = "javax.servlet.error.status_code";
- public static final String ERROR_EXCEPTION_TYPE_ATTRIBUTE = "javax.servlet.error.exception_type";
- public static final String ERROR_MESSAGE_ATTRIBUTE = "javax.servlet.error.message";
- public static final String ERROR_EXCEPTION_ATTRIBUTE = "javax.servlet.error.exception";
- public static final String ERROR_REQUEST_URI_ATTRIBUTE = "javax.servlet.error.request_uri";
- public static final String ERROR_SERVLET_NAME_ATTRIBUTE = "javax.servlet.error.servlet_name";
-
-
- /**
- * Prefix of the charset clause in a content type String: ";charset="
- */
- public static final String CONTENT_TYPE_CHARSET_PREFIX = ";charset=";
-
- /**
- * Default character encoding to use when {@code request.getCharacterEncoding}
- * returns {@code null}, according to the Servlet spec.
- * @see ServletRequest#getCharacterEncoding
- */
- public static final String DEFAULT_CHARACTER_ENCODING = "ISO-8859-1";
-
- /**
- * Standard Servlet spec context attribute that specifies a temporary
- * directory for the current web application, of type {@code java.io.File}.
- */
- public static final String TEMP_DIR_CONTEXT_ATTRIBUTE = "javax.servlet.context.tempdir";
-
- /**
- * HTML escape parameter at the servlet context level
- * (i.e. a context-param in {@code web.xml}): "defaultHtmlEscape".
- */
- public static final String HTML_ESCAPE_CONTEXT_PARAM = "defaultHtmlEscape";
-
- /**
- * Web app root key parameter at the servlet context level
- * (i.e. a context-param in {@code web.xml}): "webAppRootKey".
- */
- public static final String WEB_APP_ROOT_KEY_PARAM = "webAppRootKey";
-
- /** Default web app root key: "webapp.root" */
- public static final String DEFAULT_WEB_APP_ROOT_KEY = "webapp.root";
-
- /** Name suffixes in case of image buttons */
- public static final String[] SUBMIT_IMAGE_SUFFIXES = {".x", ".y"};
-
- /** Key for the mutex session attribute */
- public static final String SESSION_MUTEX_ATTRIBUTE = WebUtils.class.getName() + ".MUTEX";
-
-
- /**
- * Set a system property to the web application root directory.
- * The key of the system property can be defined with the "webAppRootKey"
- * context-param in {@code web.xml}. Default is "webapp.root".
- *
Can be used for tools that support substition with {@code System.getProperty}
- * values, like log4j's "${key}" syntax within log file locations.
- * @param servletContext the servlet context of the web application
- * @throws IllegalStateException if the system property is already set,
- * or if the WAR file is not expanded
- * @see #WEB_APP_ROOT_KEY_PARAM
- * @see #DEFAULT_WEB_APP_ROOT_KEY
- * @see WebAppRootListener
- * @see Log4jWebConfigurer
- */
- public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
- Assert.notNull(servletContext, "ServletContext must not be null");
- String root = servletContext.getRealPath("/");
- if (root == null) {
- throw new IllegalStateException(
- "Cannot set web app root system property when WAR file is not expanded");
- }
- String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
- String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
- String oldValue = System.getProperty(key);
- if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
- throw new IllegalStateException(
- "Web app root system property already set to different value: '" +
- key + "' = [" + oldValue + "] instead of [" + root + "] - " +
- "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
- }
- System.setProperty(key, root);
- servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
- }
-
- /**
- * Remove the system property that points to the web app root directory.
- * To be called on shutdown of the web application.
- * @param servletContext the servlet context of the web application
- * @see #setWebAppRootSystemProperty
- */
- public static void removeWebAppRootSystemProperty(ServletContext servletContext) {
- Assert.notNull(servletContext, "ServletContext must not be null");
- String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
- String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
- System.getProperties().remove(key);
- }
-
- /**
- * Return whether default HTML escaping is enabled for the web application,
- * i.e. the value of the "defaultHtmlEscape" context-param in {@code web.xml}
- * (if any). Falls back to {@code false} in case of no explicit default given.
- * @param servletContext the servlet context of the web application
- * @return whether default HTML escaping is enabled (default is false)
- */
- public static boolean isDefaultHtmlEscape(ServletContext servletContext) {
- if (servletContext == null) {
- return false;
- }
- String param = servletContext.getInitParameter(HTML_ESCAPE_CONTEXT_PARAM);
- return Boolean.valueOf(param);
- }
-
- /**
- * Return whether default HTML escaping is enabled for the web application,
- * i.e. the value of the "defaultHtmlEscape" context-param in {@code web.xml}
- * (if any).
- *
This method differentiates between no param specified at all and
- * an actual boolean value specified, allowing to have a context-specific
- * default in case of no setting at the global level.
- * @param servletContext the servlet context of the web application
- * @return whether default HTML escaping is enabled (null = no explicit default)
- */
- public static Boolean getDefaultHtmlEscape(ServletContext servletContext) {
- if (servletContext == null) {
- return null;
- }
- String param = servletContext.getInitParameter(HTML_ESCAPE_CONTEXT_PARAM);
- return (StringUtils.hasText(param)? Boolean.valueOf(param) : null);
- }
-
- /**
- * Return the temporary directory for the current web application,
- * as provided by the servlet container.
- * @param servletContext the servlet context of the web application
- * @return the File representing the temporary directory
- */
- public static File getTempDir(ServletContext servletContext) {
- Assert.notNull(servletContext, "ServletContext must not be null");
- return (File) servletContext.getAttribute(TEMP_DIR_CONTEXT_ATTRIBUTE);
- }
-
- /**
- * Return the real path of the given path within the web application,
- * as provided by the servlet container.
- *
Prepends a slash if the path does not already start with a slash,
- * and throws a FileNotFoundException if the path cannot be resolved to
- * a resource (in contrast to ServletContext's {@code getRealPath},
- * which returns null).
- * @param servletContext the servlet context of the web application
- * @param path the path within the web application
- * @return the corresponding real path
- * @throws FileNotFoundException if the path cannot be resolved to a resource
- * @see javax.servlet.ServletContext#getRealPath
- */
- public static String getRealPath(ServletContext servletContext, String path) throws FileNotFoundException {
- Assert.notNull(servletContext, "ServletContext must not be null");
- // Interpret location as relative to the web application root directory.
- if (!path.startsWith("/")) {
- path = "/" + path;
- }
- String realPath = servletContext.getRealPath(path);
- if (realPath == null) {
- throw new FileNotFoundException(
- "ServletContext resource [" + path + "] cannot be resolved to absolute file path - " +
- "web application archive not expanded?");
- }
- return realPath;
- }
-
-
- /**
- * Determine the session id of the given request, if any.
- * @param request current HTTP request
- * @return the session id, or {@code null} if none
- */
- public static String getSessionId(HttpServletRequest request) {
- Assert.notNull(request, "Request must not be null");
- HttpSession session = request.getSession(false);
- return (session != null ? session.getId() : null);
- }
-
- /**
- * Check the given request for a session attribute of the given name.
- * Returns null if there is no session or if the session has no such attribute.
- * Does not create a new session if none has existed before!
- * @param request current HTTP request
- * @param name the name of the session attribute
- * @return the value of the session attribute, or {@code null} if not found
- */
- public static Object getSessionAttribute(HttpServletRequest request, String name) {
- Assert.notNull(request, "Request must not be null");
- HttpSession session = request.getSession(false);
- return (session != null ? session.getAttribute(name) : null);
- }
-
- /**
- * Check the given request for a session attribute of the given name.
- * Throws an exception if there is no session or if the session has no such
- * attribute. Does not create a new session if none has existed before!
- * @param request current HTTP request
- * @param name the name of the session attribute
- * @return the value of the session attribute, or {@code null} if not found
- * @throws IllegalStateException if the session attribute could not be found
- */
- public static Object getRequiredSessionAttribute(HttpServletRequest request, String name)
- throws IllegalStateException {
-
- Object attr = getSessionAttribute(request, name);
- if (attr == null) {
- throw new IllegalStateException("No session attribute '" + name + "' found");
- }
- return attr;
- }
-
- /**
- * Set the session attribute with the given name to the given value.
- * Removes the session attribute if value is null, if a session existed at all.
- * Does not create a new session if not necessary!
- * @param request current HTTP request
- * @param name the name of the session attribute
- * @param value the value of the session attribute
- */
- public static void setSessionAttribute(HttpServletRequest request, String name, Object value) {
- Assert.notNull(request, "Request must not be null");
- if (value != null) {
- request.getSession().setAttribute(name, value);
- }
- else {
- HttpSession session = request.getSession(false);
- if (session != null) {
- session.removeAttribute(name);
- }
- }
- }
-
- /**
- * Get the specified session attribute, creating and setting a new attribute if
- * no existing found. The given class needs to have a public no-arg constructor.
- * Useful for on-demand state objects in a web tier, like shopping carts.
- * @param session current HTTP session
- * @param name the name of the session attribute
- * @param clazz the class to instantiate for a new attribute
- * @return the value of the session attribute, newly created if not found
- * @throws IllegalArgumentException if the session attribute could not be instantiated
- */
- public static Object getOrCreateSessionAttribute(HttpSession session, String name, Class> clazz)
- throws IllegalArgumentException {
-
- Assert.notNull(session, "Session must not be null");
- Object sessionObject = session.getAttribute(name);
- if (sessionObject == null) {
- try {
- sessionObject = clazz.newInstance();
- }
- catch (InstantiationException ex) {
- throw new IllegalArgumentException(
- "Could not instantiate class [" + clazz.getName() +
- "] for session attribute '" + name + "': " + ex.getMessage());
- }
- catch (IllegalAccessException ex) {
- throw new IllegalArgumentException(
- "Could not access default constructor of class [" + clazz.getName() +
- "] for session attribute '" + name + "': " + ex.getMessage());
- }
- session.setAttribute(name, sessionObject);
- }
- return sessionObject;
- }
-
- /**
- * Return the best available mutex for the given session:
- * that is, an object to synchronize on for the given session.
- *
Returns the session mutex attribute if available; usually,
- * this means that the HttpSessionMutexListener needs to be defined
- * in {@code web.xml}. Falls back to the HttpSession itself
- * if no mutex attribute found.
- *
The session mutex is guaranteed to be the same object during
- * the entire lifetime of the session, available under the key defined
- * by the {@code SESSION_MUTEX_ATTRIBUTE} constant. It serves as a
- * safe reference to synchronize on for locking on the current session.
- *
In many cases, the HttpSession reference itself is a safe mutex
- * as well, since it will always be the same object reference for the
- * same active logical session. However, this is not guaranteed across
- * different servlet containers; the only 100% safe way is a session mutex.
- * @param session the HttpSession to find a mutex for
- * @return the mutex object (never {@code null})
- * @see #SESSION_MUTEX_ATTRIBUTE
- * @see HttpSessionMutexListener
- */
- public static Object getSessionMutex(HttpSession session) {
- Assert.notNull(session, "Session must not be null");
- Object mutex = session.getAttribute(SESSION_MUTEX_ATTRIBUTE);
- if (mutex == null) {
- mutex = session;
- }
- return mutex;
- }
-
-
- /**
- * Return an appropriate request object of the specified type, if available,
- * unwrapping the given request as far as necessary.
- * @param request the servlet request to introspect
- * @param requiredType the desired type of request object
- * @return the matching request object, or {@code null} if none
- * of that type is available
- */
- @SuppressWarnings("unchecked")
- public static T getNativeRequest(ServletRequest request, Class requiredType) {
- if (requiredType != null) {
- if (requiredType.isInstance(request)) {
- return (T) request;
- }
- else if (request instanceof ServletRequestWrapper) {
- return getNativeRequest(((ServletRequestWrapper) request).getRequest(), requiredType);
- }
- }
- return null;
- }
-
- /**
- * Return an appropriate response object of the specified type, if available,
- * unwrapping the given response as far as necessary.
- * @param response the servlet response to introspect
- * @param requiredType the desired type of response object
- * @return the matching response object, or {@code null} if none
- * of that type is available
- */
- @SuppressWarnings("unchecked")
- public static T getNativeResponse(ServletResponse response, Class requiredType) {
- if (requiredType != null) {
- if (requiredType.isInstance(response)) {
- return (T) response;
- }
- else if (response instanceof ServletResponseWrapper) {
- return getNativeResponse(((ServletResponseWrapper) response).getResponse(), requiredType);
- }
- }
- return null;
- }
-
- /**
- * Determine whether the given request is an include request,
- * that is, not a top-level HTTP request coming in from the outside.
- * Checks the presence of the "javax.servlet.include.request_uri"
- * request attribute. Could check any request attribute that is only
- * present in an include request.
- * @param request current servlet request
- * @return whether the given request is an include request
- */
- public static boolean isIncludeRequest(ServletRequest request) {
- return (request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null);
- }
-
- /**
- * Expose the Servlet spec's error attributes as {@link javax.servlet.http.HttpServletRequest}
- * attributes under the keys defined in the Servlet 2.3 specification, for error pages that
- * are rendered directly rather than through the Servlet container's error page resolution:
- * {@code javax.servlet.error.status_code},
- * {@code javax.servlet.error.exception_type},
- * {@code javax.servlet.error.message},
- * {@code javax.servlet.error.exception},
- * {@code javax.servlet.error.request_uri},
- * {@code javax.servlet.error.servlet_name}.
- *
Does not override values if already present, to respect attribute values
- * that have been exposed explicitly before.
- *
Exposes status code 200 by default. Set the "javax.servlet.error.status_code"
- * attribute explicitly (before or after) in order to expose a different status code.
- * @param request current servlet request
- * @param ex the exception encountered
- * @param servletName the name of the offending servlet
- */
- public static void exposeErrorRequestAttributes(HttpServletRequest request, Throwable ex, String servletName) {
- exposeRequestAttributeIfNotPresent(request, ERROR_STATUS_CODE_ATTRIBUTE, HttpServletResponse.SC_OK);
- exposeRequestAttributeIfNotPresent(request, ERROR_EXCEPTION_TYPE_ATTRIBUTE, ex.getClass());
- exposeRequestAttributeIfNotPresent(request, ERROR_MESSAGE_ATTRIBUTE, ex.getMessage());
- exposeRequestAttributeIfNotPresent(request, ERROR_EXCEPTION_ATTRIBUTE, ex);
- exposeRequestAttributeIfNotPresent(request, ERROR_REQUEST_URI_ATTRIBUTE, request.getRequestURI());
- exposeRequestAttributeIfNotPresent(request, ERROR_SERVLET_NAME_ATTRIBUTE, servletName);
- }
-
- /**
- * Expose the specified request attribute if not already present.
- * @param request current servlet request
- * @param name the name of the attribute
- * @param value the suggested value of the attribute
- */
- private static void exposeRequestAttributeIfNotPresent(ServletRequest request, String name, Object value) {
- if (request.getAttribute(name) == null) {
- request.setAttribute(name, value);
- }
- }
-
- /**
- * Clear the Servlet spec's error attributes as {@link javax.servlet.http.HttpServletRequest}
- * attributes under the keys defined in the Servlet 2.3 specification:
- * {@code javax.servlet.error.status_code},
- * {@code javax.servlet.error.exception_type},
- * {@code javax.servlet.error.message},
- * {@code javax.servlet.error.exception},
- * {@code javax.servlet.error.request_uri},
- * {@code javax.servlet.error.servlet_name}.
- * @param request current servlet request
- */
- public static void clearErrorRequestAttributes(HttpServletRequest request) {
- request.removeAttribute(ERROR_STATUS_CODE_ATTRIBUTE);
- request.removeAttribute(ERROR_EXCEPTION_TYPE_ATTRIBUTE);
- request.removeAttribute(ERROR_MESSAGE_ATTRIBUTE);
- request.removeAttribute(ERROR_EXCEPTION_ATTRIBUTE);
- request.removeAttribute(ERROR_REQUEST_URI_ATTRIBUTE);
- request.removeAttribute(ERROR_SERVLET_NAME_ATTRIBUTE);
- }
-
- /**
- * Expose the given Map as request attributes, using the keys as attribute names
- * and the values as corresponding attribute values. Keys need to be Strings.
- * @param request current HTTP request
- * @param attributes the attributes Map
- */
- public static void exposeRequestAttributes(ServletRequest request, Map attributes) {
- Assert.notNull(request, "Request must not be null");
- Assert.notNull(attributes, "Attributes Map must not be null");
- for (Map.Entry entry : attributes.entrySet()) {
- request.setAttribute(entry.getKey(), entry.getValue());
- }
- }
-
- /**
- * Retrieve the first cookie with the given name. Note that multiple
- * cookies can have the same name but different paths or domains.
- * @param request current servlet request
- * @param name cookie name
- * @return the first cookie with the given name, or {@code null} if none is found
- */
- public static Cookie getCookie(HttpServletRequest request, String name) {
- Assert.notNull(request, "Request must not be null");
- Cookie cookies[] = request.getCookies();
- if (cookies != null) {
- for (Cookie cookie : cookies) {
- if (name.equals(cookie.getName())) {
- return cookie;
- }
- }
- }
- return null;
- }
-
- /**
- * Check if a specific input type="submit" parameter was sent in the request,
- * either via a button (directly with name) or via an image (name + ".x" or
- * name + ".y").
- * @param request current HTTP request
- * @param name name of the parameter
- * @return if the parameter was sent
- * @see #SUBMIT_IMAGE_SUFFIXES
- */
- public static boolean hasSubmitParameter(ServletRequest request, String name) {
- Assert.notNull(request, "Request must not be null");
- if (request.getParameter(name) != null) {
- return true;
- }
- for (String suffix : SUBMIT_IMAGE_SUFFIXES) {
- if (request.getParameter(name + suffix) != null) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Obtain a named parameter from the given request parameters.
- * See {@link #findParameterValue(java.util.Map, String)}
- * for a description of the lookup algorithm.
- * @param request current HTTP request
- * @param name the logical name of the request parameter
- * @return the value of the parameter, or {@code null}
- * if the parameter does not exist in given request
- */
- public static String findParameterValue(ServletRequest request, String name) {
- return findParameterValue(request.getParameterMap(), name);
- }
-
- /**
- * Obtain a named parameter from the given request parameters.
- *
This method will try to obtain a parameter value using the
- * following algorithm:
- *
- * Try to get the parameter value using just the given logical name.
- * This handles parameters of the form logicalName = value . For normal
- * parameters, e.g. submitted using a hidden HTML form field, this will return
- * the requested value.
- * Try to obtain the parameter value from the parameter name, where the
- * parameter name in the request is of the form logicalName_value = xyz
- * with "_" being the configured delimiter. This deals with parameter values
- * submitted using an HTML form submit button.
- * If the value obtained in the previous step has a ".x" or ".y" suffix,
- * remove that. This handles cases where the value was submitted using an
- * HTML form image button. In this case the parameter in the request would
- * actually be of the form logicalName_value.x = 123 .
- *
- * @param parameters the available parameter map
- * @param name the logical name of the request parameter
- * @return the value of the parameter, or {@code null}
- * if the parameter does not exist in given request
- */
- public static String findParameterValue(Map parameters, String name) {
- // First try to get it as a normal name=value parameter
- Object value = parameters.get(name);
- if (value instanceof String[]) {
- String[] values = (String[]) value;
- return (values.length > 0 ? values[0] : null);
- }
- else if (value != null) {
- return value.toString();
- }
- // If no value yet, try to get it as a name_value=xyz parameter
- String prefix = name + "_";
- for (String paramName : parameters.keySet()) {
- if (paramName.startsWith(prefix)) {
- // Support images buttons, which would submit parameters as name_value.x=123
- for (String suffix : SUBMIT_IMAGE_SUFFIXES) {
- if (paramName.endsWith(suffix)) {
- return paramName.substring(prefix.length(), paramName.length() - suffix.length());
- }
- }
- return paramName.substring(prefix.length());
- }
- }
- // We couldn't find the parameter value...
- return null;
- }
-
- /**
- * Return a map containing all parameters with the given prefix.
- * Maps single values to String and multiple values to String array.
- * For example, with a prefix of "spring_", "spring_param1" and
- * "spring_param2" result in a Map with "param1" and "param2" as keys.
- * @param request HTTP request in which to look for parameters
- * @param prefix the beginning of parameter names
- * (if this is null or the empty string, all parameters will match)
- * @return map containing request parameters without the prefix ,
- * containing either a String or a String array as values
- * @see javax.servlet.ServletRequest#getParameterNames
- * @see javax.servlet.ServletRequest#getParameterValues
- * @see javax.servlet.ServletRequest#getParameterMap
- */
- public static Map getParametersStartingWith(ServletRequest request, String prefix) {
- Assert.notNull(request, "Request must not be null");
- Enumeration paramNames = request.getParameterNames();
- Map params = new TreeMap();
- if (prefix == null) {
- prefix = "";
- }
- while (paramNames != null && paramNames.hasMoreElements()) {
- String paramName = paramNames.nextElement();
- if ("".equals(prefix) || paramName.startsWith(prefix)) {
- String unprefixed = paramName.substring(prefix.length());
- String[] values = request.getParameterValues(paramName);
- if (values == null || values.length == 0) {
- // Do nothing, no values found at all.
- }
- else if (values.length > 1) {
- params.put(unprefixed, values);
- }
- else {
- params.put(unprefixed, values[0]);
- }
- }
- }
- return params;
- }
-
- /**
- * Return the target page specified in the request.
- * @param request current servlet request
- * @param paramPrefix the parameter prefix to check for
- * (e.g. "_target" for parameters like "_target1" or "_target2")
- * @param currentPage the current page, to be returned as fallback
- * if no target page specified
- * @return the page specified in the request, or current page if not found
- */
- public static int getTargetPage(ServletRequest request, String paramPrefix, int currentPage) {
- Enumeration paramNames = request.getParameterNames();
- while (paramNames.hasMoreElements()) {
- String paramName = paramNames.nextElement();
- if (paramName.startsWith(paramPrefix)) {
- for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) {
- String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i];
- if (paramName.endsWith(suffix)) {
- paramName = paramName.substring(0, paramName.length() - suffix.length());
- }
- }
- return Integer.parseInt(paramName.substring(paramPrefix.length()));
- }
- }
- return currentPage;
- }
-
-
- /**
- * Extract the URL filename from the given request URL path.
- * Correctly resolves nested paths such as "/products/view.html" as well.
- * @param urlPath the request URL path (e.g. "/index.html")
- * @return the extracted URI filename (e.g. "index")
- */
- public static String extractFilenameFromUrlPath(String urlPath) {
- String filename = extractFullFilenameFromUrlPath(urlPath);
- int dotIndex = filename.lastIndexOf('.');
- if (dotIndex != -1) {
- filename = filename.substring(0, dotIndex);
- }
- return filename;
- }
-
- /**
- * Extract the full URL filename (including file extension) from the given request URL path.
- * Correctly resolves nested paths such as "/products/view.html" as well.
- * @param urlPath the request URL path (e.g. "/products/index.html")
- * @return the extracted URI filename (e.g. "index.html")
- */
- public static String extractFullFilenameFromUrlPath(String urlPath) {
- int end = urlPath.indexOf(';');
- if (end == -1) {
- end = urlPath.indexOf('?');
- if (end == -1) {
- end = urlPath.length();
- }
- }
- int begin = urlPath.lastIndexOf('/', end) + 1;
- return urlPath.substring(begin, end);
- }
-
- /**
- * Parse the given string with matrix variables. An example string would look
- * like this {@code "q1=a;q1=b;q2=a,b,c"}. The resulting map would contain
- * keys {@code "q1"} and {@code "q2"} with values {@code ["a","b"]} and
- * {@code ["a","b","c"]} respectively.
- *
- * @param matrixVariables the unparsed matrix variables string
- * @return a map with matrix variable names and values, never {@code null}
- */
- public static MultiValueMap parseMatrixVariables(String matrixVariables) {
- MultiValueMap result = new LinkedMultiValueMap();
- if (!StringUtils.hasText(matrixVariables)) {
- return result;
- }
- StringTokenizer pairs = new StringTokenizer(matrixVariables, ";");
- while (pairs.hasMoreTokens()) {
- String pair = pairs.nextToken();
- int index = pair.indexOf('=');
- if (index != -1) {
- String name = pair.substring(0, index);
- String rawValue = pair.substring(index + 1);
- for (String value : StringUtils.commaDelimitedListToStringArray(rawValue)) {
- result.add(name, value);
- }
- }
- else {
- result.add(pair, "");
- }
- }
- return result;
- }
-}
-
diff --git a/src/spec/java/org/jruby/rack/mock/fail/FailingHttpServletResponse.java b/src/spec/java/org/jruby/rack/mock/fail/FailingHttpServletResponse.java
index 584d923b..1ac5b581 100644
--- a/src/spec/java/org/jruby/rack/mock/fail/FailingHttpServletResponse.java
+++ b/src/spec/java/org/jruby/rack/mock/fail/FailingHttpServletResponse.java
@@ -23,21 +23,20 @@
*/
package org.jruby.rack.mock.fail;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.ServletOutputStream;
import java.io.IOException;
-import org.jruby.rack.mock.MockHttpServletResponse;
/**
* @author kares
*/
public class FailingHttpServletResponse extends MockHttpServletResponse {
- private FailingServletOutputStream outputStream;
+ private FailingServletOutputStream outputStream = new FailingServletOutputStream(new IOException("Broken pipe"));
@Override
- public FailingServletOutputStream getOutputStream() {
- if (outputStream == null) {
- outputStream = new FailingServletOutputStream(new IOException("Broken pipe"));
- }
+ public ServletOutputStream getOutputStream() {
return outputStream;
}
@@ -46,7 +45,7 @@ public void setOutputStream(FailingServletOutputStream outputStream) {
}
public void setFailure(IOException failure) {
- getOutputStream().setFailure(failure);
+ outputStream.setFailure(failure);
}
}
diff --git a/src/spec/java/org/jruby/rack/mock/fail/FailingServletOutputStream.java b/src/spec/java/org/jruby/rack/mock/fail/FailingServletOutputStream.java
index 5d47e0f0..008e44a1 100644
--- a/src/spec/java/org/jruby/rack/mock/fail/FailingServletOutputStream.java
+++ b/src/spec/java/org/jruby/rack/mock/fail/FailingServletOutputStream.java
@@ -23,9 +23,11 @@
*/
package org.jruby.rack.mock.fail;
+import org.springframework.mock.web.DelegatingServletOutputStream;
+
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import org.jruby.rack.mock.DelegatingServletOutputStream;
/**
* @author kares
@@ -35,7 +37,7 @@ public class FailingServletOutputStream extends DelegatingServletOutputStream {
private IOException failure;
public FailingServletOutputStream(final IOException failure) {
- super(null);
+ super(new ByteArrayOutputStream());
this.failure = failure;
}
diff --git a/src/spec/ruby/action_controller/session/java_servlet_store_spec.rb b/src/spec/ruby/action_controller/session/java_servlet_store_spec.rb
index caa804c3..444abf75 100644
--- a/src/spec/ruby/action_controller/session/java_servlet_store_spec.rb
+++ b/src/spec/ruby/action_controller/session/java_servlet_store_spec.rb
@@ -28,14 +28,11 @@
@session.stub(:synchronized).and_yield
@request = double "servlet request"
@app = double "app"
+ @app.stub(:call).and_return [200, {}, ["body"]]
@env = {"java.servlet_request" => @request, "rack.errors" => $stderr}
@session_store = ActionController::Session::JavaServletStore.new(@app)
end
- it "should raise an error if the servlet request is not present" do
- expect { @session_store.call({}) }.to raise_error(RuntimeError)
- end
-
it "should do nothing if the session is not accessed" do
@app.should_receive(:call)
@session_store.call(@env)
@@ -45,13 +42,13 @@
@app.should_receive(:call)
@session_store.call(@env)
session = @env['rack.session']
- @session_store.send(:loaded_session?, session).should == false
+ expect(@session_store.send(:loaded_session?, session)).to eq false
end
it "should pass the application response untouched" do
response = [200, {}, ["body"]]
@app.should_receive(:call).and_return response
- @session_store.call(@env).should == response
+ expect(@session_store.call(@env)).to eq response
end
it "should load the session when accessed" do
@@ -78,7 +75,7 @@
end
@session_store.call(@env)
session = @env['rack.session']
- @session_store.send(:loaded_session?, session).should == true
+ expect(@session_store.send(:loaded_session?, session)).to eq true
end
it "should use custom session hash when loading session" do
@@ -95,7 +92,7 @@
@request.should_receive(:getSession).with(false).and_return @session
@app.should_receive(:call)
@session_store.call(@env)
- @session_store.send(:extract_session_id, @env).should == @session_id
+ expect(@session_store.send(:extract_session_id, Rack::Request.new(@env))).to eq @session_id
end
it "should retrieve the marshalled session from the java session" do
@@ -107,8 +104,8 @@
@session.should_receive(:getAttribute).with(session_key).and_return marshal_data.to_java_bytes
@session.stub(:setAttribute); @session.stub(:getCreationTime).and_return 1
@app.should_receive(:call) do |env|
- env['rack.session']["foo"].should == 1
- env['rack.session']["bar"].should == true
+ expect(env['rack.session']["foo"]).to eq 1
+ expect(env['rack.session']["bar"]).to eq true
end
@session_store.call(@env)
end
@@ -121,8 +118,8 @@
@session.should_receive(:getAttribute).with("bar").and_return hash["bar"]
@session.stub(:setAttribute); @session.stub(:getCreationTime).and_return 1
@app.should_receive(:call) do |env|
- env['rack.session']["foo"].should == hash["foo"]
- env['rack.session']["bar"].should == hash["bar"]
+ expect(env['rack.session']["foo"]).to eq hash["foo"]
+ expect(env['rack.session']["bar"]).to eq hash["bar"]
end
@session_store.call(@env)
end
@@ -221,7 +218,7 @@
end
it "should attempt to invalidate an invalid servlet session" do
- session = double_http_session(nil); session.invalidate
+ session = double_http_session; session.invalidate
@request.should_receive(:getSession).with(false).and_return session
@app.should_receive(:call) do |env|
@@ -261,32 +258,29 @@
@session.should_receive(:getLastAccessedTime).and_return time
@session.stub(:setAttribute)
@app.should_receive(:call) do |env|
- env['rack.session'].getLastAccessedTime.should == time
+ expect(env['rack.session'].getLastAccessedTime).to eq time
lambda { env['rack.session'].blah_blah }.should raise_error(NoMethodError)
end
@session_store.call(@env)
end
it "supports renewing a session" do
- session = double_http_session sid = "EC72C9F8EC984052C6F13D08893121DF"
+ session = double_http_session
@request.should_receive(:getSession).ordered.with(false).and_return(session)
new_session = double_http_session
@request.should_receive(:getSession).ordered.with(true).and_return(new_session)
@app.should_receive(:call) do |env|
- env['rack.session.options'] = { :id => sid, :renew => true, :defer => true }
+ env['rack.session.options'] = { :id => session.id, :renew => true, :defer => true }
env['rack.session']['_csrf_token'] = 'v3PrzsdkWug9Q3xCthKkEzUMbZSzgQ9Bt+43lH0bEF8='
end
@session_store.call(@env)
expect( session.isInvalid ).to be true
- attrs = session.send(:getAttributes)
- expect( attrs['_csrf_token'] ).to be nil
expect( new_session.isInvalid ).to be false
- attrs = new_session.send(:getAttributes)
- expect( attrs['_csrf_token'] ).to_not be nil
+ expect( new_session.send(:getAttribute, "_csrf_token") ).to_not be nil
end
it "handles the skip session option" do
@@ -301,10 +295,8 @@
private
- def double_http_session(id = false)
- session = Java::OrgJrubyRackMock::MockHttpSession.new
- session.send(:setId, id) if id != false
- session
+ def double_http_session
+ Java::OrgSpringframeworkMockWeb::MockHttpSession.new
end
def new_session_hash(*args)
@@ -313,7 +305,7 @@ def new_session_hash(*args)
else
store = @session_store; env = args[0];
end
- ::JRuby::Rack::Session::SessionHash.new(store, env)
+ ::JRuby::Rack::Session::SessionHash.new(store, ::Rack::Request.new(env))
end
end if defined? Rails
diff --git a/src/spec/ruby/jruby/rack/integration_spec.rb b/src/spec/ruby/jruby/rack/integration_spec.rb
index 96a1f009..9464ebbb 100644
--- a/src/spec/ruby/jruby/rack/integration_spec.rb
+++ b/src/spec/ruby/jruby/rack/integration_spec.rb
@@ -20,7 +20,7 @@
describe 'rack (lambda)' do
before do
- @servlet_context = org.jruby.rack.mock.MockServletContext.new "file://#{STUB_DIR}/rack"
+ @servlet_context = org.jruby.rack.mock.RackLoggingMockServletContext.new "file://#{STUB_DIR}/rack"
@servlet_context.logger = raise_logger
# make sure we always boot runtimes in the same mode as specs :
set_compat_version @servlet_context
@@ -56,7 +56,7 @@
end
it "inits servlet" do
- servlet_config = org.jruby.rack.mock.MockServletConfig.new @servlet_context
+ servlet_config = org.springframework.mock.web.MockServletConfig.new @servlet_context
servlet = org.jruby.rack.RackServlet.new
servlet.init(servlet_config)
@@ -68,12 +68,12 @@
dispatcher = org.jruby.rack.DefaultRackDispatcher.new(@rack_context)
servlet = org.jruby.rack.RackServlet.new(dispatcher, @rack_context)
- request = org.jruby.rack.mock.MockHttpServletRequest.new(@servlet_context)
+ request = org.springframework.mock.web.MockHttpServletRequest.new(@servlet_context)
request.setMethod("GET")
request.setRequestURI("/")
request.setContentType("text/html")
request.setContent("".to_java.bytes)
- response = org.jruby.rack.mock.MockHttpServletResponse.new
+ response = org.springframework.mock.web.MockHttpServletResponse.new
servlet.service(request, response)
@@ -407,15 +407,7 @@ def expect_to_have_monkey_patched_chunked
script = %{
headers = { 'Transfer-Encoding' => 'chunked' }
- body = [ \"1\".freeze, \"\", \"\nsecond\" ]
-
- if defined? Rack::Chunked::Body # Rails 3.x
- body = Rack::Chunked::Body.new body
- else # Rack 1.1 / 1.2
- chunked = Rack::Chunked.new(nil)
- chunked.chunk(200, headers, body)
- body = chunked
- end
+ body = Rack::Chunked::Body.new [ \"1\".freeze, \"\", \"\nsecond\" ]
parts = []; body.each { |part| parts << part }
parts.join
@@ -431,10 +423,7 @@ def initialize_rails(env = nil, servlet_context = @servlet_context)
servlet_context = new_servlet_context(base)
end
listener = org.jruby.rack.rails.RailsServletContextListener.new
- # Travis-CI might have RAILS_ENV=test set, which is not desired for us :
- #if ENV['RAILS_ENV'] || ENV['RACK_ENV']
- #ENV['RAILS_ENV'] = env; ENV.delete('RACK_ENV')
- #end
+
the_env = "GEM_HOME=#{ENV['GEM_HOME']},GEM_PATH=#{ENV['GEM_PATH']}"
the_env << "\nRAILS_ENV=#{env}" if env
servlet_context.addInitParameter("jruby.runtime.env", the_env)
@@ -452,7 +441,7 @@ def restore_rails
end
def new_servlet_context(base_path = nil)
- servlet_context = org.jruby.rack.mock.MockServletContext.new base_path
+ servlet_context = org.jruby.rack.mock.RackLoggingMockServletContext.new base_path
servlet_context.logger = raise_logger
prepare_servlet_context servlet_context
servlet_context
diff --git a/src/spec/ruby/jruby/rack/logger_spec.rb b/src/spec/ruby/jruby/rack/logger_spec.rb
index bc010c7c..2453307f 100644
--- a/src/spec/ruby/jruby/rack/logger_spec.rb
+++ b/src/spec/ruby/jruby/rack/logger_spec.rb
@@ -7,7 +7,7 @@
end
let(:servlet_context) do
- servlet_context = org.jruby.rack.mock.MockServletContext.new
+ servlet_context = org.jruby.rack.mock.RackLoggingMockServletContext.new
servlet_context.logger = real_logger
servlet_context
end
diff --git a/src/spec/ruby/jruby/rack/rails_booter_spec.rb b/src/spec/ruby/jruby/rack/rails_booter_spec.rb
index e39e38ea..5d828e87 100644
--- a/src/spec/ruby/jruby/rack/rails_booter_spec.rb
+++ b/src/spec/ruby/jruby/rack/rails_booter_spec.rb
@@ -446,8 +446,8 @@ def booter.rails2?; false end
let(:request) { double("request") }
let(:response) { double("response") }
- let(:servlet_request) { org.jruby.rack.mock.MockHttpServletRequest.new }
- let(:servlet_response) { org.jruby.rack.mock.MockHttpServletResponse.new }
+ let(:servlet_request) { org.springframework.mock.web.MockHttpServletRequest.new }
+ let(:servlet_response) { org.springframework.mock.web.MockHttpServletResponse.new }
before :each do
request.stub(:env).and_return({
diff --git a/src/spec/ruby/jruby/rack/response_spec.rb b/src/spec/ruby/jruby/rack/response_spec.rb
index c9338230..7de11aa0 100644
--- a/src/spec/ruby/jruby/rack/response_spec.rb
+++ b/src/spec/ruby/jruby/rack/response_spec.rb
@@ -170,14 +170,8 @@ class << value; undef_method :each; end if value.respond_to?(:each)
]
with_dechunk do
- if defined? Rack::Chunked::Body # Rails 3.x
- body = Rack::Chunked::Body.new body
- response = JRuby::Rack::Response.new([ 200, headers, body ])
- else # Rails 2.3 -> Rack 1.1
- chunked = Rack::Chunked.new nil # nil application
- response = JRuby::Rack::Response.new chunked.chunk(200, headers, body)
- end
-
+ body = Rack::Chunked::Body.new body
+ response = JRuby::Rack::Response.new([ 200, headers, body ])
response.write_headers(response_environment)
times = 0
diff --git a/src/spec/ruby/jruby/rack/servlet_ext_spec.rb b/src/spec/ruby/jruby/rack/servlet_ext_spec.rb
index d51f2c48..17dcae19 100644
--- a/src/spec/ruby/jruby/rack/servlet_ext_spec.rb
+++ b/src/spec/ruby/jruby/rack/servlet_ext_spec.rb
@@ -83,7 +83,7 @@
describe Java::JavaxServlet::ServletContext do
let(:subject) do
- context = org.jruby.rack.mock.MockServletContext.new
+ context = org.springframework.mock.web.MockServletContext.new
context.removeAttribute("javax.servlet.context.tempdir")
context
end
@@ -119,7 +119,7 @@
@request.keys.should == names
end
- let(:subject) { org.jruby.rack.mock.MockHttpServletRequest.new }
+ let(:subject) { org.springframework.mock.web.MockHttpServletRequest.new }
it_behaves_like "hash"
@@ -152,7 +152,7 @@
@session.keys.should == names
end
- let(:subject) { org.jruby.rack.mock.MockHttpSession.new }
+ let(:subject) { org.springframework.mock.web.MockHttpSession.new }
it_behaves_like "hash"
diff --git a/src/spec/ruby/rack/application_spec.rb b/src/spec/ruby/rack/application_spec.rb
index d8a5e175..8d5fa895 100644
--- a/src/spec/ruby/rack/application_spec.rb
+++ b/src/spec/ruby/rack/application_spec.rb
@@ -33,11 +33,11 @@
end
let(:servlet_request) do
- org.jruby.rack.mock.MockHttpServletRequest.new(servlet_context)
+ org.springframework.mock.web.MockHttpServletRequest.new(servlet_context)
end
let(:servlet_response) do
- org.jruby.rack.mock.MockHttpServletResponse.new
+ org.springframework.mock.web.MockHttpServletResponse.new
end
let(:rack_config) do
@@ -830,7 +830,7 @@ def createRackServletWrapper(runtime, rackup, filename); end
@pooling_factory.init(@rack_context)
sleep(0.10)
@pooling_factory.getApplicationPool.size.should < 6
- sleep(ENV['TRAVIS'] == 'true' ? 0.9 : 0.45) # 6 x 0.15 == 0.9 but we're parallel
+ sleep(0.9)
@pooling_factory.getApplicationPool.size.should >= 6
expect( @pooling_factory.getManagedApplications ).to_not be_empty
diff --git a/src/spec/ruby/rack/handler/servlet_spec.rb b/src/spec/ruby/rack/handler/servlet_spec.rb
index 72296972..fa4bd04c 100644
--- a/src/spec/ruby/rack/handler/servlet_spec.rb
+++ b/src/spec/ruby/rack/handler/servlet_spec.rb
@@ -17,11 +17,11 @@ def _env; @_env end
let(:servlet_context) { @servlet_context ||= mock_servlet_context }
let(:servlet_request) do
- org.jruby.rack.mock.MockHttpServletRequest.new(servlet_context)
+ org.springframework.mock.web.MockHttpServletRequest.new(servlet_context)
end
let(:servlet_response) do
- org.jruby.rack.mock.MockHttpServletResponse.new
+ org.springframework.mock.web.MockHttpServletResponse.new
end
shared_examples "env" do
@@ -189,7 +189,7 @@ def _env; @_env end
@servlet_request.setRemoteHost('localhost')
@servlet_request.setRemoteUser('admin')
- { "Host" => "localhost",
+ { "Host" => "serverhost",
"Accept" => "text/*",
"Accept-Encoding" => "gzip"}.each do |name, value|
@servlet_request.addHeader(name, value)
@@ -198,7 +198,7 @@ def _env; @_env end
env = servlet.create_env @servlet_env
env["rack.version"].should == Rack::VERSION
env["CONTENT_TYPE"].should == "text/html"
- env["HTTP_HOST"].should == "localhost"
+ env["HTTP_HOST"].should == "serverhost"
env["HTTP_ACCEPT"].should == "text/*"
env["REQUEST_METHOD"].should == "GET"
env["SCRIPT_NAME"].should == "/app"
@@ -341,7 +341,7 @@ def _env; @_env end
end
it "retrieves hidden attribute" do
- servlet_request_class = Class.new(org.jruby.rack.mock.MockHttpServletRequest) do
+ servlet_request_class = Class.new(org.springframework.mock.web.MockHttpServletRequest) do
def getAttributeNames
names = super.to_a.reject { |name| name.start_with?('org.apache') }
@@ -501,8 +501,8 @@ def getAttributeNames
shared_examples "(eager)rack-env" do
before do
- @servlet_request = org.jruby.rack.mock.MockHttpServletRequest.new(@servlet_context)
- @servlet_response = org.jruby.rack.mock.MockHttpServletResponse.new
+ @servlet_request = org.springframework.mock.web.MockHttpServletRequest.new(@servlet_context)
+ @servlet_response = org.springframework.mock.web.MockHttpServletResponse.new
@servlet_env = org.jruby.rack.servlet.ServletRackEnvironment.new(
@servlet_request, @servlet_response, @rack_context
)
@@ -642,11 +642,7 @@ def getAttributeNames
request.logger.should be nil # we do not setup rack.logger
lambda { request.scheme }.should_not raise_error
- if Rack.release >= '1.3' # rack 1.3.x 1.4.x
- request.scheme.should == 'https' # X-Forwarded-Proto
- else
- request.scheme.should == 'http' # Rails 3.0 / 2.3
- end
+ request.scheme.should == 'https' # X-Forwarded-Proto
lambda { request.port }.should_not raise_error
request.port.should == 80
@@ -662,19 +658,11 @@ def getAttributeNames
if defined?(request.base_url)
lambda { request.base_url }.should_not raise_error
- if Rack.release >= '1.3' # Rails >= 3.1.x
- request.base_url.should == 'https://serverhost:80'
- else
- request.base_url.should == 'http://serverhost'
- end
+ request.base_url.should == 'https://serverhost:80'
end
lambda { request.url }.should_not raise_error
- if Rack.release >= '1.3' # Rails >= 3.1.x
- request.url.should == 'https://serverhost:80/main/app1/path/info?hello=there'
- else
- request.url.should == 'http://serverhost/main/app1/path/info?hello=there'
- end
+ request.url.should == 'https://serverhost:80/main/app1/path/info?hello=there'
end
describe 'dumped-and-loaded' do
@@ -900,9 +888,9 @@ def servlet.create_env(servlet_env)
context "servlet" do
before do
- @servlet_context = org.jruby.rack.mock.MockServletContext.new
- @servlet_request = org.jruby.rack.mock.MockHttpServletRequest.new(@servlet_context)
- @servlet_response = org.jruby.rack.mock.MockHttpServletResponse.new
+ @servlet_context = org.springframework.mock.web.MockServletContext.new
+ @servlet_request = org.springframework.mock.web.MockHttpServletRequest.new(@servlet_context)
+ @servlet_response = org.springframework.mock.web.MockHttpServletResponse.new
@servlet_env = org.jruby.rack.servlet.ServletRackEnvironment.new(
@servlet_request, @servlet_response, @rack_context
)
@@ -1051,7 +1039,7 @@ def servlet.create_env(servlet_env)
end
it "handles null values in parameter-map (Jetty)" do
- org.jruby.rack.mock.MockHttpServletRequest.class_eval do
+ org.springframework.mock.web.MockHttpServletRequest.class_eval do
field_reader :parameters
end
# reproducing https://github.com/jruby/jruby-rack/issues/154
diff --git a/src/spec/ruby/rack/servlet_context_listener_spec.rb b/src/spec/ruby/rack/servlet_context_listener_spec.rb
index 9c2a57dc..4de971e7 100644
--- a/src/spec/ruby/rack/servlet_context_listener_spec.rb
+++ b/src/spec/ruby/rack/servlet_context_listener_spec.rb
@@ -42,7 +42,7 @@
end
it "throws an error if initialization failed (and jruby.rack.error = false)" do
- @servlet_context = org.jruby.rack.mock.MockServletContext.new
+ @servlet_context = org.springframework.mock.web.MockServletContext.new
@servlet_context.add_init_parameter 'jruby.rack.error', 'false'
@factory.should_receive(:init).and_raise org.jruby.rack.RackInitializationException.new("help")
diff --git a/src/spec/ruby/rails3x/stub/active_support.rb b/src/spec/ruby/rails3x/stub/active_support.rb
new file mode 100644
index 00000000..3012c894
--- /dev/null
+++ b/src/spec/ruby/rails3x/stub/active_support.rb
@@ -0,0 +1,9 @@
+#--
+# 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.
+#++
+
+module ActiveSupport
+end
\ No newline at end of file
diff --git a/src/spec/ruby/spec_helper.rb b/src/spec/ruby/spec_helper.rb
index b629dab1..1a8d5504 100644
--- a/src/spec/ruby/spec_helper.rb
+++ b/src/spec/ruby/spec_helper.rb
@@ -163,6 +163,7 @@ def should_not_eval_as_nil(code, runtime = @runtime) # alias
begin
# NOTE: only if running with a `bundle exec` to better isolate
if $LOAD_PATH.find { |path| path =~ /\/rails\-[\w\.]*\// }
+ require 'logger' # Workaround for concurrent-ruby problems on older rails versions
require 'rails/version' # use Rails::VERSION to detect current env
require 'rails' # attempt to load rails - for "real life" testing
end
@@ -203,10 +204,10 @@ def should_not_eval_as_nil(code, runtime = @runtime) # alias
end
-java_import org.jruby.rack.mock.MockServletConfig
-java_import org.jruby.rack.mock.MockServletContext
-java_import org.jruby.rack.mock.MockHttpServletRequest
-java_import org.jruby.rack.mock.MockHttpServletResponse
+java_import org.springframework.mock.web.MockServletConfig
+java_import org.springframework.mock.web.MockServletContext
+java_import org.springframework.mock.web.MockHttpServletRequest
+java_import org.springframework.mock.web.MockHttpServletResponse
class StubInputStream < java.io.InputStream