Java Code Examples for org.eclipse.jetty.util.resource.Resource#newResource()

The following examples show how to use org.eclipse.jetty.util.resource.Resource#newResource() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KsqlRestApplication.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 6 votes vote down vote up
@Override
public ResourceCollection getStaticResources() {
  log.info("User interface enabled: {}", isUiEnabled);
  if (isUiEnabled) {
    try {
      return new ResourceCollection(
          Resource.newResource(new File(this.uiFolder, EXPANDED_FOLDER).getCanonicalFile()));
    } catch (Exception e) {
      log.error("Unable to load ui from {}. You can disable the ui by setting {} to false",
          this.uiFolder + EXPANDED_FOLDER,
          KsqlRestConfig.UI_ENABLED_CONFIG,
          e);
    }
  }

  return super.getStaticResources();
}
 
Example 2
Source File: IndexServlet.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig servletConfig) throws ServletException {
  this.servletConfig = servletConfig;

  //templateCfg.setClassForTemplateLoading(getClass(), "/");
  Resource baseResource;
  try {
    baseResource = Resource.newResource(servletConfig.getInitParameter("resourceBase"));
  } catch (IOException e) {
    throw new ServletException(e);
  }
  templateCfg.setTemplateLoader(new ResourceTemplateLoader(baseResource));
  templateCfg.setDefaultEncoding("UTF-8");

  // Sets how errors will appear.
  // During web page *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER
  // is better.
  // cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  templateCfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
}
 
Example 3
Source File: Launcher.java    From electron-java-app with Apache License 2.0 6 votes vote down vote up
private static Resource findWebRoot() throws MalformedURLException {
    // don't look up directory as a resource, it's unreliable: https://github.com/eclipse/jetty.project/issues/4173#issuecomment-539769734
    // instead we'll look up the /webapp/ROOT and retrieve the parent folder from that.
    var f = Launcher.class.getResource("/webapp/ROOT");
    if (f == null) {
        throw new IllegalStateException("Invalid state: the resource /webapp/ROOT doesn't exist, has webapp been packaged in as a resource?");
    }
    var url = f.toString();
    if (!url.endsWith("/ROOT")) {
        throw new RuntimeException("Parameter url: invalid value " + url + ": doesn't end with /ROOT");
    }
    System.err.println("/webapp/ROOT is " + f);

    // Resolve file to directory
    var webRoot = new URL(url.substring(0, url.length() - 5));
    System.err.println("WebRoot is " + webRoot);
    return Resource.newResource(webRoot);
}
 
Example 4
Source File: Loader.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
/**
 * Generate the classpath (as a string) of all classloaders
 * above the given classloader.
 * 
 * This is primarily used for jasper.
 * @return the system class path
 */
public static String getClassPath(ClassLoader loader) throws Exception
{
    StringBuilder classpath=new StringBuilder();
    while (loader != null && (loader instanceof URLClassLoader))
    {
        URL[] urls = ((URLClassLoader)loader).getURLs();
        if (urls != null)
        {     
            for (int i=0;i<urls.length;i++)
            {
                Resource resource = Resource.newResource(urls[i]);
                File file=resource.getFile();
                if (file!=null && file.exists())
                {
                    if (classpath.length()>0)
                        classpath.append(File.pathSeparatorChar);
                    classpath.append(file.getAbsolutePath());
                }
            }
        }
        loader = loader.getParent();
    }
    return classpath.toString();
}
 
Example 5
Source File: Loader.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
/**
 * Generate the classpath (as a string) of all classloaders
 * above the given classloader.
 * 
 * This is primarily used for jasper.
 * @return the system class path
 */
public static String getClassPath(ClassLoader loader) throws Exception
{
    StringBuilder classpath=new StringBuilder();
    while (loader != null && (loader instanceof URLClassLoader))
    {
        URL[] urls = ((URLClassLoader)loader).getURLs();
        if (urls != null)
        {     
            for (int i=0;i<urls.length;i++)
            {
                Resource resource = Resource.newResource(urls[i]);
                File file=resource.getFile();
                if (file!=null && file.exists())
                {
                    if (classpath.length()>0)
                        classpath.append(File.pathSeparatorChar);
                    classpath.append(file.getAbsolutePath());
                }
            }
        }
        loader = loader.getParent();
    }
    return classpath.toString();
}
 
