use of cloud.piranha.http.api.HttpServer in project piranha by piranhacloud.
the class MicroInnerDeployer method start.
/**
* Start the application.
*
* @param applicationArchive the application archive.
* @param classLoader the classloader.
* @param handlers the handlers.
* @param config the configuration.
* @return the map.
*/
public Map<String, Object> start(Archive<?> applicationArchive, ClassLoader classLoader, Map<String, Function<URL, URLConnection>> handlers, Map<String, Object> config) {
try {
WebApplication webApplication = getWebApplication(applicationArchive, classLoader);
LOGGER.log(INFO, "Starting web application " + applicationArchive.getName() + " on Piranha Micro " + webApplication.getAttribute(MICRO_PIRANHA));
// The global archive stream handler is set to resolve "shrinkwrap://" URLs (created from strings).
// Such URLs come into being primarily when code takes resolves a class or resource from the class loader by URL
// and then takes the string form of the URL representing the class or resource.
GlobalArchiveStreamHandler streamHandler = new GlobalArchiveStreamHandler(webApplication);
// Life map to the StaticURLStreamHandlerFactory used by the root class loader
handlers.put("shrinkwrap", streamHandler::connect);
// Source of annotations
Index index = getIndex();
// Target of annotations
AnnotationManager annotationManager = new InternalAnnotationScanAnnotationManager();
webApplication.getManager().setAnnotationManager(annotationManager);
// Copy annotations from our "annotations" collection from source index to target manager
forEachWebAnnotation(webAnnotation -> addAnnotationToIndex(index, webAnnotation, annotationManager));
// Collect sub-classes/interfaces of our "instances" collection from source index to target manager
forEachInstance(instanceClass -> addInstanceToIndex(index, instanceClass, annotationManager));
// Collect any sub-classes/interfaces from any HandlesTypes annotation
getAnnotations(index, HandlesTypes.class).map(this::getTarget).forEach(annotationTarget -> getAnnotationInstances(annotationTarget, HandlesTypes.class).map(HandlesTypes.class::cast).forEach(handlesTypesInstance -> stream(handlesTypesInstance.value()).forEach(e -> {
if (e.isAnnotation()) {
addAnnotationToIndex(index, e, annotationManager);
} else {
addInstanceToIndex(index, e, annotationManager);
}
})));
// Setup the default identity store, which is used as the default "username and roles database" for
// (Servlet) security.
initIdentityStore(webApplication);
setApplicationContextPath(webApplication, config, applicationArchive);
DefaultWebApplicationExtensionContext extensionContext = new DefaultWebApplicationExtensionContext();
for (WebApplicationExtension extension : ServiceLoader.load(WebApplicationExtension.class)) {
extensionContext.add(extension);
}
extensionContext.configure(webApplication);
webApplication.initialize();
webApplication.start();
if ((boolean) config.get("micro.http.start")) {
HttpWebApplicationServer webApplicationServer = new HttpWebApplicationServer();
webApplicationServer.addWebApplication(webApplication);
ServiceLoader<HttpServer> httpServers = ServiceLoader.load(HttpServer.class);
httpServer = httpServers.findFirst().orElseThrow();
httpServer.setServerPort((Integer) config.get("micro.port"));
httpServer.setSSL(Boolean.getBoolean("piranha.http.ssl"));
httpServer.setHttpServerProcessor(webApplicationServer);
httpServer.start();
}
return Map.of("deployedServlets", webApplication.getServletRegistrations().keySet(), "deployedApplication", new MicroInnerApplication(webApplication), "deployedContextRoot", webApplication.getContextPath());
} catch (IOException e) {
throw new IllegalStateException(e);
} catch (Exception e) {
throw e;
}
}
use of cloud.piranha.http.api.HttpServer in project piranha by piranhacloud.
the class MicroPiranha method run.
/**
* Run method.
*/
@Override
public void run() {
long startTime = System.currentTimeMillis();
LOGGER.log(INFO, () -> "Starting Piranha");
webApplicationServer = new HttpWebApplicationServer();
if (httpPort > 0) {
HttpServer httpServer = ServiceLoader.load(HttpServer.class).findFirst().orElseThrow();
httpServer.setServerPort(httpPort);
httpServer.setHttpServerProcessor(webApplicationServer);
httpServer.start();
}
if (httpsPort > 0) {
HttpServer httpsServer = ServiceLoader.load(HttpServer.class).findFirst().orElseThrow();
httpsServer.setHttpServerProcessor(webApplicationServer);
httpsServer.setServerPort(httpsPort);
httpsServer.setSSL(true);
httpsServer.start();
}
String contextPath = null;
if (warFile != null && warFile.getName().toLowerCase().endsWith(".war")) {
contextPath = warFile.getName().substring(0, warFile.getName().length() - 4);
if (webAppDir == null) {
webAppDir = new File(contextPath);
}
extractWarFile(warFile, webAppDir);
}
if (webAppDir != null && webAppDir.exists()) {
if (contextPath == null) {
contextPath = webAppDir.getName();
}
DefaultWebApplication webApplication = new DefaultWebApplication();
webApplication.addResource(new DirectoryResource(webAppDir));
DefaultWebApplicationClassLoader classLoader = new DefaultWebApplicationClassLoader(webAppDir);
webApplication.setClassLoader(classLoader);
if (Boolean.getBoolean("cloud.piranha.modular.enable") || jpmsEnabled) {
setupLayers(classLoader);
}
if (classLoader.getResource("/META-INF/services/" + WebApplicationExtension.class.getName()) == null) {
DefaultWebApplicationExtensionContext extensionContext = new DefaultWebApplicationExtensionContext();
extensionContext.add(extensionClass);
extensionContext.configure(webApplication);
} else {
DefaultWebApplicationExtensionContext extensionContext = new DefaultWebApplicationExtensionContext();
ServiceLoader<WebApplicationExtension> serviceLoader = ServiceLoader.load(WebApplicationExtension.class, classLoader);
extensionContext.add(serviceLoader.iterator().next());
extensionContext.configure(webApplication);
}
if (contextPath.equalsIgnoreCase("ROOT")) {
contextPath = "";
} else if (!contextPath.startsWith("/")) {
contextPath = "/" + contextPath;
}
webApplication.setContextPath(contextPath);
webApplicationServer.addWebApplication(webApplication);
try {
webApplication.initialize();
} catch (Exception e) {
LOGGER.log(ERROR, "Failed to initialize web application");
System.exit(0);
}
}
if (webAppDir == null && warFile == null) {
LOGGER.log(WARNING, "No web application deployed");
}
webApplicationServer.start();
long finishTime = System.currentTimeMillis();
LOGGER.log(INFO, "Started Piranha");
LOGGER.log(INFO, "It took {0} milliseconds", finishTime - startTime);
if (pid != null) {
File pidFile = new File("tmp", "piranha-micro.pid");
if (!pidFile.getParentFile().exists()) {
if (!pidFile.getParentFile().mkdirs()) {
LOGGER.log(WARNING, "Unable to create tmp directory for PID file");
}
}
try (PrintWriter writer = new PrintWriter(new FileWriter(pidFile))) {
writer.println(pid);
writer.flush();
} catch (IOException ioe) {
LOGGER.log(WARNING, "Unable to write PID file", ioe);
}
}
while (!stop) {
if (pid != null) {
File pidFile = new File("tmp", "piranha-micro.pid");
if (!pidFile.exists()) {
stop();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
use of cloud.piranha.http.api.HttpServer in project piranha by piranhacloud.
the class HttpWebApplicationServerTest method testSessionUrlRewriting.
@Test
void testSessionUrlRewriting() throws Exception {
HttpWebApplicationServer server = new HttpWebApplicationServer();
HttpServer httpServer = new DefaultHttpServer(8181, server, false);
DefaultWebApplication application = new DefaultWebApplication();
application.setContextPath("/context");
application.addServlet("snoop", new TestSnoopServlet());
application.addServletMapping("snoop", "/snoop/*");
server.addWebApplication(application);
server.initialize();
server.start();
httpServer.start();
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:8181/context/snoop/index.html;jsessionid=customsessionid")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(200, response.statusCode());
assertTrue(response.body().contains("customsessionid"));
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
httpServer.stop();
server.stop();
}
use of cloud.piranha.http.api.HttpServer in project piranha by piranhacloud.
the class HttpServerTest method testRequestHTTP10.
/**
* Test if the server supports HTTP/1.0.
*
* @throws Exception when an error occurs.
*/
@Test
void testRequestHTTP10() throws Exception {
int port = findPort();
HttpServer server = createServer(port, HttpServerTest::returnProtocol);
server.start();
try (Socket socket = new Socket("localhost", port);
OutputStream outputStream = socket.getOutputStream()) {
outputStream.write(("GET / HTTP/1.0\r\nHost: localhost:" + port + "\r\n\r\n").getBytes(StandardCharsets.UTF_8));
outputStream.flush();
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream response = new ByteArrayOutputStream();
inputStream.transferTo(response);
assertTrue(response.toString(StandardCharsets.UTF_8).contains("HTTP/1.0"));
}
server.stop();
}
use of cloud.piranha.http.api.HttpServer in project piranha by piranhacloud.
the class HttpServerTest method testFileNotFound.
/**
* Test file not found.
*
* @throws Exception when an error occurs.
*/
@Test
void testFileNotFound() throws Exception {
int port = findPort();
HttpServer server = createServer(port);
server.start();
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create(HTTP_LOCALHOST_PREFIX + port + "/this_is_certainly_not_there")).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
assertEquals(404, response.statusCode());
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
server.stop();
}
}
Aggregations