Search in sources :

Example 6 with DefaultSessionIdManager

use of org.eclipse.jetty.server.session.DefaultSessionIdManager in project jena by apache.

the class ExFusekiMain_2_AddShiro method addShiroFilter.

// From Barry Nouwt : https://lists.apache.org/thread.html/r1e3fa952ff9f4a9108e16f07f1edf78c67e08c9b081497c627e3b833%40%3Cusers.jena.apache.org%3E
public static void addShiroFilter(FusekiServer fusekiServer) {
    Server jettyServer = fusekiServer.getJettyServer();
    ServletContextHandler servletContextHandler = (ServletContextHandler) jettyServer.getHandler();
    ServletHandler servletHandler = servletContextHandler.getServletHandler();
    // for shiro
    EnvironmentLoaderListener ell = new EnvironmentLoaderListener();
    servletContextHandler.addEventListener(ell);
    // Copies
    List<FilterMapping> mappings = new ArrayList<FilterMapping>(Arrays.asList(servletHandler.getFilterMappings()));
    List<FilterHolder> holders = new ArrayList<FilterHolder>(Arrays.asList(servletHandler.getFilters()));
    {
        // add Shiro Filter and mapping
        FilterHolder holder1 = new FilterHolder();
        holder1.setFilter(new ShiroFilter());
        FilterMapping mapping1 = new FilterMapping();
        mapping1.setFilterName(holder1.getName());
        mapping1.setPathSpec("/*");
        mapping1.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
        mappings.add(0, mapping1);
        holders.add(0, holder1);
    }
    FilterMapping[] mappings3 = new FilterMapping[mappings.size()];
    mappings3 = mappings.toArray(mappings3);
    FilterHolder[] holders3 = new FilterHolder[holders.size()];
    holders3 = holders.toArray(holders3);
    servletHandler.setFilters(holders3);
    servletHandler.setFilterMappings(mappings3);
    // Specify the Session ID Manager
    SessionIdManager idmanager = new DefaultSessionIdManager(jettyServer);
    jettyServer.setSessionIdManager(idmanager);
    // Specify the session handler
    SessionHandler sessionsHandler = new SessionHandler();
    sessionsHandler.setUsingCookies(false);
    servletHandler.setHandler(sessionsHandler);
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) ServletHandler(org.eclipse.jetty.servlet.ServletHandler) EnvironmentLoaderListener(org.apache.shiro.web.env.EnvironmentLoaderListener) DefaultSessionIdManager(org.eclipse.jetty.server.session.DefaultSessionIdManager) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) FusekiServer(org.apache.jena.fuseki.main.FusekiServer) Server(org.eclipse.jetty.server.Server) ArrayList(java.util.ArrayList) FilterMapping(org.eclipse.jetty.servlet.FilterMapping) SessionIdManager(org.eclipse.jetty.server.SessionIdManager) DefaultSessionIdManager(org.eclipse.jetty.server.session.DefaultSessionIdManager) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ShiroFilter(org.apache.shiro.web.servlet.ShiroFilter)

Example 7 with DefaultSessionIdManager

use of org.eclipse.jetty.server.session.DefaultSessionIdManager in project jphp by jphp-compiler.

the class PHttpServer method initSessionManager.

private void initSessionManager() {
    idmanager = new DefaultSessionIdManager(server);
    server.setSessionIdManager(idmanager);
    SessionHandler sessions = new SessionHandler();
    sessions.setSessionIdManager(idmanager);
    filters.addHandler(sessions);
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) DefaultSessionIdManager(org.eclipse.jetty.server.session.DefaultSessionIdManager)

Example 8 with DefaultSessionIdManager

use of org.eclipse.jetty.server.session.DefaultSessionIdManager in project NMEAParser by tvesalainen.

the class CommandLine method start.

private void start() throws IOException, InterruptedException, JAXBException, Exception {
    config("starting NMEA Server");
    Path configfile = getArgument("configuration file");
    Config config = new Config(configfile);
    String address = config.getNmeaMulticastAddress();
    int nmeaPort = config.getNmeaMulticastPort();
    int httpPort = config.getHttpPort();
    config("NMEA Multicast Address=%s", address);
    config("NMEA Multicast Port=%s", nmeaPort);
    config("HTTP Port=%s", httpPort);
    CachedScheduledThreadPool executor = new CachedScheduledThreadPool(64);
    config("ThreadPool started %s", executor);
    NMEAService nmeaService = new NMEAService(address, nmeaPort, executor);
    PropertyServer propertyServer = new PropertyServer(Clock.systemDefaultZone(), config, executor);
    nmeaService.addNMEAObserver(propertyServer);
    nmeaService.start();
    config("NMEA Service started");
    JavaUtilLog log = new JavaUtilLog();
    // make jetty use java.util.logger
    Log.setLog(log);
    Server server = new Server(httpPort);
    HandlerList handlers = new HandlerList();
    ServletContextHandler context = new ServletContextHandler();
    context.addServlet(ResourceServlet.class, "/");
    ServletHolder holder = new ServletHolder(SseServlet.class);
    holder.setAsyncSupported(true);
    context.addServlet(holder, "/sse");
    context.addServlet(ResourceServlet.class, "*.js");
    context.addServlet(ResourceServlet.class, "*.css");
    context.addServlet(ResourceServlet.class, "*.gif");
    context.addServlet(ResourceServlet.class, "*.png");
    context.addServlet(ResourceServlet.class, "*.ico");
    context.addServlet(PrefsServlet.class, "/prefs");
    context.addServlet(I18nServlet.class, "/i18n");
    SessionHandler sessionHandler = new SessionHandler();
    context.setSessionHandler(sessionHandler);
    handlers.addHandler(context);
    server.setHandler(handlers);
    server.setSessionIdManager(new DefaultSessionIdManager(server));
    ServletContext servletContext = context.getServletContext().getContext("/sse");
    servletContext.setAttribute(PropertyServer.class.getName(), propertyServer);
    server.start();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
Also used : Path(java.nio.file.Path) HandlerList(org.eclipse.jetty.server.handler.HandlerList) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) DefaultSessionIdManager(org.eclipse.jetty.server.session.DefaultSessionIdManager) Server(org.eclipse.jetty.server.Server) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) CachedScheduledThreadPool(org.vesalainen.util.concurrent.CachedScheduledThreadPool) JavaUtilLog(org.eclipse.jetty.util.log.JavaUtilLog) ServletContext(javax.servlet.ServletContext) NMEAService(org.vesalainen.parsers.nmea.NMEAService) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 9 with DefaultSessionIdManager

use of org.eclipse.jetty.server.session.DefaultSessionIdManager 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;
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) DefaultSessionCache(org.eclipse.jetty.server.session.DefaultSessionCache) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) Server(org.eclipse.jetty.server.Server) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) CmisRepositoryContextListener(org.apache.chemistry.opencmis.server.impl.CmisRepositoryContextListener) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) BasicAuthCallContextHandler(org.apache.chemistry.opencmis.server.shared.BasicAuthCallContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) CmisBrowserBindingServlet(org.apache.chemistry.opencmis.server.impl.browser.CmisBrowserBindingServlet) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) DefaultSessionIdManager(org.eclipse.jetty.server.session.DefaultSessionIdManager) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) RequestLogImpl(ch.qos.logback.access.jetty.RequestLogImpl) LicenseManager(org.structr.api.service.LicenseManager) CmisAtomPubServlet(org.apache.chemistry.opencmis.server.impl.atompub.CmisAtomPubServlet) IOException(java.io.IOException) LinkedList(java.util.LinkedList) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) BasicAuthCallContextHandler(org.apache.chemistry.opencmis.server.shared.BasicAuthCallContextHandler) GzipHandler(org.eclipse.jetty.server.handler.gzip.GzipHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) File(java.io.File) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ResourceCollection(org.eclipse.jetty.util.resource.ResourceCollection)

Aggregations

DefaultSessionIdManager (org.eclipse.jetty.server.session.DefaultSessionIdManager)9 Server (org.eclipse.jetty.server.Server)5 SessionHandler (org.eclipse.jetty.server.session.SessionHandler)5 DefaultSessionCache (org.eclipse.jetty.server.session.DefaultSessionCache)4 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HashLoginService (org.eclipse.jetty.security.HashLoginService)2 ServerConnector (org.eclipse.jetty.server.ServerConnector)2 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)2 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)2 RequestLogImpl (ch.qos.logback.access.jetty.RequestLogImpl)1 File (java.io.File)1 IOException (java.io.IOException)1 Path (java.nio.file.Path)1 SecureRandom (java.security.SecureRandom)1 ArrayList (java.util.ArrayList)1 LinkedHashMap (java.util.LinkedHashMap)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1