Пример #1
0
  @Test public void testCustomRoutes() throws Exception {
    WebApp app =
        WebApps.$for("test", TestWebApp.class, this, "ws").start(new WebApp() {
          @Override
          public void setup() {
            bind(MyTestJAXBContextResolver.class);
            bind(MyTestWebService.class);

            route("/:foo", FooController.class);
            route("/bar/foo", FooController.class, "bar");
            route("/foo/:foo", DefaultController.class);
            route("/foo/bar/:foo", DefaultController.class, "index");
          }
        });
    String baseUrl = baseUrl(app);
    try {
      assertEquals("foo", getContent(baseUrl).trim());
      assertEquals("foo", getContent(baseUrl +"test").trim());
      assertEquals("foo1", getContent(baseUrl +"test/1").trim());
      assertEquals("bar", getContent(baseUrl +"test/bar/foo").trim());
      assertEquals("default", getContent(baseUrl +"test/foo/bar").trim());
      assertEquals("default1", getContent(baseUrl +"test/foo/1").trim());
      assertEquals("default2", getContent(baseUrl +"test/foo/bar/2").trim());
      assertEquals(404, getResponseCode(baseUrl +"test/goo"));
      assertEquals(200, getResponseCode(baseUrl +"ws/v1/test"));
      assertTrue(getContent(baseUrl +"ws/v1/test").contains("myInfo"));
    } finally {
      app.stop();
    }
  }
Пример #2
0
 @Test
 public void testApp() {
   ApplicationContext ctx = new ClassPathXmlApplicationContext("configApp.xml");
   WebApp app = (WebApp) ctx.getBean("app");
   assertEquals(654321, app.getAbc());
   assertEquals("Uraka.Lee", app.getXyz());
 }
 private void logWebAppProperties() {
   LOGGER.info(WebApp.SERVER_NAME + " version " + WebApp.getVersion());
   LOGGER.info("Build date " + WebApp.getBuildDate());
   LOGGER.info("Java version " + SystemUtils.JAVA_VERSION);
   LOGGER.info(SystemUtils.JAVA_RUNTIME_NAME + ", version " + SystemUtils.JAVA_RUNTIME_VERSION);
   LOGGER.info(SystemUtils.JAVA_VM_NAME + ", version " + SystemUtils.JAVA_VM_VERSION);
   LOGGER.info(SystemUtils.OS_NAME + ", version " + SystemUtils.OS_VERSION);
 }
Пример #4
0
 @Test public void testCreateWithPort() {
   // see if the ephemeral port is updated
   WebApp app = WebApps.$for(this).at(0).start();
   int port = app.getListenerAddress().getPort();
   assertTrue(port > 0);
   app.stop();
   // try to reuse the port
   app = WebApps.$for(this).at(port).start();
   assertEquals(port, app.getListenerAddress().getPort());
   app.stop();
 }
Пример #5
0
 @Test(expected=org.apache.hadoop.yarn.webapp.WebAppException.class)
 public void testCreateWithNonZeroPort() {
   WebApp app = WebApps.$for(this).at(50000).start();
   int port = app.getListenerAddress().getPort();
   assertEquals(50000, port);
   // start another WebApp with same NonZero port
   WebApp app2 = WebApps.$for(this).at(50000).start();
   // An exception occurs (findPort disabled)
   app.stop();
   app2.stop();
 }
Пример #6
0
 @Test public void testServePathsNoName() {
   WebApp app = WebApps.$for("", this).start();
   assertEquals("/", app.getRedirectPath());
   String[] expectedPaths = { "/*" };
   String[] pathSpecs = app.getServePathSpecs();
    
   assertEquals(1, pathSpecs.length);
   for(int i = 0; i < expectedPaths.length; i++) {
     assertTrue(ArrayUtils.contains(pathSpecs, expectedPaths[i]));
   }
   app.stop();
 }
