How to store JSP views in classpath instead of webapp? - spring

I want to store JSP files in src/main/resources/templates
but after setup i get not found error. It seems that spring.mvc.view.prefix only supports path for folder in wepabb folder.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Not Found, status=404).
application.properties
spring.mvc.view.prefix = classpath*:/templates/
spring.mvc.view.suffix = .jsp
Controller
#Controller
public class DemoController {
#RequestMapping("/")
public String index() {
return "test";
}
}
And this is the src file structure:
├───main
│ ├───java
│ │ └───com
│ │ └───example
│ │ └───demo
│ │ DemoApplication.java
│ │ DemoController.java
│ ├───resources
│ │ └───templates
│ │ test.jsp
│ └───webapp

The solution (from Dave Newton) is to put jsp file in folder
src/main/resources/META-INF/resources/WEB-INF/templates/
and set
spring.mvc.view.prefix = /WEB-INF/templates/
spring.mvc.view.suffix = .jsp
Folder src/main/resources/META-INF/resources works like src/main/webapp

Related

Best way to override single method in Illuminate\Foundation\Application through service provider

I just made changes to the application structure for my Laravel application. It works well when runnning tests (for the Http controllers). The problem is when i try to run artisan commands (that literally need to access "getNamespace()" method), it wont resolve the namespaces.
Here are the composer.json:
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/",
"Modules\\": "modules/"
},
"files": [
"app/Helpers/app.php",
"app/Helpers/form.php",
"app/Helpers/view.php"
]
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
I do aware that i can add Modules\ModuleA, Modules\ModuleB to the composer json, but that put alot of work. So i decided to override the getNamespace() method instead, but what is the best way to override single method illuminate/foundation/xxx classes through service provider?
Folder tree:
laravel-project/
├── app/
│ ├── Exception
│ ├── Providers
│ └── ...
├── modules/
│ ├── ModuleA/
│ │ ├── Services
│ │ ├── Http/
│ │ │ ├── Controllers
│ │ │ └── Requests
│ │ └── Models
│ └── ModuleB/
│ └── ...
├── tests
└── ...
If you want to override a single method in Illuminate\Foundation\Application through a service provider in Laravel, you can use the following steps:
Create a new service provider by running the command php artisan make:provider YourServiceProvider in your terminal.
In your YourServiceProvider class, extend the Illuminate\Support\ServiceProvider class.
Override the register() method in your YourServiceProvider class. In this method, you can bind your custom implementation of the method you want to override to the container. For example, if you want to override the loadEnvironmentFrom() method, you can do so as follows:
use Illuminate\Foundation\Application;
class YourServiceProvider extends ServiceProvider
{
public function register(){
$this->app->bind(Application::class, function ($app) {
return new class($app) extends Application {
public function loadEnvironmentFrom($file)
{
// Your custom implementation here
}
};
});
}
}
Then in your config.app file, add the service provider to the list of providers:
'providers' => [
// Other service providers
App\Providers\YourServiceProvider::class,
],
This way, the method you've overridden will use your custom implementation instead of the default implementation in Illuminate\Foundation\Application.
Hope this helps

Package: the importance of naming files when using initialization

