play.vfs.VirtualFile Java Examples

The following examples show how to use play.vfs.VirtualFile. 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: RouterBenchmark.java    From actframework with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void prepare() throws Exception {
    try {
        Field f = Act.class.getDeclaredField("pluginManager");
        f.setAccessible(true);
        f.set(null, new GenericPluginManager());
    } catch (Exception e) {
        throw E.unexpected(e);
    }
    app = App.testInstance();
    UrlPath.testClassInit();
    config = app.config();
    RequestHandlerResolver controllerLookup = new MockRequestHandlerResolver();
    router = new Router(controllerLookup, app);
    InputStream is = TestBase.class.getResourceAsStream("/routes");
    String fc = IO.readContentAsString(is);
    builder = new RouteTableRouterBuilder(fc.split("[\r\n]+"));
    builder.build(router);
    Play.pluginCollection = new PluginCollection();
    URL url = TestBase.class.getResource("/routes");
    Play.applicationPath = new File(FastStr.of(url.getPath()).beforeLast('/').toString());
    Play.routes = VirtualFile.fromRelativePath("routes");
    play.mvc.Router.load("");
}
 
Example #2
Source File: Controller.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * Send a 302 redirect response.
 * @param file The Location to redirect
 */
protected static void redirectToStatic(String file) {
    try {
        VirtualFile vf = Play.getVirtualFile(file);
        if (vf == null || !vf.exists()) {
            throw new NoRouteFoundException(file);
        }
        throw new RedirectToStatic(Router.reverse(Play.getVirtualFile(file)));
    } catch (NoRouteFoundException e) {
        StackTraceElement element = PlayException.getInterestingStrackTraceElement(e);
        if (element != null) {
            throw new NoRouteFoundException(file, Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber());
        } else {
            throw e;
        }
    }
}
 
Example #3
Source File: TemplateLoader.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * List all found templates
 * @return A list of executable templates
 */
public static List<Template> getAllTemplate() {
    List<Template> res = new ArrayList<Template>();
    for (VirtualFile virtualFile : Play.templatesPath) {
        scan(res, virtualFile);
    }
    for (VirtualFile root : Play.roots) {
        VirtualFile vf = root.child("conf/routes");
        if (vf != null && vf.exists()) {
            Template template = load(vf);
            if (template != null) {
                template.compile();
            }
        }
    }
    return res;
}
 
Example #4
Source File: TemplateLoader.java    From restcommander with Apache License 2.0 6 votes vote down vote up
private static void scan(List<Template> templates, VirtualFile current) {
    if (!current.isDirectory() && !current.getName().startsWith(".") && !current.getName().endsWith(".scala.html")) {
        long start = System.currentTimeMillis();
        Template template = load(current);
        if (template != null) {
            try {
                template.compile();
                if (Logger.isTraceEnabled()) {
                    Logger.trace("%sms to load %s", System.currentTimeMillis() - start, current.getName());
                }
            } catch (TemplateCompilationException e) {
                Logger.error("Template %s does not compile at line %d", e.getTemplate().name, e.getLineNumber());
                throw e;
            }
            templates.add(template);
        }
    } else if (current.isDirectory() && !current.getName().startsWith(".")) {
        for (VirtualFile virtualFile : current.list()) {
            scan(templates, virtualFile);
        }
    }
}
 
Example #5
Source File: Router.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * In PROD mode and if the routes are already loaded, this does nothing.
 * <p/>
 * <p>In DEV mode, this checks each routes file's "last modified" time to see if the routes need updated.
 *
 * @param prefix The prefix that the path of all routes in this route file start with. This prefix should not end with a '/' character.
 */
public static void detectChanges(String prefix) {
    if (Play.mode == Mode.PROD && lastLoading > 0) {
        return;
    }
    if (Play.routes.lastModified() > lastLoading) {
        load(prefix);
    } else {
        for (VirtualFile file : Play.modulesRoutes.values()) {
            if (file.lastModified() > lastLoading) {
                load(prefix);
                return;
            }
        }
    }
}
 