Пример #7
0
  /**
   * Retuns the implicit object of the specified name, or null if not found.
   *
   * <p>Notice that it does check for the current scope ({@link
   * org.zkoss.zk.ui.ext.Scopes#getCurrent}). Rather, {@link org.zkoss.zk.ui.ext.Scopes#getImplicit}
   * depends on this method.
   *
   * @param page the page. If page is null and comp is not, comp.getPage() is assumed
   * @see org.zkoss.zk.ui.ext.Scopes#getImplicit
   * @since 5.0.0
   */
  public static Object getImplicit(Page page, Component comp, String name) {
    if (comp != null && page == null) page = getCurrentPage(comp);

    if ("log".equals(name)) return _zklog;
    if ("self".equals(name)) return comp != null ? comp : (Object) page;
    if ("spaceOwner".equals(name)) return comp != null ? comp.getSpaceOwner() : (Object) page;
    if ("page".equals(name)) return page;
    if ("desktop".equals(name)) return comp != null ? getDesktop(comp) : page.getDesktop();
    if ("session".equals(name))
      return comp != null ? getSession(comp) : page.getDesktop().getSession();
    if ("application".equals(name))
      return comp != null ? getWebApp(comp) : page.getDesktop().getWebApp();
    if ("componentScope".equals(name))
      return comp != null ? comp.getAttributes() : Collections.EMPTY_MAP;
    if ("spaceScope".equals(name)) {
      final Scope scope = comp != null ? (Scope) comp.getSpaceOwner() : (Scope) page;
      return scope != null ? scope.getAttributes() : Collections.EMPTY_MAP;
    }
    if ("pageScope".equals(name))
      return page != null ? page.getAttributes() : Collections.EMPTY_MAP;
    if ("desktopScope".equals(name)) {
      final Desktop dt = comp != null ? getDesktop(comp) : page.getDesktop();
      return dt != null ? dt.getAttributes() : Collections.EMPTY_MAP;
    }
    if ("sessionScope".equals(name)) {
      final Session sess = comp != null ? getSession(comp) : page.getDesktop().getSession();
      return sess != null ? sess.getAttributes() : Collections.EMPTY_MAP;
    }
    if ("applicationScope".equals(name)) {
      final WebApp app = comp != null ? getWebApp(comp) : page.getDesktop().getWebApp();
      return app != null ? app.getAttributes() : Collections.EMPTY_MAP;
    }
    if ("requestScope".equals(name)) return REQUEST_SCOPE_PROXY;
    if ("execution".equals(name)) return EXECUTION_PROXY;
    if ("arg".equals(name)) {
      final Execution exec = Executions.getCurrent();
      return exec != null ? exec.getArg() : null;
      // bug 2937096: composer.arg shall be statically wired
      // arg is a Map prepared by application developer, so can be wired statically
    }
    if ("param".equals(name)) {
      final Execution exec = Executions.getCurrent();
      return exec != null ? exec.getParameterMap() : null;
      // bug 2945974: composer.param shall be statically wired
      // Note that request parameter is prepared by servlet container, you shall not
      // copy the reference to this map; rather, you shall clone the key-value pair one-by-one.
    }
    // 20090314, Henri Chen: No way to suppport "event" with an event proxy because
    // org.zkoss.zk.Event is not an interface
    return null;
  }
  /**
   * Invokes the next filter in the chain or the final servlet at the end of the chain.
   *
   * @param request the servlet request
   * @param response the servlet response
   * @since Servlet 2.3
   */
  @Override
  public void doFilter(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();

    WebApp webApp = _webApp;

    UserTransactionImpl ut = null;
    if (_isTop) ut = _utm.getUserTransaction();

    try {
      thread.setContextClassLoader(webApp.getClassLoader());

      if (!webApp.enterWebApp() && webApp.getConfigException() == null) {
        if (response instanceof HttpServletResponse) {
          HttpServletResponse res = (HttpServletResponse) response;

          res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }

        return;
      }

      _next.doFilter(request, response);
    } catch (Throwable e) {
      _errorPageManager.sendServletError(e, request, response);
    } finally {
      webApp.exitWebApp();

      // put finish() before access log so the session isn't tied up while
      // logging

      // needed for things like closing the session
      if (request instanceof HttpServletRequestImpl)
        ((HttpServletRequestImpl) request).finishInvocation();

      // server/1ld5
      if (_isTop) {
        ((CauchoResponse) response).close();

        try {
          if (ut != null) ut.abortTransaction();
        } catch (Throwable e) {
          log.log(Level.WARNING, e.toString(), e);
        }
      }

      thread.setContextClassLoader(oldLoader);
    }
  }
