001/* 002 * To change this license header, choose License Headers in Project Properties. 003 * To change this template file, choose Tools | Templates 004 * and open the template in the editor. 005 */ 006package org.anarres.cpp; 007 008import java.io.IOException; 009import java.io.InputStream; 010import java.nio.charset.Charset; 011import javax.annotation.Nonnull; 012 013/** 014 * 015 * @author shevek 016 */ 017public class ResourceFileSystem implements VirtualFileSystem { 018 019 private final ClassLoader loader; 020 private final Charset charset; 021 022 public ResourceFileSystem(@Nonnull ClassLoader loader, @Nonnull Charset charset) { 023 this.loader = loader; 024 this.charset = charset; 025 } 026 027 @Override 028 public VirtualFile getFile(String path) { 029 return new ResourceFile(loader, path); 030 } 031 032 @Override 033 public VirtualFile getFile(String dir, String name) { 034 return getFile(dir + "/" + name); 035 } 036 037 private class ResourceFile implements VirtualFile { 038 039 private final ClassLoader loader; 040 private final String path; 041 042 public ResourceFile(ClassLoader loader, String path) { 043 this.loader = loader; 044 this.path = path; 045 } 046 047 @Override 048 public boolean isFile() { 049 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. 050 } 051 052 @Override 053 public String getPath() { 054 return path; 055 } 056 057 @Override 058 public String getName() { 059 return path.substring(path.lastIndexOf('/') + 1); 060 } 061 062 @Override 063 public ResourceFile getParentFile() { 064 int idx = path.lastIndexOf('/'); 065 if (idx < 1) 066 return null; 067 return new ResourceFile(loader, path.substring(0, idx)); 068 } 069 070 @Override 071 public ResourceFile getChildFile(String name) { 072 return new ResourceFile(loader, path + "/" + name); 073 } 074 075 @Override 076 public Source getSource() throws IOException { 077 InputStream stream = loader.getResourceAsStream(path); 078 return new InputLexerSource(stream, charset); 079 } 080 } 081}