How does spray find resources - e.g. javascript - spray

It was simple to build my first servlet with spray-io.
But the recources referenced in the header are never found.
< head>
...
< script src="javascript/jquery/jquery-1.9.1.js"/>
...
< / head>
In which directory does one have to put those recsources, or how can spray be directed to look up there?
Simple question, but I could not figure out.
Many thankx
Girgl

With Spray routing, I use these directives -
pathPrefix("css") { get { getFromResourceDirectory("css") } } ~
pathPrefix("js") { get { getFromResourceDirectory("js") } } ~
"css" and "js" have to be in src/main/resources directory

If you are using spray routing, then it should be easy, just provide a route for your static resources. For example you can do the following:
Let's say that your static resources are in /css, /js and /img folders:
def staticPrefixes = List("css", "js", "img") map { pathPrefix(_) } reduce { _ | _ }
with pathPrefix you are making each path a prefix of an unmatched path. Then you need a directive to extract path to static file from the request, for example you can do it like this:
def stripLeadingSlash(path: String) = if (path startsWith "/") path.tail else path
val staticPath =
staticPrefixes &
cache(routeCache()) &
extract(ctx ⇒ stripLeadingSlash(ctx.request.uri.path.toString))
then construct your route which would manage your resources:
val staticRoutes =
get {
staticPath { path ⇒
getFromResource(path.toString)
}
}

Related

Make root point to static webpage in Vapor

I have a static web page stored in the Public folder of my Vapor server. It has an index.html file. However when I navigate to root (http://localhost:8080) it displays Not found.
What I need to do make root point to index.html?
On Vapor 3, adding a home route worked for me. Specifically, I added the route in routes.swift like this:
router.get { req -> Future<View> in
let dir = DirectoryConfig.detect()
let path = dir.workDir + "/Public/index.html"
return try req.view().render(path)
}
For Vapor 4 ...
Inside routes.swift:
app.get { req -> EventLoopFuture<View> in
return req.view.render(app.directory.publicDirectory + "index.html")
}
This assumes you have a "Public" folder in your project directory root with an index.html file inside.
Also, in configure.swift:
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
Build project, run server, and point a browser to localhost:8080, you don't even have to specify localhost:8080/index.html, it just goes.
You could create a middleware to handle this.
import Vapor
final class IndexPageMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
// check if path is /
guard request.url.path == "/" else {
// otherwise pass to next responder
return next.respond(to: request)
}
// respond with index
let indexPath = request.application.directory.publicDirectory + "/index.html"
let response = request.fileio.streamFile(at: indexPath)
return request.eventLoop.makeSucceededFuture(response)
}
}
then in configure.swift add the following
app.middleware.use(IndexPageMiddleware())

Jenkins Job DSL: unknown return statement

some days ago I bumped into a code snippet used to override the default configuration of the Jenkins plugin "GitHub SCM Source" (unknown author):
Closure configOverride(String repo, int id, String cred) {
return {
it / sources / 'data' / 'jenkins.branch.BranchSource' << {
source(class: 'org.jenkinsci.plugins.github_branch_source.GitHubSCMSource') {
id(id)
scanCredentialsId(cred)
checkoutCredentialsId('SAME')
repoOwner('owner')
repository(repo)
includes('*')
buildOriginBranch('true')
buildOriginBranchWithPR('true')
buildOriginPRMerge('false')
buildOriginPRHead('false')
buildForkPRMerge('true')
buildForkPRHead('false')
}
}
}
}
All it's good except that I can't understand the following line:
it / sources / 'data' / 'jenkins.branch.BranchSource' << { ... }
I tried to find some explanation about the use of '/' in groovy but no luck. Maybe I don't know what exactly to search.
Could someone help me please with a link to the docs or a short explanation.
This is overloading of
operators
Groovy allows you to overload the various operators so that they can be used with your own classes. Consider this simple class:
class Bucket {
int size
Bucket(int size) { this.size = size }
Bucket plus(Bucket other) {
return new Bucket(this.size + other.size)
}
}
Just by implementing the plus() method, the Bucket class can now be used with the + operator like so:
def b1 = new Bucket(4)
def b2 = new Bucket(11)
assert (b1 + b2).size == 15
For / one would override T div(T x)
This code snippet is used in Jenkins DSL for the "multibranchPipelineJob". The closure configOverride is used to generate an XML object which replace the default configuration in config.xml on the following path "sources/data/jenkins.branch.BranchSource".

How to expose only some routes depending on host

I have a Vapor app that needs to do most things authenticated via HTTPS, but also needs to receive unauthenticated PUT requests via HTTP.
Can I conditionalize my route definitions based on the server's host name or authentication type? How can I capture that information from the server?
If you start up the different instances of vapor using the command line argument --hostname, you can put this code in your configure.swift and then include different routes as needed per host. You will then get 404s if invalid routes are attempted on the wrong hosts.
if let index = env.arguments.index(of: "--hostname")
{
if env.arguments.count > index
{
let hostname = env.arguments[index+1]
if hostname == "hostA"
{
// load routes
}
else
{
// load other routes
}
}
}
An alternative is to use custom Middleware. Something like this enables the hostname being called in the request to be inspected and prohibited routes can be re-directed:
struct HostSpecificMiddleware:Middleware
{
func respond( to request: Request, chainingTo next: Responder ) throws -> Future<Response>
{
let host = request.http.headers.filter{ (arg) in let (name, _) = arg; return name == "Host" }[0]
if host.1 == "hostA:8080"
{
if request.http.url.path == "routeA"
{
throw Abort.redirect(to:"routeNotAllowed")
}
}
return try next.respond(to: request)
}
}
You can then configure the middleware into routes in configure.swift using:
let soMW = HostSpecificMiddleware()
let users = router.grouped(uriUsers).grouped(soMW)
The second approach gives you much more flexibility.

