Grails URLMapping deep path - grails

I have a URL like:
/test/abs/rdc/tx.js
and I need to be able to get the /abs/rdc/tx.js part for my controller.
I tried (in URLMapping):
/test/$target**
and it returns everything but the .js
I have
grails.mime.file.extensions = true
Any ideas?
UrlMapping and file name extension didn't work as it always returns .html

Grails 2.0 has made some changes to the way the format is parsed. Using the example from the link you provided, just update the code to use response.format:
def path = params.path
if (!FilenameUtils.getExtension(path) && response.format) {
path += ".${response.format}"
}
More info is in the manual under Content Negotiation. Scroll down to the section titled Request format vs. Response format.

You can try this one:
//Grails 2.3.x
"/$controller/$action?/$id?(.${format})?"{
constraints {
// apply constraints here
}
}

Related

Zend Framework 2 Get controller name from layout

I have the follow routes to different controllers and actions, that all shows the same layout and different views, example:
http://<my domain>/controllername1/action1
http://<my domain>/controllername1/
http://<my domain>/controllername2/action1
http://<my domain>/controllername3/action1
How can I get the controller name that loads the Layout in the Layout code?, something that returns: "controllername1", "controllername2" or "controllername3"
The goal is to identify in which section I'm of my site and make some customization in layout.
I checked similar replies but are for old versions of Zend Framework.
Clarification:
The idea is to get the controller name from the Layout code, not pass it from the controller code. Maybe isn't possible? Other answers are for older versions of ZendFramework (beta versions), and maybe is a more straightforward way now.
Edited: more information
I can set in my Module.php file the follow code on onBootstrap($e):
public function onBootstrap($e)
{
// (...) Other code
$application = $e->getParam('application');
$viewModel = $application->getMvcEvent()->getViewModel();
// Parsing URI to get controller name
$viewModel->controllerName = trim($_SERVER['REQUEST_URI'],'/');
if (substr_count($viewModel->controllerName, '/')) {
$viewModel->controllerName = substr($viewModel->controllerName, 0, strpos($viewModel->controllerName, '/'));
}
}
And then from the Layout code use it as follow:
echo $this->layout()->controllerName;
The first problem is that the follow piece of code should be replaced with something (more "beautiful") using ZF2 functions to get Controller name:
(...)
// Parsing URI to get controller name
$viewModel->controllerName = trim($_SERVER['REQUEST_URI'],'/');
if (substr_count($viewModel->controllerName, '/')) {
$viewModel->controllerName = substr($viewModel->controllerName, 0, strpos($viewModel->controllerName, '/'));
}
I want to avoid inject the Controller name from all controllers/actions: that is solved by using Module.php, but maybe is a more direct way.
Thanks!
You're looking for this link: How to get the controller name, action name in Zend Framework 2
$this->getEvent()->getRouteMatch()->getParam('action', 'index');
$this->getEvent()->getRouteMatch()->getParam('controller', 'index');
Otherwise you have the same question (and answer(s)) here : ZF2 - Get controller name into layout/views
MvcEvent – get NAMESPACE / Module Name from Layout
http://samsonasik.wordpress.com/2012/07/27/zend-framework-2-mvcevent-layout-view-get-namespace/
I didn't test but it seems correct : http://pastebin.com/HXbVRwTi
I know that this is an old question but there is a simple answer that should be noted here:
$this->getHelperPluginManager()->getServiceLocator()->get('Application')->getMvcEvent()->getRouteMatch()->getParam('action')
this will return any route param, 'action' in this case.
This code can be used in view or in layout.

How to create link in grails webflow without execution state in url?

I want to display an image in my webflow wich comes from my domain object.
The domain object has an byte[] Array holding an image. The "image" method in my controller delivers the image to browser. This works fine.
In my webflow I'm doing this:
<img src="${createLink(controller:'shop', action:'image', id:shopInstance.id)}">
I can see the image in my frontend (in browser) but it reloads each time i click "next" or change my state in webflow because the image url contains a param that changes each event in webflow.
The created image url (example above) looks like this:
http://localhost:8080/project/shop/image/2?execution=e2s5
I don't want that the execution param is delivered into my image url. How can i fix this?
My guess is that this is a bug. A work around I used is the following
${createLink(controller: 'controller', action: 'action').replaceAll(/\?.*$/, "")}
This will use a regex to remove the execution parameter.
Not sure why you're getting that execution param but you could try: <img src="${resource(dir: 'shop/image', file: shopInstance.id)}"> and make sure the UrlMappings.groovy file has a mapping for 'ship/image' to the proper controller.
As of Grails 2.0.4, look at ApplicationTagLib.groovy, you can see
if (request['flowExecutionKey']) {
params."execution" = request['flowExecutionKey']
urlAttrs.params = params
if (attrs.controller == null && attrs.action == null && attrs.url == null && attrs.uri == null) {
urlAttrs[LinkGenerator.ATTRIBUTE_ACTION] = GrailsWebRequest.lookup().actionName
}
}
So Grails is forcing every link rendered within webflow to include that execution params. It looks like bug to me.

Printing in icefaces