Example #6
Source File: Play.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * Add a play application (as plugin)
 *
 * @param path The application path
 */
public static void addModule(String name, File path) {
    VirtualFile root = VirtualFile.open(path);
    modules.put(name, root);
    if (root.child("app").exists()) {
        javaPath.add(root.child("app"));
    }
    if (root.child("app/views").exists()) {
        templatesPath.add(root.child("app/views"));
    }
    if (root.child("conf/routes").exists()) {
        modulesRoutes.put(name, root.child("conf/routes"));
    }
    roots.add(root);
    if (!name.startsWith("_")) {
        Logger.info("Module %s is available (%s)", name, path.getAbsolutePath());
    }
}
 
Example #7
Source File: ApplicationClassloader.java    From restcommander with Apache License 2.0 5 votes vote down vote up
void scan(List<ApplicationClass> classes, String packageName, VirtualFile current) {
    if (!current.isDirectory()) {
        if (current.getName().endsWith(".java") && !current.getName().startsWith(".")) {
            String classname = packageName + current.getName().substring(0, current.getName().length() - 5);
            classes.add(Play.classes.getApplicationClass(classname));
        }
    } else {
        for (VirtualFile virtualFile : current.list()) {
            scan(classes, packageName + current.getName() + ".", virtualFile);
        }
    }
}
 
Example #8
Source File: TestRunnerPlugin.java    From restcommander with Apache License 2.0 5 votes vote down vote up
@Override
public void onLoad() {
    VirtualFile appRoot = VirtualFile.open(Play.applicationPath);
    Play.javaPath.add(appRoot.child("test"));
    for (VirtualFile module : Play.modules.values()) {
        File modulePath = module.getRealFile();
        if (!modulePath.getAbsolutePath().startsWith(Play.frameworkPath.getAbsolutePath()) && !Play.javaPath.contains(module.child("test"))) {
            Play.javaPath.add(module.child("test"));
        }
    }
}
 
Example #9
Source File: ApplicationClassloader.java    From restcommander with Apache License 2.0 5 votes vote down vote up
void scanPrecompiled(List<ApplicationClass> classes, String packageName, VirtualFile current) {
    if (!current.isDirectory()) {
        if (current.getName().endsWith(".class") && !current.getName().startsWith(".")) {
            String classname = packageName.substring(5) + current.getName().substring(0, current.getName().length() - 6);
            classes.add(new ApplicationClass(classname));
        }
    } else {
        for (VirtualFile virtualFile : current.list()) {
            scanPrecompiled(classes, packageName + current.getName() + ".", virtualFile);
        }
    }
}
 
Example #10
Source File: ClassStateHashCreator.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public synchronized int computePathHash(List<VirtualFile> paths) {
    StringBuffer buf = new StringBuffer();
    for (VirtualFile virtualFile : paths) {
        scan(buf, virtualFile);
    }
    // TODO: should use better hashing-algorithm.. MD5? SHA1?
    // I think hashCode() has too many collisions..
    return buf.toString().hashCode();
}
 
Example #11
Source File: ClassStateHashCreator.java    From restcommander with Apache License 2.0 5 votes vote down vote up
private void scan(StringBuffer buf, VirtualFile current) {
    if (!current.isDirectory()) {
        if (current.getName().endsWith(".java")) {
            buf.append( getClassDefsForFile(current));
        }
    } else if (!current.getName().startsWith(".")) {
        // TODO: we could later optimizie it further if we check if the entire folder is unchanged
        for (VirtualFile virtualFile : current.list()) {
            scan(buf, virtualFile);
        }
    }
}
 
