@Override
  public void configure(WebAppContext context) throws Exception {
    if (!context.isConfigurationDiscovered()) return;

    // order the fragments
    context.getMetaData().orderFragments();
  }
  @Override
  public void preConfigure(WebAppContext context) throws Exception {
    if (!context.isConfigurationDiscovered()) return;

    // find all web-fragment.xmls
    findWebFragments(context, context.getMetaData());
  }
 public File findWorkDirectory(WebAppContext context) throws IOException {
   if (context.getBaseResource() != null) {
     Resource web_inf = context.getWebInf();
     if (web_inf != null && web_inf.exists()) {
       return new File(web_inf.getFile(), "work");
     }
   }
   return null;
 }
 /**
  * @see
  *     org.eclipse.jetty.webapp.AbstractConfiguration#cloneConfigure(org.eclipse.jetty.webapp.WebAppContext,
  *     org.eclipse.jetty.webapp.WebAppContext)
  */
 @Override
 public void cloneConfigure(WebAppContext template, WebAppContext context) throws Exception {
   File tmpDir =
       File.createTempFile(
           WebInfConfiguration.getCanonicalNameForWebAppTmpDir(context),
           "",
           template.getTempDirectory().getParentFile());
   if (tmpDir.exists()) {
     IO.delete(tmpDir);
   }
   tmpDir.mkdir();
   tmpDir.deleteOnExit();
   context.setTempDirectory(tmpDir);
 }
  /**
   * Look for jars in WEB-INF/lib
   *
   * @param context
   * @return the list of jar resources found within context
   * @throws Exception
   */
  protected List<Resource> findJars(WebAppContext context) throws Exception {
    List<Resource> jarResources = new ArrayList<Resource>();

    Resource web_inf = context.getWebInf();
    if (web_inf == null || !web_inf.exists()) return null;

    Resource web_inf_lib = web_inf.addPath("/lib");

    if (web_inf_lib.exists() && web_inf_lib.isDirectory()) {
      String[] files = web_inf_lib.list();
      for (int f = 0; files != null && f < files.length; f++) {
        try {
          Resource file = web_inf_lib.addPath(files[f]);
          String fnlc = file.getName().toLowerCase(Locale.ENGLISH);
          int dot = fnlc.lastIndexOf('.');
          String extension = (dot < 0 ? null : fnlc.substring(dot));
          if (extension != null && (extension.equals(".jar") || extension.equals(".zip"))) {
            jarResources.add(file);
          }
        } catch (Exception ex) {
          LOG.warn(Log.EXCEPTION, ex);
        }
      }
    }
    return jarResources;
  }
  public void makeTempDirectory(File parent, WebAppContext context, boolean deleteExisting)
      throws IOException {
    if (parent != null && parent.exists() && parent.canWrite() && parent.isDirectory()) {
      String temp = getCanonicalNameForWebAppTmpDir(context);
      File tmpDir = new File(parent, temp);

      if (deleteExisting && tmpDir.exists()) {
        if (!IO.delete(tmpDir)) {
          if (LOG.isDebugEnabled()) LOG.debug("Failed to delete temp dir " + tmpDir);
        }

        // If we can't delete the existing tmp dir, create a new one
        if (tmpDir.exists()) {
          String old = tmpDir.toString();
          tmpDir = File.createTempFile(temp + "_", "");
          if (tmpDir.exists()) IO.delete(tmpDir);
          LOG.warn("Can't reuse " + old + ", using " + tmpDir);
        }
      }

      if (!tmpDir.exists()) tmpDir.mkdir();

      // If the parent is not a work directory
      if (!isTempWorkDirectory(tmpDir)) {
        tmpDir.deleteOnExit();
      }

      if (LOG.isDebugEnabled()) LOG.debug("Set temp dir " + tmpDir);
      context.setTempDirectory(tmpDir);
    }
  }
 private static JaggeryContext createJaggeryContext(
     OutputStream out,
     String scriptPath,
     HttpServletRequest request,
     HttpServletResponse response) {
   WebAppContext context = new WebAppContext();
   context.setTenantId(Integer.toString(CarbonContext.getCurrentContext().getTenantId()));
   context.setOutputStream(out);
   context.setServletRequest(request);
   context.setServletResponse(response);
   context.setServletConext(request.getServletContext());
   context.setScriptPath(scriptPath);
   context.getIncludesCallstack().push(scriptPath);
   context.getIncludedScripts().put(scriptPath, true);
   return context;
 }
  private static void defineProperties(Context cx, JaggeryContext context, ScriptableObject scope) {
    WebAppContext ctx = (WebAppContext) context;

    JavaScriptProperty request = new JavaScriptProperty("request");
    request.setValue(cx.newObject(scope, "Request", new Object[] {ctx.getServletRequest()}));
    request.setAttribute(ScriptableObject.READONLY);
    RhinoEngine.defineProperty(scope, request);

    JavaScriptProperty response = new JavaScriptProperty("response");
    response.setValue(cx.newObject(scope, "Response", new Object[] {ctx.getServletResponse()}));
    response.setAttribute(ScriptableObject.READONLY);
    RhinoEngine.defineProperty(scope, response);

    JavaScriptProperty session = new JavaScriptProperty("session");
    session.setValue(
        cx.newObject(scope, "Session", new Object[] {ctx.getServletRequest().getSession()}));
    session.setAttribute(ScriptableObject.READONLY);
    RhinoEngine.defineProperty(scope, session);

    JavaScriptProperty application = new JavaScriptProperty("application");
    application.setValue(cx.newObject(scope, "Application", new Object[] {ctx.getServletConext()}));
    application.setAttribute(ScriptableObject.READONLY);
    RhinoEngine.defineProperty(scope, application);

    if (isWebSocket(ctx.getServletRequest())) {
      JavaScriptProperty websocket = new JavaScriptProperty("websocket");
      websocket.setValue(cx.newObject(scope, "WebSocket", new Object[0]));
      websocket.setAttribute(ScriptableObject.READONLY);
      RhinoEngine.defineProperty(scope, websocket);
    }
  }
  public void doStart() throws Exception {
    setConfigurations(configs);

    // Initialize map containing all jars in /WEB-INF/lib
    webInfJarMap.clear();
    for (File file : webInfJars) {
      // Return all jar files from class path
      String fileName = file.getName();
      if (fileName.endsWith(".jar")) webInfJarMap.put(fileName, file);
    }

    if (this.jettyEnvXml != null) envConfig.setJettyEnvXml(new File(this.jettyEnvXml).toURL());
    setShutdown(false);
    super.doStart();
  }
  @Override
  public void deconfigure(WebAppContext context) throws Exception {
    // delete temp directory if we had to create it or if it isn't called work
    Boolean tmpdirConfigured = (Boolean) context.getAttribute(TEMPDIR_CONFIGURED);

    if (context.getTempDirectory() != null
        && (tmpdirConfigured == null || !tmpdirConfigured.booleanValue())
        && !isTempWorkDirectory(context.getTempDirectory())) {
      IO.delete(context.getTempDirectory());
      context.setTempDirectory(null);

      // clear out the context attributes for the tmp dir only if we had to
      // create the tmp dir
      context.setAttribute(TEMPDIR_CONFIGURED, null);
      context.setAttribute(WebAppContext.TEMPDIR, null);
    }

    // reset the base resource back to what it was before we did any unpacking of resources
    context.setBaseResource(_preUnpackBaseResource);
  }
 /**
  * Look for any web-fragment.xml fragments in META-INF of jars in WEB-INF/lib
  *
  * @throws Exception
  */
 public void findWebFragments(final WebAppContext context, final MetaData metaData)
     throws Exception {
   @SuppressWarnings("unchecked")
   List<Resource> frags = (List<Resource>) context.getAttribute(FRAGMENT_RESOURCES);
   if (frags != null) {
     for (Resource frag : frags) {
       if (frag
           .isDirectory()) // tolerate the case where the library is a directory, not a jar. useful
                           // for OSGi for example
       {
         metaData.addFragment(
             frag, Resource.newResource(frag.getURL() + "/META-INF/web-fragment.xml"));
       } else // the standard case: a jar most likely inside WEB-INF/lib
       {
         metaData.addFragment(
             frag, Resource.newResource("jar:" + frag.getURL() + "!/META-INF/web-fragment.xml"));
       }
     }
   }
 }
  @Override
  public void configure(WebAppContext context) throws Exception {
    // cannot configure if the context is already started
    if (context.isStarted()) {
      if (LOG.isDebugEnabled())
        LOG.debug("Cannot configure webapp " + context + " after it is started");
      return;
    }

    Resource web_inf = context.getWebInf();

    // Add WEB-INF classes and lib classpaths
    if (web_inf != null
        && web_inf.isDirectory()
        && context.getClassLoader() instanceof WebAppClassLoader) {
      // Look for classes directory
      Resource classes = web_inf.addPath("classes/");
      if (classes.exists()) ((WebAppClassLoader) context.getClassLoader()).addClassPath(classes);

      // Look for jars
      Resource lib = web_inf.addPath("lib/");
      if (lib.exists() || lib.isDirectory())
        ((WebAppClassLoader) context.getClassLoader()).addJars(lib);
    }

    // Look for extra resource
    @SuppressWarnings("unchecked")
    List<Resource> resources = (List<Resource>) context.getAttribute(RESOURCE_URLS);
    if (resources != null) {
      Resource[] collection = new Resource[resources.size() + 1];
      int i = 0;
      collection[i++] = context.getBaseResource();
      for (Resource resource : resources) collection[i++] = resource;
      context.setBaseResource(new ResourceCollection(collection));
    }
  }
  @Override
  public void preConfigure(final WebAppContext context) throws Exception {
    // Look for a work directory
    File work = findWorkDirectory(context);
    if (work != null) makeTempDirectory(work, context, false);

    // Make a temp directory for the webapp if one is not already set
    resolveTempDirectory(context);

    // Extract webapp if necessary
    unpack(context);

    // Apply an initial ordering to the jars which governs which will be scanned for META-INF
    // info and annotations. The ordering is based on inclusion patterns.
    String tmp = (String) context.getAttribute(WEBINF_JAR_PATTERN);
    Pattern webInfPattern = (tmp == null ? null : Pattern.compile(tmp));
    tmp = (String) context.getAttribute(CONTAINER_JAR_PATTERN);
    Pattern containerPattern = (tmp == null ? null : Pattern.compile(tmp));

    // Apply ordering to container jars - if no pattern is specified, we won't
    // match any of the container jars
    PatternMatcher containerJarNameMatcher =
        new PatternMatcher() {
          public void matched(URI uri) throws Exception {
            context.getMetaData().addContainerJar(Resource.newResource(uri));
          }
        };
    ClassLoader loader = context.getClassLoader();
    while (loader != null && (loader instanceof URLClassLoader)) {
      URL[] urls = ((URLClassLoader) loader).getURLs();
      if (urls != null) {
        URI[] containerUris = new URI[urls.length];
        int i = 0;
        for (URL u : urls) {
          try {
            containerUris[i] = u.toURI();
          } catch (URISyntaxException e) {
            containerUris[i] = new URI(u.toString().replaceAll(" ", "%20"));
          }
          i++;
        }
        containerJarNameMatcher.match(containerPattern, containerUris, false);
      }
      loader = loader.getParent();
    }

    // Apply ordering to WEB-INF/lib jars
    PatternMatcher webInfJarNameMatcher =
        new PatternMatcher() {
          @Override
          public void matched(URI uri) throws Exception {
            context.getMetaData().addWebInfJar(Resource.newResource(uri));
          }
        };
    List<Resource> jars = findJars(context);

    // Convert to uris for matching
    URI[] uris = null;
    if (jars != null) {
      uris = new URI[jars.size()];
      int i = 0;
      for (Resource r : jars) {
        uris[i++] = r.getURI();
      }
    }
    webInfJarNameMatcher.match(
        webInfPattern, uris, true); // null is inclusive, no pattern == all jars match
  }
  /**
   * Create a canonical name for a webapp temp directory. The form of the name is: <code>
   * "Jetty_"+host+"_"+port+"__"+resourceBase+"_"+context+"_"+virtualhost+base36_hashcode_of_whole_string
   * </code> host and port uniquely identify the server context and virtual host uniquely identify
   * the webapp
   *
   * @return the canonical name for the webapp temp directory
   */
  public static String getCanonicalNameForWebAppTmpDir(WebAppContext context) {
    StringBuffer canonicalName = new StringBuffer();
    canonicalName.append("jetty-");

    // get the host and the port from the first connector
    Server server = context.getServer();
    if (server != null) {
      Connector[] connectors = context.getServer().getConnectors();

      if (connectors.length > 0) {
        // Get the host
        String host = (connectors == null || connectors[0] == null ? "" : connectors[0].getHost());
        if (host == null) host = "0.0.0.0";
        canonicalName.append(host);

        // Get the port
        canonicalName.append("-");
        // try getting the real port being listened on
        int port = (connectors == null || connectors[0] == null ? 0 : connectors[0].getLocalPort());
        // if not available (eg no connectors or connector not started),
        // try getting one that was configured.
        if (port < 0) port = connectors[0].getPort();
        canonicalName.append(port);
        canonicalName.append("-");
      }
    }

    // Resource  base
    try {
      Resource resource = context.getBaseResource();
      if (resource == null) {
        if (context.getWar() == null || context.getWar().length() == 0)
          resource = context.newResource(context.getResourceBase());

        // Set dir or WAR
        resource = context.newResource(context.getWar());
      }

      String tmp = URIUtil.decodePath(resource.getURL().getPath());
      if (tmp.endsWith("/")) tmp = tmp.substring(0, tmp.length() - 1);
      if (tmp.endsWith("!")) tmp = tmp.substring(0, tmp.length() - 1);
      // get just the last part which is the filename
      int i = tmp.lastIndexOf("/");
      canonicalName.append(tmp.substring(i + 1, tmp.length()));
      canonicalName.append("-");
    } catch (Exception e) {
      LOG.warn("Can't generate resourceBase as part of webapp tmp dir name", e);
    }

    // Context name
    String contextPath = context.getContextPath();
    contextPath = contextPath.replace('/', '_');
    contextPath = contextPath.replace('\\', '_');
    canonicalName.append(contextPath);

    // Virtual host (if there is one)
    canonicalName.append("-");
    String[] vhosts = context.getVirtualHosts();
    if (vhosts == null || vhosts.length <= 0) canonicalName.append("any");
    else canonicalName.append(vhosts[0]);

    // sanitize
    for (int i = 0; i < canonicalName.length(); i++) {
      char c = canonicalName.charAt(i);
      if (!Character.isJavaIdentifierPart(c) && "-.".indexOf(c) < 0)
        canonicalName.setCharAt(i, '.');
    }

    canonicalName.append("-");
    return canonicalName.toString();
  }
  public void unpack(WebAppContext context) throws IOException {
    Resource web_app = context.getBaseResource();
    _preUnpackBaseResource = context.getBaseResource();

    if (web_app == null) {
      String war = context.getWar();
      if (war != null && war.length() > 0) web_app = context.newResource(war);
      else web_app = context.getBaseResource();

      // Accept aliases for WAR files
      if (web_app.getAlias() != null) {
        LOG.debug(web_app + " anti-aliased to " + web_app.getAlias());
        web_app = context.newResource(web_app.getAlias());
      }

      if (LOG.isDebugEnabled())
        LOG.debug(
            "Try webapp="
                + web_app
                + ", exists="
                + web_app.exists()
                + ", directory="
                + web_app.isDirectory()
                + " file="
                + (web_app.getFile()));
      // Is the WAR usable directly?
      if (web_app.exists() && !web_app.isDirectory() && !web_app.toString().startsWith("jar:")) {
        // No - then lets see if it can be turned into a jar URL.
        Resource jarWebApp = JarResource.newJarResource(web_app);
        if (jarWebApp.exists() && jarWebApp.isDirectory()) web_app = jarWebApp;
      }

      // If we should extract or the URL is still not usable
      if (web_app.exists()
          && ((context.isCopyWebDir()
                  && web_app.getFile() != null
                  && web_app.getFile().isDirectory())
              || (context.isExtractWAR()
                  && web_app.getFile() != null
                  && !web_app.getFile().isDirectory())
              || (context.isExtractWAR() && web_app.getFile() == null)
              || !web_app.isDirectory())) {
        // Look for sibling directory.
        File extractedWebAppDir = null;

        if (war != null) {
          // look for a sibling like "foo/" to a "foo.war"
          File warfile = Resource.newResource(war).getFile();
          if (warfile != null && warfile.getName().toLowerCase(Locale.ENGLISH).endsWith(".war")) {
            File sibling =
                new File(
                    warfile.getParent(),
                    warfile.getName().substring(0, warfile.getName().length() - 4));
            if (sibling.exists() && sibling.isDirectory() && sibling.canWrite())
              extractedWebAppDir = sibling;
          }
        }

        if (extractedWebAppDir == null)
          // Then extract it if necessary to the temporary location
          extractedWebAppDir = new File(context.getTempDirectory(), "webapp");

        if (web_app.getFile() != null && web_app.getFile().isDirectory()) {
          // Copy directory
          LOG.info("Copy " + web_app + " to " + extractedWebAppDir);
          web_app.copyTo(extractedWebAppDir);
        } else {
          // Use a sentinel file that will exist only whilst the extraction is taking place.
          // This will help us detect interrupted extractions.
          File extractionLock = new File(context.getTempDirectory(), ".extract_lock");

          if (!extractedWebAppDir.exists()) {
            // it hasn't been extracted before so extract it
            extractionLock.createNewFile();
            extractedWebAppDir.mkdir();
            LOG.info("Extract " + web_app + " to " + extractedWebAppDir);
            Resource jar_web_app = JarResource.newJarResource(web_app);
            jar_web_app.copyTo(extractedWebAppDir);
            extractionLock.delete();
          } else {
            // only extract if the war file is newer, or a .extract_lock file is left behind meaning
            // a possible partial extraction
            if (web_app.lastModified() > extractedWebAppDir.lastModified()
                || extractionLock.exists()) {
              extractionLock.createNewFile();
              IO.delete(extractedWebAppDir);
              extractedWebAppDir.mkdir();
              LOG.info("Extract " + web_app + " to " + extractedWebAppDir);
              Resource jar_web_app = JarResource.newJarResource(web_app);
              jar_web_app.copyTo(extractedWebAppDir);
              extractionLock.delete();
            }
          }
        }
        web_app = Resource.newResource(extractedWebAppDir.getCanonicalPath());
      }

      // Now do we have something usable?
      if (!web_app.exists() || !web_app.isDirectory()) {
        LOG.warn("Web application not found " + war);
        throw new java.io.FileNotFoundException(war);
      }

      context.setBaseResource(web_app);

      if (LOG.isDebugEnabled()) LOG.debug("webapp=" + web_app);
    }

    // Do we need to extract WEB-INF/lib?
    if (context.isCopyWebInf() && !context.isCopyWebDir()) {
      Resource web_inf = web_app.addPath("WEB-INF/");

      File extractedWebInfDir = new File(context.getTempDirectory(), "webinf");
      if (extractedWebInfDir.exists()) IO.delete(extractedWebInfDir);
      extractedWebInfDir.mkdir();
      Resource web_inf_lib = web_inf.addPath("lib/");
      File webInfDir = new File(extractedWebInfDir, "WEB-INF");
      webInfDir.mkdir();

      if (web_inf_lib.exists()) {
        File webInfLibDir = new File(webInfDir, "lib");
        if (webInfLibDir.exists()) IO.delete(webInfLibDir);
        webInfLibDir.mkdir();

        LOG.info("Copying WEB-INF/lib " + web_inf_lib + " to " + webInfLibDir);
        web_inf_lib.copyTo(webInfLibDir);
      }

      Resource web_inf_classes = web_inf.addPath("classes/");
      if (web_inf_classes.exists()) {
        File webInfClassesDir = new File(webInfDir, "classes");
        if (webInfClassesDir.exists()) IO.delete(webInfClassesDir);
        webInfClassesDir.mkdir();
        LOG.info(
            "Copying WEB-INF/classes from "
                + web_inf_classes
                + " to "
                + webInfClassesDir.getAbsolutePath());
        web_inf_classes.copyTo(webInfClassesDir);
      }

      web_inf = Resource.newResource(extractedWebInfDir.getCanonicalPath());

      ResourceCollection rc = new ResourceCollection(web_inf, web_app);

      if (LOG.isDebugEnabled()) LOG.debug("context.resourcebase = " + rc);

      context.setBaseResource(rc);
    }
  }
  @Override
  public void doHandle(
      String target,
      Request request,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse)
      throws IOException, ServletException {

    LOG.info("handling " + target);

    // !!! doHandle() is called twice for a request when using redirectiion, first time with
    // request.getPathInfo()
    // set to the URI and target set to the path, then with request.getPathInfo() set to null and
    // target set to the .jsp
    try {
      // request.setHandled(true);
      boolean secured;
      if (request.getScheme().equals("https")) {
        secured = true;
      } else if (request.getScheme().equals("http")) {
        secured = false;
      } else {
        httpServletResponse
            .getWriter()
            .println(
                String.format(
                    "<h1>Unknown scheme %s at %s</h1>",
                    request.getScheme(), request.getUri().getDecodedPath()));
        return;
      }

      if (request.getMethod().equals("GET")) {
        if (isInJar || target.endsWith(".jsp")) {
          // !!! when not in jar there's no need to do anything about params if it's not a .jsp,
          // as this will get called again for the corresponding .jsp
          if (prepareForJspGet(target, request, httpServletResponse, secured)) {
            return;
          }
        }
        if (target.startsWith(PATH_OPEN_ARTICLE)) {
          handleOpenArticle(request, httpServletResponse, target);
          return;
        }
        super.doHandle(target, request, httpServletRequest, httpServletResponse);
        LOG.info("handling of " + target + " went to super");

        // httpServletResponse.setDateHeader("Date", System.currentTimeMillis());     //ttt2 review
        // these, probably not use
        // httpServletResponse.setDateHeader("Expires", System.currentTimeMillis() + 60000);

        return;
      }

      if (request.getMethod().equals("POST")) {
        if (request.getUri().getDecodedPath().equals(PATH_LOGIN)) {
          handleLoginPost(request, httpServletResponse, secured);
        } else if (request.getUri().getDecodedPath().equals(PATH_SIGNUP)) {
          handleSignupPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_CHANGE_PASSWORD)) {
          handleChangePasswordPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_UPDATE_FEED_LIST)) {
          handleUpdateFeedListPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_ADD_FEED)) {
          handleAddFeedPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_REMOVE_FEED)) {
          handleRemoveFeedPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_CHANGE_SETTINGS)) {
          handleChangeSettingsPost(request, httpServletResponse);
        }
      }

      /*{ // for tests only;
          httpServletResponse.getWriter().println(String.format("<h1>Unable to process request %s</h1>",
                  request.getUri().getDecodedPath()));
          request.setHandled(true);
      }*/
    } catch (Exception e) {
      LOG.error("Error processing request", e);
      try {
        // redirectToError(e.toString(), request, httpServletResponse); //!!! redirectToError leads
        // to infinite loop, probably related to
        // the fact that we get 2 calls for a regular request when redirecting
        httpServletResponse
            .getWriter()
            .println(
                String.format(
                    "<h1>Unable to process request %s</h1>", // ttt1 generate some HTML
                    request.getUri().getDecodedPath()));
        request.setHandled(true);
      } catch (Exception e1) {
        LOG.error("Error redirecting", e1);
      }
    }
  }
