text:
package org.springframework.web.servlet;

import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.SourceFilteringListener;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.i18n.SimpleLocaleContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.ConfigurableWebEnvironment;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter;
import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.context.support.ServletRequestHandledEvent;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.util.NestedServletException;
import org.springframework.web.util.WebUtils;

/**
 * Base servlet for Spring's web framework. Provides integration with
 * a Spring application context, in a JavaBean-based overall solution.
 *
 *
This class offers the following functionality:
 *

 *
Manages a {@link org.springframework.web.context.WebApplicationContext
 * WebApplicationContext} instance per servlet. The servlet's configuration is determined
 * by beans in the servlet's namespace.
 *
Publishes events on request processing, whether or not a request is
 * successfully handled.
 *

 *
 *
Subclasses must implement {@link #doService} to handle requests. Because this extends
 * {@link HttpServletBean} rather than HttpServlet directly, bean properties are
 * automatically mapped onto it. Subclasses can override {@link #initFrameworkServlet()}
 * for custom initialization.
 *
 *
Detects a "contextClass" parameter at the servlet init-param level,
 * falling back to the default context class,
 * {@link org.springframework.web.context.support.XmlWebApplicationContext
 * XmlWebApplicationContext}, if not found. Note that, with the default
 * {@code FrameworkServlet}, a custom context class needs to implement the
 * {@link org.springframework.web.context.ConfigurableWebApplicationContext
 * ConfigurableWebApplicationContext} SPI.
 *
 *
Accepts an optional "contextInitializerClasses" servlet init-param that
 * specifies one or more {@link org.springframework.context.ApplicationContextInitializer
 * ApplicationContextInitializer} classes. The managed web application context will be
 * delegated to these initializers, allowing for additional programmatic configuration,
 * e.g. adding property sources or activating profiles against the {@linkplain
 * org.springframework.context.ConfigurableApplicationContext#getEnvironment() context's
 * environment}. See also {@link org.springframework.web.context.ContextLoader} which
 * supports a "contextInitializerClasses" context-param with identical semantics for
 * the "root" web application context.
 *
 *
Passes a "contextConfigLocation" servlet init-param to the context instance,
 * parsing it into potentially multiple file paths which can be separated by any
 * number of commas and spaces, like "test-servlet.xml, myServlet.xml".
 * If not explicitly specified, the context implementation is supposed to build a
 * default location from the namespace of the servlet.
 *
 *
Note: In case of multiple config locations, later bean definitions will
 * override ones defined in earlier loaded files, at least when using Spring's
 * default ApplicationContext implementation. This can be leveraged to
 * deliberately override certain bean definitions via an extra XML file.
 *
 *
The default namespace is "'servlet-name'-servlet", e.g. "test-servlet" for a
 * servlet-name "test" (leading to a "/WEB-INF/test-servlet.xml" default location
 * with XmlWebApplicationContext). The namespace can also be set explicitly via
 * the "namespace" servlet init-param.
 *
 *
As of Spring 3.1, {@code FrameworkServlet} may now be injected with a web
 * application context, rather than creating its own internally. This is useful in Servlet
 * 3.0+ environments, which support programmatic registration of servlet instances. See
 * {@link #FrameworkServlet(WebApplicationContext)} Javadoc for details.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @author Chris Beams
 * @author Rossen Stoyanchev
 * @author Phillip Webb
 * @see #doService
 * @see #setContextClass
 * @see #setContextConfigLocation
 * @see #setContextInitializerClasses
 * @see #setNamespace
 */
@SuppressWarnings("serial")
public abstract class FrameworkServlet extends HttpServletBean implements ApplicationContextAware {

	/**
	 * Suffix for WebApplicationContext namespaces. If a servlet of this class is
	 * given the name "test" in a context, the namespace used by the servlet will
	 * resolve to "test-servlet".
	 */
	public static final String DEFAULT_NAMESPACE_SUFFIX = "-servlet";

	/**
	 * Default context class for FrameworkServlet.
	 * @see org.springframework.web.context.support.XmlWebApplicationContext
	 */
	public static final Class<?> DEFAULT_CONTEXT_CLASS = XmlWebApplicationContext.class;

	/**
	 * Prefix for the ServletContext attribute for the WebApplicationContext.
	 * The completion is the servlet name.
	 */
	public static final String SERVLET_CONTEXT_PREFIX = FrameworkServlet.class.getName() + ".CONTEXT.";

	/**
	 * Any number of these characters are considered delimiters between
	 * multiple values in a single init-param String value.
	 */
	private static final String INIT_PARAM_DELIMITERS = ",; \t\n";

	/** Checking for Servlet 3.0+ HttpServletResponse.getStatus() */
	private static final boolean responseGetStatusAvailable =
			ClassUtils.hasMethod(HttpServletResponse.class, "getStatus");

	/** ServletContext attribute to find the WebApplicationContext in */
	private String contextAttribute;

	/** WebApplicationContext implementation class to create */
	private Class<?> contextClass = DEFAULT_CONTEXT_CLASS;

	/** WebApplicationContext id to assign */
	private String contextId;

	/** Namespace for this servlet */
	private String namespace;

	/** Explicit context config location */
	private String contextConfigLocation;

	/** Actual ApplicationContextInitializer instances to apply to the context */
	private final List<ApplicationContextInitializer<ConfigurableApplicationContext>> contextInitializers =
			new ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>>();

	/** Comma-delimited ApplicationContextInitializer class names set through init param */
	private String contextInitializerClasses;

	/** Should we publish the context as a ServletContext attribute? */
	private boolean publishContext = true;

	/** Should we publish a ServletRequestHandledEvent at the end of each request? */
	private boolean publishEvents = true;

	/** Expose LocaleContext and RequestAttributes as inheritable for child threads? */
	private boolean threadContextInheritable = false;

	/** Should we dispatch an HTTP OPTIONS request to {@link #doService}? */
	private boolean dispatchOptionsRequest = false;

	/** Should we dispatch an HTTP TRACE request to {@link #doService}? */
	private boolean dispatchTraceRequest = false;

	/** WebApplicationContext for this servlet */
	private WebApplicationContext webApplicationContext;

	/** If the WebApplicationContext was injected via {@link #setApplicationContext} */
	private boolean webApplicationContextInjected = false;

	/** Flag used to detect whether onRefresh has already been called */
	private boolean refreshEventReceived = false;

	/**
	 * Create a new {@code FrameworkServlet} that will create its own internal web
	 * application context based on defaults and values provided through servlet
	 * init-params. Typically used in Servlet 2.5 or earlier environments, where the only
	 * option for servlet registration is through {@code web.xml} which requires the use
	 * of a no-arg constructor.
	 *
Calling {@link #setContextConfigLocation} (init-param 'contextConfigLocation')
	 * will dictate which XML files will be loaded by the
	 * {@linkplain #DEFAULT_CONTEXT_CLASS default XmlWebApplicationContext}
	 *
Calling {@link #setContextClass} (init-param 'contextClass') overrides the
	 * default {@code XmlWebApplicationContext} and allows for specifying an alternative class,
	 * such as {@code AnnotationConfigWebApplicationContext}.
	 *
Calling {@link #setContextInitializerClasses} (init-param 'contextInitializerClasses')
	 * indicates which {@link ApplicationContextInitializer} classes should be used to
	 * further configure the internal application context prior to refresh().
	 * @see #FrameworkServlet(WebApplicationContext)
	 */
	public FrameworkServlet() {
	}