Пример #9
0
  /**
   * Outputs the HTML tags of the given component to the given writer.
   *
   * @param path the request path. If null, the servlet path is assumed.
   * @param out the output (never null).
   * @param richlet the richlet to run. If you have only one component to show and no need process
   *     it under an execution, you could use {@link #render(javax.servlet.ServletContext,
   *     javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
   *     org.zkoss.zk.ui.Component, String, java.io.Writer)} instead.
   * @since 5.0.5
   */
  public static final void render(
      ServletContext ctx,
      HttpServletRequest request,
      HttpServletResponse response,
      Richlet richlet,
      String path,
      Writer out)
      throws ServletException, IOException {
    if (path == null) path = Https.getThisServletPath(request);

    WebManager webman = WebManager.getWebManagerIfAny(ctx);
    if (webman == null) {
      final String ATTR = "org.zkoss.zkplus.embed.updateURI";
      String updateURI = Library.getProperty(ATTR);
      if (updateURI == null) updateURI = "/zkau";
      else updateURI = Utils.checkUpdateURI(updateURI, ATTR);
      webman = new WebManager(ctx, updateURI);
    }

    final Session sess = WebManager.getSession(ctx, request);
    final WebApp wapp = sess.getWebApp();
    final WebAppCtrl wappc = (WebAppCtrl) wapp;
    final Object old =
        I18Ns.setup(sess, request, response, wapp.getConfiguration().getResponseCharset());
    Execution exec = null;
    try {
      final Desktop desktop = webman.getDesktop(sess, request, response, path, true);
      if (desktop == null) // forward or redirect
      return;

      final RequestInfo ri =
          new RequestInfoImpl(wapp, sess, desktop, request, PageDefinitions.getLocator(wapp, path));
      sess.setAttribute(Attributes.GAE_FIX, new Integer(0));
      ((SessionCtrl) sess).notifyClientRequest(true);

      final UiFactory uf = wappc.getUiFactory();
      final Page page = WebManager.newPage(uf, ri, richlet, response, path);
      exec = new ExecutionImpl(ctx, request, response, desktop, page);
      exec.setAttribute(Attributes.PAGE_REDRAW_CONTROL, "page");
      exec.setAttribute(Attributes.PAGE_RENDERER, new PageRenderer(exec));

      wappc.getUiEngine().execNewPage(exec, richlet, page, out);
      // no need to set device type here, since UiEngine will do it later
    } finally {
      I18Ns.cleanup(request, old);
      if (exec != null) {
        exec.removeAttribute(Attributes.PAGE_REDRAW_CONTROL);
        exec.removeAttribute(Attributes.PAGE_RENDERER);
      }
    }
  }
Пример #10
0
 @Test public void testDefaultRoutes() throws Exception {
   WebApp app = WebApps.$for("test", this).start();
   String baseUrl = baseUrl(app);
   try {
     assertEquals("foo", getContent(baseUrl +"test/foo").trim());
     assertEquals("foo", getContent(baseUrl +"test/foo/index").trim());
     assertEquals("bar", getContent(baseUrl +"test/foo/bar").trim());
     assertEquals("default", getContent(baseUrl +"test").trim());
     assertEquals("default", getContent(baseUrl +"test/").trim());
     assertEquals("default", getContent(baseUrl).trim());
   } finally {
     app.stop();
   }
 }
  public URLConnection getResource(URL url) throws IOException {
    if (!"jndi".equals(url.getProtocol())) return null;

    // handle jndi:/server (single slash) parsing (gf)
    String file = url.getFile();

    if ("".equals(url.getHost()) && file.startsWith("/server")) {
      file = file.substring(7, file.length());

      if (file.startsWith(getContextPath())) file = file.substring(getContextPath().length());
      else {
        // server/102p
        int p = file.indexOf('/', 1);

        if (p > 0) {
          String contextPath = file.substring(0, p);
          WebApp webApp = (WebApp) getContext(contextPath);

          if (webApp != null) return webApp.getResource(url);
        }
      }
    }

    String realPath = getRealPath(file);
    Path rootDirectory = getRootDirectory();
    Path path = rootDirectory.lookup(realPath);

    if (path.exists()) return new URL(path.getURL()).openConnection();

    int fileIdx;

    URLConnection connection = null;

    if (file.length() > 1 && (fileIdx = file.indexOf("/", 1)) > -1) {
      String context = file.substring(0, file.indexOf("/", 1));

      if (context.equals(getContextPath())) { // disable cross-context lookup

        file = file.substring(fileIdx, file.length());
        realPath = getRealPath(file);
        path = rootDirectory.lookup(realPath);

        if (path.exists()) connection = new URL(path.getURL()).openConnection();
      }
    }

    if (connection != null) return connection;

    return new FileNotFoundURLConnection(url);
  }
 public void contextInitialized(final ServletContextEvent sce) {
   try {
     m_servletContext = sce.getServletContext();
     WebApp.load(m_servletContext);
     final boolean runServerInHpmaMode = runServerInHpmaMode();
     WebApp.setHPMAMode(runServerInHpmaMode);
     logWebAppInfo();
     logDatabaseInfo();
     PasswordMethod.setDefaultMethod(PasswordMethod.DIGEST_A1, PasswordMethod.RETS_REALM);
   } catch (Throwable e) {
     LOGGER.fatal("Caught", e);
     throw new RuntimeException(e);
   }
 }