Exemple #17
0
    public static void main(String[] args) throws Exception {
        int timeout = (int) Duration.ONE_HOUR.getMilliseconds();

        Server server = new Server();
        SocketConnector connector = new SocketConnector();

        // Set some timeout options to make debugging easier.
        connector.setMaxIdleTime(timeout);
        connector.setSoLingerTime(-1);
        connector.setPort(8080);
        server.addConnector(connector);

        Resource keystore = Resource.newClassPathResource("/keystore");
        if (keystore != null && keystore.exists()) {
            // if a keystore for a SSL certificate is available, start a SSL
            // connector on port 8443.
            // By default, the quickstart comes with a Apache Wicket Quickstart
            // Certificate that expires about half way september 2021. Do not
            // use this certificate anywhere important as the passwords are
            // available in the source.

            connector.setConfidentialPort(8443);

            SslContextFactory factory = new SslContextFactory();
            factory.setKeyStoreResource(keystore);
            factory.setKeyStorePassword("wicket");
            factory.setTrustStoreResource(keystore);
            factory.setKeyManagerPassword("wicket");
            SslSocketConnector sslConnector = new SslSocketConnector(factory);
            sslConnector.setMaxIdleTime(timeout);
            sslConnector.setPort(8443);
            sslConnector.setAcceptors(4);
            server.addConnector(sslConnector);

            System.out.println("SSL access to the quickstart has been enabled on port 8443");
            System.out.println("You can access the application using SSL on https://localhost:8443");
            System.out.println();
        }

        WebAppContext bb = new WebAppContext();
        bb.setServer(server);
        bb.setContextPath("/");
        bb.setWar("src/main/webapp");

        // START JMX SERVER
        // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        // MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
        // server.getContainer().addEventListener(mBeanContainer);
        // mBeanContainer.start();

        server.setHandler(bb);

        try {
            System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
            server.start();
            System.in.read();
            System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
            server.stop();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
 public void doStop() throws Exception {
   setShutdown(true);
   // just wait a little while to ensure no requests are still being processed
   Thread.currentThread().sleep(500L);
   super.doStop();
 }
Exemple #19
0
  /** Resolve all servlet/filter/listener metadata from all sources: descriptors and annotations. */
  public void resolve(WebAppContext context) throws Exception {
    LOG.debug("metadata resolve {}", context);

    // Ensure origins is fresh
    _origins.clear();

    // Set the ordered lib attribute
    if (_ordering != null) {
      List<String> orderedLibs = new ArrayList<String>();
      for (Resource webInfJar : _orderedWebInfJars) {
        // get just the name of the jar file
        String fullname = webInfJar.getName();
        int i = fullname.indexOf(".jar");
        int j = fullname.lastIndexOf("/", i);
        orderedLibs.add(fullname.substring(j + 1, i + 4));
      }
      context.setAttribute(ServletContext.ORDERED_LIBS, orderedLibs);
    }

    // set the webxml version
    if (_webXmlRoot != null) {
      context.getServletContext().setEffectiveMajorVersion(_webXmlRoot.getMajorVersion());
      context.getServletContext().setEffectiveMinorVersion(_webXmlRoot.getMinorVersion());
    }

    for (DescriptorProcessor p : _descriptorProcessors) {
      p.process(context, getWebDefault());
      p.process(context, getWebXml());
      for (WebDescriptor wd : getOverrideWebs()) {
        LOG.debug("process {} {}", context, wd);
        p.process(context, wd);
      }
    }

    // get an apply the annotations that are not associated with a fragment (and hence for
    // which no ordering applies
    List<DiscoveredAnnotation> nonFragAnnotations = _annotations.get(NON_FRAG_RESOURCE);
    if (nonFragAnnotations != null) {
      for (DiscoveredAnnotation a : nonFragAnnotations) {
        LOG.debug("apply {}", a);
        a.apply();
      }
    }

    // apply the annotations that are associated with a fragment, according to the
    // established ordering
    List<Resource> resources = getOrderedWebInfJars();
    for (Resource r : resources) {
      FragmentDescriptor fd = _webFragmentResourceMap.get(r);
      if (fd != null) {
        for (DescriptorProcessor p : _descriptorProcessors) {
          LOG.debug("process {} {}", context, fd);
          p.process(context, fd);
        }
      }

      List<DiscoveredAnnotation> fragAnnotations = _annotations.get(r);
      if (fragAnnotations != null) {
        for (DiscoveredAnnotation a : fragAnnotations) {
          LOG.debug("apply {}", a);
          a.apply();
        }
      }
    }
  }
 @Override
 public void postConfigure(WebAppContext context) throws Exception {
   context.setAttribute(FRAGMENT_RESOURCES, null);
 }
  /**
   * Get a temporary directory in which to unpack the war etc etc. The algorithm for determining
   * this is to check these alternatives in the order shown:
   *
   * <p>A. Try to use an explicit directory specifically for this webapp:
   *
   * <ol>
   *   <li>Iff an explicit directory is set for this webapp, use it. Do NOT set delete on exit.
   *   <li>Iff javax.servlet.context.tempdir context attribute is set for this webapp && exists &&
   *       writeable, then use it. Do NOT set delete on exit.
   * </ol>
   *
   * <p>B. Create a directory based on global settings. The new directory will be called
   * "Jetty_"+host+"_"+port+"__"+context+"_"+virtualhost Work out where to create this directory:
   *
   * <ol>
   *   <li>Iff $(jetty.home)/work exists create the directory there. Do NOT set delete on exit. Do
   *       NOT delete contents if dir already exists.
   *   <li>Iff WEB-INF/work exists create the directory there. Do NOT set delete on exit. Do NOT
   *       delete contents if dir already exists.
   *   <li>Else create dir in $(java.io.tmpdir). Set delete on exit. Delete contents if dir already
   *       exists.
   * </ol>
   */
  public void resolveTempDirectory(WebAppContext context) {
    // If a tmp directory is already set, we're done
    File tmpDir = context.getTempDirectory();
    if (tmpDir != null && tmpDir.isDirectory() && tmpDir.canWrite()) {
      context.setAttribute(TEMPDIR_CONFIGURED, Boolean.TRUE);
      return; // Already have a suitable tmp dir configured
    }

    // No temp directory configured, try to establish one.
    // First we check the context specific, javax.servlet specified, temp directory attribute
    File servletTmpDir = asFile(context.getAttribute(WebAppContext.TEMPDIR));
    if (servletTmpDir != null && servletTmpDir.isDirectory() && servletTmpDir.canWrite()) {
      // Use as tmpDir
      tmpDir = servletTmpDir;
      // Ensure Attribute has File object
      context.setAttribute(WebAppContext.TEMPDIR, tmpDir);
      // Set as TempDir in context.
      context.setTempDirectory(tmpDir);
      return;
    }

    try {
      // Put the tmp dir in the work directory if we had one
      File work = new File(System.getProperty("jetty.home"), "work");
      if (work.exists() && work.canWrite() && work.isDirectory()) {
        makeTempDirectory(
            work, context, false); // make a tmp dir inside work, don't delete if it exists
      } else {
        File baseTemp = asFile(context.getAttribute(WebAppContext.BASETEMPDIR));
        if (baseTemp != null && baseTemp.isDirectory() && baseTemp.canWrite()) {
          // Use baseTemp directory (allow the funky Jetty_0_0_0_0.. subdirectory logic to kick in
          makeTempDirectory(baseTemp, context, false);
        } else {
          makeTempDirectory(
              new File(System.getProperty("java.io.tmpdir")),
              context,
              true); // make a tmpdir, delete if it already exists
        }
      }
    } catch (Exception e) {
      tmpDir = null;
      LOG.ignore(e);
    }

    // Third ... Something went wrong trying to make the tmp directory, just make
    // a jvm managed tmp directory
    if (context.getTempDirectory() == null) {
      try {
        // Last resort
        tmpDir = File.createTempFile("JettyContext", "");
        if (tmpDir.exists()) IO.delete(tmpDir);
        tmpDir.mkdir();
        tmpDir.deleteOnExit();
        context.setTempDirectory(tmpDir);
      } catch (IOException e) {
        tmpDir = null;
        throw new IllegalStateException(
            "Cannot create tmp dir in "
                + System.getProperty("java.io.tmpdir")
                + " for context "
                + context,
            e);
      }
    }
  }
Exemple #22
0
  private void run() throws Exception {
    InetSocketAddress address;

    if (this.host != null) {
      address = new InetSocketAddress(this.host, this.port);
    } else {
      address = new InetSocketAddress(this.port);
    }

    Server server = new Server(address);

    ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ModelRegistry modelRegistry = new ModelRegistry();

    final MetricRegistry metricRegistry = new MetricRegistry();

    Binder binder =
        new AbstractBinder() {

          @Override
          protected void configure() {
            bind(modelRegistry).to(ModelRegistry.class);
            bind(metricRegistry).to(MetricRegistry.class);
          }
        };

    ResourceConfig config = new ResourceConfig(ModelResource.class);
    config.register(binder);
    config.register(JacksonFeature.class);
    config.register(MultiPartFeature.class);
    config.register(ObjectMapperProvider.class);
    config.register(RolesAllowedDynamicFeature.class);

    // Naive implementation that grants the "admin" role to all local network users
    config.register(NetworkSecurityContextFilter.class);

    ServletContextHandler servletHandler = new ServletContextHandler();
    servletHandler.setContextPath(this.contextPath);

    ServletContainer jerseyServlet = new ServletContainer(config);

    servletHandler.addServlet(new ServletHolder(jerseyServlet), "/*");

    InstrumentedHandler instrumentedHandler = new InstrumentedHandler(metricRegistry);
    instrumentedHandler.setHandler(servletHandler);

    handlerCollection.addHandler(instrumentedHandler);

    if (this.consoleWar != null) {
      WebAppContext consoleHandler = new WebAppContext();
      consoleHandler.setContextPath(this.contextPath + "/console"); // XXX
      consoleHandler.setWar(this.consoleWar.getAbsolutePath());

      handlerCollection.addHandler(consoleHandler);
    }

    server.setHandler(handlerCollection);

    DirectoryDeployer deployer = null;

    if (this.modelDir != null) {

      if (!this.modelDir.isDirectory()) {
        throw new IOException(this.modelDir.getAbsolutePath() + " is not a directory");
      }

      deployer = new DirectoryDeployer(modelRegistry, this.modelDir.toPath());
    }

    server.start();

    if (deployer != null) {
      deployer.start();
    }

    server.join();

    if (deployer != null) {
      deployer.interrupt();

      deployer.join();
    }
  }
Exemple #23
0
  private static ScriptableObject executeScript(
      JaggeryContext jaggeryContext,
      ScriptableObject scope,
      String fileURL,
      final boolean isJSON,
      boolean isBuilt,
      boolean isIncludeOnce)
      throws ScriptException {
    WebAppContext webAppContext = (WebAppContext) jaggeryContext;
    Stack<String> includesCallstack = jaggeryContext.getIncludesCallstack();
    Map<String, Boolean> includedScripts = jaggeryContext.getIncludedScripts();
    ServletContext context = webAppContext.getServletConext();
    String parent = includesCallstack.lastElement();

    String keys[] = WebAppManager.getKeys(context.getContextPath(), parent, fileURL);
    fileURL = getNormalizedScriptPath(keys);
    if (includesCallstack.search(fileURL) != -1) {
      return scope;
    }
    if (isIncludeOnce && includedScripts.get(fileURL) != null) {
      return scope;
    }

    ScriptReader source;
    RhinoEngine engine = jaggeryContext.getEngine();
    if (isBuilt) {
      source =
          new ScriptReader(context.getResourceAsStream(fileURL)) {
            @Override
            protected void build() throws IOException {
              try {
                if (isJSON) {
                  sourceReader =
                      new StringReader("(" + HostObjectUtil.streamToString(sourceIn) + ")");
                } else {
                  sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                }
              } catch (ScriptException e) {
                throw new IOException(e);
              }
            }
          };
    } else {
      source = new ScriptReader(context.getResourceAsStream(fileURL));
    }

    ScriptCachingContext sctx =
        new ScriptCachingContext(webAppContext.getTenantId(), keys[0], keys[1], keys[2]);
    sctx.setSecurityDomain(new JaggerySecurityDomain(fileURL, context));
    long lastModified = WebAppManager.getScriptLastModified(context, fileURL);
    sctx.setSourceModifiedTime(lastModified);

    includedScripts.put(fileURL, true);
    includesCallstack.push(fileURL);
    if (isJSON) {
      scope = (ScriptableObject) engine.eval(source, scope, sctx);
    } else {
      engine.exec(source, scope, sctx);
    }
    includesCallstack.pop();
    return scope;
  }