use of org.eclipse.jetty.util.resource.ResourceCollection in project head by mifos.
the class WorkspaceServerLauncher method createWebAppContext.
@Override
protected WebAppContext createWebAppContext() throws Exception {
final WebContextWithServletContextResourceExtension webAppContext;
webAppContext = new WebContextWithServletContextResourceExtension(null, "/" + getContext());
final ResourceCollection baseResources = baseResources();
if (baseResources != null) {
// This is if a web.xml
webAppContext.setBaseResource(baseResources);
} else {
// This is if there is no web.xml, only META-INF/resources & web-fragment.xml
final File tempFileDir = File.createTempFile("jetty-empty-context", Long.toString(System.nanoTime()));
IO.delete(tempFileDir);
tempFileDir.mkdirs();
tempFileDir.deleteOnExit();
webAppContext.setBaseResource(Resource.newResource(tempFileDir.toURI()));
}
webAppContext.replaceConfiguration(MetaInfConfiguration.class, new MetaInfFolderConfiguration());
webAppContext.replaceConfiguration(FragmentConfiguration.class, new FragmentFolderConfiguration());
webAppContext.replaceConfiguration(WebInfConfiguration.class, new WebInfFolderExtendedConfiguration());
//For JNDI
webAppContext.addConfiguration(new PlusConfiguration());
webAppContext.addConfiguration(new EnvConfiguration());
// This will make EVERYTHING on the classpath be
// scanned for META-INF/resources and web-fragment.xml - great for dev!
// NOTE: Several patterns can be listed, separate by comma
webAppContext.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*");
webAppContext.setAttribute(WebInfConfiguration.WEBINF_JAR_PATTERN, ".*");
// Needed for http://mifosforge.jira.com/browse/MIFOS-4918
File tmp = new File("./targetEclipse/jetty-work");
IO.delete(tmp);
tmp.mkdirs();
webAppContext.setTempDirectory(tmp);
return webAppContext;
}
use of org.eclipse.jetty.util.resource.ResourceCollection in project head by mifos.
the class WorkspaceServerLauncher method baseResources.
private ResourceCollection baseResources() throws IOException, MalformedURLException {
final List<Resource> webResourceModules = new LinkedList<Resource>();
final URL webXml = webXmlUrl();
if (webXml != null) {
webResourceModules.add(Util.chop(webXml, WEB_INF_WEB_XML));
}
if (!webResourceModules.isEmpty()) {
return new ResourceCollection(webResourceModules.toArray(new Resource[webResourceModules.size()]));
} else {
return null;
}
}
use of org.eclipse.jetty.util.resource.ResourceCollection in project nutzboot by nutzam.
the class JettyStarter method init.
public void init() throws Exception {
// 创建基础服务器
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setIdleTimeout(getThreadPoolIdleTimeout());
threadPool.setMinThreads(getMinThreads());
threadPool.setMaxThreads(getMaxThreads());
server = new Server(threadPool);
HttpConfiguration httpConfig = conf.make(HttpConfiguration.class, "jetty.httpConfig.");
HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);
ServerConnector connector = new ServerConnector(server, httpFactory);
connector.setHost(getHost());
connector.setPort(getPort());
connector.setIdleTimeout(getIdleTimeout());
server.setConnectors(new Connector[] { connector });
// 设置应用上下文
wac = new WebAppContext();
wac.setContextPath(getContextPath());
// wac.setExtractWAR(false);
// wac.setCopyWebInf(true);
// wac.setProtectedTargets(new String[]{"/java", "/javax", "/org",
// "/net", "/WEB-INF", "/META-INF"});
wac.setTempDirectory(new File("temp"));
wac.setClassLoader(classLoader);
wac.setConfigurationDiscovered(true);
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
wac.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
}
List<Resource> resources = new ArrayList<>();
for (String resourcePath : Arrays.asList("static/", "webapp/")) {
File f = new File(resourcePath);
if (f.exists()) {
resources.add(Resource.newResource(f));
}
Enumeration<URL> urls = appContext.getClassLoader().getResources(resourcePath);
while (urls.hasMoreElements()) {
resources.add(Resource.newResource(urls.nextElement()));
}
}
if (conf.has(PROP_STATIC_PATH_LOCAL)) {
File f = new File(conf.get(PROP_STATIC_PATH_LOCAL));
if (f.exists()) {
log.debug("found static local path, add it : " + f.getAbsolutePath());
resources.add(Resource.newResource(f));
} else {
log.debug("static local path not exist, skip it : " + f.getPath());
}
}
wac.setBaseResource(new ResourceCollection(resources.toArray(new Resource[resources.size()])) {
@Override
public Resource addPath(String path) throws IOException, MalformedURLException {
// TODO 为啥ResourceCollection读取WEB-INF的时候返回null
// 从而导致org.eclipse.jetty.webapp.WebAppContext.getWebInf()抛NPE
// 先临时hack吧
Resource resource = super.addPath(path);
if (resource == null && "WEB-INF/".equals(path)) {
return Resource.newResource(new File("XXXX"));
}
return resource;
}
});
server.setHandler(wac);
List<String> list = Configuration.ClassList.serverDefault(server);
list.add("org.eclipse.jetty.annotations.AnnotationConfiguration");
wac.setConfigurationClasses(list);
wac.getServletContext().setExtendedListenerTypes(true);
wac.getSessionHandler().setMaxInactiveInterval(conf.getInt(PROP_SESSION_TIMEOUT, 30) * 60);
// 设置一下额外的东西
server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", getMaxFormContentSize());
server.setDumpAfterStart(false);
server.setDumpBeforeStop(false);
server.setStopAtShutdown(true);
addNutzSupport();
ServerContainer sc = WebSocketServerContainerInitializer.configureContext(wac);
for (Class<?> klass : Scans.me().scanPackage(appContext.getPackage())) {
if (klass.getAnnotation(ServerEndpoint.class) != null) {
sc.addEndpoint(klass);
}
}
}
use of org.eclipse.jetty.util.resource.ResourceCollection in project structr by structr.
the class HttpService method initialize.
@Override
public boolean initialize(final StructrServices services) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
final LicenseManager licenseManager = services.getLicenseManager();
final boolean isTest = Services.isTesting();
String sourceJarName = getClass().getProtectionDomain().getCodeSource().getLocation().toString();
if (!isTest && StringUtils.stripEnd(sourceJarName, System.getProperty("file.separator")).endsWith("classes")) {
String jarFile = System.getProperty("jarFile");
if (StringUtils.isEmpty(jarFile)) {
throw new IllegalArgumentException(getClass().getName() + " was started in an environment where the classloader cannot determine the JAR file containing the main class.\n" + "Please specify the path to the JAR file in the parameter -DjarFile.\n" + "Example: -DjarFile=${project.build.directory}/${project.artifactId}-${project.version}.jar");
}
sourceJarName = jarFile;
}
// load configuration from properties file
maxIdleTime = Services.parseInt(System.getProperty("maxIdleTime"), 30000);
requestHeaderSize = Services.parseInt(System.getProperty("requestHeaderSize"), 8192);
if (Settings.Async.getValue()) {
logger.info("Running in asynchronous mode");
}
// other properties
final String keyStorePath = Settings.KeystorePath.getValue();
final String keyStorePassword = Settings.KeystorePassword.getValue();
final String contextPath = System.getProperty("contextPath", "/");
final boolean enableHttps = Settings.HttpsEnabled.getValue();
final boolean enableGzipCompression = Settings.GzipCompression.getValue();
final boolean logRequests = Settings.RequestLogging.getValue();
final String logPrefix = Settings.LogPrefix.getValue();
final String host = Settings.ApplicationHost.getValue();
final int httpsPort = Settings.HttpsPort.getValue();
boolean enableRewriteFilter = true;
// get current base path
String basePath = System.getProperty("home", Settings.getBasePath());
if (StringUtils.isEmpty(basePath)) {
// use cwd and, if that fails, /tmp as a fallback
basePath = System.getProperty("user.dir", "/tmp");
}
// create base directory if it does not exist
final File baseDir = new File(basePath);
if (!baseDir.exists()) {
baseDir.mkdirs();
}
server = new Server(Settings.HttpPort.getValue());
final ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.addHandler(new DefaultHandler());
final ServletContextHandler servletContext = new ServletContextHandler(server, contextPath, true, true);
if (enableGzipCompression) {
gzipHandler = new GzipHandler();
gzipHandler.setIncludedMimeTypes("text/html", "text/plain", "text/css", "text/javascript", "application/json");
gzipHandler.setInflateBufferSize(32768);
gzipHandler.setMinGzipSize(256);
gzipHandler.setCompressionLevel(9);
gzipHandler.setIncludedMethods("GET", "POST", "PUT", "HEAD", "DELETE");
gzipHandler.addIncludedPaths("/*");
gzipHandler.setDispatcherTypes(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC));
}
servletContext.setGzipHandler(gzipHandler);
final List<Connector> connectors = new LinkedList<>();
// create resource collection from base path & source JAR
try {
servletContext.setBaseResource(new ResourceCollection(Resource.newResource(basePath), JarResource.newJarResource(Resource.newResource(sourceJarName))));
} catch (Throwable t) {
logger.warn("Base resource {} not usable: {}", new Object[] { basePath, t.getMessage() });
}
// this is needed for the filters to work on the root context "/"
servletContext.addServlet("org.eclipse.jetty.servlet.DefaultServlet", "/");
servletContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
if (Settings.ConfigServletEnabled.getValue()) {
// configuration wizard entry point
servletContext.addServlet("org.structr.rest.servlet.ConfigServlet", "/structr/config/*");
}
// CMIS setup
if (Settings.CmisEnabled.getValue() && (licenseManager == null || licenseManager.isModuleLicensed("cmis"))) {
try {
servletContext.addEventListener(new CmisRepositoryContextListener());
final ServletHolder cmisAtomHolder = servletContext.addServlet(CmisAtomPubServlet.class.getName(), "/structr/cmis/atom/*");
cmisAtomHolder.setInitParameter("callContextHandler", BasicAuthCallContextHandler.class.getName());
cmisAtomHolder.setInitParameter("cmisVersion", "1.1");
final ServletHolder cmisBrowserHolder = servletContext.addServlet(CmisBrowserBindingServlet.class.getName(), "/structr/cmis/browser/*");
cmisBrowserHolder.setInitParameter("callContextHandler", BasicAuthCallContextHandler.class.getName());
cmisBrowserHolder.setInitParameter("cmisVersion", "1.1");
} catch (Throwable t) {
logger.warn("Cannot initialize CMIS servlet", t);
}
}
sessionCache = new DefaultSessionCache(servletContext.getSessionHandler());
if (licenseManager != null) {
final String hardwareId = licenseManager.getHardwareFingerprint();
DefaultSessionIdManager idManager = new DefaultSessionIdManager(server);
idManager.setWorkerName(hardwareId);
sessionCache.getSessionHandler().setSessionIdManager(idManager);
}
final StructrSessionDataStore sessionDataStore = new StructrSessionDataStore();
// sessionDataStore.setSavePeriodSec(60);
sessionCache.setSessionDataStore(sessionDataStore);
// sessionCache.setSaveOnCreate(true);
sessionCache.setSaveOnInactiveEviction(false);
sessionCache.setRemoveUnloadableSessions(true);
servletContext.getSessionHandler().setSessionCache(sessionCache);
if (enableRewriteFilter) {
final FilterHolder rewriteFilter = new FilterHolder(UrlRewriteFilter.class);
rewriteFilter.setInitParameter("confPath", "urlrewrite.xml");
servletContext.addFilter(rewriteFilter, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC));
}
contexts.addHandler(servletContext);
// enable request logging
if (logRequests) {
final String etcPath = basePath + "/etc";
final File etcDir = new File(etcPath);
if (!etcDir.exists()) {
etcDir.mkdir();
}
final String logbackConfFilePath = basePath + "/etc/logback-access.xml";
final File logbackConfFile = new File(logbackConfFilePath);
if (!logbackConfFile.exists()) {
// synthesize a logback accees log config file
List<String> config = new LinkedList<>();
config.add("<configuration>");
config.add(" <appender name=\"FILE\" class=\"ch.qos.logback.core.rolling.RollingFileAppender\">");
config.add(" <rollingPolicy class=\"ch.qos.logback.core.rolling.TimeBasedRollingPolicy\">");
config.add(" <fileNamePattern>logs/" + logPrefix + "-%d{yyyy_MM_dd}.request.log.zip</fileNamePattern>");
config.add(" </rollingPolicy>");
config.add(" <encoder>");
config.add(" <charset>UTF-8</charset>");
config.add(" <pattern>%h %l %u %t \"%r\" %s %b %n%fullRequest%n%n%fullResponse</pattern>");
config.add(" </encoder>");
config.add(" </appender>");
config.add(" <appender-ref ref=\"FILE\" />");
config.add("</configuration>");
try {
logbackConfFile.createNewFile();
FileUtils.writeLines(logbackConfFile, "UTF-8", config);
} catch (IOException ioex) {
logger.warn("Unable to write logback configuration.", ioex);
}
}
final FilterHolder loggingFilter = new FilterHolder(TeeFilter.class);
servletContext.addFilter(loggingFilter, "/*", EnumSet.of(DispatcherType.REQUEST, Settings.Async.getValue() ? DispatcherType.ASYNC : DispatcherType.FORWARD));
loggingFilter.setInitParameter("includes", "");
final RequestLogHandler requestLogHandler = new RequestLogHandler();
final String logPath = basePath + "/logs";
final File logDir = new File(logPath);
// Create logs directory if not existing
if (!logDir.exists()) {
logDir.mkdir();
}
final RequestLogImpl requestLog = new RequestLogImpl();
requestLog.setName("REQUESTLOG");
requestLog.start();
requestLogHandler.setRequestLog(requestLog);
final HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] { contexts, requestLogHandler });
server.setHandler(handlers);
} else {
server.setHandler(contexts);
}
final List<ContextHandler> resourceHandler = collectResourceHandlers();
for (ContextHandler contextHandler : resourceHandler) {
contexts.addHandler(contextHandler);
}
final Map<String, ServletHolder> servlets = collectServlets(licenseManager);
// add servlet elements
int position = 1;
for (Map.Entry<String, ServletHolder> servlet : servlets.entrySet()) {
final ServletHolder servletHolder = servlet.getValue();
final String path = servlet.getKey();
servletHolder.setInitOrder(position++);
logger.info("Adding servlet {} for {}", new Object[] { servletHolder, path });
servletContext.addServlet(servletHolder, path);
}
contexts.addHandler(servletContext);
if (StringUtils.isNotBlank(host) && Settings.HttpPort.getValue() > -1) {
httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(httpsPort);
// httpConfig.setOutputBufferSize(8192);
httpConfig.setRequestHeaderSize(requestHeaderSize);
final ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
httpConnector.setHost(host);
httpConnector.setPort(Settings.HttpPort.getValue());
connectors.add(httpConnector);
} else {
logger.warn("Unable to configure HTTP server port, please make sure that {} and {} are set correctly in structr.conf.", Settings.ApplicationHost.getKey(), Settings.HttpPort.getKey());
}
if (enableHttps) {
if (httpsPort > -1 && keyStorePath != null && !keyStorePath.isEmpty() && keyStorePassword != null) {
httpsConfig = new HttpConfiguration(httpConfig);
httpsConfig.addCustomizer(new SecureRequestCustomizer());
final SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(keyStorePath);
sslContextFactory.setKeyStorePassword(keyStorePassword);
final ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(httpsConfig));
https.setPort(httpsPort);
https.setIdleTimeout(500000);
https.setHost(host);
https.setPort(httpsPort);
connectors.add(https);
} else {
logger.warn("Unable to configure SSL, please make sure that {}, {} and {} are set correctly in structr.conf.", new Object[] { Settings.HttpsPort.getKey(), Settings.KeystorePath.getKey(), Settings.KeystorePassword.getKey() });
}
}
if (!connectors.isEmpty()) {
server.setConnectors(connectors.toArray(new Connector[0]));
} else {
logger.error("No connectors configured, aborting.");
System.exit(0);
}
server.setStopTimeout(1000);
server.setStopAtShutdown(true);
return true;
}
use of org.eclipse.jetty.util.resource.ResourceCollection in project dropwizard by dropwizard.
the class ServletEnvironmentTest method setsBaseResourceList.
@Test
void setsBaseResourceList(@TempDir Path tempDir) throws Exception {
Resource wooResource = Resource.newResource(Files.createDirectory(tempDir.resolve("dir-1")));
Resource fooResource = Resource.newResource(Files.createDirectory(tempDir.resolve("dir-2")));
final Resource[] testResources = new Resource[] { wooResource, fooResource };
environment.setBaseResource(testResources);
assertThat(handler.getBaseResource()).isExactlyInstanceOf(ResourceCollection.class);
assertThat(((ResourceCollection) handler.getBaseResource()).getResources()).contains(wooResource, fooResource);
}
Aggregations