Пример #13
0
 // This is to test the GuiceFilter should only be applied to webAppContext,
 // not to staticContext  and logContext;
 @Test public void testYARNWebAppContext() throws Exception {
   // setting up the log context
   System.setProperty("hadoop.log.dir", "/Not/Existing/dir");
   WebApp app = WebApps.$for("test", this).start(new WebApp() {
     @Override public void setup() {
       route("/", FooController.class);
     }
   });
   String baseUrl = baseUrl(app);
   try {
     // should not redirect to foo
     assertFalse("foo".equals(getContent(baseUrl +"static").trim()));
     // Not able to access a non-existing dir, should not redirect to foo.
     assertEquals(404, getResponseCode(baseUrl +"logs"));
     // should be able to redirect to foo.
     assertEquals("foo", getContent(baseUrl).trim());
   } finally {
     app.stop();
   }
 }
  /**
   * Creates a new FilterChainFilter.
   *
   * @param next the next filterChain
   * @param filter the user's filter
   */
  public WebAppFilterChain(FilterChain next, WebApp webApp, boolean isTop) {
    _next = next;
    _webApp = webApp;
    _errorPageManager = webApp.getErrorPageManager();
    _isTop = isTop;

    try {
      if (_isTop) {
        _tm = TransactionManagerImpl.getInstance();
        _utm = UserTransactionProxy.getInstance();
      }
    } catch (Throwable e) {
      log.log(Level.WARNING, e.toString(), e);
    }
  }
 private void logRetsConfigInfo() {
   LOGGER.info("GetObject root: " + WebApp.getGetObjectRoot());
   LOGGER.info("GetObject photo pattern: " + WebApp.getPhotoPattern());
 }
Пример #16
0
  /** Creates the invocation. */
  @Override
  public Invocation buildInvocation(Invocation invocation) throws ConfigException {
    if (_configException != null) {
      FilterChain chain = new ExceptionFilterChain(_configException);
      invocation.setFilterChain(chain);
      invocation.setDependency(AlwaysModified.create());

      return invocation;
    } else if (!_lifecycle.waitForActive(_startWaitTime)) {
      log.fine(this + " container is not active");

      int code = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
      FilterChain chain = new ErrorFilterChain(code);
      invocation.setFilterChain(chain);

      invocation.setWebApp(getErrorWebApp());

      invocation.setDependency(AlwaysModified.create());

      return invocation;
    }

    FilterChain chain;

    WebAppController controller = getWebAppController(invocation);

    WebApp webApp = getWebApp(invocation, controller, true);

    boolean isAlwaysModified;

    if (webApp != null) {
      invocation = webApp.buildInvocation(invocation);
      chain = invocation.getFilterChain();
      isAlwaysModified = false;
    } else if (controller != null) {
      int code = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
      chain = new ErrorFilterChain(code);
      ContextFilterChain contextChain = new ContextFilterChain(chain);
      contextChain.setErrorPageManager(getErrorPageManager());
      chain = contextChain;
      invocation.setFilterChain(contextChain);
      isAlwaysModified = true;
    } else {
      int code = HttpServletResponse.SC_NOT_FOUND;
      chain = new ErrorFilterChain(code);
      ContextFilterChain contextChain = new ContextFilterChain(chain);
      contextChain.setErrorPageManager(getErrorPageManager());
      chain = contextChain;
      invocation.setFilterChain(contextChain);
      isAlwaysModified = true;
    }

    if (_rewriteDispatch != null) {
      String uri = invocation.getURI();
      String queryString = invocation.getQueryString();

      FilterChain rewriteChain =
          _rewriteDispatch.map(DispatcherType.REQUEST, uri, queryString, chain);

      if (rewriteChain != chain) {
        // server/13sf, server/1kq1
        WebApp rootWebApp = findWebAppByURI("/");

        if (rootWebApp == null) {
          // server/1u12
          rootWebApp = getErrorWebApp();
        }

        invocation.setWebApp(rootWebApp);

        // server/1k21 vs server/1kk7
        // if (rootWebApp != webApp)
        rewriteChain = rootWebApp.createWebAppFilterChain(rewriteChain, invocation, true);

        invocation.setFilterChain(rewriteChain);
        isAlwaysModified = false;
      }
    }

    if (isAlwaysModified) invocation.setDependency(AlwaysModified.create());

    return invocation;
  }
 @Override
 public String toString() {
   return (getClass().getSimpleName() + "[" + _webApp.getURL() + ", next=" + _next + "]");
 }
