org.eclipse.jetty.util.resource.Resource Java Examples

The following examples show how to use org.eclipse.jetty.util.resource.Resource. 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: AbstractSpringServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {
    server = new org.eclipse.jetty.server.Server(port);

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath(contextPath);
    webappcontext.setBaseResource(Resource.newClassPathResource(resourcePath));

    server.setHandler(new HandlerCollection(webappcontext, new DefaultHandler()));

    try {
        configureServer(server);
        server.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #2
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 #3
Source File: AbstractJettyServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {
    server = new Server(port);

    try {
        final WebAppContext context = new WebAppContext();
        context.setContextPath(contextPath);

        context.setConfigurations(new Configuration[] {
            new WebXmlConfiguration(),
            new AnnotationConfiguration()
        });

        for (final Resource resource: resources) {
            context.getMetaData().addContainerResource(resource);
        }

        configureContext(context);
        server.setHandler(context);

        configureServer(server);
        server.start();
    } catch (final Exception ex) {
        ex.printStackTrace();
        fail(ex.getMessage());
    }
}
 
Example #4
Source File: ApplicationGroupTest.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testStaticResourceIsolation() throws Exception {
  TestApp app1 = new TestApp("/app1");
  TestApp app2 = new TestApp("/app2") {
    @Override
    public void setupResources(final Configurable<?> config, final TestRestConfig appConfig) {
      config.register(RestResource.class);
      config.property(ServletProperties.FILTER_STATIC_CONTENT_REGEX, "/(index\\.html|)");
    }

    @Override
    protected ResourceCollection getStaticResources() {
      return new ResourceCollection(Resource.newClassPathResource("static"));
    }
  };

  server.registerApplication(app1);
  server.registerApplication(app2);
  server.start();

  assertThat(makeGetRequest("/app1/index.html"), is(Code.NOT_FOUND));
  assertThat(makeGetRequest("/app2/index.html"), is(Code.OK));
}
 
Example #5
Source File: ApiWebSite.java    From dapeng-soa with Apache License 2.0 6 votes vote down vote up
public static Server createServer(int port) throws MalformedURLException, URISyntaxException {
    Server server = new Server();
    server.setStopAtShutdown(true);

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    connector.setReuseAddress(true);

    server.setConnectors(new Connector[]{connector});

    WebAppContext webContext = new WebAppContext("webapp", CONTEXT);
    webContext.setBaseResource(Resource.newResource(new URL(ApiWebSite.class.getResource("/webapp/WEB-INF"), ".")));
    webContext.setClassLoader(ApiWebSite.class.getClassLoader());

    server.setHandler(webContext);

    return server;
}
 
Example #6
Source File: FileHandler.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public Resource getResource(String path) {
    try {
        Resource resource = super.getResource(path);
        if (resource == null) return null;
        if (!(resource instanceof PathResource) || !resource.exists()) return resource;
        File f = resource.getFile();
        if (f.isDirectory() && !path.equals("/")) return resource;
        CacheResource cache = resourceCache.get(f);
        if (cache != null) return cache;
        if (f.length() < CACHE_LIMIT || f.getName().endsWith(".html") || path.equals("/")) {
            cache = new CacheResource((PathResource) resource);
            resourceCache.put(f, cache);
            return cache;
        }
        return resource;
    } catch (IOException e) {
        Data.logger.warn("", e);
    }
    return null;
}
 
Example #7
Source File: DigestServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {
    server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/digestauth");
    webappcontext.setBaseResource(Resource.newClassPathResource("/digestauth"));

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});

    server.setHandler(handlers);

    try {
        configureServer();
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: AegisServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {
    //System.out.println("Starting Server");

    server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/");
    webappcontext.setBaseResource(Resource.newClassPathResource("/webapp"));

    server.setHandler(new HandlerCollection(webappcontext, new DefaultHandler()));
    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example #9
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 #10
Source File: JettyAutoConfiguration.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
@Bean
public WebServerFactoryCustomizer<JettyServletWebServerFactory> jsfJettyFactoryCustomizer() {
	return factory -> factory.addServerCustomizers(new JettyServerCustomizer() {
		@Override
		@SneakyThrows(IOException.class)
		public void customize(Server server) {
			Handler[] childHandlersByClass = server.getChildHandlersByClass(WebAppContext.class);
			final WebAppContext webAppContext = (WebAppContext) childHandlersByClass[0];

			String classPathResourceString = JettyAutoConfiguration.this.jettyProperties.getClassPathResource();

			webAppContext.setBaseResource(new ResourceCollection(
				Resource.newResource(new ClassPathResource(classPathResourceString).getURI()),
				webAppContext.getBaseResource()));

			log.info("Setting Jetty classLoader to {} directory", classPathResourceString);
		}
	});
}
 
Example #11
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 #12
Source File: JettyServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
static WebAppContext newWebAppContext() throws MalformedURLException {
    final WebAppContext handler = new WebAppContext();
    handler.setContextPath("/");
    handler.setBaseResource(Resource.newResource(webAppRoot()));
    handler.setClassLoader(new URLClassLoader(
            new URL[] {
                    Resource.newResource(new File(webAppRoot(),
                                                  "WEB-INF" + File.separatorChar +
                                                  "lib" + File.separatorChar +
                                                  "hello.jar")).getURI().toURL()
            },
            JettyService.class.getClassLoader()));

    handler.addBean(new ServletContainerInitializersStarter(handler), true);
    handler.setAttribute(
            "org.eclipse.jetty.containerInitializers",
            Collections.singletonList(new ContainerInitializer(new JettyJasperInitializer(), null)));
    return handler;
}
 
Example #13
Source File: ResolverTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void startServer() throws Throwable {
    Server server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/resolver");
    webappcontext.setBaseResource(Resource.newClassPathResource("/resolver"));

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
    server.setHandler(handlers);
    server.start();
    Throwable e = webappcontext.getUnavailableException();
    if (e != null) {
        throw e;
    }
    server.stop();
}
 
Example #14
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 #15
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 #16
Source File: CertificateUtils.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
public static Collection<? extends CRL> loadCRL(String crlPath) throws Exception
{
    Collection<? extends CRL> crlList = null;

    if (crlPath != null)
    {
        InputStream in = null;
        try
        {
            in = Resource.newResource(crlPath).getInputStream();
            crlList = CertificateFactory.getInstance("X.509").generateCRLs(in);
        }
        finally
        {
            if (in != null)
            {
                in.close();
            }
        }
    }

    return crlList;
}
 
Example #17
Source File: CertificateUtils.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
public static Collection<? extends CRL> loadCRL(String crlPath) throws Exception
{
    Collection<? extends CRL> crlList = null;

    if (crlPath != null)
    {
        InputStream in = null;
        try
        {
            in = Resource.newResource(crlPath).getInputStream();
            crlList = CertificateFactory.getInstance("X.509").generateCRLs(in);
        }
        finally
        {
            if (in != null)
            {
                in.close();
            }
        }
    }

    return crlList;
}
 
Example #18
Source File: DefaultFileLocatorHelper.java    From livingdoc-confluence with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Only useful for equinox: on felix we get the file:// url already. Other
 * OSGi implementations have not been tested
 * <p>
 * Get a URL to the content of the bundle entry that uses the file:
 * protocol. The content of the bundle entry may be downloaded or extracted
 * to the local file system in order to create a file: URL.
 *
 * @return a URL to the content of the bundle entry that uses the file:
 * protocol
 * </p>
 * @throws IOException
 */
@Override
public URL getFileURL(URL url) throws Exception

{
    if ("bundleresource".equals(url.getProtocol()) || "bundleentry".equals(url.getProtocol())) {

        URLConnection conn = url.openConnection();
        conn.setDefaultUseCaches(Resource.getDefaultUseCaches());
        if (BUNDLE_URL_CONNECTION_getFileURL == null && match(conn.getClass().getName(),
                BUNDLE_URL_CONNECTION_CLASSES)) {
            BUNDLE_URL_CONNECTION_getFileURL = conn.getClass().getMethod("getFileURL", null);
            BUNDLE_URL_CONNECTION_getFileURL.setAccessible(true);
        }
        if (BUNDLE_URL_CONNECTION_getFileURL != null) {
            return ( URL ) BUNDLE_URL_CONNECTION_getFileURL.invoke(conn, null);
        }

    }
    return url;
}
 
Example #19
Source File: DefaultFileLocatorHelper.java    From livingdoc-confluence with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Only useful for equinox: on felix we get the file:// or jar:// url
 * already. Other OSGi implementations have not been tested
 * <p>
 * Get a URL to the bundle entry that uses a common protocol (i.e. file:
 * jar: or http: etc.).
 * </p>
 *
 * @return a URL to the bundle entry that uses a common protocol
 */
@Override
public URL getLocalURL(URL url) throws Exception {
    if ("bundleresource".equals(url.getProtocol()) || "bundleentry".equals(url.getProtocol())) {

        URLConnection conn = url.openConnection();
        conn.setDefaultUseCaches(Resource.getDefaultUseCaches());
        if (BUNDLE_URL_CONNECTION_getLocalURL == null && match(conn.getClass().getName(),
                BUNDLE_URL_CONNECTION_CLASSES)) {
            BUNDLE_URL_CONNECTION_getLocalURL = conn.getClass().getMethod("getLocalURL", null);
            BUNDLE_URL_CONNECTION_getLocalURL.setAccessible(true);
        }
        if (BUNDLE_URL_CONNECTION_getLocalURL != null) {
            return ( URL ) BUNDLE_URL_CONNECTION_getLocalURL.invoke(conn, null);
        }
    }
    return url;
}
 
Example #20
Source File: AudioResourceServlet.java    From BeyondUPnP with Apache License 2.0 6 votes vote down vote up
@Override
public Resource getResource(String pathInContext) {
    Resource resource = null;

    Log.i(AudioResourceServlet.class.getSimpleName(),"Path:" + pathInContext);
    try {
        String id = Utils.parseResourceId(pathInContext);
        Log.i(AudioResourceServlet.class.getSimpleName(),"Id:" + id);

        Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.parseLong(id));
        Cursor cursor = BeyondApplication.getApplication().getContentResolver().query(
                uri, null,null, null, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
        File file = new File(path);
        if (file.exists()) {
            resource = FileResource.newResource(file);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return resource;
}
 
Example #21
Source File: CachingResource.java    From crushpaper with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Resource addPath(String path) throws IOException,
		MalformedURLException {
	String fullPath = directory + path;

	// If it was already cached return from the cache.
	CachingResource cached = cachedResources.get(fullPath);
	if (cached != null) {
		return cached;
	}

	// Get the real underlying resource.
	Resource underlyingResource = resource.addPath(path);
	if (underlyingResource == null) {
		return null;
	}

	// Cache the resource.
	cached = new CachingResource(underlyingResource, null);
	cached.cache();
	cachedResources.put(fullPath, cached);

	// Return it.
	return cached;
}
 
Example #22
Source File: JettyServiceStartupTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
static WebAppContext newWebAppContext() throws MalformedURLException {
    final File webAppRoot = WebAppContainerTest.webAppRoot();
    final WebAppContext handler = new WebAppContext();
    handler.setContextPath("/");
    handler.setBaseResource(Resource.newResource(webAppRoot));
    handler.setClassLoader(new URLClassLoader(
            new URL[] {
                    Resource.newResource(new File(webAppRoot,
                                                  "WEB-INF" + File.separatorChar +
                                                  "lib" + File.separatorChar +
                                                  "hello.jar")).getURI().toURL()
            },
            JettyService.class.getClassLoader()));

    handler.addBean(new ServletContainerInitializersStarter(handler), true);
    handler.setAttribute(
            "org.eclipse.jetty.containerInitializers",
            Collections.singletonList(new ContainerInitializer(new JettyJasperInitializer(), null)));
    return handler;
}
 
Example #23
Source File: JsMinifyingResource.java    From crushpaper with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Resource addPath(String path) throws IOException,
		MalformedURLException {
	Resource toReturn = resource.addPath(path);
	if (toReturn == null) {
		return null;
	}

	return new JsMinifyingResource(toReturn);
}
 
Example #24
Source File: CertificateUtils.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
public static KeyStore getKeyStore(InputStream storeStream, String storePath, String storeType, String storeProvider, String storePassword) throws Exception
{
    KeyStore keystore = null;

    if (storeStream != null || storePath != null)
    {
        InputStream inStream = storeStream;
        try
        {
            if (inStream == null)
            {
                inStream = Resource.newResource(storePath).getInputStream();
            }
            
            if (storeProvider != null)
            {
                keystore = KeyStore.getInstance(storeType, storeProvider);
            }
            else
            {
                keystore = KeyStore.getInstance(storeType);
            }

            keystore.load(inStream, storePassword == null ? null : storePassword.toCharArray());
        }
        finally
        {
            if (inStream != null)
            {
                inStream.close();
            }
        }
    }
    
    return keystore;
}
 
Example #25
Source File: FakeGoServer.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void start() throws Exception {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    server.addConnector(connector);

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setCertAlias("cruise");
    sslContextFactory.setKeyStoreResource(Resource.newClassPathResource("testdata/fake-server-keystore"));
    sslContextFactory.setKeyStorePassword("serverKeystorepa55w0rd");

    ServerConnector secureConnnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(new HttpConfiguration())
    );
    server.addConnector(secureConnnector);

    WebAppContext wac = new WebAppContext(".", "/go");
    ServletHolder holder = new ServletHolder();
    holder.setServlet(new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            resp.getOutputStream().println("Hello");
        }
    });
    wac.addServlet(holder, "/hello");
    addFakeAgentBinaryServlet(wac, "/admin/agent", TEST_AGENT, this);
    addFakeAgentBinaryServlet(wac, "/admin/agent-launcher.jar", TEST_AGENT_LAUNCHER, this);
    addFakeAgentBinaryServlet(wac, "/admin/agent-plugins.zip", TEST_AGENT_PLUGINS, this);
    addFakeAgentBinaryServlet(wac, "/admin/tfs-impl.jar", TEST_TFS_IMPL, this);
    addlatestAgentStatusCall(wac);
    addDefaultServlet(wac);
    server.setHandler(wac);
    server.setStopAtShutdown(true);
    server.start();

    port = connector.getLocalPort();
    securePort = secureConnnector.getLocalPort();
}
 
Example #26
Source File: WebInfFolderExtendedConfiguration.java    From logsniffer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected List<Resource> findJars(final WebAppContext context) throws Exception {
	List<Resource> r = super.findJars(context); // let original
												// WebInfConfiguration do
												// it's thing first
	if (r == null) {
		r = new LinkedList<Resource>();
	}

	final List<Resource> containerJarResources = context.getMetaData().getOrderedWebInfJars();
	r.addAll(containerJarResources);

	return r;
}
 
Example #27
Source File: JettySingleApplicationTest.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"),
            // Limit the classpath scanning to org.apache.demo.complete package
            Resource.newClassPathResource("/org/apache/demo/applications/complete")
        }, PORT);
}
 