	/**
	 * Create a new {@code FrameworkServlet} with the given web application context. This
	 * constructor is useful in Servlet 3.0+ environments where instance-based registration
	 * of servlets is possible through the {@link ServletContext#addServlet} API.
	 *
Using this constructor indicates that the following properties / init-params
	 * will be ignored:
	 *

	 *
{@link #setContextClass(Class)} / 'contextClass'

	 *
{@link #setContextConfigLocation(String)} / 'contextConfigLocation'

	 *
{@link #setContextAttribute(String)} / 'contextAttribute'

	 *
{@link #setNamespace(String)} / 'namespace'

	 *

	 *
The given web application context may or may not yet be {@linkplain
	 * ConfigurableApplicationContext#refresh() refreshed}. If it (a) is an implementation
	 * of {@link ConfigurableWebApplicationContext} and (b) has not
	 * already been refreshed (the recommended approach), then the following will occur:
	 *

	 *
If the given context does not already have a {@linkplain
	 * ConfigurableApplicationContext#setParent parent}, the root application context
	 * will be set as the parent.

	 *
If the given context has not already been assigned an {@linkplain
	 * ConfigurableApplicationContext#setId id}, one will be assigned to it

	 *
{@code ServletContext} and {@code ServletConfig} objects will be delegated to
	 * the application context

	 *
{@link #postProcessWebApplicationContext} will be called

	 *
Any {@link ApplicationContextInitializer}s specified through the
	 * "contextInitializerClasses" init-param or through the {@link
	 * #setContextInitializers} property will be applied.

	 *
{@link ConfigurableApplicationContext#refresh refresh()} will be called

	 *

	 * If the context has already been refreshed or does not implement
	 * {@code ConfigurableWebApplicationContext}, none of the above will occur under the
	 * assumption that the user has performed these actions (or not) per his or her
	 * specific needs.
	 *
See {@link org.springframework.web.WebApplicationInitializer} for usage examples.
	 * @param webApplicationContext the context to use
	 * @see #initWebApplicationContext
	 * @see #configureAndRefreshWebApplicationContext
	 * @see org.springframework.web.WebApplicationInitializer
	 */
	public FrameworkServlet(WebApplicationContext webApplicationContext) {
		this.webApplicationContext = webApplicationContext;
	}

	/**
	 * Set the name of the ServletContext attribute which should be used to retrieve the
	 * {@link WebApplicationContext} that this servlet is supposed to use.
	 */
	public void setContextAttribute(String contextAttribute) {
		this.contextAttribute = contextAttribute;
	}

	/**
	 * Return the name of the ServletContext attribute which should be used to retrieve the
	 * {@link WebApplicationContext} that this servlet is supposed to use.
	 */
	public String getContextAttribute() {
		return this.contextAttribute;
	}

	/**
	 * Set a custom context class. This class must be of type
	 * {@link org.springframework.web.context.WebApplicationContext}.
	 *
When using the default FrameworkServlet implementation,
	 * the context class must also implement the
	 * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
	 * interface.
	 * @see #createWebApplicationContext
	 */
	public void setContextClass(Class<?> contextClass) {
		this.contextClass = contextClass;
	}

	/**
	 * Return the custom context class.
	 */
	public Class<?> getContextClass() {
		return this.contextClass;
	}

	/**
	 * Specify a custom WebApplicationContext id,
	 * to be used as serialization id for the underlying BeanFactory.
	 */
	public void setContextId(String contextId) {
		this.contextId = contextId;
	}

	/**
	 * Return the custom WebApplicationContext id, if any.
	 */
	public String getContextId() {
		return this.contextId;
	}

	/**
	 * Set a custom namespace for this servlet,
	 * to be used for building a default context config location.
	 */
	public void setNamespace(String namespace) {
		this.namespace = namespace;
	}

	/**
	 * Return the namespace for this servlet, falling back to default scheme if
	 * no custom namespace was set: e.g. "test-servlet" for a servlet named "test".
	 */
	public String getNamespace() {
		return (this.namespace != null ? this.namespace : getServletName() + DEFAULT_NAMESPACE_SUFFIX);
	}

	/**
	 * Set the context config location explicitly, instead of relying on the default
	 * location built from the namespace. This location string can consist of
	 * multiple locations separated by any number of commas and spaces.
	 */
	public void setContextConfigLocation(String contextConfigLocation) {
		this.contextConfigLocation = contextConfigLocation;
	}

	/**
	 * Return the explicit context config location, if any.
	 */
	public String getContextConfigLocation() {
		return this.contextConfigLocation;
	}

	/**
	 * Specify which {@link ApplicationContextInitializer} instances should be used
	 * to initialize the application context used by this {@code FrameworkServlet}.
	 * @see #configureAndRefreshWebApplicationContext
	 * @see #applyInitializers
	 */
	@SuppressWarnings("unchecked")
	public void setContextInitializers(ApplicationContextInitializer<?>... initializers) {
		if (initializers != null) {
			for (ApplicationContextInitializer<?> initializer : initializers) {
				this.contextInitializers.add((ApplicationContextInitializer<ConfigurableApplicationContext>) initializer);
			}
		}
	}

	/**
	 * Specify the set of fully-qualified {@link ApplicationContextInitializer} class
	 * names, per the optional "contextInitializerClasses" servlet init-param.
	 * @see #configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext)
	 * @see #applyInitializers(ConfigurableApplicationContext)
	 */
	public void setContextInitializerClasses(String contextInitializerClasses) {
		this.contextInitializerClasses = contextInitializerClasses;
	}

	/**
	 * Set whether to publish this servlet's context as a ServletContext attribute,
	 * available to all objects in the web container. Default is "true".
	 *
This is especially handy during testing, although it is debatable whether
	 * it's good practice to let other application objects access the context this way.
	 */
	public void setPublishContext(boolean publishContext) {
		this.publishContext = publishContext;
	}

	/**
	 * Set whether this servlet should publish a ServletRequestHandledEvent at the end
	 * of each request. Default is "true"; can be turned off for a slight performance
	 * improvement, provided that no ApplicationListeners rely on such events.
	 * @see org.springframework.web.context.support.ServletRequestHandledEvent
	 */
	public void setPublishEvents(boolean publishEvents) {
		this.publishEvents = publishEvents;
	}

	/**
	 * Set whether to expose the LocaleContext and RequestAttributes as inheritable
	 * for child threads (using an {@link java.lang.InheritableThreadLocal}).
	 *
Default is "false", to avoid side effects on spawned background threads.
	 * Switch this to "true" to enable inheritance for custom child threads which
	 * are spawned during request processing and only used for this request
	 * (that is, ending after their initial task, without reuse of the thread).
	 *
WARNING: Do not use inheritance for child threads if you are
	 * accessing a thread pool which is configured to potentially add new threads
	 * on demand (e.g. a JDK {@link java.util.concurrent.ThreadPoolExecutor}),
	 * since this will expose the inherited context to such a pooled thread.
	 */
	public void setThreadContextInheritable(boolean threadContextInheritable) {
		this.threadContextInheritable = threadContextInheritable;
	}

	/**
	 * Set whether this servlet should dispatch an HTTP OPTIONS request to
	 * the {@link #doService} method.
	 *
Default is "false", applying {@link javax.servlet.http.HttpServlet}'s
	 * default behavior (i.e. enumerating all standard HTTP request methods
	 * as a response to the OPTIONS request).
	 *
Turn this flag on if you prefer OPTIONS requests to go through the
	 * regular dispatching chain, just like other HTTP requests. This usually
	 * means that your controllers will receive those requests; make sure
	 * that those endpoints are actually able to handle an OPTIONS request.
	 *
Note that HttpServlet's default OPTIONS processing will be applied
	 * in any case if your controllers happen to not set the 'Allow' header
	 * (as required for an OPTIONS response).
	 */
	public void setDispatchOptionsRequest(boolean dispatchOptionsRequest) {
		this.dispatchOptionsRequest = dispatchOptionsRequest;
	}

	/**
	 * Set whether this servlet should dispatch an HTTP TRACE request to
	 * the {@link #doService} method.
	 *
Default is "false", applying {@link javax.servlet.http.HttpServlet}'s
	 * default behavior (i.e. reflecting the message received back to the client).
	 *
Turn this flag on if you prefer TRACE requests to go through the
	 * regular dispatching chain, just like other HTTP requests. This usually
	 * means that your controllers will receive those requests; make sure
	 * that those endpoints are actually able to handle a TRACE request.
	 *
Note that HttpServlet's default TRACE processing will be applied
	 * in any case if your controllers happen to not generate a response
	 * of content type 'message/http' (as required for a TRACE response).
	 */
	public void setDispatchTraceRequest(boolean dispatchTraceRequest) {
		this.dispatchTraceRequest = dispatchTraceRequest;
	}

