下面列出了org.springframework.beans.factory.BeanNotOfRequiredTypeException#org.glassfish.grizzly.http.server.HttpServer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void addHTTPSRedirectHandler(HttpServer httpServerRef, int httpsPort)
{
httpServerRef.getServerConfiguration().addHttpHandler(
new HttpHandler()
{
@Override
public void service(Request request, Response response) throws Exception
{
response.setStatus(HttpStatus.NOT_FOUND_404);
response.sendRedirect(
String.format("https://%s:%d", request.getServerName(), httpsPort) +
request.getHttpHandlerPath()
);
}
}
);
}
public static void main(String[] args) {
try {
System.out.println("MinIE Service");
final HttpServer server = GrizzlyHttpServerFactory
.createHttpServer(BASE_URI, create(), false);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
server.shutdownNow();
}
}));
server.start();
System.out.println(String.format("Application started.%n" +
"Stop the application using CTRL+C"));
Thread.currentThread().join();
} catch (IOException | InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static HttpServer startServer() {
HttpServer server = new HttpServer();
server.addListener(new NetworkListener("grizzly", "0.0.0.0", 8080));
final TCPNIOTransportBuilder transportBuilder = TCPNIOTransportBuilder.newInstance();
//transportBuilder.setIOStrategy(WorkerThreadIOStrategy.getInstance());
transportBuilder.setIOStrategy(SameThreadIOStrategy.getInstance());
server.getListener("grizzly").setTransport(transportBuilder.build());
final ResourceConfig rc = new ResourceConfig().packages("xyz.muetsch.jersey");
rc.register(JacksonFeature.class);
final ServerConfiguration config = server.getServerConfiguration();
config.addHttpHandler(RuntimeDelegate.getInstance().createEndpoint(rc, GrizzlyHttpContainer.class), "/rest/todo/");
try {
server.start();
} catch (IOException e) {
e.printStackTrace();
}
return server;
}
public void startServer() throws TelegramApiRequestException {
ResourceConfig rc = new ResourceConfig();
rc.register(restApi);
rc.register(JacksonFeature.class);
final HttpServer grizzlyServer;
if (keystoreServerFile != null && keystoreServerPwd != null) {
SSLContextConfigurator sslContext = new SSLContextConfigurator();
// set up security context
sslContext.setKeyStoreFile(keystoreServerFile); // contains server keypair
sslContext.setKeyStorePass(keystoreServerPwd);
grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc, true,
new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(false));
} else {
grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);
}
try {
grizzlyServer.start();
} catch (IOException e) {
throw new TelegramApiRequestException("Error starting webhook server", e);
}
}
private void addAccessLog(HttpServer httpServer) {
try {
String accessLogLocation = serverData.getRootContext().getBean(AccessLogLocationBean.class).getAccessLogLocation();
accessLogLocation = accessLogLocation + "/" + replaceSlash(serverData.getModule().getContext()) + "-access.log";
final AccessLogBuilder builder = new AccessLogBuilder(accessLogLocation);
builder.rotatedDaily();
builder.rotationPattern("yyyy-MM-dd");
builder.instrument(httpServer.getServerConfiguration());
} catch (Exception e) {
logger.error(InternalErrorCode.SERVER_STARTUP_FAILED_TO_CREATE_ACCESS_LOG.toString() + ": " + e.getMessage());
if (e.getCause() != null)
logger.error("CAUSED BY: " + InternalErrorCode.SERVER_STARTUP_FAILED_TO_CREATE_ACCESS_LOG.toString() + ": " + e.getCause().getMessage());
}
}
@Test
public void testJsonSerialization_application() throws Exception {
// This test guarantees that in an non-OSGi environment,
// our REST application uses the properties we define.
// And, in particular, the JSon serialization that we tailored.
URI uri = UriBuilder.fromUri( "http://localhost/" ).port( 8090 ).build();
RestApplication restApp = new RestApplication( this.manager );
HttpServer httpServer = null;
String received = null;
try {
httpServer = GrizzlyServerFactory.createHttpServer( uri, restApp );
Assert.assertTrue( httpServer.isStarted());
URI targetUri = UriBuilder.fromUri( uri ).path( UrlConstants.APPLICATIONS ).build();
received = Utils.readUrlContent( targetUri.toString());
} finally {
if( httpServer != null )
httpServer.stop();
}
String expected = JSonBindingUtils.createObjectMapper().writeValueAsString( Arrays.asList( this.app ));
Assert.assertEquals( expected, received );
}
private void setupSwagger(HttpServer httpServer, boolean advertiseHttps) {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("Pinot Controller API");
beanConfig.setDescription("APIs for accessing Pinot Controller information");
beanConfig.setContact("https://github.com/apache/incubator-pinot");
beanConfig.setVersion("1.0");
if (advertiseHttps) {
beanConfig.setSchemes(new String[]{"https"});
} else {
beanConfig.setSchemes(new String[]{"http"});
}
beanConfig.setBasePath("/");
beanConfig.setResourcePackage(RESOURCE_PACKAGE);
beanConfig.setScan(true);
ClassLoader loader = this.getClass().getClassLoader();
CLStaticHttpHandler apiStaticHttpHandler = new CLStaticHttpHandler(loader, "/api/");
// map both /api and /help to swagger docs. /api because it looks nice. /help for backward compatibility
httpServer.getServerConfiguration().addHttpHandler(apiStaticHttpHandler, "/api/");
httpServer.getServerConfiguration().addHttpHandler(apiStaticHttpHandler, "/help/");
URL swaggerDistLocation = loader.getResource("META-INF/resources/webjars/swagger-ui/2.2.2/");
CLStaticHttpHandler swaggerDist = new CLStaticHttpHandler(new URLClassLoader(new URL[]{swaggerDistLocation}));
httpServer.getServerConfiguration().addHttpHandler(swaggerDist, "/swaggerui-dist/");
}
private void setupSwagger(HttpServer httpServer) {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("Pinot Server API");
beanConfig.setDescription("APIs for accessing Pinot server information");
beanConfig.setContact("https://github.com/apache/incubator-pinot");
beanConfig.setVersion("1.0");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setBasePath(baseUri.getPath());
beanConfig.setResourcePackage(RESOURCE_PACKAGE);
beanConfig.setScan(true);
CLStaticHttpHandler staticHttpHandler =
new CLStaticHttpHandler(AdminApiApplication.class.getClassLoader(), "/api/");
// map both /api and /help to swagger docs. /api because it looks nice. /help for backward compatibility
httpServer.getServerConfiguration().addHttpHandler(staticHttpHandler, "/api/");
httpServer.getServerConfiguration().addHttpHandler(staticHttpHandler, "/help/");
URL swaggerDistLocation =
AdminApiApplication.class.getClassLoader().getResource("META-INF/resources/webjars/swagger-ui/2.2.2/");
CLStaticHttpHandler swaggerDist = new CLStaticHttpHandler(new URLClassLoader(new URL[]{swaggerDistLocation}));
httpServer.getServerConfiguration().addHttpHandler(swaggerDist, "/swaggerui-dist/");
}
public static void main(String[] args) {
try {
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new ViewApplicationConfig(), false);
Runtime.getRuntime()
.addShutdownHook(new Thread(() -> {
server.shutdownNow();
}));
server.start();
System.out.println(String.format("Application started.\nTry out %s\nStop the application using CTRL+C", BASE_URI + "fruit"));
} catch (IOException ex) {
Logger.getLogger(EmbeddedHttpServer.class.getName())
.log(Level.SEVERE, null, ex);
}
}
private void setupServer(Application application) {
ResourceConfig rc = ResourceConfig.forApplication(application);
Properties serverProperties = readProperties();
int port = Integer.parseInt(serverProperties.getProperty(PORT_PROPERTY));
URI serverUri = UriBuilder.fromPath(ROOT_RESOURCE_PATH).scheme("http").host("localhost").port(port).build();
final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(serverUri, rc);
try {
grizzlyServer.start();
} catch (IOException e) {
e.printStackTrace();
}
server = grizzlyServer;
}
@Before
public void before(final MockTracer tracer) throws IOException {
// clear traces
tracer.reset();
httpServer = HttpServer.createSimpleServer(".", port);
httpServer.start();
setupServer(httpServer);
}
@Before
public void before(final MockTracer tracer) throws IOException {
// clear traces
tracer.reset();
httpServer = new HttpServer();
NetworkListener listener = new NetworkListener("grizzly", DEFAULT_NETWORK_HOST, PORT);
httpServer.addListener(listener);
httpServer.start();
}
public static void main(final String[] args) throws IOException {
final HttpServer server = new HttpServer();
final NetworkListener listener = new NetworkListener("grizzly", DEFAULT_NETWORK_HOST, 18906);
server.addListener(listener);
server.start();
server.getServerConfiguration().addHttpHandler(new HttpHandler() {
@Override
public void service(final Request request, final Response response) {
TestUtil.checkActiveSpan();
response.setStatus(200);
}
});
int responseCode = -1;
try {
final URL url = new URL("http://localhost:18906/");
final HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
responseCode = connection.getResponseCode();
connection.disconnect();
}
finally {
server.shutdownNow();
if (200 != responseCode)
throw new AssertionError("ERROR: response: " + responseCode);
TestUtil.checkSpan(true, new ComponentSpanCount("java-grizzly-http-server", 1), new ComponentSpanCount("http-url-connection", 1));
}
}
private void enableCompression(HttpServer httpServerRef)
{
CompressionConfig compressionConfig = httpServerRef.getListener("grizzly").getCompressionConfig();
compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON);
compressionConfig.setCompressibleMimeTypes("text/plain", "text/html", "application/json");
compressionConfig.setCompressionMinSize(COMPRESSION_MIN_SIZE);
}
/**
* Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
*/
protected static HttpServer startServer() {
// create a resource config that scans for JAX-RS resources and providers in com.miguno package
final ResourceConfig rc = new ResourceConfig().packages("com.miguno");
// create and start a new instance of grizzly http server
// exposing the Jersey application at BASE_URI
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
public void startServer(String ip, int port) {
URI serverURI = UriBuilder.fromUri("http://" + ip).port(port).build();
// Create test web application context.
WebappContext webappContext = new WebappContext("NULS-V2-SDK-PROVIDER-SERVER", "/");
ServletRegistration servletRegistration = webappContext.addServlet("jersey-servlet", ServletContainer.class);
servletRegistration.setInitParameter("javax.ws.rs.Application", "io.nuls.provider.api.config.NulsResourceConfig");
servletRegistration.addMapping("/*");
httpServer = new HttpServer();
NetworkListener listener = new NetworkListener("grizzly2", ip, port);
TCPNIOTransport transport = listener.getTransport();
ThreadPoolConfig workerPool = ThreadPoolConfig.defaultConfig()
.setCorePoolSize(4)
.setMaxPoolSize(4)
.setQueueLimit(1000)
.setThreadFactory((new ThreadFactoryBuilder()).setNameFormat("grizzly-http-server-%d").build());
transport.configureBlocking(false);
transport.setSelectorRunnersCount(2);
transport.setWorkerThreadPoolConfig(workerPool);
transport.setIOStrategy(WorkerThreadIOStrategy.getInstance());
transport.setTcpNoDelay(true);
listener.setSecure(false);
httpServer.addListener(listener);
ServerConfiguration config = httpServer.getServerConfiguration();
config.setDefaultQueryEncoding(Charsets.UTF8_CHARSET);
webappContext.deploy(httpServer);
try {
ClassLoader loader = this.getClass().getClassLoader();
httpServer.start();
Log.info("http restFul server is started!url is " + serverURI.toString());
} catch (IOException e) {
Log.error(e);
httpServer.shutdownNow();
}
}
public static void main(String[] args) {
try {
final ResourceConfig resourceConfig = new ResourceConfig(SseResource.class);
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(CONTEXT, resourceConfig, false);
server.start();
System.out.println(String.format("Mock Server started at %s%s", CONTEXT, BASE_PATH));
Thread.currentThread().join();
} catch (IOException | InterruptedException ex) {
System.out.println(ex.getMessage());
}
}
/**
* @see cloud.piranha.http.api.HttpServer#start()
*/
@Override
public void start() {
if (httpServer == null) {
httpServer = HttpServer.createSimpleServer(null, port);
httpServer.getListener("grizzly").setSecure(ssl);
}
addHttpHandler();
try {
httpServer.start();
} catch (IOException ioe) {
LOGGER.log(Level.WARNING, "An I/O error occurred while starting the HTTP server", ioe);
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new JerseyApplication());
server.start();
Thread.sleep(50);
System.out.println("\n\nopen http://localhost:8080 in your browser\n\n");
}
public HttpServer startAPIServer(Player player, int port) {
logger.debug("Starting Player API server at " + getURI(port));
player.setEndpoint(getURI(port));
PlayerAPI api = new PlayerAPI(player);
final ResourceConfig rc = new ResourceConfig().register(api);
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create("http://0.0.0.0:" + port + BASE_PATH),
rc);
return server;
}
public TintServer(String host, Integer port, @Nullable File configFile,
@Nullable Properties additionalProperties) {
LOGGER.info("starting " + host + "\t" + port + " (" + new Date() + ")...");
int timeoutInSeconds = -1;
try {
// Load the pipeline
TintPipeline pipeline = new TintPipeline();
pipeline.loadDefaultProperties();
pipeline.loadPropertiesFromFile(configFile);
pipeline.addProperties(additionalProperties);
// todo: parametrize this!
// pipeline.loadSerializers();
pipeline.load();
LOGGER.info("Pipeline loaded");
final HttpServer httpServer = new HttpServer();
NetworkListener nl = new NetworkListener("tint-server", host, port);
httpServer.addListener(nl);
TintHandler tintHandler = new TintHandler(pipeline);
tintHandler.setRequestURIEncoding(Charset.forName("UTF-8"));
httpServer.getServerConfiguration().setSessionTimeoutSeconds(timeoutInSeconds);
httpServer.getServerConfiguration().setMaxPostSize(4194304);
httpServer.getServerConfiguration().addHttpHandler(tintHandler, "/tint");
httpServer.start();
Thread.currentThread().join();
} catch (Exception e) {
LOGGER.error("error running " + host + ":" + port);
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new JerseyApplication());
System.out.println("Press any key to close");
System.in.read();
server.shutdownNow();
}
/**
* Gracefully stop REST service.
*/
@Override
protected void shutDown() throws Exception {
long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "shutDown");
try {
log.info("Stopping REST server listening on port: {}", this.restServerConfig.getPort());
final GrizzlyFuture<HttpServer> shutdown = httpServer.shutdown(30, TimeUnit.SECONDS);
log.info("Awaiting termination of REST server");
shutdown.get();
log.info("REST server terminated");
} finally {
LoggerHelpers.traceLeave(log, this.objectId, "shutDown", traceId);
}
}
public static void runWithConfig(ServerConfiguration config) throws Exception {
URI baseUri = UriBuilder.fromUri("http://0.0.0.0/").port(config.port).build();
// ResourceConfig rConfig = new
// ResourceConfig(QueryResource.class).register;
MultiCube cube = new MultiCubeImpl(new File(config.path).getAbsolutePath());
cube.load(cube.getPath());
CubeApplication rConfig = new CubeApplication(config, cube);
registerStuff(rConfig);
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, rConfig);
Log.info("Starting server");
server.start();
Thread.currentThread().join();
Log.info("Shutting down");
}
public void start() throws IOException
{
initResources();
URI baseUri = UriBuilder.fromUri("http://localhost/").port(9998).build();
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
server.start();
}
public void start() throws IOException
{
initResources();
URI baseUri = UriBuilder.fromUri("http://localhost/").port(9998).build();
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
server.start();
}
public static void main(String[] args) throws IOException {
String host = "0.0.0.0";
int port = 8080;
if (args.length > 0) {
host = args[0];
}
if (args.length > 1) {
port = Integer.parseInt(args[1]);
}
final HttpServer server = startServer(host,port);
System.in.read();
server.shutdown();
}
public static void main(String[] args) {
try {
System.out.println("Starting Weather App local testing server: " + BASE_URL);
System.out.println("Not for production use");
final ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.register(RestWeatherCollectorEndpoint.class);
resourceConfig.register(RestWeatherQueryEndpoint.class);
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URL), resourceConfig, false);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
server.shutdownNow();
}
}));
HttpServerProbe probe = new HttpServerProbe.Adapter() {
public void onRequestReceiveEvent(HttpServerFilter filter, Connection connection, Request request) {
System.out.println(request.getRequestURI());
}
};
server.getServerConfiguration().getMonitoringConfig().getWebServerConfig().addProbes(probe);
System.out.println(format("Weather Server started.\n url=%s\n", BASE_URL));
server.start();
Thread.currentThread().join();
} catch (IOException | InterruptedException ex) {
Logger.getLogger(WeatherServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
OSM osm = new OSM(args[0]);
if (args.length > 1 && args[1].startsWith("--load")) {
osm.intersectionDetection = true;
osm.tileIndexing = true;
if (args[1].equalsIgnoreCase("--loadurl")) {
osm.readFromUrl(args[2]);
} else {
osm.readFromFile(args[2]);
}
// TODO catch writing exceptions here and shut down properly, closing OSM database.
LOG.info("Done populating OSM database.");
osm.close();
return;
}
Thread updateThread = Updater.spawnUpdateThread(osm);
LOG.info("Starting VEX HTTP server on port {} of interface {}", PORT, BIND_ADDRESS);
HttpServer httpServer = new HttpServer();
httpServer.addListener(new NetworkListener("vanilla_extract", BIND_ADDRESS, PORT));
// Bypass Jersey etc. and add a low-level Grizzly handler.
// As in servlets, * is needed in base path to identify the "rest" of the path.
httpServer.getServerConfiguration().addHttpHandler(new VexHttpHandler(osm), "/*");
try {
httpServer.start();
LOG.info("VEX server running.");
Thread.currentThread().join();
updateThread.interrupt();
} catch (BindException be) {
LOG.error("Cannot bind to port {}. Is it already in use?", PORT);
} catch (IOException ioe) {
LOG.error("IO exception while starting server.");
} catch (InterruptedException ie) {
LOG.info("Interrupted, shutting down.");
}
httpServer.shutdown();
}
@Test
public void executeATakesAsAServlet() throws Exception {
final String name = "webapp";
final HttpServer server = HttpServer.createSimpleServer("./", 18080);
final WebappContext context = new WebappContext(name);
final ServletRegistration servlet = context.addServlet(
"takes",
SrvTake.class
);
servlet.setInitParameter("take", TkApp.class.getName());
servlet.addMapping("/test");
context.deploy(server);
server.start();
new JdkRequest("http://localhost:18080/test")
.fetch()
.as(RestResponse.class)
.assertStatus(HttpURLConnection.HTTP_OK)
.assertBody(
new StringContains(
new FormattedText(
SrvTakeTest.MSG,
name
).asString()
)
);
server.shutdownNow();
}