Example #28
Source File: EmbeddedJettyConfigurationTest.java    From junit-servers with MIT License 5 votes vote down vote up
@Test
void it_should_build_configuration() {
	final int port = 8080;
	final String path = "/foo";
	final String webapp = "foo";
	final String classpath = "/target/classes";
	final int stopTimeout = 50;
	final Resource resource = mock(Resource.class);
	final String containerJarPattern = ".*\\.jar";
	final String webInfJarPattern = ".*";

	final EmbeddedJettyConfiguration result = EmbeddedJettyConfiguration.builder()
		.withPort(port)
		.withClasspath(classpath)
		.withWebapp(webapp)
		.withPath(path)
		.withStopTimeout(stopTimeout)
		.disableStopAtShutdown()
		.withBaseResource(resource)
		.withContainerJarPattern(containerJarPattern)
		.withWebInfJarPattern(webInfJarPattern)
		.build();

	assertThat(result.getPort()).isEqualTo(port);
	assertThat(result.getPath()).isEqualTo(path);
	assertThat(result.getClasspath()).isEqualTo(classpath);
	assertThat(result.getWebapp()).isEqualTo(webapp);
	assertThat(result.getStopTimeout()).isEqualTo(stopTimeout);
	assertThat(result.isStopAtShutdown()).isFalse();
	assertThat(result.getBaseResource()).isSameAs(resource);
	assertThat(result.getContainerJarPattern()).isEqualTo(containerJarPattern);
	assertThat(result.getWebInfJarPattern()).isEqualTo(webInfJarPattern);
}
 
Example #29
Source File: WebServer.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Generate Options Description JavaScript to serve http://drillhost/options ACE library search features
 * @throws IOException
 */
private void generateOptionsDescriptionJSFile() throws IOException {
  // Obtain list of Options & their descriptions
  OptionManager optionManager = this.drillbit.getContext().getOptionManager();
  OptionList publicOptions = optionManager.getPublicOptionList();
  List<OptionValue> options = new ArrayList<>(publicOptions);
  // Add internal options
  OptionList internalOptions = optionManager.getInternalOptionList();
  options.addAll(internalOptions);
  Collections.sort(options);
  int numLeftToWrite = options.size();

  // Template source Javascript file
  InputStream optionsDescripTemplateStream = Resource.newClassPathResource(OPTIONS_DESCRIBE_TEMPLATE_JS).getInputStream();
  // Generated file
  File optionsDescriptionFile = new File(getOrCreateTmpJavaScriptDir(), OPTIONS_DESCRIBE_JS);
  final String file_content_footer = "};";
  // Create a copy of a template and write with that!
  java.nio.file.Files.copy(optionsDescripTemplateStream, optionsDescriptionFile.toPath());
  logger.info("Will write {} descriptions to {}", numLeftToWrite, optionsDescriptionFile.getAbsolutePath());

  try (BufferedWriter writer = new BufferedWriter(new FileWriter(optionsDescriptionFile, true))) {
    // Iterate through options
    for (OptionValue option : options) {
      numLeftToWrite--;
      String optionName = option.getName();
      OptionDescription optionDescription = optionManager.getOptionDefinition(optionName).getValidator().getOptionDescription();
      if (optionDescription != null) {
        // Note: We don't need to worry about short descriptions for WebUI, since they will never be explicitly accessed from the map
        writer.append("  \"").append(optionName).append("\" : \"")
        .append(StringEscapeUtils.escapeEcmaScript(optionDescription.getDescription()))
        .append( numLeftToWrite > 0 ? "\"," : "\"");
        writer.newLine();
      }
    }
    writer.append(file_content_footer);
    writer.newLine();
    writer.flush();
  }
}
 
Example #30
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;
}