public final void start(int port) throws Exception { String nodeId = registerForNotifications(); port = setPort(port); System.out.println("DSO SharedQueue (node " + nodeId + ")"); System.out.println( "Open your browser and go to - http://" + getHostName() + ":" + port + "/webapp\n"); Server server = new Server(); Connector connector = new SocketConnector(); connector.setPort(port); server.setConnectors(new Connector[] {connector}); queue = new Queue(port); worker = queue.createWorker(nodeId); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setResourceBase("."); ContextHandler ajaxContext = new ContextHandler(); ajaxContext.setContextPath(SimpleHttpHandler.ACTION); ajaxContext.setResourceBase(cwd.getPath()); ajaxContext.setClassLoader(Thread.currentThread().getContextClassLoader()); ajaxContext.addHandler(new SimpleHttpHandler(queue)); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] {ajaxContext, resourceHandler}); server.setHandler(handlers); startReaper(); server.start(); server.join(); }
private void checkIfContextIsFree(String path) { Handler[] handlers = _contextCollection.getChildHandlersByClass(ContextHandler.class); for (int i = 0; handlers != null && i < handlers.length; i++) { ContextHandler ctx = (ContextHandler) handlers[i]; if (ctx.getContextPath().equals(path)) throw new IllegalArgumentException("another context already bound to path " + path); } }
@Override public void removeContext(String path) throws IllegalArgumentException { Handler handler = null; Handler[] handlers = _contextCollection.getChildHandlersByClass(ContextHandler.class); for (int i = 0; handlers != null && i < handlers.length && handler == null; i++) { ContextHandler ctx = (ContextHandler) handlers[i]; if (ctx.getContextPath().equals(path)) handler = ctx; } if (handler != null) _contextCollection.removeHandler(handler); }
/** @since Jetty 6 */ static ContextHandler getWebApp(String appName) { ContextHandlerCollection server = getConsoleServer(); if (server == null) return null; Handler handlers[] = server.getHandlers(); if (handlers == null) return null; String path = '/' + appName; for (int i = 0; i < handlers.length; i++) { ContextHandler ch = (ContextHandler) handlers[i]; if (path.equals(ch.getContextPath())) return ch; } return null; }
/** * stop it and remove the context * * @throws just about anything, caller would be wise to catch Throwable */ static void stopWebApp(String appName) { ContextHandler wac = getWebApp(appName); if (wac == null) return; try { // not graceful is default in Jetty 6? wac.stop(); } catch (Exception ie) { } ContextHandlerCollection server = getConsoleServer(); if (server == null) return; try { server.removeHandler(wac); server.mapContexts(); } catch (IllegalStateException ise) { } }
/** {@inheritDoc} */ public void configureWebApp() throws Exception { log.debug("Configuring Jetty webapp"); // Get context WebAppContext context = getWebAppContext(); // If app is already started... if (context.isStarted()) { log.debug("Cannot configure webapp after it is started"); return; } // Get WEB_INF directory Resource webInf = context.getWebInf(); if (webInf != null && webInf.isDirectory()) { // Get properties file with virtualHosts and context path Resource config = webInf.addPath("red5-web.properties"); if (config.exists()) { log.debug("Configuring red5-web.properties"); // Load configuration properties Properties props = new Properties(); props.load(config.getInputStream()); // Get context path and virtual hosts String contextPath = props.getProperty("webapp.contextPath"); String virtualHosts = props.getProperty("webapp.virtualHosts"); // Get hostnames String[] hostnames = virtualHosts.split(","); for (int i = 0; i < hostnames.length; i++) { hostnames[i] = hostnames[i].trim(); if (hostnames[i].equals("*")) { // A virtual host "null" must be used so requests for // any host will be served. hostnames = null; break; } } // Set virtual hosts and context path to context context.setVirtualHosts(hostnames); context.setContextPath(contextPath); LoaderBase.setRed5ApplicationContext(contextPath, new JettyApplicationContext(context)); } } else if (webInf == null) { // No WEB-INF directory found, register as default application log.info( "No WEB-INF directory found for " + context.getContextPath() + ", creating default application."); BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance("red5.xml"); BeanFactoryReference bfr = bfl.useBeanFactory("red5.common"); // Create WebScope dynamically WebScope scope = new WebScope(); IServer server = (IServer) bfr.getFactory().getBean(IServer.ID); scope.setServer(server); scope.setGlobalScope(server.getGlobal("default")); // Get default Red5 context from context loader that is JettyLoader in this case ApplicationContext appCtx = JettyLoader.getApplicationContext(); ContextLoader loader = (ContextLoader) appCtx.getBean("context.loader"); appCtx = loader.getContext("default.context"); // Create context for the WebScope and initialize Context scopeContext = new Context(); scopeContext.setContextPath("/"); scopeContext.setClientRegistry((IClientRegistry) appCtx.getBean("global.clientRegistry")); scopeContext.setMappingStrategy((IMappingStrategy) appCtx.getBean("global.mappingStrategy")); scopeContext.setServiceInvoker((IServiceInvoker) appCtx.getBean("global.serviceInvoker")); scopeContext.setScopeResolver((IScopeResolver) appCtx.getBean("red5.scopeResolver")); // The context needs an ApplicationContext so resources can be // resolved GenericWebApplicationContext webCtx = new GenericWebApplicationContext(); webCtx.setDisplayName("Automatic generated WebAppContext"); webCtx.setParent(appCtx); webCtx.setServletContext(ContextHandler.getCurrentContext()); scopeContext.setApplicationContext(webCtx); // Store context in scope scope.setContext(scopeContext); // Use default ApplicationAdapter as handler scope.setHandler(new ApplicationAdapter()); // Make available as "/<directoryName>" and allow access from all // hosts scope.setContextPath(context.getContextPath()); scope.setVirtualHosts("*"); LoaderBase.setRed5ApplicationContext( context.getContextPath(), new JettyApplicationContext(context)); // Register WebScope in server scope.register(); } }
public PicoContextHandler createContext(String contextPath, boolean withSessionHandler) { ContextHandler context = new ContextHandler(); context.setContextPath(contextPath); server.addHandler(context); return new PicoContextHandler(context, server, parentContainer, withSessionHandler); }
/** {@inheritDoc} */ public Object getScriptedObject(ScriptSource scriptSourceLocator, Class[] scriptInterfaces) throws IOException, ScriptCompilationException { // TODO: how to do this when running under Tomcat? ContextHandler handler = WebAppContext.getCurrentWebAppContext(); String basePath = ""; if (handler != null) { File root = handler.getBaseResource().getFile(); if (root != null && root.exists()) { basePath = root.getAbsolutePath() + File.separator + "WEB-INF" + File.separator; } } String strScript = scriptSourceLocator.getScriptAsString(); if (scriptInterfaces.length > 0) { try { PySystemState state = new PySystemState(); if (!"".equals(basePath)) { // Add webapp paths that can contain classes and .jar files to python search path state.path.insert(0, Py.newString(basePath + "classes")); File jarRoot = new File(basePath + "lib"); if (jarRoot.exists()) { for (String filename : jarRoot.list( new FilenameFilter() { public boolean accept(File dir, String name) { return (name.endsWith(".jar")); } })) { state.path.insert(1, Py.newString(basePath + "lib" + File.separator + filename)); } } } PythonInterpreter interp = new PythonInterpreter(null, state); interp.exec(strScript); PyObject getInstance = interp.get("getInstance"); if (!(getInstance instanceof PyFunction)) { throw new ScriptCompilationException("\"getInstance\" is not a function."); } PyObject _this; if (arguments == null) { _this = ((PyFunction) getInstance).__call__(); } else { PyObject[] args = new PyObject[arguments.length]; for (int i = 0; i < arguments.length; i++) { args[i] = new PyJavaInstance(arguments[i]); } _this = ((PyFunction) getInstance).__call__(args); } return _this.__tojava__(scriptInterfaces[0]); } catch (Exception ex) { logger.error("Error while loading script.", ex); if (ex instanceof IOException) { // Raise to caller throw (IOException) ex; } else if (ex instanceof ScriptCompilationException) { // Raise to caller throw (ScriptCompilationException) ex; } throw new ScriptCompilationException(ex.getMessage()); } } logger.error("No scriptInterfaces provided."); return null; }
static boolean isWebAppRunning(String appName) { ContextHandler wac = getWebApp(appName); if (wac == null) return false; return wac.isStarted(); }
@BeforeClass @SuppressWarnings("unchecked") public static void setUpClass() throws Exception { URI webappUri = EmbeddedJettyServer.extractResourceDir("webapp", true); server = new Server(port); ServletHolder jerseyServletHolder = new ServletHolder(ServletContainer.class); jerseyServletHolder.setInitParameter( "com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig"); jerseyServletHolder.setInitParameter( "com.sun.jersey.config.property.packages", "fr.inria.edelweiss.kgramserver.webservice"); Context servletCtx = new Context(server, "/kgram", Context.SESSIONS); servletCtx.addServlet(jerseyServletHolder, "/*"); logger.info("----------------------------------------------"); logger.info("Corese/KGRAM endpoint started on http://localhost:" + port + "/kgram"); logger.info("----------------------------------------------"); ResourceHandler resource_handler = new ResourceHandler(); resource_handler.setWelcomeFiles(new String[] {"index.html"}); resource_handler.setResourceBase(webappUri.getRawPath()); ContextHandler staticContextHandler = new ContextHandler(); staticContextHandler.setContextPath("/"); staticContextHandler.setHandler(resource_handler); logger.info("----------------------------------------------"); logger.info("Corese/KGRAM webapp UI started on http://localhost:" + port); logger.info("----------------------------------------------"); HandlerList handlers_s1 = new HandlerList(); handlers_s1.setHandlers(new Handler[] {staticContextHandler, servletCtx}); server.setHandler(handlers_s1); try { server.start(); } catch (Exception e) { e.printStackTrace(); } ///// Data extraction humanData = File.createTempFile("human", ".rdf"); FileWriter fw = new FileWriter(humanData); InputStream is = RDFS_entailmentsTest.class.getClassLoader().getResourceAsStream("human_2007_09_11.rdf"); int c; while ((c = is.read()) != -1) { fw.write(c); } is.close(); fw.close(); humanOnt = File.createTempFile("humanOnt", ".rdfs"); fw = new FileWriter(humanOnt); is = RDFS_entailmentsTest.class.getClassLoader().getResourceAsStream("human_2007_09_11.rdfs"); while ((c = is.read()) != -1) { fw.write(c); } is.close(); fw.close(); ///// Data upload ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(new URI("http://localhost:" + port + "/kgram")); // entailments MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("entailments", "true"); service.path("sparql").path("reset").post(formData); formData = new MultivaluedMapImpl(); formData.add("remote_path", humanOnt.getAbsolutePath()); service.path("sparql").path("load").post(formData); formData = new MultivaluedMapImpl(); formData.add("remote_path", humanData.getAbsolutePath()); service.path("sparql").path("load").post(formData); }