Example 6
Source File: Util.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Resource chop(final URL baseURL, final String toChop)
		throws MalformedURLException, IOException {
	String base = baseURL.toExternalForm();
	if (!base.endsWith(toChop)) {
		throw new IllegalArgumentException(base + " does not endWith "
				+ toChop);
	}
	base = base.substring(0, base.length() - toChop.length());

	if (base.startsWith("jar:file:") && base.endsWith("!")) {
		// If it was a jar:file:/.../.jar!/META-INF/web-fragment.xml, then
		// 'jar:' & '!' has to go as well:
		base = base.substring(0, base.length() - 1);
		base = "file:" + base.substring("jar:file:".length());
	}
	return Resource.newResource(base);
}
 
Example 7
Source File: VmRuntimeWebAppContext.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart() throws Exception {
  // unpack and Adjust paths.
  Resource base = getBaseResource();
  if (base == null) {
    base = Resource.newResource(getWar());
  }
  Resource dir;
  if (base.isDirectory()) {
    dir = base;
  } else {
    throw new IllegalArgumentException();
  }
  Resource qswebxml = dir.addPath("/WEB-INF/quickstart-web.xml");
  if (qswebxml.exists()) {
    setConfigurationClasses(quickstartConfigurationClasses);
  }
  super.doStart();
}
 
Example 8
Source File: JettyServer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private ContextHandler createDocsWebApp(final String contextPath) {
    try {
        final ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(false);

        // load the docs directory
        final File docsDir = Paths.get("docs").toRealPath().toFile();
        final Resource docsResource = Resource.newResource(docsDir);

        // load the component documentation working directory
        final String componentDocsDirPath = props.getProperty(NiFiProperties.COMPONENT_DOCS_DIRECTORY, "work/docs/components");
        final File workingDocsDirectory = Paths.get(componentDocsDirPath).toRealPath().getParent().toFile();
        final Resource workingDocsResource = Resource.newResource(workingDocsDirectory);

        // load the rest documentation
        final File webApiDocsDir = new File(webApiContext.getTempDirectory(), "webapp/docs");
        if (!webApiDocsDir.exists()) {
            final boolean made = webApiDocsDir.mkdirs();
            if (!made) {
                throw new RuntimeException(webApiDocsDir.getAbsolutePath() + " could not be created");
            }
        }
        final Resource webApiDocsResource = Resource.newResource(webApiDocsDir);

        // create resources for both docs locations
        final ResourceCollection resources = new ResourceCollection(docsResource, workingDocsResource, webApiDocsResource);
        resourceHandler.setBaseResource(resources);

        // create the context handler
        final ContextHandler handler = new ContextHandler(contextPath);
        handler.setHandler(resourceHandler);

        logger.info("Loading documents web app with context path set to " + contextPath);
        return handler;
    } catch (Exception ex) {
        throw new IllegalStateException("Resource directory paths are malformed: " + ex.getMessage());
    }
}
 
Example 9
Source File: AssetServlet.java    From onedev with MIT License 5 votes vote down vote up
@Override
public final Resource getResource(String pathInContext) {
	ServletContextHandler.Context context = (ServletContextHandler.Context) getServletContext();
	ServletContextHandler contextHandler = (ServletContextHandler) context.getContextHandler();
	
	for (ServletMapping mapping: contextHandler.getServletHandler().getServletMappings()) {
		if (mapping.getServletName().equals(getServletName())) {
			for (String pathSpec: mapping.getPathSpecs()) {
				String relativePath = null;
				if (pathSpec.endsWith("/*")) {
					pathSpec = StringUtils.substringBeforeLast(pathSpec, "/*");
					if (pathInContext.startsWith(pathSpec + "/")) 
						relativePath = pathInContext.substring(pathSpec.length());
				} else if (pathSpec.startsWith("*.")) {
					pathSpec = StringUtils.stripStart(pathSpec, "*");
					if (pathInContext.endsWith(pathSpec))
						relativePath = pathInContext;
				} else if (pathSpec.equals(pathInContext)) {
					relativePath = pathInContext;
				}
				if (relativePath != null) {
					relativePath = StringUtils.stripStart(relativePath, "/");
					Resource resource = Resource.newResource(loadResource(relativePath));
					if (resource != null && resource.exists())
						return resource;
				}
			}
		}
	}
	
	return null;
}
 
