Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.yammer.dropwizard.config;
  
 
 import java.util.List;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 // TODO: 10/12/11 <coda> -- test Environment
 /*
     REVIEW: 11/12/11 <coda> -- Probably better to invert this code.
     Instead of letting it collect intermediate results and then exposing those via package-private
     getters, it might be better to pass this a ServletContextHandler, etc., and have it modify
     those directly. That's easier to test.
 */

A Dropwizard service's environment.
 
 public class Environment extends AbstractLifeCycle {
     private static final Logger LOGGER = LoggerFactory.getLogger(Environment.class);
 
     private final String name;
     private final Configuration configuration;
     private final DropwizardResourceConfig config;
     private final ImmutableSet.Builder<HealthCheckhealthChecks;
     private final ImmutableMap.Builder<StringServletHolderservlets;
     private final ImmutableMultimap.Builder<StringFilterHolderfilters;
     private final ImmutableSet.Builder<Tasktasks;
     private final ImmutableSet.Builder<StringprotectedTargets;
     private Resource baseResource;
     private final AggregateLifeCycle lifeCycle;
     private final ObjectMapperFactory objectMapperFactory;
     private SessionHandler sessionHandler;
     private Validator validator;

    
Creates a new environment.

Parameters:
name the name of the service
configuration the service's Configuration
objectMapperFactory the com.yammer.dropwizard.json.ObjectMapperFactory for the service
 
     public Environment(String name,
                        Configuration configuration,
                        ObjectMapperFactory objectMapperFactory,
                        Validator validator) {
         this. = name;
         this. = configuration;
         this. = objectMapperFactory;
         this. = validator;
         this. = new DropwizardResourceConfig(false) {
             @Override
             public void validate() {
                 super.validate();
                 logResources();
                 logProviders();
                 logHealthChecks();
                 logManagedObjects();
                 logEndpoints();
                 logTasks();
             }
        };
        this. = ImmutableSet.builder();
        this. = ImmutableMap.builder();
        this. = ImmutableMultimap.builder();
        this. = ImmutableSet.builder();
        this. = ImmutableSet.builder();
        this. = Resource.newClassPathResource(".");
        this. = ImmutableSet.builder();
        this. = ImmutableList.builder();
        this. = new AggregateLifeCycle();
        this. = new ServletContainer();
        addTask(new GarbageCollectionTask());
    }
    @Override
    protected void doStart() throws Exception {
        .start();
    }
    @Override
    protected void doStop() throws Exception {
        .stop();
    }

    
Adds the given object as a Jersey singleton resource.

Parameters:
resource a Jersey singleton resource
    public void addResource(Object resource) {
        .getSingletons().add(checkNotNull(resource));
    }

    
Scans the packages and sub-packages of the given java.lang.Class objects for resources and providers.

Parameters:
classes the classes whose packages to scan
    public void scanPackagesForResourcesAndProviders(Class<?>... classes) {
        checkNotNull(classes);
        final String[] names = new String[classes.length];
        for (int i = 0; i < classes.lengthi++) {
            names[i] = classes[i].getPackage().getName();
        }
        .init(new PackageNamesScanner(names));
    }

    
Adds the given class as a Jersey resource.

N.B.: This class must either have a no-args constructor or use Jersey's built-in dependency injection.

Parameters:
klass a Jersey resource class
    public void addResource(Class<?> klass) {
        .getClasses().add(checkNotNull(klass));
    }

    
Adds the given object as a Jersey provider.

Parameters:
provider a Jersey provider
    public void addProvider(Object provider) {
        .getSingletons().add(checkNotNull(provider));
    }

    
Adds the given class as a Jersey provider.

N.B.: This class must either have a no-args constructor or use Jersey's built-in dependency injection.

Parameters:
klass a Jersey provider class
    public void addProvider(Class<?> klass) {
        .getClasses().add(checkNotNull(klass));
    }

    
Adds the given health check to the set of health checks exposed on the admin port.

Parameters:
healthCheck a health check
    public void addHealthCheck(HealthCheck healthCheck) {
        .add(checkNotNull(healthCheck));
    }

    
Adds the given com.yammer.dropwizard.lifecycle.Managed instance to the set of objects managed by the server's lifecycle. When the server starts, managed will be started. When the server stops, managed will be stopped.

Parameters:
managed a managed object
    public void manage(Managed managed) {
        .addBean(new JettyManaged(checkNotNull(managed)));
    }

    
Adds the given Jetty org.eclipse.jetty.util.component.LifeCycle instances to the server's lifecycle.

Parameters:
managed a Jetty-managed object
    public void manage(LifeCycle managed) {
        .addBean(checkNotNull(managed));
    }

    
Add a servlet instance.

Parameters:
servlet the servlet instance
urlPattern the URL pattern for requests that should be handled by servlet
Returns:
a ServletBuilder instance allowing for further configuration
    public ServletBuilder addServlet(Servlet servlet,
                                     String urlPattern) {
        final ServletHolder holder = new NonblockingServletHolder(checkNotNull(servlet));
        final ServletBuilder servletConfig = new ServletBuilder(holder);
        servletConfig.addUrlPattern(checkNotNull(urlPattern));
        return servletConfig;
    }

    
Add a servlet class.

Parameters:
klass the servlet class
urlPattern the URL pattern for requests that should be handled by instances of klass
Returns:
a ServletBuilder instance allowing for further configuration
    public ServletBuilder addServlet(Class<? extends Servletklass,
                                     String urlPattern) {
        final ServletHolder holder = new ServletHolder(checkNotNull(klass));
        final ServletBuilder servletConfig = new ServletBuilder(holder);
        servletConfig.addUrlPattern(checkNotNull(urlPattern));
        return servletConfig;
    }

    
Add a filter instance.

Parameters:
filter the filter instance
urlPattern the URL pattern for requests that should be handled by filter
Returns:
a FilterBuilder instance allowing for further configuration
    public FilterBuilder addFilter(Filter filter,
                                   String urlPattern) {
        final FilterHolder holder = new FilterHolder(checkNotNull(filter));
        final FilterBuilder filterConfig = new FilterBuilder(holder);
        filterConfig.addUrlPattern(checkNotNull(urlPattern));
        return filterConfig;
    }

    
Add a filter class.

Parameters:
klass the filter class
urlPattern the URL pattern for requests that should be handled by instances of klass
Returns:
a FilterBuilder instance allowing for further configuration
    public FilterBuilder addFilter(Class<? extends Filterklass,
                                   String urlPattern) {
        final FilterHolder holder = new FilterHolder(checkNotNull(klass));
        final FilterBuilder filterConfig = new FilterBuilder(holder);
        filterConfig.addUrlPattern(checkNotNull(urlPattern));
        return filterConfig;
    }

    
Add one or more servlet event listeners.

    public void addServletListeners(EventListener... listeners) {
        this..add(listeners);
    }

    
    public void addTask(Task task) {
        .add(checkNotNull(task));
    }

    
Adds a protected Target (ie a target that 404s)

Parameters:
target a protected target
    public void addProtectedTarget(String target) {
        .add(checkNotNull(target));
    }
    public void setBaseResource(Resource baseResource) {
        this. = baseResource;
    }
    public void setSessionHandler(SessionHandler sessionHandler) {
        this. = sessionHandler;
    }

    
Enables the Jersey feature with the given name.

Parameters:
name the name of the feature to be enabled
See also:
com.sun.jersey.api.core.ResourceConfig
    public void enableJerseyFeature(String name) {
        .getFeatures().put(checkNotNull(name), .);
    }

    
Disables the Jersey feature with the given name.

Parameters:
name the name of the feature to be disabled
See also:
com.sun.jersey.api.core.ResourceConfig
    public void disableJerseyFeature(String name) {
        .getFeatures().put(checkNotNull(name), .);
    }

    
Sets the given Jersey property.

Parameters:
name the name of the Jersey property
value the value of the Jersey property
See also:
com.sun.jersey.api.core.ResourceConfig
    public void setJerseyProperty(String name, @Nullable Object value) {
        .getProperties().put(checkNotNull(name), value);
    }

    
Gets the given Jersey property.

Parameters:
name the name of the Jersey property
See also:
com.sun.jersey.api.core.ResourceConfig
    @SuppressWarnings("unchecked")
    public <T> T getJerseyProperty(String name) {
        return (T) .getProperties().get(name);
    }


    
Creates a new java.util.concurrent.ExecutorService instance with the given parameters whose lifecycle is managed by the service.

Parameters:
nameFormat a java.lang.String.format(java.lang.String,java.lang.Object[])-compatible format String, to which a unique integer (0, 1, etc.) will be supplied as the single parameter.
corePoolSize the number of threads to keep in the pool, even if they are idle.
maximumPoolSize the maximum number of threads to allow in the pool.
keepAliveTime when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
unit the time unit for the keepAliveTime argument.
Returns:
a new java.util.concurrent.ExecutorService instance
    public ExecutorService managedExecutorService(String nameFormat,
                                                  int corePoolSize,
                                                  int maximumPoolSize,
                                                  long keepAliveTime,
                                                  TimeUnit unit) {
        final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(nameFormat)
                                                                      .build();
        final ExecutorService executor = new ThreadPoolExecutor(corePoolSize,
                                                                maximumPoolSize,
                                                                keepAliveTime,
                                                                unit,
                                                                new LinkedBlockingQueue<Runnable>(),
                                                                threadFactory);
        manage(new ExecutorServiceManager(executor, 5, .nameFormat));
        return executor;
    }

    
Creates a new java.util.concurrent.ScheduledExecutorService instance with the given parameters whose lifecycle is managed by the service.

Parameters:
nameFormat a java.lang.String.format(java.lang.String,java.lang.Object[])-compatible format String, to which a unique integer (0, 1, etc.) will be supplied as the single parameter.
corePoolSize the number of threads to keep in the pool, even if they are idle.
Returns:
a new java.util.concurrent.ScheduledExecutorService instance
                                                                    int corePoolSize) {
        final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(nameFormat)
                                                                      .build();
        final ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(corePoolSize,
                                                                                  threadFactory);
        manage(new ExecutorServiceManager(executor, 5, .nameFormat));
        return executor;
    }
    public Validator getValidator() {
        return ;
    }
    public void setValidator(Validator validator) {
        this. = checkNotNull(validator);
    }
    /*
    * Internal Accessors
    */
        return .build();
    }
        return .build();
    }
        return .build();
    }
        return .build();
    }
        return .build();
    }
        return ;
    }
        return .build();
    }
    private void logManagedObjects() {
        final ImmutableSet.Builder<Stringbuilder = ImmutableSet.builder();
        for (Object bean : .getBeans()) {
            builder.add(bean.toString());
        }
        .debug("managed objects = {}"builder.build());
    }
    private void logHealthChecks() {
        final ImmutableSet.Builder<Stringbuilder = ImmutableSet.builder();
        for (HealthCheck healthCheck : .build()) {
            final String canonicalName = healthCheck.getClass().getCanonicalName();
            if (canonicalName == null) {
                builder.add(String.format("%s(\"%s\")",
                                          HealthCheck.class.getCanonicalName(),
                                          healthCheck.getName()));
            } else {
                builder.add(canonicalName);
            }
        }
        .debug("health checks = {}"builder.build());
    }
    private void logResources() {
        final ImmutableSet.Builder<Stringbuilder = ImmutableSet.builder();
        for (Class<?> klass : .getClasses()) {
            if (klass.isAnnotationPresent(Path.class)) {
                builder.add(klass.getCanonicalName());
            }
        }
        for (Object o : .getSingletons()) {
            if (o.getClass().isAnnotationPresent(Path.class)) {
                builder.add(o.getClass().getCanonicalName());
            }
        }
        .debug("resources = {}"builder.build());
    }
    private void logProviders() {
        final ImmutableSet.Builder<Stringbuilder = ImmutableSet.builder();
        for (Class<?> klass : .getClasses()) {
            if (klass.isAnnotationPresent(Provider.class)) {
                builder.add(klass.getCanonicalName());
            }
        }
        for (Object o : .getSingletons()) {
            if (o.getClass().isAnnotationPresent(Provider.class)) {
                builder.add(o.getClass().getCanonicalName());
            }
        }
        .debug("providers = {}"builder.build());
    }
    private void logEndpoints() {
        final StringBuilder stringBuilder = new StringBuilder(1024).append("The following paths were found for the configured resources:\n\n");
        final ImmutableList.Builder<Class<?>> builder = ImmutableList.builder();
        for (Object o : .getSingletons()) {
            if (o.getClass().isAnnotationPresent(Path.class)) {
                builder.add(o.getClass());
            }
        }
        for (Class<?> klass : .getClasses()) {
            if (klass.isAnnotationPresent(Path.class)) {
                builder.add(klass);
            }
        }
        for (Class<?> klass : builder.build()) {
            final String path = klass.getAnnotation(Path.class).value();
            String rootPath = .getHttpConfiguration().getRootPath();
            if (rootPath.endsWith("/*")) {
                rootPath = rootPath.substring(0, rootPath.length() - (path.startsWith("/") ? 2 : 1));
            }
            final ImmutableList.Builder<Stringendpoints = ImmutableList.builder();
            for (AnnotatedMethod method : annotatedMethods(klass)) {
                final StringBuilder pathBuilder = new StringBuilder()
                        .append(rootPath)
                        .append(path);
                if (method.isAnnotationPresent(Path.class)) {
                    final String methodPath = method.getAnnotation(Path.class).value();
                    if (!methodPath.startsWith("/") && !path.endsWith("/")) {
                        pathBuilder.append('/');
                    }
                    pathBuilder.append(methodPath);
                }
                for (HttpMethod verb : method.getMetaMethodAnnotations(HttpMethod.class)) {
                    endpoints.add(String.format("    %-7s %s (%s)",
                                                verb.value(),
                                                pathBuilder.toString(),
                                                klass.getCanonicalName()));
                }
            }
            for (String line : Ordering.natural().sortedCopy(endpoints.build())) {
                stringBuilder.append(line).append('\n');
            }
        }
        .info(stringBuilder.toString());
    }
    private void logTasks() {
        final StringBuilder stringBuilder = new StringBuilder(1024).append("\n\n");
        for (Task task : .build()) {
            stringBuilder.append(String.format("    %-7s /tasks/%s (%s)\n",
                                               "POST",
                                               task.getName(),
                                               task.getClass().getCanonicalName()));
        }
        .info("tasks = {}"stringBuilder.toString());
    }
    private MethodList annotatedMethods(Class<?> resource) {
        return new MethodList(resourcetrue).hasMetaAnnotation(HttpMethod.class);
    }
    public SessionHandler getSessionHandler() {
        return ;
    }
        return ;
    }
        return ;
    }
        return ;
    }
    public void setJerseyServletContainer(ServletContainer jerseyServletContainer) {
        this. = jerseyServletContainer;
    }
    public String getName() {
        return ;
    }
        return .build();
    }
    public void addServerLifecycleListener(ServerLifecycleListener listener) {
        .add(listener);
    }
New to GrepCode? Check out our FAQ X