Example #12
Source File: ClassStateHashCreator.java    From restcommander with Apache License 2.0 5 votes vote down vote up
private String getClassDefsForFile( VirtualFile current ) {

        File realFile = current.getRealFile();
        // first we look in cache

        FileWithClassDefs fileWithClassDefs = classDefsInFileCache.get( realFile );
        if( fileWithClassDefs != null && fileWithClassDefs.fileNotChanges() ) {
            // found the file in cache and it has not changed on disk
            return fileWithClassDefs.getClassDefs();
        }

        // didn't find it or it has changed on disk
        // we must re-parse it

        StringBuilder buf = new StringBuilder();
        Matcher matcher = classDefFinderPattern.matcher(current.contentAsString());
        buf.append(current.getName());
        buf.append("(");
        while (matcher.find()) {
            buf.append(matcher.group(1));
            buf.append(",");
        }
        buf.append(")");
        String classDefs = buf.toString();

        // store it in cache
        classDefsInFileCache.put( realFile, new FileWithClassDefs(realFile, classDefs));
        return classDefs;
    }
 
Example #13
Source File: ApplicationClasses.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the corresponding source file for a given class name.
 * It handles innerClass too !
 * @param name The fully qualified class name 
 * @return The virtualFile if found
 */
public static VirtualFile getJava(String name) {
    String fileName = name;
    if (fileName.contains("$")) {
        fileName = fileName.substring(0, fileName.indexOf("$"));
    }
    fileName = fileName.replace(".", "/") + ".java";
    for (VirtualFile path : Play.javaPath) {
        VirtualFile javaFile = path.child(fileName);
        if (javaFile.exists()) {
            return javaFile;
        }
    }
    return null;
}
 
Example #14
Source File: ServletWrapper.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public void serveStatic(HttpServletResponse servletResponse, HttpServletRequest servletRequest, RenderStatic renderStatic) throws IOException {

        VirtualFile file = Play.getVirtualFile(renderStatic.file);
        if (file == null || file.isDirectory() || !file.exists()) {
            serve404(servletRequest, servletResponse, new NotFound("The file " + renderStatic.file + " does not exist"));
        } else {
            servletResponse.setContentType(MimeTypes.getContentType(file.getName()));
            boolean raw = Play.pluginCollection.serveStatic(file, Request.current(), Response.current());
            if (raw) {
                copyResponse(Request.current(), Response.current(), servletRequest, servletResponse);
            } else {
                if (Play.mode == Play.Mode.DEV) {
                    servletResponse.setHeader("Cache-Control", "no-cache");
                    servletResponse.setHeader("Content-Length", String.valueOf(file.length()));
                    if (!servletRequest.getMethod().equals("HEAD")) {
                        copyStream(servletResponse, file.inputstream());
                    } else {
                        copyStream(servletResponse, new ByteArrayInputStream(new byte[0]));
                    }
                } else {
                    long last = file.lastModified();
                    String etag = "\"" + last + "-" + file.hashCode() + "\"";
                    if (!isModified(etag, last, servletRequest)) {
                        servletResponse.setHeader("Etag", etag);
                        servletResponse.setStatus(304);
                    } else {
                        servletResponse.setHeader("Last-Modified", Utils.getHttpDateFormatter().format(new Date(last)));
                        servletResponse.setHeader("Cache-Control", "max-age=" + Play.configuration.getProperty("http.cacheControl", "3600"));
                        servletResponse.setHeader("Etag", etag);
                        copyStream(servletResponse, file.inputstream());
                    }
                }
            }
        }
    }
 
Example #15
Source File: TestEngine.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public static List<String> allSeleniumTests() {
    List<String> results = new ArrayList<String>();
    seleniumTests("test", results);
    for (VirtualFile root : Play.roots) {
        seleniumTests(root.relativePath() + "/test", results);
    }
    Collections.sort(results);
    return results;
}
 
Example #16
Source File: PluginCollection.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public boolean serveStatic(VirtualFile file, Http.Request request, Http.Response response){
    for (PlayPlugin plugin : getEnabledPlugins()) {
        if (plugin.serveStatic(file, request, response)) {
            //raw = true;
            return true;
        }
    }
    return false;
}
 
