
com.yammer.dropwizard.cli.ServerCommand Maven / Gradle / Ivy
package com.yammer.dropwizard.cli;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.yammer.dropwizard.AbstractService;
import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.config.ServerFactory;
import com.yammer.dropwizard.logging.Log;
import org.apache.commons.cli.CommandLine;
import org.eclipse.jetty.server.Server;
import java.io.IOException;
// TODO: 10/12/11 -- write tests for ServerCommand
/**
* Runs a service as an HTTP server.
*
* @param the {@link Configuration} subclass which is loaded from the configuration file
*/
public class ServerCommand extends ConfiguredCommand {
private final Class configurationClass;
/**
* Creates a new {@link ServerCommand} with the given configuration class.
*
* @param configurationClass the configuration class the YAML file is parsed as
*/
public ServerCommand(Class configurationClass) {
super("server", "Starts an HTTP server running the service");
this.configurationClass = configurationClass;
}
/*
* Since we don't subclass ServerCommand, we need a concrete reference to the configuration
* class.
*/
@Override
protected Class getConfigurationClass() {
return configurationClass;
}
@Override
protected void run(AbstractService service,
T configuration,
CommandLine params) throws Exception {
final Environment environment = new Environment(service, configuration);
service.initializeWithBundles(configuration, environment);
final Server server = new ServerFactory(configuration.getHttpConfiguration(),
service.getName()).buildServer(environment);
final Log log = Log.forClass(ServerCommand.class);
logBanner(service, log);
try {
server.start();
server.join();
} catch (Exception e) {
log.error(e, "Unable to start server, shutting down");
server.stop();
}
}
private void logBanner(AbstractService service, Log log) {
try {
final String banner = Resources.toString(Resources.getResource("banner.txt"),
Charsets.UTF_8);
log.info("Starting {}\n{}", service.getName(), banner);
} catch (IllegalArgumentException ignored) {
// don't display the banner if there isn't one
log.info("Starting {}", service.getName());
} catch (IOException ignored) {
log.info("Starting {}", service.getName());
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy