Java Code Examples for org.eclipse.jetty.util.resource.FileResource

Following code examples demonstrate how to use org.eclipse.jetty.util.resource.FileResource from jetty. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.eclipse.jetty.util.resource.FileResource and various code implementation of this class.

	public Resource getResource(String pathInContext) {
		Request request = HttpChannel.getCurrentHttpChannel().getRequest();
		String queryString = request.getQueryString();
		if(queryString==null||queryString.equals("")) return null;
		String[] paths = queryString.split(",");
		FileResource[] resources = new FileResource[paths.length];
		
		for(int i=0;i<paths.length;i++){
			resources[i] = (FileResource)super.getResource("/"+paths[i]);
		}
		
		ConcatResource concatResource = null;
		try {
			concatResource = new ConcatResource( (pathInContext.endsWith(".gz")?true:false),pathInContext, resources,paths);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}
		return concatResource;
	} 


    public void init(String path, URI webApp, URI classPath) throws MalformedURLException {
        this.server = new Server(0);

        WebAppContext context = new WebAppContext();

        context.setClassLoader(Thread.currentThread().getContextClassLoader());

        Resource resourceBase = newResource(webApp);
        context.setResourceBase(String.valueOf(resourceBase));

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

        File tempDirectory = new File("/tmp");
        context.setTempDirectory(tempDirectory);

        FileResource containerResources = new FileResource(classPath);
        context.getMetaData().addContainerResource(containerResources);

        String webXmlPath = webApp.getPath() +"/WEB-INF/web.xml";
        context.setDescriptor(webXmlPath);

        context.setContextPath(path);
        context.setParentLoaderPriority(true);

        server.setHandler(context);
    } 

	public Resource getResource(String uriInContext) throws MalformedURLException {
		Resource r = super.getResource(uriInContext);
		if (r instanceof FileResource) {
			if (!(((FileResource) r).getFile()).exists()) {
				if (otherDirs != null) {
					for (FileResource s : otherDirs) {
						try {
							FileResource ff = (FileResource) s.addPath(uriInContext);
							if (ff.getFile().exists()) {
								r = ff;
								break;
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}

			}
		}
		return r;
	} 

  private FileResource createServletContextPath() {
    File contextRoot = FileUtil.getTempDir( this.toString() );
    try {
      return new FileResource( contextRoot.toURI().toURL() );
    } catch( Exception e ) {
      throw new RuntimeException( e );
    }
  } 

   public Resource addPath(String uri) throws IOException {
      Resource resource = m_resources.get(uri);

      if (resource == null) {
         File file = new File(m_docRoot, uri);

         if (file.exists()) {
            try {
               resource = new FileResource(file.toURI().toURL());

               m_resources.putIfAbsent(uri, resource);
            } catch (URISyntaxException e) {
            }
         }
      }

      if (resource == null) {
         URL url = m_manager.getResourceUrl(uri);

         if (url != null) {
            try {
               String protocol = url.getProtocol();

               if (protocol.equals("file")) {
                  resource = new FileResource(url);
                  m_resources.putIfAbsent(uri, resource);
               } else if (protocol.equals("jar")) {
                  resource = new URLResource(url, null, true) {
                  };
                  m_resources.putIfAbsent(uri, resource);
               }
            } catch (URISyntaxException e) {
            }
         }
      }

      if (resource != null) {
         return resource;
      } else {
         return super.addPath(uri);
      }
   } 

  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    HandlerList handlerList = new HandlerList();
    
    WebAppContext contextHandler = new WebAppContext(handlerList, "Chat Webapp", "/chat");
    URL homepage = EventServer.class.getResource("/");
    Resource homepageResource = new FileResource(homepage);
    ResourceCollection resources = new ResourceCollection(homepageResource);
    contextHandler.setBaseResource(resources);
    ServletContextHandler socketHandler = new ServletContextHandler(handlerList, "/events");
    
    WebSocketHandler wsHandler = new WebSocketHandler() {
      @Override
      public void configure(WebSocketServletFactory factory) {
        factory.register(ChatSocket.class);
      }
    };
    socketHandler.setHandler(wsHandler);
    server.setHandler(handlerList);
    server.start();
    server.join();
  } 

    public void start() throws Exception {   
        HandlerList handlers = new HandlerList();
        for (Entry<String, URL> entry:resources.entrySet()) {
            ContextHandler urlContext = new ContextHandler(entry.getKey());
            URL directory = entry.getValue();
            ResourceHandler directoryHandler = new ResourceHandler();        
            directoryHandler.setDirectoriesListed(true);            
            directoryHandler.setBaseResource(new FileResource(directory));            
            urlContext.setHandler(directoryHandler);
            handlers.addHandler(urlContext);
        }

        server.setHandler(handlers);        
        server.start();
    } 

                    @Override
                    public void failed(Throwable x)
                    {
                        LOG.warn(x.toString());
                        LOG.debug(x);
                        async.complete();
                    } 

    public void start() throws Exception {
        server = new Server(8080);

        WebAppContext webAppContext = new WebAppContext();
        webAppContext.setResourceBase("src/main/webapp");
        webAppContext.setContextPath("/");
        File[] mavenLibs = Maven.resolver().loadPomFromFile("pom.xml")
                    .importCompileAndRuntimeDependencies()
                    .resolve().withTransitivity().asFile();
        for (File file: mavenLibs) {
            webAppContext.getMetaData().addWebInfJar(new FileResource(file.toURI()));
        }
        webAppContext.getMetaData().addContainerResource(new FileResource(new File("./target/classes").toURI()));

        webAppContext.setConfigurations(new Configuration[] {
            new AnnotationConfiguration(),
            new WebXmlConfiguration(),
            new WebInfConfiguration()
        });
        server.setHandler(webAppContext);

        logger.info(">>> STARTING EMBEDDED JETTY SERVER");
        server.start();
        
    } 

            protected WebAppContext createdWebAppContext() throws Exception {
                final String path = configuration.getPath();
                final String webapp = configuration.getWebapp();
                final String classpath = configuration.getClasspath();

                WebAppContext ctx = new WebAppContext();
                ctx.setClassLoader(Thread.currentThread().getContextClassLoader());
                ctx.setContextPath(path);

                ctx.setBaseResource(newResource(webapp));

                ctx.setConfigurations(new Configuration[]{
                        new WebInfConfiguration(),
                        new WebXmlConfiguration(),
                        new AnnotationConfiguration(),
                        new JettyWebXmlConfiguration(),
                        new MetaInfConfiguration(),
                        new FragmentConfiguration(),
                });

                if (isNotBlank(classpath)) {
                    File classes = new File(classpath);
                    FileResource containerResources = new FileResource(classes.toURI());
                    ctx.getMetaData().addContainerResource(containerResources);
                }

                Server server = getDelegate();

                ctx.setParentLoaderPriority(true);
                ctx.setWar(webapp);
                ctx.setServer(server);

                server.setHandler(ctx);

                return ctx;
            } 

    public void start() throws Exception {

        LOG.info("Configuring web server from: " + configXMLURL);
        Resource input = new FileResource(configXMLURL);
        XmlConfiguration configuration = new XmlConfiguration(input.getInputStream());
        server = (Server)configuration.configure();
        input.close();

        server.start();

    } 

	private static Server createServer(ProxyProperties pp) throws Exception {

		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		Resource keystore = new FileResource(cl.getResource("keystore"));
		String password = Password.obfuscate("clxystudio");

		Server server = new Server(pp.getHttpPort());

		HttpConfiguration httpConfig = new HttpConfiguration();
		httpConfig.setSecureScheme("https");
		httpConfig.setSecurePort(pp.getHttpsPort());

		SslContextFactory sslContextFactory = new SslContextFactory();
		sslContextFactory.setKeyStoreResource(keystore);
		sslContextFactory.setKeyStorePassword(password);
		sslContextFactory.setKeyManagerPassword(password);
		sslContextFactory.setTrustStoreResource(keystore);
		sslContextFactory.setTrustStorePassword(password);
		sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA",
				"SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA",
				"SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
				"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
		HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
		httpsConfig.addCustomizer(new SecureRequestCustomizer());
		ServerConnector sslConnector = new ServerConnector(
				server,
				new SslConnectionFactory(sslContextFactory, "http/1.1"),
				new HttpConnectionFactory(httpsConfig));
		sslConnector.setPort(pp.getHttpsPort());
		server.addConnector(sslConnector);

		return server;
	} 

    public static void main(String[] args) throws Exception {
    	System.setProperty(ContextStarter.VAR_CTX_PATH, "p4test");
    	
    	URL holder = StartApp.class.getResource("/bizobj-portofino-test-StartApp.properties");
        File fh = new File(holder.toURI());
        String root = fh.getParentFile().getParentFile().getParentFile().getParentFile().getCanonicalPath();
        Resource testWar = new FileResource(new File(root + "/test-project/src/main/webapp").toURI());
        Resource mainWar = new FileResource(new File(root + "/main-project/src/main/webapp").toURI());
        Resource rc = new ResourceCollection(testWar, mainWar);
        ContextStarter.startServer(rc, new File(root + "/test-project/src/main/webapp/WEB-INF/web.xml"));
    } 

	public static void main(String[] args) throws Exception {
		GPSJettyServer server = new GPSJettyServer();
		server.start();
		server.stop();
	} 

    public Resource addPath(String path) throws IOException{
        path = URIUtil.canonicalPath(path);
        if(path == null)throw new MalformedURLException();
        if("/".equals(path)){
            try{
                return new FileResource(new URI(uris.get(0)));
            }catch(URISyntaxException e){
                throw new MalformedURLException(path);
            }
        }
        path = URIUtil.encodePath(path);
        URI uri = null;
        try{
            for(int i=0;i<files.size();i++){
                if(files.get(i).isDirectory()){
                    uri = new URI(URIUtil.addPaths(uris.get(i), path));
                }else{
                    uri = new URI(String.format("%s%s", uris.get(i), path));
                }
                FileResource fileResource = new FileResource(uri);
                if(fileResource.exists())return fileResource;
            }
        }catch(final URISyntaxException e){
            throw new MalformedURLException(){{initCause(e);}};
        }
        return new FileResource(uri);
    } 

                    }

                    public void failed(Throwable x)
                    {
                        LOG.warning(x.toString());
                        LOG.debug(x);
                        async.complete();
                    } 

    public Resource getResource(String url) {
        String path = url.substring("/videos/".length());
        File location = folderMapper.getLocation(path);
        Resource r = new FileResource(location.toURI());
        return r;
    } 

	public void preConfigure(final WebAppContext context) throws Exception {
		
		final ArrayList<Resource> resources = new ArrayList<Resource>();
		ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL[] urls = ((URLClassLoader)cl).getURLs();
        for(URL url: urls){
        	Resource r= new FileResource(url);
        	if (r.isDirectory()) {
        		resources.add(r);
        	}
        }
		scanJars(context, resources, false);
	} 

   }

   private static Handler getFilesystemHandler()
   {
      ResourceHandler handler = new ResourceHandler();
      handler.setDirectoriesListed(true);
      handler.setBaseResource(new FileResource(getFilesystemRoot().toURI()));

      ContextHandler context = new ContextHandler("/fs");
      context.setHandler(handler);

      return context;
   } 

    

    private void handleClasses(final WebAppContext context,
                               final AnnotationParser parser, URI dir)
            throws Exception {
        Resource classesDir = new FileResource(dir.toURL());

        if (classesDir.exists()) {
            clearAnnotationList(parser.getAnnotationHandlers());
            parser.parse(classesDir, new ClassNameResolver() {
                public boolean isExcluded(String name) {
                    if (context.isSystemClass(name))
                        return true;
                    if (context.isServerClass(name))
                        return false;
                    return false;
                }

                public boolean shouldOverride(String name) {
                    if (context.isParentLoaderPriority())
                        return false;
                    return true;
                }
            });

            List<DiscoveredAnnotation> annotations = new ArrayList<DiscoveredAnnotation>();
            gatherAnnotations(annotations, parser.getAnnotationHandlers());
            context.getMetaData().addDiscoveredAnnotations(annotations);
        }
    } 

    public void setUp() throws Exception {
        server = new Server(0);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        context.setBaseResource(new FileResource(new File("src/test/webapp").getAbsoluteFile().toURI().toURL()));
        setUpContext(context);
        server.setHandler(context);
        server.start();

        port = ((ServerConnector) server.getConnectors()[0]).getLocalPort();

    } 

	public void start() throws Exception {
		server = new Server();
		Connector connector = new SocketConnector();
		connector.setPort(port);
		server.setConnectors(new Connector[]{connector});

		HandlerList handlerList = new HandlerList(); 
		
		ResourceHandler rootHandler = new ResourceHandler();
		rootHandler.setBaseResource(new FileResource(new URL("file:"+root.getCanonicalPath())));
		ResourceHandler libHandler = new ResourceHandler();
		libHandler.setBaseResource(new FileResource(new URL("file:"+lib.getCanonicalPath())));
		
		boolean useV8 = Boolean.valueOf(System.getProperty("V8", "false"));
		boolean useRhinoAST = Boolean.valueOf(System.getProperty("rhinoAST", "true"));
		JSOptimizerFactory jsOptimizerFactory = null;
		if (useV8) {
			jsOptimizerFactory = new org.dojotoolkit.optimizer.amd.v8.AMDJSOptimizerFactory();
		} else if (useRhinoAST) {
			jsOptimizerFactory = new org.dojotoolkit.optimizer.amd.rhinoast.AMDJSOptimizerFactory();
		} else {
			jsOptimizerFactory = new org.dojotoolkit.optimizer.amd.rhino.AMDJSOptimizerFactory();
		}
		System.out.println("Using jsOptimizerFactory ["+jsOptimizerFactory.getClass().getName()+"]");

		JSCompressorFactory jsCompressorFactory = null;
		if (compress) {
			jsCompressorFactory = new JSCompressorFactoryImpl();
		}
		MultiRootResourceLoader resourceLoader = new MultiRootResourceLoader(new File[] {root, lib});
		RhinoClassLoader rhinoClassLoader = new RhinoClassLoader(resourceLoader);

		File tempDir = new File("./tmp");
		if (!tempDir.exists()) {
			tempDir.mkdirs();
		}
		JSContentHandler jsContentHandler = new JSContentHandler(resourceLoader, jsOptimizerFactory, rhinoClassLoader, jsCompressorFactory, tempDir);
		handlerList.addHandler(jsContentHandler);
		handlerList.addHandler(rootHandler);
		handlerList.addHandler(libHandler);
		
		server.setHandler(handlerList);
		server.start();
		System.out.println("Server started and available on port : "+port);
		System.out.println("Loading from ["+root+"]");
	} 

    public static void main(String[] args) throws Exception {
        Server server = new Server();
        int port = getServerPort();
        int sslPort = getSslPort();

        Connector connector = createSelectChannelConnector(server, port);

        Connector sslConnector = createSSLConnector(server, sslPort);

        Connector[] connectors = new Connector[]{connector, sslConnector};
        server.setConnectors(connectors);

        WebAppContext webAppContext = new WebAppContext();
        webAppContext.setServer(server);
        webAppContext.setContextPath("/");
        webAppContext.setWar("src/main/webapp");
        webAppContext.setMaxFormContentSize(1 * 1024 * 1024);
        webAppContext.getMetaData().addContainerResource(new FileResource(new File("./target/classes").toURI()));
        webAppContext.setResourceBase("src/main/webapp");
        webAppContext.setTempDirectory(new File("./target/tmp"));
        webAppContext.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
        server.setHandler(webAppContext);


        try {
            System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP!!");
            server.start();
            while (System.in.available() == 0) {
                Thread.sleep(5000);
            }
            server.stop();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(100);
        }

    } 

    public static void main(String[] args) throws Exception {
        Server server = new Server();
        ServerConnector scc = new ServerConnector(server);
        scc.setPort(Integer.parseInt(System.getProperty("jetty.port", "9090")));
        server.setConnectors(new Connector[]{scc});

        WebAppContext context = new WebAppContext();
        context.setServer(server);
        context.setContextPath("/");
        context.setWar("src/main/webapp");
        context.setResourceBase("src/main/webapp");
        context.getMetaData().addContainerResource(new FileResource(new File("./target/classes").toURI()));
        context.setConfigurations(new Configuration[]{
                new WebXmlConfiguration(),
                new AnnotationConfiguration()
        });

        server.setHandler(context);
        
        try {
            System.out.println(">>> STARTING EMBEDDED JETTY SERVER");
            server.start();
            while (System.in.available() == 0) {
                Thread.sleep(5000);
            }
            server.stop();
            server.join();
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(100);
        }

    } 

	public static void main(String[] args) throws Exception {
		Server server = new Server();
        int port = getServerPort();
        int sslPort = getSslPort();
        
		Connector connector = createSelectChannelConnector(server, port);
        
		Connector sslConnector = createSSLConnector(server, sslPort);
			
        Connector[] connectors = new Connector[] { connector, sslConnector };
        server.setConnectors(connectors);

		WebAppContext webAppContext = new WebAppContext();
		webAppContext.setServer(server);
		webAppContext.setContextPath("/");
		webAppContext.setWar("src/main/webapp");
		webAppContext.setMaxFormContentSize(1 * 1024 * 1024);
		webAppContext.getMetaData().addContainerResource(new FileResource(new File("./target/classes").toURI()));
		webAppContext.setResourceBase("src/main/webapp");
		webAppContext.setTempDirectory(new File("./target/tmp"));
		webAppContext.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
		server.setHandler(webAppContext);

		try {
			System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP!!");
			server.start();
			while (System.in.available() == 0) {
				Thread.sleep(5000);
			}
			server.stop();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(100);
		}
	} 

	public static void main(String[] args) throws Exception {
		CapsidJettyServer server = new CapsidJettyServer();
		server.start();
		server.stop();
	} 

    public static void configureConnector( Server server, HttpsConnectorConf config ) {

        Resource keyStoreResource = new FileResource( config.getKeyStore() );

        HttpConfiguration httpConfiguration = getStandardConfiguration( config );

        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStoreResource( keyStoreResource );
        sslContextFactory.setKeyStorePassword( config.getKeyStorePassword() );
        sslContextFactory.setKeyManagerPassword( config.getKeyManagerPassord() );
        SslConnectionFactory sslConnectionFactory = new SslConnectionFactory( sslContextFactory,
                                                                              HttpVersion.HTTP_1_1.asString() );


        HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory( httpConfiguration );

        ServerConnector sslConnector = new ServerConnector( server, sslConnectionFactory, httpConnectionFactory );
        configureCommonFields( sslConnector, config );
        sslConnector.setPort( config.getPort() );
        server.addConnector( sslConnector );

    } 

    public void start(){

        server = new Server(port);

        SpamWebSocketHandler myWebSocketHandler = new SpamWebSocketHandler();

        URL url=this.getClass().getClassLoader() .getResource("org/noahx/websocket/http");

        ResourceHandler resourceHandler=new ResourceHandler();
        try {
            resourceHandler.setBaseResource(new FileResource(url));
        } catch (IOException e) {
        } catch (URISyntaxException e) {
        }

        myWebSocketHandler.setHandler(resourceHandler);

        server.setHandler(myWebSocketHandler);

        try {
            server.start();
            server.join();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    } 

    }

    private static void initWebappContext(Server server, ConfigJetty configs)
            throws IOException, URISyntaxException {
        web = new WebAppContext();

        if (configs.getParentLoaderPriority()) {
            System.err.println("ParentLoaderPriority enabled");
            web.setParentLoaderPriority(true);
        }

        web.setContextPath(configs.getContext());

        
        List<String> configurationClasses = configs.getConfigurationClassesList();
        if (configurationClasses.size() != 0) {
            web.setConfigurationClasses(configurationClasses.toArray(new String[0]));

            for (String conf : configurationClasses) {
                System.err.println("Enable config class:" + conf);
            }

        }

        web.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer",
                "false");

        if (configs.getWebAppClassPath() != null) {
            ProjectClassLoader loader = new ProjectClassLoader(web,
                    configs.getWebAppClassPath(), configs.getExcludedclasspath());
            web.setClassLoader(loader);
        }

        List<Resource> resources = new ArrayList<Resource>();

        URL urlWebapp = new File(configs.getWebAppDir()).toURI().toURL();
        Resource webapp = new FileResource(urlWebapp);
        resources.add(webapp);

        Map<String, String> map = configs.getResourceMap();
        for (String key : map.keySet()) {
            resources.add(new VirtualResource(webapp, "/" + key, map.get(key)));
        }

        ResourceCollection webAppDirResources
                = new ResourceCollection(resources.toArray(new Resource[0]));
        web.setBaseResource(webAppDirResources);

        server.setHandler(web);
    } 

   public Resource getFallbackResource(String uri) {
      Resource resource = m_resources.get(uri);

      if (resource == null) {
         URL url = m_urls.get(uri);

         if (url != null) {
            try {
               String protocol = url.getProtocol();

               if (protocol.equals("file")) {
                  resource = new FileResource(url);
                  m_resources.put(uri, resource);
               } else if (protocol.equals("jar")) {
                  resource = new URLResource(url, null, true) {
                  };
                  m_resources.put(uri, resource);
               }
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      }

      return resource;
   } 

    public Resource getResource(String pathInContext) {
        Resource resource = null;

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

            Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.parseLong(id));
            Cursor cursor = VApplication.getContext()
                                        .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;
    } 

    public Resource getResource(String pathInContext) {
        Resource resource = null;

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

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

        return resource;
    } 

    public Resource getResource(String pathInContext) {
        Resource resource = null;

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

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

        return resource;
    } 

        public Builder setRootDir(File dir) throws IOException, URISyntaxException {
            context.setBaseResource(new FileResource(dir.toURI().toURL()));
            return this;
        } 

	public void close() {
		for(FileResource fr : frs){
			fr.close();
		}

	} 

	public boolean exists() {
		if(this.gzip) return false;
		
		for(FileResource fr : frs){
			if(!fr.exists()){
				return false;
			}
		}
		return true;
	} 

	public long lastModified() {
		long LM = 0;
		for(FileResource fr : frs){
			if(fr.lastModified()>LM){
				LM = fr.lastModified();
			}
		}
		return LM;
	} 

Advertisement
Javadoc
------------------------------------------------------------
Advertisement