I wrote a structure like display in the tree below.
.
├── README.md
├── db
│ └── db.go
├── go.mod
├── go.sum
├── handler
│ ├── category.go
│ ├── handler.go
│ └── users.go
├── main.go
├── model
│ ├── category.go
│ ├── model.go
│ └── users.go
└── route
├── category.go // init() ❌ error to using package vars
├── route.go // init() writing package vars
└── users.go // init() ✅ no error to using package vars
All the files in the packages except the one with the same name (route/route.go, handler/handler.go,...) are generated automatically. For these files to extend the package variables, I use golang's func init(){} ex:
route/route.go
package route
import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
var (
// public routes
e *echo.Echo = echo.New()
// restricted routes
r *echo.Group = e.Group("/restricted")
)
func init() {
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:3000"},
AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE, echo.OPTIONS},
AllowHeaders: []string{echo.HeaderAuthorization, echo.HeaderContentType},
}))
e.Use(middleware.Recover())
r.Use(middleware.JWT([]byte("secret")))
}
route/category.go
package route
import (
"github.com/username/project/handler"
)
func init() {
r.GET("/category", handler.ListCategory)
r.POST("/category/add", handler.CreateCategory)
r.GET("/category/:id", handler.ReadCategory)
r.PUT("/category/edit/:id", handler.UpdateCategory)
r.DELETE("/category/:id", handler.DeleteCategory)
}
route/user.go
package route
import (
"github.com/username/project/handler"
)
func init() {
r.GET("/users", handler.ListUsers)
r.POST("/users/add", handler.CreateUser)
r.PUT("/users/edit/:id", handler.UpdateUser)
r.DELETE("/users/:id", handler.DeleteUser)
e.POST("/auth", handler.Login)
e.POST("/lost", handler.Lost)
e.POST("/password", handler.Password)
}
As you already understood, the category.go init() starts before the router.go init(), which is described here: Go Package initialization.
After coding a pretty program that auto writes routes like route/category.go. I realize that to solve this problem, I will have to rename router/router.go to router/0router.go (it works) so that it is still at the top of the pillar, but it's not a good approach.
Have any suggestions for this tree and the use of golang ini() ?
Thank you
Use variable declaration expressions to avoid file name dependencies. The assignments execute before the init() functions that reference the variables.
var (
// public routes
e *echo.Echo = newPublic()
// restricted routes
r *echo.Group = newRestricted()
)
func newPublic() *echo.Echo {
e := echo.New()
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:3000"},
AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE, echo.OPTIONS},
AllowHeaders: []string{echo.HeaderAuthorization, echo.HeaderContentType},
}))
e.Use(middleware.Recover())
}
func newRestricted() *echo.Group {
r := e.Group("/restricted")
r.Use(middleware.JWT([]byte("secret")))
return r
}

Gulp destination relative to source

I am trying to parse all SCSS files in all folders, and I need them to be in relative destinations to the original file.
Here is the representation of folder structure I want (basically, scss files in scss folders need to be saved as css files in css folder next to the original scss folder) and rogue scss files (not in scss folder) should have css file saved in same destination as the scss file.
html
│ README.md
│
└───app_abc
│ │ index.php
│ │ something_else.php
│ │
│ └───styles
│ └───scss
│ │ _mixins.scss
│ │ layout.scss
│ │ content.scss
│ │
│ └───css
│ layout.css
│ content.css
│
└───app_def
│ │ index.php
│ │ something_else.php
│ │ rogue.scss
│ │ rogue.css
│ │
│ └───styles
│ └───scss
│ │ _mixins.scss
│ │ layout.scss
│ │ content.scss
│ │
│ └───css
│ layout.css
│ content.css
└───app_ghi
...
I tried playing with it for hours yesterday and today, but to no avail. I can make it to create the CSS file in the same folder, but that's not what I want.
Here is my gulpfile.js (there is a lot of "debug" stuff in it).
var gulp = require('gulp'),
sass = require('gulp-sass'),
path = require('path'),
through = require('through2');
const debug = require('gulp-debug');
const sassFiles = './html/**/[^_]*.scss';
function parsePath() {
return through.obj(function (file, enc, cb) {
console.log(file.base);
console.log(file.cwd);
console.log(file.path);
console.log(file.name);
console.log(path.relative(file.cwd, file.path));
console.log(path.relative(path.join(file.cwd, file.base), file.path))
console.log(path.relative(path.join(file.cwd, file.base), file.path).replace('scss', 'css'))
console.log(file.path.replace(file.name, '').replace('scss', 'css'))
cb();
});
}
gulp.task('sass', function(){
return gulp.src(sassFiles)
.pipe(debug({title: 'test:', minimal: false}))
.pipe(parsePath())
.pipe(sass().on('error', sass.logError))
//.pipe(gulp.dest('css'))
//.pipe(gulp.dest(function (file) {
//return file.path.replace('scss', 'css');
//return path.relative(path.join(file.cwd, file.base), file.path).replace('scss', 'css');
//}))
.pipe(gulp.dest(function (file) {
console.log(file.base);
return file.base;
}));
});
gulp.task('watch', ['sass'], function(){
gulp.watch(sassFiles, ['sass']);
})
Thanks for any help.
Ps.: In any case it was needed, I am running on Debian Jessie x64.
Pps.: I did google and read quite a lot of stackoverflow threads, but none of them had a solution to my problem (well, if it had, it didn't work for me).
This is working. It handles your rogueSASS files correctly and creates a css folder where you want it with the css files in there.
IMPORTANT : The gulp.src files are relative to where your gulpfile.js is located. For this code I have it in the HTML folder - at the same level as the app_xxx folders. If you put it somewhere else you will have to modify the sassFiles and rogueSassFiles declarations.
var gulp = require("gulp");
var sass = require("gulp-sass");
// flatten can be useful to solve tricky long directory changes
// var flatten = require("gulp-flatten");
var rename = require("gulp-rename");
// var using = require("gulp-using");
const sassFiles = './**/styles/scss/*.scss';
const rogueSassFiles = ['./**/*.scss', '!./**/styles/**'];
gulp.task('watch', ['sass', 'rogueSASS'], function () {
gulp.watch( sassFiles, ['sass']);
gulp.watch( rogueSassFiles, ['rogueSASS']);
})
gulp.task('sass', function () {
return gulp.src(sassFiles)
.pipe(sass().on('error', sass.logError))
// remove the "scss" folder name from the end of the directory list
.pipe(rename(function (path) {
var temp = path.dirname.slice(0, -4);
path.dirname = temp + "css";
}))
.pipe(gulp.dest('.'))
})
gulp.task('rogueSASS', function () {
return gulp.src(rogueSassFiles)
// gulp-using shows which files are getting through gulp.src !!
// .pipe(using())
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('.'))
})
These could be made into one task.