Example #17
Source File: PluginCollection.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public Template loadTemplate(VirtualFile file){
    for(PlayPlugin plugin : getEnabledPlugins() ) {
        Template pluginProvided = plugin.loadTemplate(file);
        if(pluginProvided != null) {
            return pluginProvided;
        }
    }
    return null;
}
 
Example #18
Source File: PlayBuilder.java    From restcommander with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"deprecation"})
public void build(){
    
    Play.configuration = configuration;
    Play.classes = new ApplicationClasses();
    Play.javaPath = new ArrayList<VirtualFile>();
    Play.applicationPath = new File(".");
    Play.classloader = new ApplicationClassloader();
    Play.plugins = Collections.unmodifiableList( new ArrayList<PlayPlugin>());

}
 
Example #19
Source File: AgentConfigProvider.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public void saveConfigFile(CONFIG_FILE_TYPE configFile,
		String configFileContent) {

	if (configFile == null) {
		models.utils.LogUtils.printLogError("ERROR reading config: configFile is empty.");
	}

	// String nodeGroupConfFileLocation =
	// Play.configuration.getProperty("agentmaster.nodegroup.conf.file.location");

	// in test
	String nodeGroupConfFileLocation = "conf/"
			+ configFile.toString().toLowerCase(Locale.ENGLISH) + ".conf";
	try {

		VirtualFile vf = VirtualFile
				.fromRelativePath(nodeGroupConfFileLocation);
		File realFile = vf.getRealFile();

		boolean append = false;
		FileWriter fw = new FileWriter(realFile, append);
		fw.write(configFileContent);

		fw.close();
		models.utils.LogUtils.printLogNormal("Completed saveConfigFile with size: "
				+ configFileContent.length() + " at "
				+ DateUtils.getNowDateTimeStr());

	} catch (Throwable e) {
		models.utils.LogUtils.printLogError("Error in saveConfigFile."
				+ e.getLocalizedMessage());
		e.printStackTrace();
	}

}
 
Example #20
Source File: AgentUtils.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public static void saveStringToFile(String filePath, String fileContent) {

		if (filePath == null) {
			models.utils.LogUtils.printLogError("ERROR reading filePath: filePath is empty.");
		}

		// String nodeGroupConfFileLocation =
		// Play.configuration.getProperty("agentmaster.nodegroup.conf.file.location");

		// in test
		try {

			VirtualFile vf = VirtualFile.fromRelativePath(filePath);
			File realFile = vf.getRealFile();

			boolean append = false;
			FileWriter fw = new FileWriter(realFile, append);
			fw.write(fileContent);

			fw.close();
			models.utils.LogUtils.printLogNormal("Completed saveStringToFile with size: "
					+ fileContent.length() / VarUtils.CONVERSION_1024
					+ " KB Path: " + filePath + " at "
					+ DateUtils.getNowDateTimeStr());

		} catch (Throwable e) {
			models.utils.LogUtils.printLogError("Error in saveStringToFile."
					+ e.getLocalizedMessage());
			e.printStackTrace();
		}

	}
 
Example #21
Source File: ApplicationClassloader.java    From restcommander with Apache License 2.0 5 votes vote down vote up
List<ApplicationClass> getAllClasses(String basePackage) {
    List<ApplicationClass> res = new ArrayList<ApplicationClass>();
    for (VirtualFile virtualFile : Play.javaPath) {
        res.addAll(getAllClasses(virtualFile, basePackage));
    }
    return res;
}
 
Example #22
Source File: ApplicationClassloader.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * You know ...
 */