Пример #18
0
  /** Creates the invocation. */
  public void buildForwardInvocation(Invocation invocation) throws ServletException {
    WebApp webApp = buildSubInvocation(invocation);

    if (webApp != null) webApp.buildForwardInvocation(invocation);
  }
Пример #19
0
  public static void main(String[] argv) throws IOException {
    InputStream propStream;

    Properties sys = System.getProperties();

    // DSpace version
    System.out.printf("DSpace version:  %s\n", Util.getSourceVersion());

    // SCM revision
    Properties scm = new Properties();
    propStream = Version.class.getResourceAsStream("/scm.properties");
    if (null != propStream) {
      scm.load(propStream);
    }
    System.out.printf("  SCM revision:  %s\n", scm.get("revision"));
    System.out.printf("    SCM branch:  %s\n", scm.get("branch"));

    // OS version
    System.out.printf(
        "            OS:  %s(%s) version %s\n",
        sys.get("os.name"), sys.get("os.arch"), sys.get("os.version"));

    // UIs used
    List<WebApp> apps = UtilServiceFactory.getInstance().getWebAppService().getApps();
    System.out.println("  Applications:");
    for (WebApp app : apps) {
      System.out.printf("                %s at %s\n", app.getAppName(), app.getUrl());
    }

    // Is Discovery available?
    ConfigurationService config = DSpaceServicesFactory.getInstance().getConfigurationService();
    String[] consumers = config.getArrayProperty("event.dispatcher.default.consumers");
    String discoveryStatus = "not enabled.";
    for (String consumer : consumers) {
      if (consumer.equals("discovery")) {
        discoveryStatus = "enabled.";
        break;
      }
    }
    System.out.println("     Discovery:  " + discoveryStatus);

    // Java version
    System.out.printf(
        "           JRE:  %s version %s\n", sys.get("java.vendor"), sys.get("java.version"));

    // ant version
    Properties ant = new Properties();
    propStream = Version.class.getResourceAsStream("/ant.properties");
    if (null != propStream) {
      ant.load(propStream);
    }
    System.out.printf("   Ant version:  %s\n", ant.get("ant.version"));

    // maven version
    Properties maven = new Properties();
    propStream = Version.class.getResourceAsStream("/maven.properties");
    if (null != propStream) {
      maven.load(propStream);
    }
    System.out.printf(" Maven version:  %s\n", maven.get("maven.version"));

    // DSpace directory path
    System.out.printf("   DSpace home:  %s\n", config.getProperty("dspace.dir"));
  }
Пример #20
0
  /** Creates the invocation. */
  public void buildLoginInvocation(Invocation invocation) throws ServletException {
    WebApp app = buildSubInvocation(invocation);

    if (app != null) app.buildErrorInvocation(invocation);
  }
Пример #21
0
 static String baseUrl(WebApp app) {
   return "http://localhost:"+ app.port() +"/";
 }
Пример #22
0
  /** Creates the invocation for a rewrite-dispatch/dispatch. */
  public void buildDispatchInvocation(Invocation invocation) throws ServletException {
    WebApp app = buildSubInvocation(invocation);

    if (app != null) app.buildDispatchInvocation(invocation);
  }
 public void contextDestroyed(final ServletContextEvent sce) {
   WebApp.getNonceReaper().stop();
   m_servletContext = null;
 }
Пример #24
0
 @Test public void testCreate() {
   WebApp app = WebApps.$for(this).start();
   app.stop();
 }