drupal redirect language url alias

I would like to redirect urls that are using the wrong url alias.
Example, in my site I have:
English -> /prices/high-school -> node/112
Spanish -> (/es)/precios/high-school -> node/115
When a person or search engine reaches /es/prices/high-school a 404 is returned. What I would like is to redirect /es/prices/high-school to node/115.
I would like to do this in a general form, writing a module or using an existing one if possbile.
Thanks.
I already figured it out.
In the preprocess hook I need to check the page, strip the prefix and get the node id from the original id.
See code below:
if(current_path()=="search404")
{
$url = request_path();
if (startsWith($url,'es/') ||
startsWith($url,'de/') ||
startsWith($url,'it/') ||
startsWith($url,'fr/') )
{
$originalPath = substr($url,3,strlen($url)-3);
$path = drupal_lookup_path("source", $originalPath,"en");
if (isset($path))
{
$node = menu_get_object("node", 1, $path);
if (isset($node))
{
$prefix = substr($url,0,2);
$translated_paths = translation_path_get_translations('node/' . $node->nid);
if (isset($translated_paths) && array_key_exists ($prefix,$translated_paths))
{
if (isset($_GET['destination'])) {
unset($_GET['destination']);
}
$new_path = $translated_paths[$prefix];
drupal_goto($new_path, array(),301);
}
}
}
}
}
It won't be a solution to add different url aliases for the language versions? I mean:
node/112 -> /prices/high-school
node/115 -> /es/precios/escuela-secundaria
i18n module handles language based paths and redirects too.

How do I serve static files from a different URL with Dart?

With Dart, I've got awesome.html, but I'd like it to be /awesome. Is this purely an .htaccess (I'm using Apache) thing, or is there a way to go about this the Dart or "modern web development" way?
This .htaccess bit directs /awesome to /awesome.html:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .*[^/]$ %{REQUEST_URI}/ [L,R=301]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)/$ $1.html [L]
But then all my relative URL references (to css/js/images) break, and if I rewrite them from "assets/whatever" to "/assets/whatever" it'll break when working in the Dart Editor since it uses URLs like:
http://127.0.0.1:3030/Users/dave/Sites/my-dart-app/web/awesome.html
Ideas? Best practices? Thank you!
thanks for the question!
The answer depends on if you have a proxy or web server in front of your Dart server VM. If you have a proxy in front, then the proxy can do the URL rewriting before the request hits your Dart VM. This is a nice scenario anyway, because a proxy can do caching, SSL, load balancing, and more. The Dart VM is then just an "app server" in this scenario. I would recommend placing an industrial strength web server or proxy in front just as a best practice.
However, if you want to do URL masking and rewriting purely in Dart, here is some code. As Kai says in the comments above, this is generally a framework's job. But I'll include some code here anyway for fun. :)
import 'dart:io';
import 'dart:json';
class StaticFileHandler {
final String basePath;
StaticFileHandler(this.basePath);
_send404(HttpResponse response) {
response.statusCode = HttpStatus.NOT_FOUND;
response.outputStream.close();
}
String rewritePath(String path) {
String newPath = path;
if (path == '/' || path.endsWith('/')) {
newPath = '${path}index.html';
} else if (!path.endsWith('.html')) {
newPath = "${path}.html";
}
return newPath;
}
// TODO: etags, last-modified-since support
onRequest(HttpRequest request, HttpResponse response) {
String path = rewritePath(request.path);
final File file = new File('${basePath}${path}');
file.exists().then((found) {
if (found) {
file.fullPath().then((String fullPath) {
if (!fullPath.startsWith(basePath)) {
_send404(response);
} else {
file.openInputStream().pipe(response.outputStream);
}
});
} else {
_send404(response);
}
});
}
}
runServer(String basePath, int port) {
HttpServer server = new HttpServer();
server.defaultRequestHandler = new StaticFileHandler(basePath).onRequest;
server.onError = (error) => print(error);
server.listen('127.0.0.1', 1337);
print('listening for connections on $port');
}
main() {
var script = new File(new Options().script);
var directory = script.directorySync();
runServer("${directory.path}", 1337);
}
By the way, I've updated the rewritePath() function in Seth's code some so that it doesn't rewrite assets like .dart and .css files to .html, and so that it works w/ my client-side stuff living in /web.
String rewritePath(String path) {
String newPath = path;
if (path == '/' || path.endsWith('/')) {
newPath = '/web${path}index.html';
} else if (!path.endsWith('.html')) {
if (path.contains('.')) {
newPath = '/web${path}';
} else {
newPath = '/web${path}.html';
}
} else {
newPath = '/web${path}.html';
}
//peek into how it's rewriting the paths
print('$path -> $newPath');
return newPath;
}
It's of course super basic, and a framework that handles routing would certainly come in handy (would love to see what you're building #Kai).

Resources