@Override
public Enumeration<URL> getResources(String name) throws IOException {
    List<URL> urls = new ArrayList<URL>();
    for (VirtualFile vf : Play.javaPath) {
        VirtualFile res = vf.child(name);
        if (res != null && res.exists()) {
            try {
                urls.add(res.getRealFile().toURI().toURL());
            } catch (MalformedURLException ex) {
                throw new UnexpectedException(ex);
            }
        }
    }
    Enumeration<URL> parent = super.getResources(name);
    while (parent.hasMoreElements()) {
        URL next = parent.nextElement();
        if (!urls.contains(next)) {
            urls.add(next);
        }
    }
    final Iterator<URL> it = urls.iterator();
    return new Enumeration<URL>() {

        public boolean hasMoreElements() {
            return it.hasNext();
        }

        public URL nextElement() {
            return it.next();
        }
    };
}
 
Example #23
Source File: ApplicationClassloader.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * You know ...
 */
@Override
public URL getResource(String name) {
    for (VirtualFile vf : Play.javaPath) {
        VirtualFile res = vf.child(name);
        if (res != null && res.exists()) {
            try {
                return res.getRealFile().toURI().toURL();
            } catch (MalformedURLException ex) {
                throw new UnexpectedException(ex);
            }
        }
    }
    return super.getResource(name);
}
 
Example #24
Source File: ApplicationClassloader.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * You know ...
 */
@Override
public InputStream getResourceAsStream(String name) {
    for (VirtualFile vf : Play.javaPath) {
        VirtualFile res = vf.child(name);
        if (res != null && res.exists()) {
            return res.inputstream();
        }
    }
    return super.getResourceAsStream(name);
}
 
Example #25
Source File: Router.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a route file.
 * If an action starts with <i>"plugin:name"</i>, replace that route by the ones declared
 * in the plugin route file denoted by that <i>name</i>, if found.
 *
 * @param routeFile
 * @param prefix    The prefix that the path of all routes in this route file start with. This prefix should not
 *                  end with a '/' character.
 */
static void parse(VirtualFile routeFile, String prefix) {
    String fileAbsolutePath = routeFile.getRealFile().getAbsolutePath();
    String content = routeFile.contentAsString();
    if (content.indexOf("${") > -1 || content.indexOf("#{") > -1 || content.indexOf("%{") > -1) {
        // Mutable map needs to be passed in.
        content = TemplateLoader.load(routeFile).render(new HashMap<String, Object>(16));
    }
    parse(content, prefix, fileAbsolutePath);
}
 
Example #26
Source File: ApplicationClassloader.java    From restcommander with Apache License 2.0 5 votes vote down vote up
List<ApplicationClass> getAllClasses(VirtualFile path, String basePackage) {
    if (basePackage.length() > 0 && !basePackage.endsWith(".")) {
        basePackage += ".";
    }
    List<ApplicationClass> res = new ArrayList<ApplicationClass>();
    for (VirtualFile virtualFile : path.list()) {
        scan(res, basePackage, virtualFile);
    }
    return res;
}
 
Example #27
Source File: CompilationException.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public CompilationException(VirtualFile source, String problem, int line, int start, int end) {
    super(problem);
    this.problem = problem;
    this.line = line;
    this.source = source;
    this.start = start;
    this.end = end;
}
 
Example #28
Source File: MessagesPlugin.java    From restcommander with Apache License 2.0 4 votes vote down vote up
static Properties read(VirtualFile vf) {
    if (vf != null) {
        return IO.readUtf8Properties(vf.inputstream());
    }
    return null;
}
 