Static files not working in Django development

I'm trying to follow the section in the Django docs called Managing static files. I am interested in finding out:
What I am doing wrong.
Or, what is wrong with the Django docs.
1) Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
In the default settings.py file:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles', #<****HERE*****
)
2) In your settings file, define STATIC_URL, for example: STATIC_URL = '/static/'
In the default settings.py:
STATIC_URL = '/static/'
3) In your templates, either hardcode the url like /static/my_app/myexample.jpg
In mysite2/mysite2/views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse('''
<h2>Hello</h2>
<img src="/static/mysite2/Aerial03.jpg">
''')
4) Store your static files in a folder called static in your app. For example: my_app/static/my_app/myimage.jpg.
Here is my directory structure:
(django186p34)~/django_projects$ tree mysite2
mysite2
├── db.sqlite3
├── manage.py
└── mysite2
├── __init__.py
├── settings.py
├── static #<****HERE*****
│   └── mysite2
│   └── Aerial03.jpg
├── urls.py
├── views.py
└── wsgi.py
4 directories, 13 files
But after starting the server:
(django186p34)~/django_projects/mysite2$ python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
November 26, 2015 - 02:44:57
Django version 1.8.6, using settings 'mysite2.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
And then navigating in my browser to:
http://localhost:8000/
I see the text:
Hello
but the image is not found:
[Error] Failed to load resource: the server responded with a status of 404 http://localhost:8000/static/mysite2/Aerial03.jpg
I've tried many combinations of urls in my html and nothing works.
Here is settings.py in its entirety(I made no changes):
"""
Django settings for mysite2 project.
Generated by 'django-admin startproject' using Django 1.8.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pmaup3%)m09cs2goldduw2iogso%(#8cz0s-zmr%*e'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'mysite2.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite2.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
This fixed things:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite2', #<*****HERE*****
)
And if you organize things so that you have apps inside your project, e.g.:
(django186p34)~/django_projects$ tree mysite3
mysite3
├── db.sqlite3
├── manage.py
├── myapp
│   ├── __init__.py
│   ├── admin.py
│   ├── migrations
│   │  
│   │  
│   ├── models.py
│   ├── static
│   │   └── myapp
│   │   └── Aerial03.jpg
│   ├── tests.py
│   ├── urls.py
│   └── views.py
└── mysite3
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
8 directories, 24 files
Then in settings.py add your app name to INSTALLED_APPS:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', #<*****HERE*****
)
Everything else in the default settings.py stays the same. However, the urls are different:
mysite3/mysite3/urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^myapp/', include('myapp.urls')),
]
mysite3/myapp/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
And in your browser, the url becomes:
http://localhost:8000/myapp/
myapp/views.py:
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse('''
<h2>Hello</h2>
<img src="/static/myapp/Aerial03.jpg">
''')

Can't get gulp-ruby-sass or gulp-sass to work at all

I'm trying to use gulp-ruby-sass and/or gulp-sass but neither are working for me and think i've got it all set up correctly. I've looked at a bunch of other SO posts but nothing works for me as yet.
I've got another gulp task which is recursively copying an assets directory and index.html from src to dist and this works every time.
To test the sass setup is correct i run a vanilla sass compile and then run gulp; the sass changes work and render via the recursive copy. Here's the commands for that sass test:
$ sass ./sass/main.scss ./src/assets/css/main.css
$ gulp
Forgetting the vanilla sass test and back to the gulp sass issue here - in my gulpfile i'm running the gulp sass task before i run the recursive copy task, so if it worked then the sass changes should be applied and copied. At least that's what i thought.
Here's my dir structure showing relevant files:
├── src
│ ├── index.html
│ └── assets
│ ├── css
│ │ └── main.css
│ ├── js
│ │ └── app.js
│ └── img
│ └── etc.jpg
│
├── dist
│ └── index.html ( from ./src via recursive copy)
│ └── assets
│ └── (same as ./src/assets via recursive copy)
│
├── sass
│ ├── main.scss
│ ├── _partial1.scss
│ ├── _partial2.scss
│ └── etc ...
│
├── gulpfile.js
│
├── node_modules
│ └── etc ...
│
└── bower_components
└── etc ...
In gulpfile.js there are a couple of file mapping objects which work fine for the recursive copy of src/assets/. But for the sake of testing the gulp-ruby-sass task i'm hard-coding the sass/css paths to remove the possibility of the file mapping as an error.
For the record I'm running on OSX Maverics 10.9.5 and think i have the correct environment setup:
$ ruby -v
ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin13]
$ sass -v
Sass 3.4.9 (Selective Steve)
Here's my gulpfile.js showing approaches that i've tried so far, with gulp-sass related task commented-out:
var gulp = require('gulp');
var watch = require('gulp-watch');
var gsass = require('gulp-ruby-sass');
// var gsass = require('gulp-sass');
var gutil = require('gulp-util');
// Base paths:
var basePaths = {
srcRoot: './src/',
distRoot: './dist/',
bowerRoot: './bower_components/'
};
// File paths:
var filePaths = {
sassRoot: basePaths.srcRoot + 'sass/',
assetsBuildRoot: basePaths.srcRoot + 'assets/',
jqMin: basePaths.bowerRoot + 'jquery/dist/jquery.min.js',
html: basePaths.srcRoot + 'index.html'
};
// With gulp-ruby-sass
gulp.task('compile-sass', function() {
gulp.src('./sass/main.scss')
.pipe(gsass({sourcemap: true, sourcemapPath: './sass/'}))
.on('error', function (err) { console.log(err.message); })
.pipe(gulp.dest('./src/assets/css'));
});
// With gulp-sass
// gulp.task('gsass', function () {
// gulp.src('./sass/*.scss')
// .pipe(gsass())
// .pipe(gulp.dest('./src/assets/css'));
// });
// Assets directory copied recursively from /src to /dist:
gulp.src(filePaths.assetsBuildRoot + '**/*.*', {base : basePaths.srcRoot})
.pipe(gulp.dest(basePaths.distRoot));
// Copy index.html from /src to /dist:
gulp.src(filePaths.html)
.pipe(gulp.dest(basePaths.distRoot));
gulp.task('default', function() {
// With gulp-ruby-sass
// return gulp.src('./sass/main.scss')
// .pipe(gsass({sourcemap: true, sourcemapPath: './sass/'}))
// .on('error', function (err) { console.log(err.message); })
// .pipe(gulp.dest('./src/assets/css'));
// gulp.watch('compile-sass');
console.log('You reached the finishing line');
});
I have tried allsorts to bugfix, e.g.:
Removing all of the vanilla sass compiled .css files and running the gulp compile, but no .css is produced.
Also tried removing all of the *.map files generated by the vanilla sass compile then running gulp but no dice.
Can anyone see anything glaringly and obviously wrong?
Thanks in advance.
If you are using Sass >= 3.4, you will need to install gulp-ruby-sass version 1.0.0-alpha:
npm install --save-dev gulp-ruby-sass#1.0.0-alpha
In this new version, gulp-ruby-sass is a gulp source adapter and the syntax has changed slightly. Instead of:
gulp.task('compile-sass', function() {
gulp.src('./sass/main.scss')
task code here
});
The new syntax is:
gulp.task('compile-sass', function() {
return sass('./sass/main.scss')
task code here
});
You can find more info in the new version documentation including the new syntax for sourcemaps. https://github.com/sindresorhus/gulp-ruby-sass/tree/rw/1.0

Resources