Example 10
Source File: VmRuntimeWebAppDeployer.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
@Override
protected void doStart() throws Exception {
  
  Resource resource = Resource.newResource(webapp);
  File file = resource.getFile();
  if (!resource.exists())
      throw new IllegalStateException("WebApp resouce does not exist "+resource);

  String lcName=file.getName().toLowerCase(Locale.ENGLISH);

  if (lcName.endsWith(".xml")) {
      XmlConfiguration xmlc = new XmlConfiguration(resource.getURI().toURL());
      xmlc.getIdMap().put("Server", contexts.getServer());
      xmlc.getProperties().put("jetty.home",System.getProperty("jetty.home","."));
      xmlc.getProperties().put("jetty.base",System.getProperty("jetty.base","."));
      xmlc.getProperties().put("jetty.webapp",file.getCanonicalPath());
      xmlc.getProperties().put("jetty.webapps",file.getParentFile().getCanonicalPath());
      xmlc.getProperties().putAll(properties);
      handler = (ContextHandler)xmlc.configure();
  } else {
    WebAppContext wac=new WebAppContext();
    wac.setWar(webapp);
    wac.setContextPath("/");
  }
  
  contexts.addHandler(handler);
  if (contexts.isRunning())
    handler.start();
}
 
Example 11
Source File: JettyEmptyPathApplicationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public EmbeddedJettyServer() {
    super("/",
        new Resource[] {
            // Limit the classpath scanning to org.apache.demo.resources package
            Resource.newClassPathResource("/org/apache/demo/resources"),
            // Include JAX-RS application from org.apache.applications.empty package
            Resource.newClassPathResource("/org/apache/demo/applications/emptypath"),
            // Include Jackson @Providers into classpath scanning
            Resource.newResource(JacksonJsonProvider.class.getProtectionDomain().getCodeSource().getLocation())
        }, PORT);
}
 
Example 12
Source File: JettyNoApplicationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public EmbeddedJettyServer() {
    super("/",
        new Resource[] {
            // Limit the classpath scanning to org.apache.demo.resources package
            Resource.newClassPathResource("/org/apache/demo/resources"),
            // Include Jackson @Providers into classpath scanning
            Resource.newResource(JacksonJsonProvider.class.getProtectionDomain().getCodeSource().getLocation())
        }, PORT);
}
 
Example 13
Source File: JettyEmptyApplicationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public EmbeddedJettyServer() {
    super("/",
        new Resource[] {
            // Limit the classpath scanning to org.apache.demo.resources package
            Resource.newClassPathResource("/org/apache/demo/resources"),
            // Include JAX-RS application from org.apache.applications.empty package
            Resource.newClassPathResource("/org/apache/demo/applications/empty"),
            // Include Jackson @Providers into classpath scanning
            Resource.newResource(JacksonJsonProvider.class.getProtectionDomain().getCodeSource().getLocation())
        }, PORT);
}
 
Example 14
Source File: Jetty9Server.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void performCustomConfiguration() throws Exception {
    File jettyConfig = systemEnvironment.getJettyConfigFile();
    if (jettyConfig.exists()) {
        replaceJettyXmlIfItBelongsToADifferentVersion(jettyConfig);
        LOG.info("Configuring Jetty using {}", jettyConfig.getAbsolutePath());
        XmlConfiguration configuration = new XmlConfiguration(Resource.newResource(jettyConfig));
        configuration.configure(server);
    } else {
        String message = String.format(
                "No custom jetty configuration (%s) found, using defaults.",
                jettyConfig.getAbsolutePath());
        LOG.info(message);
    }
}