	/**
	 * Called by Spring via {@link ApplicationContextAware} to inject the current
	 * application context. This method allows FrameworkServlets to be registered as
	 * Spring beans inside an existing {@link WebApplicationContext} rather than
	 * {@link #findWebApplicationContext() finding} a
	 * {@link org.springframework.web.context.ContextLoaderListener bootstrapped} context.
	 *
Primarily added to support use in embedded servlet containers.
	 * @since 4.0
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		if (this.webApplicationContext == null && applicationContext instanceof WebApplicationContext) {
			this.webApplicationContext = (WebApplicationContext) applicationContext;
			this.webApplicationContextInjected = true;
		}
	}

	/**
	 * Overridden method of {@link HttpServletBean}, invoked after any bean properties
	 * have been set. Creates this servlet's WebApplicationContext.
	 */
	@Override
	protected final void initServletBean() throws ServletException {
		getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
		if (this.logger.isInfoEnabled()) {
			this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
		}
		long startTime = System.currentTimeMillis();

		try {
			this.webApplicationContext = initWebApplicationContext();
			initFrameworkServlet();
		}
		catch (ServletException ex) {
			this.logger.error("Context initialization failed", ex);
			throw ex;
		}
		catch (RuntimeException ex) {
			this.logger.error("Context initialization failed", ex);
			throw ex;
		}

		if (this.logger.isInfoEnabled()) {
			long elapsedTime = System.currentTimeMillis() - startTime;
			this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
					elapsedTime + " ms");
		}
	}

	/**
	 * Initialize and publish the WebApplicationContext for this servlet.
	 *
Delegates to {@link #createWebApplicationContext} for actual creation
	 * of the context. Can be overridden in subclasses.
	 * @return the WebApplicationContext instance
	 * @see #FrameworkServlet(WebApplicationContext)
	 * @see #setContextClass
	 * @see #setContextConfigLocation
	 */
	protected WebApplicationContext initWebApplicationContext() {
		WebApplicationContext rootContext =
				WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		WebApplicationContext wac = null;

		if (this.webApplicationContext != null) {
			// A context instance was injected at construction time -> use it
			wac = this.webApplicationContext;
			if (wac instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
				if (!cwac.isActive()) {
					// The context has not yet been refreshed -> provide services such as
					// setting the parent context, setting the application context id, etc
					if (cwac.getParent() == null) {
						// The context instance was injected without an explicit parent -> set
						// the root application context (if any; may be null) as the parent
						cwac.setParent(rootContext);
					}
					configureAndRefreshWebApplicationContext(cwac);
				}
			}
		}
		if (wac == null) {
			// No context instance was injected at construction time -> see if one
			// has been registered in the servlet context. If one exists, it is assumed
			// that the parent context (if any) has already been set and that the
			// user has performed any initialization such as setting the context id
			wac = findWebApplicationContext();
		}
		if (wac == null) {
			// No context instance is defined for this servlet -> create a local one
			wac = createWebApplicationContext(rootContext);
		}

		if (!this.refreshEventReceived) {
			// Either the context is not a ConfigurableApplicationContext with refresh
			// support or the context injected at construction time had already been
			// refreshed -> trigger initial onRefresh manually here.
			onRefresh(wac);
		}

		if (this.publishContext) {
			// Publish the context as a servlet context attribute.
			String attrName = getServletContextAttributeName();
			getServletContext().setAttribute(attrName, wac);
			if (this.logger.isDebugEnabled()) {
				this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
						"' as ServletContext attribute with name [" + attrName + "]");
			}
		}

		return wac;
	}

	/**
	 * Retrieve a {@code WebApplicationContext} from the {@code ServletContext}
	 * attribute with the {@link #setContextAttribute configured name}. The
	 * {@code WebApplicationContext} must have already been loaded and stored in the
	 * {@code ServletContext} before this servlet gets initialized (or invoked).
	 *
Subclasses may override this method to provide a different
	 * {@code WebApplicationContext} retrieval strategy.
	 * @return the WebApplicationContext for this servlet, or {@code null} if not found
	 * @see #getContextAttribute()
	 */
	protected WebApplicationContext findWebApplicationContext() {
		String attrName = getContextAttribute();
		if (attrName == null) {
			return null;
		}
		WebApplicationContext wac =
				WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);
		if (wac == null) {
			throw new IllegalStateException("No WebApplicationContext found: initializer not registered?");
		}
		return wac;
	}

	/**
	 * Instantiate the WebApplicationContext for this servlet, either a default
	 * {@link org.springframework.web.context.support.XmlWebApplicationContext}
	 * or a {@link #setContextClass custom context class}, if set.
	 *
This implementation expects custom contexts to implement the
	 * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
	 * interface. Can be overridden in subclasses.
	 *
Do not forget to register this servlet instance as application listener on the
	 * created context (for triggering its {@link #onRefresh callback}, and to call
	 * {@link org.springframework.context.ConfigurableApplicationContext#refresh()}
	 * before returning the context instance.
	 * @param parent the parent ApplicationContext to use, or {@code null} if none
	 * @return the WebApplicationContext for this servlet
	 * @see org.springframework.web.context.support.XmlWebApplicationContext
	 */
	protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
		Class<?> contextClass = getContextClass();
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("Servlet with name '" + getServletName() +
					"' will try to create custom WebApplicationContext context of class '" +
					contextClass.getName() + "'" + ", using parent context [" + parent + "]");
		}
		if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
			throw new ApplicationContextException(
					"Fatal initialization error in servlet with name '" + getServletName() +
					"': custom WebApplicationContext class [" + contextClass.getName() +
					"] is not of type ConfigurableWebApplicationContext");
		}
		ConfigurableWebApplicationContext wac =
				(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

		wac.setEnvironment(getEnvironment());
		wac.setParent(parent);
		wac.setConfigLocation(getContextConfigLocation());

		configureAndRefreshWebApplicationContext(wac);

		return wac;
	}

	protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
		if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
			// The application context id is still set to its original default value
			// -> assign a more useful id based on available information
			if (this.contextId != null) {
				wac.setId(this.contextId);
			}
			else {
				// Generate default id...
				wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
						ObjectUtils.getDisplayString(getServletContext().getContextPath()) + "/" + getServletName());
			}
		}

		wac.setServletContext(getServletContext());
		wac.setServletConfig(getServletConfig());
		wac.setNamespace(getNamespace());
		wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

		// The wac environment's #initPropertySources will be called in any case when the context
		// is refreshed; do it eagerly here to ensure servlet property sources are in place for
		// use in any post-processing or initialization that occurs below prior to #refresh
		ConfigurableEnvironment env = wac.getEnvironment();
		if (env instanceof ConfigurableWebEnvironment) {
			((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
		}

		postProcessWebApplicationContext(wac);
		applyInitializers(wac);
		wac.refresh();
	}

	/**
	 * Instantiate the WebApplicationContext for this servlet, either a default
	 * {@link org.springframework.web.context.support.XmlWebApplicationContext}
	 * or a {@link #setContextClass custom context class}, if set.
	 * Delegates to #createWebApplicationContext(ApplicationContext).
	 * @param parent the parent WebApplicationContext to use, or {@code null} if none
	 * @return the WebApplicationContext for this servlet
	 * @see org.springframework.web.context.support.XmlWebApplicationContext
	 * @see #createWebApplicationContext(ApplicationContext)
	 */
	protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
		return createWebApplicationContext((ApplicationContext) parent);
	}

	/**
	 * Post-process the given WebApplicationContext before it is refreshed
	 * and activated as context for this servlet.
	 *
The default implementation is empty. {@code refresh()} will
	 * be called automatically after this method returns.
	 *
Note that this method is designed to allow subclasses to modify the application
	 * context, while {@link #initWebApplicationContext} is designed to allow
	 * end-users to modify the context through the use of
	 * {@link ApplicationContextInitializer}s.
	 * @param wac the configured WebApplicationContext (not refreshed yet)
	 * @see #createWebApplicationContext
	 * @see #initWebApplicationContext
	 * @see ConfigurableWebApplicationContext#refresh()
	 */
	protected void postProcessWebApplicationContext(ConfigurableWebApplicationContext wac) {
	}

	/**
	 * Delegate the WebApplicationContext before it is refreshed to any
	 * {@link ApplicationContextInitializer} instances specified by the
	 * "contextInitializerClasses" servlet init-param.
	 *
See also {@link #postProcessWebApplicationContext}, which is designed to allow
	 * subclasses (as opposed to end-users) to modify the application context, and is
	 * called immediately before this method.
	 * @param wac the configured WebApplicationContext (not refreshed yet)
	 * @see #createWebApplicationContext
	 * @see #postProcessWebApplicationContext
	 * @see ConfigurableApplicationContext#refresh()
	 */
	protected void applyInitializers(ConfigurableApplicationContext wac) {
		String globalClassNames = getServletContext().getInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM);
		if (globalClassNames != null) {
			for (String className : StringUtils.tokenizeToStringArray(globalClassNames, INIT_PARAM_DELIMITERS)) {
				this.contextInitializers.add(loadInitializer(className, wac));
			}
		}

		if (this.contextInitializerClasses != null) {
			for (String className : StringUtils.tokenizeToStringArray(this.contextInitializerClasses, INIT_PARAM_DELIMITERS)) {
				this.contextInitializers.add(loadInitializer(className, wac));
			}
		}

		AnnotationAwareOrderComparator.sort(this.contextInitializers);
		for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
			initializer.initialize(wac);
		}
	}

	@SuppressWarnings("unchecked")
	private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
			String className, ConfigurableApplicationContext wac) {
		try {
			Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
			Class<?> initializerContextClass =
					GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
			if (initializerContextClass != null) {
				Assert.isAssignable(initializerContextClass, wac.getClass(), String.format(
						"Could not add context initializer [%s] since its generic parameter [%s] " +
						"is not assignable from the type of application context used by this " +
						"framework servlet [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
						wac.getClass().getName()));
			}
			return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
		}
		catch (Exception ex) {
			throw new IllegalArgumentException(String.format("Could not instantiate class [%s] specified " +
					"via 'contextInitializerClasses' init-param", className), ex);
		}
	}

	/**
	 * Return the ServletContext attribute name for this servlet's WebApplicationContext.
	 *
The default implementation returns
	 * {@code SERVLET_CONTEXT_PREFIX + servlet name}.
	 * @see #SERVLET_CONTEXT_PREFIX
	 * @see #getServletName
	 */
	public String getServletContextAttributeName() {
		return SERVLET_CONTEXT_PREFIX + getServletName();
	}

	/**
	 * Return this servlet's WebApplicationContext.
	 */
	public final WebApplicationContext getWebApplicationContext() {
		return this.webApplicationContext;
	}

	/**
	 * This method will be invoked after any bean properties have been set and
	 * the WebApplicationContext has been loaded. The default implementation is empty;
	 * subclasses may override this method to perform any initialization they require.
	 * @throws ServletException in case of an initialization exception
	 */
	protected void initFrameworkServlet() throws ServletException {
	}

	/**
	 * Refresh this servlet's application context, as well as the
	 * dependent state of the servlet.
	 * @see #getWebApplicationContext()
	 * @see org.springframework.context.ConfigurableApplicationContext#refresh()
	 */
	public void refresh() {
		WebApplicationContext wac = getWebApplicationContext();
		if (!(wac instanceof ConfigurableApplicationContext)) {
			throw new IllegalStateException("WebApplicationContext does not support refresh: " + wac);
		}
		((ConfigurableApplicationContext) wac).refresh();
	}

	/**
	 * Callback that receives refresh events from this servlet's WebApplicationContext.
	 *
The default implementation calls {@link #onRefresh},
	 * triggering a refresh of this servlet's context-dependent state.
	 * @param event the incoming ApplicationContext event
	 */
	public void onApplicationEvent(ContextRefreshedEvent event) {
		this.refreshEventReceived = true;
		onRefresh(event.getApplicationContext());
	}

	/**
	 * Template method which can be overridden to add servlet-specific refresh work.
	 * Called after successful context refresh.
	 *
This implementation is empty.
	 * @param context the current WebApplicationContext
	 * @see #refresh()
	 */
	protected void onRefresh(ApplicationContext context) {
		// For subclasses: do nothing by default.
	}

	/**
	 * Close the WebApplicationContext of this servlet.
	 * @see org.springframework.context.ConfigurableApplicationContext#close()
	 */
	@Override
	public void destroy() {
		getServletContext().log("Destroying Spring FrameworkServlet '" + getServletName() + "'");
		// Only call close() on WebApplicationContext if locally managed...
		if (this.webApplicationContext instanceof ConfigurableApplicationContext && !this.webApplicationContextInjected) {
			((ConfigurableApplicationContext) this.webApplicationContext).close();
		}
	}

	/**
	 * Override the parent class implementation in order to intercept PATCH
	 * requests.
	 */
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String method = request.getMethod();
		if (method.equalsIgnoreCase(RequestMethod.PATCH.name())) {
			processRequest(request, response);
		}
		else {
			super.service(request, response);
		}
	}

	/**
	 * Delegate GET requests to processRequest/doService.
	 *
Will also be invoked by HttpServlet's default implementation of {@code doHead},
	 * with a {@code NoBodyResponse} that just captures the content length.
	 * @see #doService
	 * @see #doHead
	 */
	@Override
	protected final void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		processRequest(request, response);
	}

	/**
	 * Delegate POST requests to {@link #processRequest}.
	 * @see #doService
	 */
	@Override
	protected final void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		processRequest(request, response);
	}

	/**
	 * Delegate PUT requests to {@link #processRequest}.
	 * @see #doService
	 */
	@Override
	protected final void doPut(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		processRequest(request, response);
	}

	/**
	 * Delegate DELETE requests to {@link #processRequest}.
	 * @see #doService
	 */
	@Override
	protected final void doDelete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		processRequest(request, response);
	}

	/**
	 * Delegate OPTIONS requests to {@link #processRequest}, if desired.
	 *
Applies HttpServlet's standard OPTIONS processing otherwise,
	 * and also if there is still no 'Allow' header set after dispatching.
	 * @see #doService
	 */
	@Override
	protected void doOptions(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		if (this.dispatchOptionsRequest || request.getHeader("Origin") != null) {
			processRequest(request, response);
			if (response.containsHeader("Allow")) {
				// Proper OPTIONS response coming from a handler - we're done.
				return;
			}
		}

		// Use response wrapper for Servlet 2.5 compatibility where
		// the getHeader() method does not exist
		super.doOptions(request, new HttpServletResponseWrapper(response) {
			@Override
			public void setHeader(String name, String value) {
				if ("Allow".equals(name)) {
					value = (StringUtils.hasLength(value) ? value + ", " : "") + RequestMethod.PATCH.name();
				}
				super.setHeader(name, value);
			}
		});
	}

	/**
	 * Delegate TRACE requests to {@link #processRequest}, if desired.
	 *
Applies HttpServlet's standard TRACE processing otherwise.
	 * @see #doService
	 */
	@Override
	protected void doTrace(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		if (this.dispatchTraceRequest) {
			processRequest(request, response);
			if ("message/http".equals(response.getContentType())) {
				// Proper TRACE response coming from a handler - we're done.
				return;
			}
		}
		super.doTrace(request, response);
	}

	/**
	 * Process this request, publishing an event regardless of the outcome.
	 *
The actual event handling is performed by the abstract
	 * {@link #doService} template method.
	 */
	protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		long startTime = System.currentTimeMillis();
		Throwable failureCause = null;

		LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
		LocaleContext localeContext = buildLocaleContext(request);

		RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);

		WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
		asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());

		initContextHolders(request, localeContext, requestAttributes);

		try {
			doService(request, response);
		}
		catch (ServletException ex) {
			failureCause = ex;
			throw ex;
		}
		catch (IOException ex) {
			failureCause = ex;
			throw ex;
		}
		catch (Throwable ex) {
			failureCause = ex;
			throw new NestedServletException("Request processing failed", ex);
		}

		finally {
			resetContextHolders(request, previousLocaleContext, previousAttributes);
			if (requestAttributes != null) {
				requestAttributes.requestCompleted();
			}

			if (logger.isDebugEnabled()) {
				if (failureCause != null) {
					this.logger.debug("Could not complete request", failureCause);
				}
				else {
					if (asyncManager.isConcurrentHandlingStarted()) {
						logger.debug("Leaving response open for concurrent processing");
					}
					else {
						this.logger.debug("Successfully completed request");
					}
				}
			}

			publishRequestHandledEvent(request, response, startTime, failureCause);
		}
	}

	/**
	 * Build a LocaleContext for the given request, exposing the request's
	 * primary locale as current locale.
	 * @param request current HTTP request
	 * @return the corresponding LocaleContext, or {@code null} if none to bind
	 * @see LocaleContextHolder#setLocaleContext
	 */
	protected LocaleContext buildLocaleContext(HttpServletRequest request) {
		return new SimpleLocaleContext(request.getLocale());
	}

	/**
	 * Build ServletRequestAttributes for the given request (potentially also
	 * holding a reference to the response), taking pre-bound attributes
	 * (and their type) into consideration.
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param previousAttributes pre-bound RequestAttributes instance, if any
	 * @return the ServletRequestAttributes to bind, or {@code null} to preserve
	 * the previously bound instance (or not binding any, if none bound before)
	 * @see RequestContextHolder#setRequestAttributes
	 */
	protected ServletRequestAttributes buildRequestAttributes(
			HttpServletRequest request, HttpServletResponse response, RequestAttributes previousAttributes) {

		if (previousAttributes == null || previousAttributes instanceof ServletRequestAttributes) {
			return new ServletRequestAttributes(request, response);
		}
		else {
			return null;  // preserve the pre-bound RequestAttributes instance
		}
	}

	private void initContextHolders(
			HttpServletRequest request, LocaleContext localeContext, RequestAttributes requestAttributes) {

		if (localeContext != null) {
			LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);
		}
		if (requestAttributes != null) {
			RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
		}
		if (logger.isTraceEnabled()) {
			logger.trace("Bound request context to thread: " + request);
		}
	}

	private void resetContextHolders(HttpServletRequest request,
			LocaleContext prevLocaleContext, RequestAttributes previousAttributes) {

		LocaleContextHolder.setLocaleContext(prevLocaleContext, this.threadContextInheritable);
		RequestContextHolder.setRequestAttributes(previousAttributes, this.threadContextInheritable);
		if (logger.isTraceEnabled()) {
			logger.trace("Cleared thread-bound request context: " + request);
		}
	}

	private void publishRequestHandledEvent(
			HttpServletRequest request, HttpServletResponse response, long startTime, Throwable failureCause) {

		if (this.publishEvents) {
			// Whether or not we succeeded, publish an event.
			long processingTime = System.currentTimeMillis() - startTime;
			int statusCode = (responseGetStatusAvailable ? response.getStatus() : -1);
			this.webApplicationContext.publishEvent(
					new ServletRequestHandledEvent(this,
							request.getRequestURI(), request.getRemoteAddr(),
							request.getMethod(), getServletConfig().getServletName(),
							WebUtils.getSessionId(request), getUsernameForRequest(request),
							processingTime, failureCause, statusCode));
		}
	}

	/**
	 * Determine the username for the given request.
	 *
The default implementation takes the name of the UserPrincipal, if any.
	 * Can be overridden in subclasses.
	 * @param request current HTTP request
	 * @return the username, or {@code null} if none found
	 * @see javax.servlet.http.HttpServletRequest#getUserPrincipal()
	 */
	protected String getUsernameForRequest(HttpServletRequest request) {
		Principal userPrincipal = request.getUserPrincipal();
		return (userPrincipal != null ? userPrincipal.getName() : null);
	}

	/**
	 * Subclasses must implement this method to do the work of request handling,
	 * receiving a centralized callback for GET, POST, PUT and DELETE.
	 *
The contract is essentially the same as that for the commonly overridden
	 * {@code doGet} or {@code doPost} methods of HttpServlet.
	 *
This class intercepts calls to ensure that exception handling and
	 * event publication takes place.
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @throws Exception in case of any kind of processing failure
	 * @see javax.servlet.http.HttpServlet#doGet
	 * @see javax.servlet.http.HttpServlet#doPost
	 */
	protected abstract void doService(HttpServletRequest request, HttpServletResponse response)
			throws Exception;

	/**
	 * ApplicationListener endpoint that receives events from this servlet's WebApplicationContext
	 * only, delegating to {@code onApplicationEvent} on the FrameworkServlet instance.
	 */
	private class ContextRefreshListener implements ApplicationListener<ContextRefreshedEvent> {

		@Override
		public void onApplicationEvent(ContextRefreshedEvent event) {
			FrameworkServlet.this.onApplicationEvent(event);
		}
	}

	/**
	 * CallableProcessingInterceptor implementation that initializes and resets
	 * FrameworkServlet's context holders, i.e. LocaleContextHolder and RequestContextHolder.
	 */
	private class RequestBindingInterceptor extends CallableProcessingInterceptorAdapter {

		@Override
		public <T> void preProcess(NativeWebRequest webRequest, Callable<T> task) {
			HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
			if (request != null) {
				HttpServletResponse response = webRequest.getNativeRequest(HttpServletResponse.class);
				initContextHolders(request, buildLocaleContext(request), buildRequestAttributes(request, response, null));
			}
		}
		@Override
		public <T> void postProcess(NativeWebRequest webRequest, Callable<T> task, Object concurrentResult) {
			HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
			if (request != null) {
				resetContextHolders(request, null, null);
			}
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
package net.glowstone.inventory;

import net.glowstone.constants.ItemIds;
import org.bukkit.event.inventory.InventoryType.SlotType;
import org.bukkit.inventory.ItemStack;

import java.util.Arrays;
import java.util.List;

public class GlowInventorySlot {

    private static final SlotType DEFAULT_TYPE = SlotType.CONTAINER;

    private ItemStack item;
    private SlotType type;

    public GlowInventorySlot() {
        this(DEFAULT_TYPE);
    }

    public GlowInventorySlot(SlotType type) {
        this(null, type);
    }

    public GlowInventorySlot(ItemStack item) {
        this(item, DEFAULT_TYPE);
    }

    public GlowInventorySlot(ItemStack item, SlotType type) {
        this.item = item;
        this.type = type;
    }

    public ItemStack getItem() {
        return item;
    }

    public void setItem(ItemStack item) {
        this.item = ItemIds.sanitize(item);
    }

    public SlotType getType() {
        return type;
    }

    public void setType(SlotType type) {
        this.type = type;
    }

    public static GlowInventorySlot[] createArray(int len) {
        GlowInventorySlot[] result = new GlowInventorySlot[len];

        for (int i = 0; i < len; i++) {
            result[i] = new GlowInventorySlot();
        }

        return result;
    }

    public static List<GlowInventorySlot> createList(int len) {
        return Arrays.asList(createArray(len));
    }
}


text:
class AddAviToUsers < ActiveRecord::Migration
 def self.up
    change_table :users do |t|
      t.attachment :avatar
    end
  end

  def self.down
      remove_column :users, :avatar, :attachment
  end
 end


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet'>
  <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet'>
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link rel="stylesheet" href="/styles.css">
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-precomposed.png">
  <link rel="shortcut icon" href="/public/favicon.ico">
  <link rel="alternate" type="application/atom+xml" title="" href="/atom.xml">

            home
            work
            about

niels segers

        automator of things

View running docker containers in ZSH prompt

  <time datetime="2018-02-27T00:00:00+01:00" class="post-date">27 Feb 2018</time>

I find it oddly amusing to see how many docker container I have running on my prompt while working.

First you'll have to create the following function in your .zshrc file. Which basically just gets the count of containers in your docker ps.

function docker_prompt () {
  docker ps -q |wc -l |tr -d ' '
}

Then you proceed to insert this docker_prompt function in your PROMPT. As I'm using the oh-my-zsh theme called sorin I went to edit ~/.oh-my-zsh/themes/sorin.zsh-theme.

PROMPT='%{$fg[red]%}containers:(%{$fg[blue]%}$(docker_prompt)%{$fg[red]%}) %{$fg[cyan]%}%c$(git_prompt_info) %(!.%{$fg_bold[red]%}#.%{$fg_bold[green]%}❯)%{$reset_color%} '

Et voila, your prompt now shows your running container count!

containers:(0) ~ ❯

Related posts

          Auto deploying Go binaries to Github
          <time datetime="2018-04-12T00:00:00+02:00">12 Apr 2018</time>

          Supdock in Go?
          <time datetime="2018-04-03T00:00:00+02:00">03 Apr 2018</time>

          Scheduling of AWS Spot instances
          <time datetime="2018-02-27T00:00:00+01:00">27 Feb 2018</time>


text:
"use strict";

/* eslint-env browser */
/* global config */

var chai = require("chai");
var sinon = require("sinon");
var EventEmitter = require("events").EventEmitter;
var childProcess = require("child_process");
var ps = require("ps-node");
var expect = chai.expect;
var phridge = require("../lib/main.js");
var Phantom = require("../lib/Phantom.js");
var Page = require("../lib/Page.js");
var instances = require("../lib/instances.js");
var slow = require("./helpers/slow.js");
var testServer = require("./helpers/testServer.js");
var Writable = require("stream").Writable;
var createChildProcessMock = require("./helpers/createChildProcessMock.js");

require("./helpers/setup.js");

describe("Phantom", function () {
    var childProcessMock = createChildProcessMock();
    var phantom;
    var spawnPhantom;
    var exitPhantom;
    var stdout;
    var stderr;

    function mockConfigStreams() {
        stdout = phridge.config.stdout;
        stderr = phridge.config.stderr;
        phridge.config.stdout = new Writable();
        phridge.config.stderr = new Writable();
    }

    function unmockConfigStreams() {
        phridge.config.stdout = stdout;
        phridge.config.stderr = stderr;
    }

    spawnPhantom = slow(function () {
        if (phantom && phantom._isDisposed === false) {
            return undefined;
        }
        return phridge.spawn({ someConfig: true })
            .then(function (newPhantom) {
                phantom = newPhantom;
            });
    });
    exitPhantom = slow(function () {
        if (!phantom) {
            return undefined;
        }
        return phantom.dispose();
    });

    before(testServer.start);
    after(exitPhantom);
    after(testServer.stop);

    describe(".prototype", function () {

        beforeEach(spawnPhantom);

        it("should inherit from EventEmitter", function () {
            expect(phantom).to.be.instanceOf(EventEmitter);
        });

        describe("when an unexpected error on the childProcess occurs", function () {

            it("should emit an 'unexpectedExit'-event", function (done) {
                var error = new Error("Something bad happened");

                phantom.on("unexpectedExit", function (err) {
                    expect(err).to.equal(error);
                    done();
                });
                phantom.childProcess.emit("error", error);
            });

        });

        describe("when the childProcess was killed autonomously", function () {

            it("should be safe to call .dispose() after the process was killed", function () {
                phantom.childProcess.kill();
                return phantom.dispose();
            });

            it("should emit an 'unexpectedExit'-event", function (done) {
                phantom.on("unexpectedExit", function () {
                    done();
                });
                phantom.childProcess.kill();
            });

            it("should not emit an 'unexpectedExit'-event when the phantom instance was disposed in the meantime", function (done) {
                phantom.on("unexpectedExit", function () {
                    done(); // Will trigger an error that done() has been called twice
                });
                phantom.childProcess.kill();
                phantom.dispose().then(done, done);
            });

        });

        describe(".constructor(childProcess)", function () {
            var phantom; // It's important to shadow the phantom variable inside this describe block.
                         // This way spawnPhantom and exitPhantom don't use our mocked Phantom instance.

            after(function () {
                // Remove mocked Phantom instances from the instances-array
                instances.length = 0;
            });

            it("should return an instance of Phantom", function () {
                phantom = new Phantom(childProcessMock);
                expect(phantom).to.be.an.instanceof(Phantom);
            });

            it("should set the childProcess", function () {
                phantom = new Phantom(childProcessMock);
                expect(phantom.childProcess).to.equal(childProcessMock);
            });

            it("should add the instance to the instances array", function () {
                expect(instances).to.contain(phantom);
            });

        });

        describe(".childProcess", function () {

            it("should provide a reference on the child process object created by node", function () {
                expect(phantom.childProcess).to.be.an("object");
                expect(phantom.childProcess.stdin).to.be.an("object");
                expect(phantom.childProcess.stdout).to.be.an("object");
                expect(phantom.childProcess.stderr).to.be.an("object");
            });

        });

        describe(".run(arg1, arg2, arg3, fn)", function () {

            describe("with fn being an asynchronous function", function () {

                it("should provide a resolve function", function () {
                    return expect(phantom.run(function (resolve) {
                        resolve("everything ok");
                    })).to.eventually.equal("everything ok");
                });

                it("should provide the possibility to resolve with any stringify-able data", function () {
                    return Promise.all([
                        expect(phantom.run(function (resolve) {
                            resolve();
                        })).to.eventually.equal(undefined),
                        expect(phantom.run(function (resolve) {
                            resolve(true);
                        })).to.eventually.equal(true),
                        expect(phantom.run(function (resolve) {
                            resolve(2);
                        })).to.eventually.equal(2),
                        expect(phantom.run(function (resolve) {
                            resolve(null);
                        })).to.eventually.equal(null),
                        expect(phantom.run(function (resolve) {
                            resolve([1, 2, 3]);
                        })).to.eventually.deep.equal([1, 2, 3]),
                        expect(phantom.run(function (resolve) {
                            resolve({
                                someArr: [1, 2, 3],
                                otherObj: {}
                            });
                        })).to.eventually.deep.equal({
                            someArr: [1, 2, 3],
                            otherObj: {}
                        })
                    ]);
                });

                it("should provide a reject function", function () {
                    return phantom.run(function (resolve, reject) {
                        reject(new Error("not ok"));
                    }).catch(function (err) {
                        expect(err.message).to.equal("not ok");
                    });
                });

                it("should print an error when resolve is called and the request has already been finished", slow(function (done) {
                    var execPath = '"' + process.execPath + '" ';

                    childProcess.exec(execPath + require.resolve("./cases/callResolveTwice"), function (error, stdout, stderr) {
                        expect(error).to.equal(null);
                        expect(stderr).to.contain("Cannot call resolve() after the promise has already been resolved or rejected");
                        done();
                    });
                }));

                it("should print an error when reject is called and the request has already been finished", slow(function (done) {
                    var execPath = '"' + process.execPath + '" ';

                    childProcess.exec(execPath + require.resolve("./cases/callRejectTwice"), function (error, stdout, stderr) {
                        expect(error).to.equal(null);
                        expect(stderr).to.contain("Cannot call reject() after the promise has already been resolved or rejected");
                        done();
                    });
                }));

            });

            describe("with fn being a synchronous function", function () {

                it("should resolve to the returned value", function () {
                    return expect(phantom.run(function () {
                        return "everything ok";
                    })).to.eventually.equal("everything ok");
                });

                it("should provide the possibility to resolve with any stringify-able data", function () {
                    return Promise.all([
                        expect(phantom.run(function () {
                            // returns undefined
                        })).to.eventually.equal(undefined),
                        expect(phantom.run(function () {
                            return true;
                        })).to.eventually.equal(true),
                        expect(phantom.run(function () {
                            return 2;
                        })).to.eventually.equal(2),
                        expect(phantom.run(function () {
                            return null;
                        })).to.eventually.equal(null),
                        expect(phantom.run(function () {
                            return [1, 2, 3];
                        })).to.eventually.deep.equal([1, 2, 3]),
                        expect(phantom.run(function () {
                            return {
                                someArr: [1, 2, 3],
                                otherObj: {}
                            };
                        })).to.eventually.deep.equal({
                            someArr: [1, 2, 3],
                            otherObj: {}
                        })
                    ]);
                });

                it("should reject the promise if fn throws an error", function () {
                    return phantom.run(function () {
                        throw new Error("not ok");
                    }).catch(function (err) {
                        expect(err.message).to.equal("not ok");
                    });
                });

            });

            it("should provide all phantomjs default modules as convenience", function () {
                return expect(phantom.run(function () {
                    return Boolean(webpage && system && fs && webserver && child_process); // eslint-disable-line
                })).to.eventually.equal(true);
            });

            it("should provide the config object to store all kind of configuration", function () {
                return expect(phantom.run(function () {
                    return config;
                })).to.eventually.deep.equal({
                    someConfig: true
                });
            });

            it("should provide the possibility to pass params", function () {
                var params = {
                    some: ["param"],
                    withSome: "crazy",
                    values: {
                        number1: 1
                    }
                };

                return expect(phantom.run(params, params, params, function (params1, params2, params3) {
                    return [params1, params2, params3];
                })).to.eventually.deep.equal([params, params, params]);
            });

            it("should report errors", function () {
                return expect(phantom.run(function () {
                    undefinedVariable; // eslint-disable-line
                })).to.be.rejectedWith("Can't find variable: undefinedVariable");
            });

            it("should preserve all error details like stack traces", function () {
                return Promise.all([
                    phantom
                        .run(function brokenFunction() {
                            undefinedVariable; // eslint-disable-line
                        }).catch(function (err) {
                            expect(err).to.have.property("message", "Can't find variable: undefinedVariable");
                            expect(err).to.have.property("stack");
                            //console.log(err.stack);
                        }),
                    phantom
                        .run(function (resolve, reject) {
                            reject(new Error("Custom Error"));
                        })
                        .catch(function (err) {
                            expect(err).to.have.property("message", "Custom Error");
                            expect(err).to.have.property("stack");
                        })
                ]);
            });

            it("should run all functions on the same empty context", function () {
                return phantom.run(/** @this Object */function () {
                    if (JSON.stringify(this) !== "{}") {
                        throw new Error("The context is not an empty object");
                    }
                    this.message = "Hi from the first run";
                }).then(function () {
                    return phantom.run(/** @this Object */function () {
                        if (this.message !== "Hi from the first run") {
                            throw new Error("The context is not persistent");
                        }
                    });
                });
            });

            it("should reject with an error if PhantomJS process is killed", function () {
                // Phantom will eventually emit an error event when the childProcess was killed
                // In order to prevent node from throwing the error, we need to add a dummy error event listener
                phantom.on("error", Function.prototype);
                phantom.childProcess.kill();
                return phantom.run(function () {})
                    .then(function () {
                        throw new Error("There should be an error");
                    }, function (err) {
                        expect(err).to.be.an.instanceOf(Error);
                        expect(err.message).to.contain("Cannot communicate with PhantomJS process");
                        expect(err.originalError).to.be.an.instanceOf(Error);
                        expect(err.message).to.contain(err.originalError.message);
                    });
            });

        });

        describe(".createPage()", function () {

            it("should return an instance of Page", function () {
                expect(phantom.createPage()).to.be.an.instanceof(Page);
            });

        });

        describe(".openPage(url)", function () {

            it("should resolve to an instance of Page", slow(/** @this Runner */function () {
                return expect(phantom.openPage(this.testServerUrl)).to.eventually.be.an.instanceof(Page);
            }));

            it("should resolve when the given page has loaded", slow(/** @this Runner */function () {
                return phantom.openPage(this.testServerUrl).then(function (page) {
                    return page.run(/** @this WebPage */function () {
                        var headline;
                        var imgIsLoaded;

                        headline = this.evaluate(function () {
                            return document.querySelector("h1").innerText;
                        });
                        imgIsLoaded = this.evaluate(function () {
                            return document.querySelector("img").width > 0;
                        });

                        if (headline !== "This is a test page") {
                            throw new Error("Unexpected headline: " + headline);
                        }
                        if (imgIsLoaded !== true) {
                            throw new Error("The image has not loaded yet");
                        }
                    });
                });
            }));

            it("should reject when the page is not available", slow(function () {
                return expect(
                    phantom.openPage("http://localhost:1")
                ).to.be.rejectedWith("Cannot load http://localhost:1: PhantomJS returned status fail");
            }));

        });

        describe(".dispose()", function () {

            before(mockConfigStreams);
            beforeEach(spawnPhantom);
            after(unmockConfigStreams);

            it("should terminate the child process with exit-code 0 and then resolve", slow(function () {
                var exit = false;

                phantom.childProcess.on("exit", function (code) {
                    expect(code).to.equal(0);
                    exit = true;
                });

                return phantom.dispose().then(function () {
                    expect(exit).to.equal(true);
                    phantom = null;
                });
            }));

            it("should remove the instance from the instances array", slow(function () {
                return phantom.dispose().then(function () {
                    expect(instances).to.not.contain(phantom);
                    phantom = null;
                });
            }));

            // @see https://github.com/peerigon/phridge/issues/27
            it("should neither call end() on config.stdout nor config.stderr", function () {
                phridge.config.stdout.end = sinon.spy();
                phridge.config.stderr.end = sinon.spy();

                return phantom.dispose().then(function () {
                    expect(phridge.config.stdout.end).to.have.callCount(0);
                    expect(phridge.config.stderr.end).to.have.callCount(0);
                    phantom = null;
                });
            });

            it("should be safe to call .dispose() multiple times", slow(function () {
                return Promise.all([
                    phantom.dispose(),
                    phantom.dispose(),
                    phantom.dispose()
                ]);
            }));

            it("should not be possible to call .run() after .dispose()", function () {
                expect(phantom.dispose().then(function () {
                    return phantom.run(function () {});
                })).to.be.rejectedWith("Cannot run function: Phantom instance is already disposed");
            });

            it("should not be possible to call .run() after an unexpected exit", function () {
                phantom.childProcess.emit("error");
                return phantom.run(function () {})
                    .then(function () {
                        throw new Error("There should be an error");
                    }, function (err) {
                        expect(err).to.be.an.instanceOf(Error);
                        expect(err.message).to.contain("Cannot run function");
                        expect(err.originalError).to.be.an.instanceOf(Error);
                        expect(err.message).to.contain(err.originalError.message);
                    });
            });

            // @see https://github.com/peerigon/phridge/issues/41
            it("should not schedule a new ping when a pong message is received right after calling dispose()", function () {
                var message = JSON.stringify({ status: "pong" });
                var promise = phantom.dispose();

                // Simulate a pong message from PhantomJS
                phantom._receive(message);

                return promise;
            });

        });

    });

});

// This last test checks for the presence of PhantomJS zombies that might have been spawned during tests.
// We don't want phridge to leave zombies at all circumstances.
after(slow(function (done) {
    setTimeout(function () {
        ps.lookup({
            command: "phantomjs"
        }, function onLookUp(err, phantomJsProcesses) {
            if (err) {
                throw new Error(err);
            }
            if (phantomJsProcesses.length > 0) {
                throw new Error("PhantomJS zombies detected");
            }
            done();
        });
    }, 2000);
}));


text:
import mimetypes
import os
import tarfile
import zipfile
from datetime import timedelta
from django import forms
from django.contrib.auth.models import User
from django.utils import timezone
from django.utils.timezone import utc
from accounts.models import Moderator
from mod.models import Mod, Server, TaskEvent

class ModAdminForm(forms.ModelForm):

    class Meta:
        model = Mod

    def clean_mod_file(self):
        mod_file = self.cleaned_data['mod_file']
        mimetype = mimetypes.guess_type(mod_file.name)[0]
        if mimetype not in ('application/zip', 'application/x-tar'):
            raise forms.ValidationError(
                u'You can only upload .zip and .tar files.')
        if mimetype == 'application/zip':
            if not zipfile._check_zipfile(mod_file.file):
                raise forms.ValidationError(
                    u'The file is no valid archieve.')
        elif mimetype == 'application/x-tar':
            try:
                t = tarfile.open(fileobj=mod_file.file)
                t.close()
            except:
                raise forms.ValidationError(
                    u'The file is no valid archieve.')
        return mod_file

class ServerAdminForm(forms.ModelForm):

    class Meta:
        model = Server
        fields = ('owner', 'mod', 'is_active')

class MapUploadForm(forms.Form):
    map_file = forms.FileField(label='Map')

    def clean_map_file(self):
        map_file = self.cleaned_data['map_file']
        if os.path.splitext(map_file.name)[1] != '.map':
            raise forms.ValidationError('The uploaded file is not a map.')
        if map_file.read(4) not in ['DATA', 'ATAD']:
            raise forms.ValidationError('The uploaded file is not a valid map file.')
        map_file.seek(os.SEEK_SET)
        return map_file

class ChangeModForm(forms.ModelForm):
    mod = forms.ModelChoiceField(Mod.objects, empty_label=None)

    def __init__(self, user, *args, **kwargs):
        super(ChangeModForm, self).__init__(*args, **kwargs)
        if not user.is_staff:
            self.fields['mod'].queryset = user.profile.allowed_mods.all()

    def clean_mod(self):
        mod = self.cleaned_data['mod']
        if mod == Server.objects.get(pk=self.instance.pk).mod:
            raise forms.ValidationError('You chose the very same mod.')
        return mod

    class Meta:
        model = Server
        fields = ('mod',)

    def save(self):
        old_instance = Server.objects.get(pk=self.instance.pk)
        self.instance.reset_settings(old_instance)
        self.instance.save()

class ServerDescriptionForm(forms.ModelForm):

    class Meta:
        model = Server
        fields = ('description',)

class ModeratorForm(forms.Form):
    user = forms.ModelChoiceField(User.objects, empty_label=None)

    def __init__(self, user, server, *args, **kwargs):
        super(ModeratorForm, self).__init__(*args, **kwargs)
        self.server = server
        self.fields['user'].queryset = User.objects.exclude(pk=user.pk)
        for moderator in server.moderators.all():
            self.fields['user'].queryset = self.fields['user'].queryset.exclude(pk=moderator.user.pk)

    def save(self):
        user = self.cleaned_data['user']
        moderator = Moderator(server=self.server, user=user)
        moderator.save()

class CommandForm(forms.Form):
    command = forms.CharField(max_length=500)

class TaskEventAdminForm(forms.ModelForm):
    timezone_offset = forms.IntegerField(widget=forms.HiddenInput())

    class Meta:
        model = TaskEvent

    def __init__(self, *args, **kwargs):
        super(TaskEventAdminForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder = ['timezone_offset', 'name', 'task_type', 'date', 'repeat']

    def clean_date(self):
        date = self.cleaned_data['date']
        date = date.replace(tzinfo=utc)
        date = date+timedelta(minutes=self.cleaned_data['timezone_offset'])
        if date <= timezone.now():
            raise forms.ValidationError('Choose a time in the future.')
        date_before = date-timedelta(minutes=1)
        date_after = date+timedelta(minutes=1)
        events = TaskEvent.objects.filter(date__range=[date_before, date_after])
        if len(events):
            raise forms.ValidationError('Only one event per minute is allowed.')
        return date

    def clean_repeat(self):
        repeat = self.cleaned_data['repeat']
        if repeat < 0:
            raise forms.ValidationError('Time has to be positive.')
        return repeat

class TaskEventForm(TaskEventAdminForm):
    date = forms.DateTimeField(help_text='MM/DD/YYYY hh:mm:ss')

    class Meta:
        model = TaskEvent
        fields = ('name', 'task_type', 'date', 'repeat')


text:
require 'active_support/core_ext/object/to_query'
require 'httpclient'
require 'httpclient/include_client'

module HTTPHelper

  class Client
    extend HTTPClient::IncludeClient

    include_http_client

    def initialize(host = self.class::DEFAULT_HOST)
      @host = host
    end

    def url(path)
      URI.join(@host, path)
    end
  end

  class ApiClient < Client
    DEFAULT_HOST = 'http://localhost:7071'

    def post(path, body = nil, header: {})
      http_client.post(url(path), body: body, header: header)
    end
  end

  def host
    'http://localhost:7071'
  end

  def api_client
    ApiClient.new
  end

  def api_get(path, params = {})
    JSON.parse get("#{api}#{path}", query: params.to_query).content
  end

  def api_post(path, body = nil)
    post("#{api}#{path}", body: body).content
  end

  ##
  # These methods return 'response' and use 'default_host' variable
  def do_post(path, body="")
    post("#{host}#{path}", body: body.to_json, status: nil)
  end

  def do_get(path, **params)
    get("#{host}#{path}", status: nil, query: params.to_query)
  end

  def do_async_get(path, **params)
    get("#{host}#{path}", status: nil, query: params.to_query, async: true)
  end

  def do_delete(path, **params)
    delete("#{host}#{path}", status: nil)
  end
  ##
  # These methods require whole uri with host
  def get(url, **options)
    do_request('get', url, **options)
  end

  def delete(url, **options)
    do_request('delete', url, **options)
  end

  def post(url, **options)
    do_request('post', url, **options)
  end

  ##
  # These also require whole uri and return just content / parsed json

  def post_json(url, **options)
    JSON.parse(do_request('post', url, header: {'Content-Type' => 'application/json'}, **options).content)
  end

  def get_content(url, **options)
    response = get(url, **options)
    response.content || ""
  end

  def get_json(url, **options)
    json = get_content(url, **options)
    JSON.parse(json)
  end

  def delete_json(url, **options)
    json = delete_content(url, **options)
    JSON.parse(json)
  end

  def http_client
    @_http_client ||= HTTPClient.new
  end

  private

  def do_request(method, url, status: 200, query: nil, host: nil, body: nil, header: {}, async: false)
    uri = URI.parse(url)

    if host
      header['Host'] = uri.host
      uri.host = URI.parse(host).host
    end

    method = "#{method}_async" if async

    response = http_client.request(method,
                                  uri,
                                  body: body,
                                  query: query,
                                  header: header)

    expect(response.status).to eq(status) if status

    response # this returns something that has a content and status
  end

end


text:
module Twitter
  # Wrapper for the Twitter REST API
  #
  # @note All methods have been separated into modules and follow the same grouping used in {http://dev.twitter.com/doc the Twitter API Documentation}.
  # @see http://dev.twitter.com/pages/every_developer
  class Client < API
    # Require client method modules after initializing the Client class in
    # order to avoid a superclass mismatch error, allowing those modules to be
    # Client-namespaced.
    require 'twitter/client/account'
    require 'twitter/client/activity'
    require 'twitter/client/block'
    require 'twitter/client/direct_messages'
    require 'twitter/client/favorites'
    require 'twitter/client/friends_and_followers'
    require 'twitter/client/friendship'
    require 'twitter/client/geo'
    require 'twitter/client/help'
    require 'twitter/client/legal'
    require 'twitter/client/list'
    require 'twitter/client/list_members'
    require 'twitter/client/list_subscribers'
    require 'twitter/client/local_trends'
    require 'twitter/client/notification'
    require 'twitter/client/saved_searches'
    require 'twitter/client/search'
    require 'twitter/client/spam_reporting'
    require 'twitter/client/timeline'
    require 'twitter/client/trends'
    require 'twitter/client/tweets'
    require 'twitter/client/urls'
    require 'twitter/client/user'
    require 'twitter/client/utils'

    alias :api_endpoint :endpoint

    include Twitter::Client::Utils

    include Twitter::Client::Account
    include Twitter::Client::Activity
    include Twitter::Client::Block
    include Twitter::Client::DirectMessages
    include Twitter::Client::Favorites
    include Twitter::Client::FriendsAndFollowers
    include Twitter::Client::Friendship
    include Twitter::Client::Geo
    include Twitter::Client::Help
    include Twitter::Client::Legal
    include Twitter::Client::List
    include Twitter::Client::ListMembers
    include Twitter::Client::ListSubscribers
    include Twitter::Client::LocalTrends
    include Twitter::Client::Notification
    include Twitter::Client::SavedSearches
    include Twitter::Client::Search
    include Twitter::Client::SpamReporting
    include Twitter::Client::Timeline
    include Twitter::Client::Trends
    include Twitter::Client::Tweets
    include Twitter::Client::Urls
    include Twitter::Client::User
  end
end