I've just started looking at Ratpack, and my initial use case to as a simple development server. It seems quite trivial to get it to serve a directory of static files (in Groovy), I paraphrase this article:
#!/usr/bin/env groovy
#Grab('io.ratpack:ratpack-groovy:1.5.1')
import static ratpack.groovy.Groovy.ratpack
ratpack {
handlers {
files { dir "static" index }
}
}
I see there's an option to define an index page (for example, index.html), but this is static. I'd like it to serve a dynamic directory listing, as Apache can. I'd hoped this would simply require enabling a option, but I cannot find any indication such a thing exists.
I can't help feeling I have missed something. Can anyone point me in the right direction?
There's no built in directory listing feature. You would have to implement your own.
Related
Based on a video with Codeigniter4, I created the Modules folder on the ROOTPATH and the Controllers, Views..etc folders in the Modules folder. It works fine, but when I want to call my view file inside the module
<?php
namespace Modules\Giris\Controllers;
use App\Controllers\BaseController;
class IndexController extends BaseController
{
public function index(){
return view('Modules\Giris\Views\index');
}
}
I need to specify a very long path like How can I make it just like view('index') and call the file from the Views folder in that module if I write it in a module? I don't want to write "Modules\Login\Views" in short is this possible?
Thanks in advance for all the kind replies.
Because view requires a string you couldn't provide a namespaced reference as you might think you should. Furthermore the code adds a .php extension and the "view path" (defined in your config\paths file) as part of its process (see system/View/View.php and render()). Therefore without modifying Codeigniter (which could be done but would affect all your code) the easiest way is to simply declare a public property or constant and make reference to that instead. Also helps if you need to change the path at any point.
I.e. protected $path = 'Modules\Giris\Views\' and then view($this->path.'index'); is probably the easiest way.
I have already created a test blueprint that works, so I kinda got the idea, but I would like to make sure that I am approaching this correctly.
I want to extend the field type prompt to offer custom types alongside String, int, boolean etc.
This means I need to modify the templates, like templates/src/main/java/package/domain/Entity.java.ejs
My blueprint only had generators/client and generators/entity-client, so I guess I have to:
create generators/entity-server
create index.js
create files.js (can I copy that from here https://github.com/jhipster/generator-jhipster/blob/master/generators/entity-server/files.js ?)
create the templates in entity-server/templates
create generators/entity
copy and modify generators/entity/prompts.js: do I have to just write a new prompts.js, or do I have to copy over everything in generators/entity and only change what I would like to change ?
For the templates, can I copy them from the JHipster repo ?
Should I ? If not, why not and what is the alternative ?
If copying them is the right move, do I have to copy everything ? Or just the ones I want to modify ? (I haven't checked yet if I will need to modify everything)
When JHipster is updated, I suppose either I manually merge the new files, or I risk that slowly my code will differ more and more from the JHipster code ?
Is there a simpler method to achieve what I am trying to do ?
It would be nice if I could just say I want to add TypeX and TypeY to that prompt and provide limited templates that only cover those types, like a template for the import, one for the field, and one for the setter and getter, and if only the import is provided, a generic template is used.
I'll try to answer to all your questions.
First to create Blueprint I suggest to use https://github.com/jhipster/generator-jhipster-blueprint even in another folder and copy all you need for your current project. I think it's easier and you could choose which generator you want to add e.g. entity-server and entity.
Prompts phase
If you want to modify prompt phase you can merge your phase with the JHipster one like that
get prompting() {
const phaseFromJHipster = super._prompting();
const phaseFromMe = {
askForTheme: prompts.askForTheme,
setMySharedConfigOptions() {
this.configOptions.theme = this.theme;
}
};
return { ...phaseFromJHipster, ...phaseFromMe };
}
(source: https://github.com/avdev4j/samSuffit/tree/master/generators/client)
But by doing this you can't modify existing questions, for this case you should copy all existing questions into your blueprint.
Templates management
Your blueprint is linked with a JHipster version. As I used to say (in my talks) is that you should copy and modify templates from JHipster except for configuration files because it's a bit tricky to handle. For them, I prefer to use JHipster API like 'replaceContent()' or the needle API which allowed you to insert some code into some files (like a dependency in the pom.xml file).
Of course you can use the way you want, but with experiences I prefer to control my templates and merge them when I upgrade the JHipster version.
You should only copy the templates you want to modify, merge JHipster and your writing phase. JHipster use yeoman, which use memfs to handle file generation. Every files are created in memory and dumped at the final step. You can easily override a file without performance compromise.
get writing() {
const phaseFromJHipster = super._writing();
/* eslint-disable */
const phaseFromSam = {
writeSamFiles() {
if (this.clientFramework === 'angularX') {
return writeAngularFiles.call(this);
}
}
};
/* eslint-enable */
return { ...phaseFromJHipster, ...phaseFromSam };
}
JHipster upgrade
I suggest you to check templates when upgrading JHipster and apply modifications if needed. Otherwise, you could have bugs. Also, I suggest to set a definitive (like 6.1.0) version of JHipster in your blueprint package.json.
As far I know there is no way to do what you want to do. I'm thinking of a way to modify prompts easily without copying all other questions, if you want to contribute ;).
You can check my blueprint sample I use to show in my talks:
https://github.com/avdev4j/samSuffit/
I hope It can help you can, feel free to ask more.
regards,
I'm porting a Symfony 1.2 project to Symfony 2.x. I'm currently running the latest 2.1.0-dev release.
From my old project I have a class called Tools which has some simple functions for things like munging arrays into strings and generating slugs from strings. I'd like to use this class in my new project but I'm unclear how to use this class outside of a bundle.
I've looked at various answers here which recommend changing app/autoload.php but my autoload.php looks different to the ones in the answers, maybe something has changed here between 2.0 and 2.1.
I'd like to keep my class in my src or app directories as they're under source control. My vendors directory isn't as I'm using composer to take care of that.
Any advice would be appreciated here.
Another way is to use the /app/config/autoload.php:
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
$loader = require __DIR__.'/../vendor/autoload.php';
$loader->add( 'YOURNAMESPACE', __DIR__.'/../vendor/YOURVENDOR/src' );
// intl
if (!function_exists('intl_get_error_code')) {
require_once _DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';
$loader->add('', __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs');
}
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;
Just replace YOURNAMESPACE and YOURVENDOR with your values. Works quite well for me, so far.
You're correct, I stumbled upon the changes in autoload from 2.0 to 2.1. The above code works fine with the latest version, to which I upgraded my project ;-)
For a simple case like this the quickest solution is creating a folder (for example Common) directly under src and put your class in it.
src
-- Common
-- Tools.php
Tools.php contains your class with proper namespace, for example
<?php
namespace Common;
class Tools
{
public static function slugify($string)
{
// ...
}
}
Before calling your function do not forget the use statement
use Common\Tools;
// ...
Tools::slugify('my test string');
If you put your code under src following the proper folder structure and namespace as above, it will work without touching app/autoload.php.
I'm planning to integrate Groovy Script Engine to my game so it will give the game nice moddability but how do you prevent players from writing evil scripts like deleting all files on C: drive?
Groovy includes library like java.io.File by default so it will be pretty easy to do once they decided to write such scripts.
I guess I can't prevent users from writing something like while(1==1){} but is there anyway to at least not let them allow to delete/modify files or something dangerous for PCs?
There's a blog post by Cedric Champeau on customising the Groovy Compilation process, the second part of it shows how to use SecureASTCustomizer and CompilerConfiguration to limit what Scripts can do (and then has examples of defining your own AST checks for System.exit, etc...
Look into the SecurityContext class.
The Groovy Web Console appears to have already solved this problem, because it won't execute something like System.exit(1). The source code is available on GitHub, so you can see how they did it.
If you're not sure where to start, I suggest getting in touch with the author, who should be able to point you in the right direction.
I know this is a old question. I'm posting this as it might help some people out there.
We needed to allow end-users to upload Groovy scripts and execute them as part of a web application (that does a lot of other things). Our concern was that within these Groovy scripts, some users might attempt to read files from the file system, read System properties, call System.exit(), etc.
I looked into http://mrhaki.blogspot.com/2014/04/groovy-goodness-restricting-script.html but that will not prevent an expert Groovy developer from bypassing the checks as pointed out by others in other posts.
I then tried to get http://www.sdidit.nl/2012/12/groovy-dsl-executing-scripts-in-sandbox.html working but setting the Security Manager and Policy implementation at runtime did not work for me. I kept running into issues during app server startup and web page access. It seemed like by the time the Policy implementation took hold, it was too late and "CodeSources" (in Java-Security-speak) already took its access settings from the default Java policy file.
I then stumbled across the excellent white paper by Ted Neward (http://www.tedneward.com/files/Papers/JavaPolicy/JavaPolicy.pdf) that explained quite convincingly that the best approach (for my use case) was to set the Policy implementation on JVM startup (instead of dynamically later on).
Below is the approach that worked for me (that combines Rene's and Ted's approaches). BTW: We're using Groovy 2.3.10.
In the [JDK_HOME]/jre/lib/security/java.security file, set the "policy.provider" value to "com.yourcompany.security.MySecurityPolicy".
Create the MySecurityPolicy class:
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AllPermission;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.util.HashSet;
import java.util.Set;
public class MySecurityPolicy extends Policy {
private final Set<URL> locations;
public MySecurityPolicy() {
try {
locations = new HashSet<URL>();
locations.add(new URL("file", "", "/groovy/shell"));
locations.add(new URL("file", "", "/groovy/script"));
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
}
#Override
public PermissionCollection getPermissions(CodeSource codeSource) {
// Do not store these in static or instance variables. It won't work. Also... they're cached by security infrastructure ... so this is okay.
PermissionCollection perms = new Permissions();
if (!locations.contains(codeSource.getLocation())) {
perms.add(new AllPermission());
}
return perms;
}
}
Jar up MySecurityPolicy and drop the jar in [JDK_HOME]/jre/lib/ext directory.
Add "-Djava.security.manager" to the JVM startup options. You do not need to provide a custom security manager. The default one works fine.
The "-Djava.security.manager" option enables Java Security Manager for the whole application. The application and all its dependencies will have "AllPermission" and will thereby be allowed to do anything.
Groovy scripts run under the "/groovy/shell" and "/groovy/script" "CodeSources". They're not necessarily physical directories on the file system. The code above does not give Groovy scripts any permissions.
Users could still do the following:
Thread.currentThread().interrupt();
while (true) {} (infinite loop)
You could prepend the following (dynamically at runtime) to the beginning of every script before passing it onto the Groovy shell for execution:
#ThreadInterrupt
import groovy.transform.ThreadInterrupt
#TimedInterrupt(5)
import groovy.transform.TimedInterrupt
These are expalined at http://www.jroller.com/melix/entry/upcoming_groovy_goodness_automatic_thread
The first one handles "Thread.currentThread().interrupt()" a little more gracefully (but it doesn't prevent the user from interupting the thread). Perhaps, you could use AST to prevent interupts to some extent. In our case, it's not a big issue as each Groovy script execution runs in its own thread and if bad actors wish to kill their own thread, they could knock themselves out.
The second one prevents the infinite loop in that all scripts time out after 5 seconds. You can adjust the time.
Note that I noticed a performance degradation in the Groovy script execution time but did not notice a significant degradation in the rest of the web application.
Hope that helps.
I want to set up include paths (and other paths, like view script paths) based on the module being accessed. Is this safe? If not, how could I safely set up include paths dynamically? I'm doing something like the code below (this is from a controller plugin.)
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {
$modName = $request->getModuleName();
$modulePath = APP_PATH.'/modules/'.$modName.'/classes';
set_include_path(get_include_path().PATH_SEPARATOR.$modulePath);
}
I'm not sure whether it is safe or not, but it doesn't sound like the best practice. What if someone entered a module name like ../admin/? You should sanitize the module name before using it.
It's fine as long as you sanitize your variables before using them, but it won't be very performant. Fiddling with include paths at runtime causes a serious impact performance.
You're trying to load models/helpers per module? You should look at Zend_Application:
Zend_Application provides a bootstrapping facility for applications which provides reusable resources, common- and module-based bootstrap classes and dependency checking. It also takes care of setting up the PHP environment and introduces autoloading by default.
Emphasis by me