Example #29
Source File: LogConsole.java    From restcommander with Apache License 2.0 4 votes vote down vote up
public static String readConfigFile(String fileName, String numLines) {
 int lineCountForDisplay = 0;
 if("all".equalsIgnoreCase(numLines)) {
     lineCountForDisplay = 0;
 } else {
     lineCountForDisplay = Integer.parseInt(numLines);
 }
    if (fileName == null) {
        return "ERROR reading config: configFile is empty.";
    }
    List<String> linesTotal = new ArrayList<String>();
    StringBuilder sb = new StringBuilder();
    
    String logDir = (fileName.contains("models.utils.LogUtils.printLogNormal")) ? "logs/" : "log/";
    
    String logFileLocation = logDir
            + fileName.toString().toLowerCase(Locale.ENGLISH) ;
    try {
       
        VirtualFile vf = VirtualFile
                .fromRelativePath(logFileLocation);
        File realFile = vf.getRealFile();
        FileReader fr = new FileReader(realFile);
        BufferedReader reader = new BufferedReader(fr);
        String line = null;
        while ((line = reader.readLine()) != null) {
            line = line + "<br />";
            linesTotal.add(line);
        }
    } catch (Throwable e) {
        models.utils.LogUtils.printLogError("Error in readConfigFile."
                + e.getLocalizedMessage());
       // e.printStackTrace();
    }
    
    if(VarUtils.IN_DETAIL_DEBUG){
    	models.utils.LogUtils.printLogNormal("linesTotal size:"+linesTotal.size());
    	models.utils.LogUtils.printLogNormal("lineCountForDisplay:"+lineCountForDisplay);
    	
    }
    if(lineCountForDisplay == 0) {
        for (int j= 0; j< linesTotal.size(); j++) {
            sb.append(linesTotal.get(j));
        }
    } else if (linesTotal.size() > lineCountForDisplay) {
        for (int j= (linesTotal.size() - lineCountForDisplay); j< linesTotal.size(); j++) {
            sb.append(linesTotal.get(j));
        }
    } else {
        for (int j= 0; j< linesTotal.size(); j++) {
            sb.append(linesTotal.get(j));
        }
    }
    
    if(VarUtils.IN_DETAIL_DEBUG){
    	models.utils.LogUtils.printLogNormal("linesTotal size:"+linesTotal.size());
    	
    }
    return sb.toString();
}
 
Example #30
Source File: PlayGrizzlyAdapter.java    From restcommander with Apache License 2.0 4 votes vote down vote up
public void serveStatic(GrizzlyRequest grizzlyRequest, GrizzlyResponse grizzlyResponse, RenderStatic renderStatic) {
    VirtualFile file = Play.getVirtualFile(renderStatic.file);
    if (file == null || file.isDirectory() || !file.exists()) {
        serve404(grizzlyRequest, grizzlyResponse, new NotFound("The file " + renderStatic.file + " does not exist"));
    } else {
        grizzlyResponse.setContentType(MimeTypes.getContentType(file.getName()));
        boolean raw = false;
        for (PlayPlugin plugin : Play.plugins) {
            if (plugin.serveStatic(file, Request.current(), Response.current())) {
                raw = true;
                break;
            }
        }
        try {
            if (raw) {
                copyResponse(Request.current(), Response.current(), grizzlyRequest, grizzlyResponse);
            } else {
                if (Play.mode == Play.Mode.DEV) {
                    grizzlyResponse.setHeader("Cache-Control", "no-cache");
                    grizzlyResponse.setHeader("Content-Length", String.valueOf(file.length()));
                    if (!grizzlyRequest.getMethod().equals("HEAD")) {
                        copyStream(grizzlyResponse, file.inputstream());
                    } else {
                        copyStream(grizzlyResponse, new ByteArrayInputStream(new byte[0]));
                    }
                } else {
                    long last = file.lastModified();
                    String etag = "\"" + last + "-" + file.hashCode() + "\"";
                    if (!isModified(etag, last, grizzlyRequest)) {
                        grizzlyResponse.setHeader("Etag", etag);
                        grizzlyResponse.setStatus(304);
                    } else {
                        grizzlyResponse.setHeader("Last-Modified", Utils.getHttpDateFormatter().format(new Date(last)));
                        grizzlyResponse.setHeader("Cache-Control", "max-age=" + Play.configuration.getProperty("http.cacheControl", "3600"));
                        grizzlyResponse.setHeader("Etag", etag);
                        copyStream(grizzlyResponse, file.inputstream());
                    }
                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}