I would like to print reports in icefaces, but could got find any proper method for it. Please guide me for implementation of the same in my project.
I've used the ice:outputResource tag to let the user download a PDF report file. The resource attribute of that tag should point a managed bean property that implements com.icesoft.faces.context.Resource.
after getting idea from JOTN I'm finally able to put it together.
We can use the outputresource tag to link to any type of resource, not only static ones but also dynamically generated files(on the fly).
Let us have a look at the following example:
JSF Page:
..
..
<ice:outputResource id="outputResource1" attachment="false" fileName="File1.pdf" label="Click to download attachment" mimeType="application/pdf" rendered="true" resource="#{ReportParam01.reportfilers}" shared="false"/>
..
..
Here I've observed that the outputresource link won't appear until the file is actually generated(i case of on the fly documents).
Let us assume we wish to generate a pdf file dynamically. The following steps will link it to the above mentioned outputrespurce.
Managed Bean:
public class....{
....
// This is the resource linked to the <ice:outputresource> tag.
// Encapsulation has been done to link it.
Reource reportfilers;
....
public void createDocument() {
Document reportDoc = new Document(PageSize.A4);
File file1 = new File("Report.pdf");
PdfWriter.getInstance(reportDoc, new FileOutputStream(f));
// writing to pdf code continues
reportfilers = new FileResource(file1);
}
....
....
}
Calling the above method (if it has no exceptions) will make the link to show up and the user can download the file.

Rendering HTML files in Grails

I've looked around but could not find a way of simply including or rendering *.html files in Grails. My application needs to g.render or <g:render> templates which are delivered as html files. For this, as we know, html files have to be converted to _foo.gsp files in order to get rendered. I am totally surprised as to why isn't there a direct support for html or is there one??
Thanks!
One obvious option is to simply rename your HTML files from foo.html to _foo.gsp and then use <render template="foo">. However this is so obvious that I'm sure you've already thought of it.
If you simply want to render a HTML file from within a controller you can use the text parameter of the render controller method
def htmlContent = new File('/bar/foo.html').text
render text: htmlContent, contentType:"text/html", encoding:"UTF-8"
If you want to do the same thing from within a .gsp, you could write a tag. Something like the following (untested) should work:
import org.springframework.web.context.request.RequestContextHolder
class HtmlTagLib {
static namespace = 'html'
def render = {attrs ->
def filePath = attrs.file
if (!file) {
throwTagError("'file' attribute must be provided")
}
def htmlContent = new File(filePath).text
out << htmlContent
}
}
You can call this tag from a GSP using
<html:render file="/bar/foo.html"/>
What is it you are trying to accomplish?
Render html from a controller?
In that case, all you should have to do is redirect the user to file from your control.
redirect(uri:"/html/my.html")
Use html-files instead of gsp template-files?
Thing is, Grails is a "Convention over Configuration"-platform and that means you will have to do some things "the Grails way". The files needs the _ and the .gsp but the name can be whatever you like even if it's easier when you use the same name as the controller. What you gain from doing that is the knowledge that every developer that knows grails and comes into your project will understand how things are tied together and that will help them get started quickly.
Little bit fixed the Don's example, works fine for me
import org.apache.commons.io.IOUtils
class HtmlTagLib {
static namespace = 'html'
def render = {attrs ->
def filePath = attrs.file
if (!filePath) {
throwTagError("'file' attribute must be provided")
}
IOUtils.copy(request.servletContext.getResourceAsStream(filePath), out);
}
}
I wanted to write static html/ajax pages hosted in grails app (v2.4.4), but use the controller for the url rewrite. I was able to accomplish this by moving the file to web-app/ (for ease of reference), and simply use the render() method with 'file' and 'contentType' params, such as:
// My controller action
def tmp() {
render file: 'web-app/tmp.html', contentType: 'text/html'
}
Note: I only tried this using run-app, and haven't packaged a war and deployed to tomcat, yet.
Doc: http://grails.github.io/grails-doc/2.4.4/ref/Controllers/render.html
Closure include = { attr ->
out << Holders.getServletContext().getResource(attr.file).getContent();
}
It is relative to the web-app folder of your grails main application
I was able to use #momo's approach to allow inclusion of external files for grails rendering plugin, where network paths would get botched in higher environments - mine ended up like:
def includeFile = { attr ->
URL resource = Holders.getServletContext().getResource(attr.file)
InputStream content = resource.getContent()
String text = content?.text
log.info "includeFile($attr) - resource: $resource, content.text.size(): ${text?.size()}"
out << text
}

Grails: URL mapping - how to pass file extension?

I have some folder with different files.
I want to use something like this: http://myserver.com/foo/bar/test.html
I'm using this way to obtain path:
"/excursion/$path**" (controller:"excursion", action:"sweet")
But it doesn't helps with file extensions... How to disable file extensions truncating ?
P.S.
class ExcursionController {
def defaultAction = "sweet"
def sweet = {
render "${params.path}"
}
}
Request http://myserver.com/excursion/foo/bar/test.html
The result is "foo/bar/test" with no extension :(
what does
render "${params.path}.${request.format}"
give you?
Disable file extension truncation by adding this line to grails-app/conf/Config.groovy:
grails.mime.file.extensions = false
This impacts content negotiation, so I suggest you read section 7.8 of the Grails user guide

Resources