qrcode-0.1 with Grails 2.0.1 - grails

Look this is my problem: I have updated to Grails 2.0.1 and now I have to make a QR Code. I have installed the qrcode plugin 0.1 but it is not working. I'm usign the tag:
<qrcode:image text="${createPromoInstance.id}" />
but it seems it doesn't do anything. I debugged with google chrome and I realized that in the "Elements" tab, the tag is being changed for <call></call>
I was asking yesterday about this, and someone said me that the plugin has some bugs that doesn't work with Grails 2.0.1, and he gave me some advices about what can I do.
For example, I editted the QRController like this:
class QrcodeController{
QRCodeRenderer qrcodeRenderer = new QRCodeRenderer()
def index = {
qrcodeRenderer.renderPng(response, request.getHeader("REFERER"), 300i)
} //It doesn't have any change
def url = {
String uri = params.u
String size = getSize(params)
qrcodeRenderer.renderPng(response, uri, size.toInteger().intValue())
} //it doesn't have any change
protected String getSize(Map params){
String size = params.s
if(!size || size.matches(/\D\)) {size = "128"}
return size
} //I have added the "protected word"
def text = {
String content = params.t //it used to be params.text
String size = getSize(params)
qrcodeRenderer.renderPng(response, content, size.toInteger().intValue())
}
}
and he said if I make those changes it will work, but no, it doesn't! I'm trying to render the code in an empty gsp just to try it out like so:
<%page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title><title>
<head>
<body>
<div>
<qrcode:image text="${createPromoInstance.id} />
</div>
</body>
</html>
As I understand it should work, but it doesn't. Does anyone know what am I doing wrong? I have to do something else to get the rendered QR Code?
Thanks for the help!
Jonatan!

I found the answer... I will just leave it here if anyone need it.
to get this working you need to do some changes as I wrote before.
protected String getSize(Map params{ //it used to be String getSize(Map params)
String size = params.s
if (!size || size.matches(\/D/) {size = "128"}
return size
}
and
def text = {
String content = params.t //it used to be params.text
String size = getSize(params)
qrcodeRenderer.renderPng(response, content, size.toInteger().intValue())
}
but this is not everything, you have to change something else in the BuildConfig like so:
//find the plugin call
plugins{
//this is how my plugins call looks like, here you might see the calls of the plugins you have installed
runtime: ":hibernate:$grailsVersion"
runtime: ":jquery:1.7.1"
runtime: ":resources:1.1.6"
//and you gotta add this
compile: ":qrcode:0.1"
/*.
.
.*/
build: ":tomcat:$grailsVersion"
}
Then you must go to the plugin taglib "QRCodeTagLib" and replace this:
def image = {attrs->
def size = attrs.height?:attrs.width
String text = attrs.text
String src = createLink(controller:'qrcode',action:'text',params:[t:text,s:size])
//it used to be like this
/*def mkp = new groovy.xml.MarkupBuilder(out)
mkp{
img(alt:url, src:src)
}
*/
//and now it looks like this
out <<"<img alt=\"${text}\" src=\"${src}\"/>"
}
and that's it, your QR Code will be rendered!
Hope it will be useful for anyone!
Jonatan!!
PD: The credit is not mine for this code, somebody helped me on the grails facebook page! Lots of thanks for Ingo. :)
ah! Other thing... He added something in the bootstrap but it didn't work for me, in the bootstrap he put:
QRCode m = new QRCode()
m.save()
try it and let me know if that works for you! :)

Related

How to set default language to English

I've tried to set it in Bootstrap but it don't work
Also tried in ../conf/spring/resources.groovy .. it don't work either.
In Bootstrap i tried with:
Locale defLocale = new Locale("en", "GB");
Locale.setDefault(defLocale);
And in resources.groovy I tried this:
import org.springframework.web.servlet.i18n.SessionLocaleResolver
beans = {
localeResolver(SessionLocaleResolver) {
defaultLocale= new java.util.Locale("en","GB")
}
}
and a lot of variants I found when googling.
I'm sure it must be a way but it seems very hard to find.
When you create a session(for example when logging in), you can do the following:
if(setDefaultLanguage) {
session['org.springframework.web.servlet.i18n.' +
'SessionLocaleResolver.LOCALE'] = 'en-GB'
}
Try this,
String springLocaleAtt = 'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'
session[springLocaleAtt] = new Locale('en_GB')

Open report in new tab using jasper plugin in grails

I am using jasper plugin to generate my report. All is fine but except my pdf is opening on the current tab, when I want to open it in a new tab.
I have no idea how to do it. Can anybody please help me on this please?
I am using "i-report" to design my pdf. Here is my code below :
def index = {
println(params)
def testModel = this.getProperties().containsKey('chainModel') ?
chainModel : null
JasperReportDef report = null
if (params.containsKey('auto_print_dialog')){
report = docuJasperService.buildReportDefinition(params,
request.getLocale(), testModel)
}
else{
report = jasperService.buildReportDefinition(params,
request.getLocale(), testModel)
}
generateResponse(report)
}
def generateResponse = {reportDef ->
if (!reportDef.fileFormat.inline && !reportDef.parameters._inline) {
//response.characterEncoding = "UTF-8"
//response.setHeader("Content-disposition",
//"inline; filename=${params._name}");
response.setHeader("Content-disposition", "inline;
filename="+(reportDef.parameters._name ?: reportDef.name) +
"."+reportDef.fileFormat.extension);
response.contentType = "application/pdf"
response.outputStream << reportDef.contentStream.toByteArray()
} else {
render(text: reportDef.contentStream, contentType:
reportDef.fileFormat.mimeTyp,
encoding: reportDef.parameters.encoding ?
reportDef.parameters.encoding : 'UTF-8');
}
}
This is going to be handled by the link you use to generate the report. Typically adding a target of _blank will do the trick. For example:
<g:link controller="myReports" action="whateverReport" target="_blank">Click for your report</g:link>
This will open the link in a new tab.
If you are using a form adding target to the form will submit the form to a new tab. For example:
<form name="myForm" action="whateverReport" method="POST" target="_blank">
or
<g:form name="myForm" controller="myReports" action="whateverReport" target="_blank">
You could even do so with javascript window.open if you needed, but I will leave that example out of this answer as it's well documented elsewhere.

Security Error when trying to load content from resource in a Firefox Addon (SDK)

I am creating a firefox addon using the SDK. My goal is simple, to intercept a specific iframe and load my own HTML page (packaged as a resource with my addon) instead of the content that was requested originally.
So far I have the following code:
var httpRequestObserver =
{
observe: function(subject, topic, data)
{
var httpChannel, requestURL;
if (topic == "http-on-modify-request") {
httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
var newRequestURL, i;
if (/someurl/.test(requestURL)) {
var ioService = Cc["#mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
httpChannel.redirectTo(ioService.newURI(self.data.url('pages/test.html'), undefined, undefined));
}
return;
}
}
};
var observerService = Cc["#mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
observerService.addObserver(httpRequestObserver, "http-on-modify-request", false);
This code works in that it detects the proper iframe loading and does the redirect correctly. However, I get the following error:
Security Error: Content at http://url.com may not load or link to
jar:file:///.../pages/test.html.
How can I get around this limitation?
actually man i was really over thinking this.
its already solved when I changed to using loadContext. Now when you get loadContext you get the contentWindow of whatever browser element (tab browser, or frame or iframe) and then just abort the http request like you are doing and then loadContext.associatedWindow.document.location = self.data('pages/tests.html');
done
ill paste the code here removing all the private stuff. you might need the chrome.manifest ill test it out and paste the code back here
Cu.import('resource://gre/modules/Services.jsm');
var httpRequestObserver = {
observe: function (subject, topic, data) {
var httpChannel, requestURL;
if (topic == "http-on-modify-request") {
httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
var newRequestURL, i;
if (/someurl/.test(requestURL)) {
var goodies = loadContextGoodies(httpChannel);
if (goodies) {
httpChannel.cancel(Cr.NS_BINDING_ABORTED);
goodies.contentWindow.location = self.data.url('pages/test.html');
} else {
//dont do anything as there is no contentWindow associated with the httpChannel, liekly a google ad is loading or some ajax call or something, so this is not an error
}
}
return;
}
}
};
Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false);
//this function gets the contentWindow and other good stuff from loadContext of httpChannel
function loadContextGoodies(httpChannel) {
//httpChannel must be the subject of http-on-modify-request QI'ed to nsiHTTPChannel as is done on line 8 "httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);"
//start loadContext stuff
var loadContext;
try {
var interfaceRequestor = httpChannel.notificationCallbacks.QueryInterface(Ci.nsIInterfaceRequestor);
//var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request //instead do the loadContext stuff below
try {
loadContext = interfaceRequestor.getInterface(Ci.nsILoadContext);
} catch (ex) {
try {
loadContext = subject.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);
} catch (ex2) {}
}
} catch (ex0) {}
if (!loadContext) {
//no load context so dont do anything although you can run this, which is your old code
//this probably means that its loading an ajax call or like a google ad thing
return null;
} else {
var contentWindow = loadContext.associatedWindow;
if (!contentWindow) {
//this channel does not have a window, its probably loading a resource
//this probably means that its loading an ajax call or like a google ad thing
return null;
} else {
var aDOMWindow = contentWindow.top.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
var gBrowser = aDOMWindow.gBrowser;
var aTab = gBrowser._getTabForContentWindow(contentWindow.top); //this is the clickable tab xul element, the one found in the tab strip of the firefox window, aTab.linkedBrowser is same as browser var above //can stylize tab like aTab.style.backgroundColor = 'blue'; //can stylize the tab like aTab.style.fontColor = 'red';
var browser = aTab.linkedBrowser; //this is the browser within the tab //this is where the example in the previous section ends
return {
aDOMWindow: aDOMWindow,
gBrowser: gBrowser,
aTab: aTab,
browser: browser,
contentWindow: contentWindow
};
}
}
//end loadContext stuff
}
NOTE: Now try this first, I didn't test it yet, if you get a security error when it tries to redirect then create a chrome.manifest file and put it in the root directory. If it throws a security error than you definitely need a chrome.manifest file and that will without question fix it up. I'll test this myself later tonight when I get some time.
The chrome.manifest should look like this:
content kaboom-data ./resources/kaboom/data/ contentaccessible=yes
Then in the code way above change the redirect line from goodies.contentWindow.location = self.data.url('pages/test.html'); to goodies.contentWindow.location = 'chrome://kaboom-data/pages/test.html');.
see this addon here: https://addons.mozilla.org/en-US/firefox/addon/ghforkable/?src=search
in the chrome.manifest file we set the contentaccessible parameter to yes
you dont need sdk for this addon. its so simple, just ocpy paste that into a bootstrap skeleton as seen here:
Bootstrap With Some Features, Like chrome.manifest which you will need
Bootstrap Ultra Basic
if you want to really do a redirect of a page to your site, maybe you want to make a custom about page? if you would like ill throw togather a demo for you on making a custom about page. you can see a bit hard to understand demo here
posting my trials here so it can help all:
trail 1 failed - created chrome.manifest file with contents content kaboom-data resources/kaboom/data/ contentaccessible=yes
var myuri = Services.io.newURI('chrome://kaboom-data/content/pages/test.html', undefined, undefined);
httpChannel.redirectTo(myuri);
Error Thrown
Security Error: Content at http://digg.com/tools/diggthis/confirm? may
not load or link to
jar:file:///C:/Documents%20and%20Settings/SONY%20VAIO/Application%20Data/Mozilla/Firefox/Profiles/vr10qb8s.default/extensions/jid1-g4RtC8vdvPagpQ#jetpack.xpi!/resources/kaboom/data/pages/test.html.
trial 2 failed - created resource in bootstrap.js
alias.spec =
file:///C:/Documents%20and%20Settings/SONY%20VAIO/Application%20Data/Mozilla/Firefox/Profiles/vr10qb8s.default/extensions/jid1-g4RtC8vdvPagpQ#jetpack.xpi
alias updated to spec:
jar:file:///C:/Documents%20and%20Settings/SONY%20VAIO/Application%20Data/Mozilla/Firefox/Profiles/vr10qb8s.default/extensions/jid1-g4RtC8vdvPagpQ#jetpack.xpi!/
let resource = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
let alias = Services.io.newFileURI(data.installPath);
Cu.reportError('alias.spec = ' + alias.spec);
if (!data.installPath.isDirectory()) {
alias = Services.io.newURI("jar:" + alias.spec + "!/", null, null);
Cu.reportError('alias updated to spec: ' + alias.spec);
}
resource.setSubstitution("kaboom_data", alias);
...
var myuri = Services.io.newURI('resource://kaboom_data/resources/kaboom/data/pages/test.html', undefined, undefined);
httpChannel.redirectTo(myuri);
Error Thrown
Security Error: Content at http://digg.com/tools/diggthis/confirm? may
not load or link to
jar:file:///C:/Documents%20and%20Settings/SONY%20VAIO/Application%20Data/Mozilla/Firefox/Profiles/vr10qb8s.default/extensions/jid1-g4RtC8vdvPagpQ#jetpack.xpi!/resources/kaboom/data/pages/test.html.
CONCLUSION
in both trials above it was the weirdest thing, it wouldnt show the resource or chrome path in the security error thrown but it would give the full jar path. Leading me to believe that this has something to do with redirectTo function.
The solution that did work was your solution of
var gBrowser = utils.getMostRecentBrowserWindow().gBrowser;
var domWin = httpChannel.notificationCallbacks.getInterface(Ci.nsIDOMWindow);
var browser = gBrowser.getBrowserForDocument(domWin.document);
//redirect
browser.loadURI(self.data.url('pages/test.html'));
however I changed this to use loadContext instead of this method because it is the recommended way. also gBrowser to getMostRecentBrowserWindow will fail if the url load is slow and in that time the user swithces to another tab or window
I also changed to use Services.jsm as you had imported Cu anyways. Using Services.jsm is super fast not even blink fast. Its just a pointer.
Im still working on trying to the redirectTo method working its really bothering me. The changes I made are to my local copy.
Have you considered turning your local HTML file into a data URL and loading that?

How to convert GroovySOAP client code into groovy-wslite?

Hi I am having a bit of trouble figuring out how I can access this web service: http://www.webservicex.net/CurrencyConvertor.asmx?WSDL
Using the groovy Wslite library, seems to work fine with the depreciated Groovy Soap library but I am not allowed to use that.
The libraries are described here:
Groovy Soap Use
Groovy-Wslite
I am totally new to groovy and these technologies in general so forgive my ignorance.
Basically I want this code:
import groovy.swing.SwingBuilder
import groovy.net.soap.SoapClient
proxy = new SoapClient("http://www.webservicex.net/CurrencyConvertor.asmx?WSDL")
def currency = ['USD', 'EUR', 'CAD', 'GBP', 'AUD']
def rate = 0.0
swing = new SwingBuilder()
refresh = swing.action(
name:'Refresh',
closure:this.&refreshText,
mnemonic:'R'
)
frame = swing.frame(title:'Currency Demo') {
panel {
label 'Currency rate from '
comboBox(id:'from', items:currency)
label ' to '
comboBox(id:'to', items:currency)
label ' is '
textField(id:'currency', columns:10, rate.toString())
button(text:'Go !', action:refresh)
}
}
frame.pack()
frame.show()
def refreshText(event) {
rate = proxy.ConversionRate(swing.from.getSelectedItem(), swing.to.getSelectedItem())
swing.currency.text = rate
}
Converted to work with the groovy-wslite library and I cant get it to work no matter what I do.
Here is the Wslite library again.
wslite library
Any help is greatly appreciated.
I find it helpful to use a tool like soapUI first to figure out what request a service is expecting. From there it's a matter of using the markup builder to build that request. The following should work from the groovyConsole:
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='0.8.0')
import wslite.soap.*
def client = new SOAPClient('http://www.webservicex.net/CurrencyConvertor.asmx')
def response = client.send(SOAPAction: 'http://www.webserviceX.NET/ConversionRate') {
body {
ConversionRate( xmlns: 'http://www.webserviceX.NET/') {
FromCurrency('GBP')
ToCurrency('USD')
}
}
}
assert response
assert 200 == response.httpResponse.statusCode
println response.ConversionRateResponse.ConversionRateResult.text()

Bootstrap doesn't save entities

I'm completely new to Grails and I'm doing the tutorial "Getting started with Grails Second Edition" by Scott Davis and Jason Rudolph.
When I'm setting up the BootStrap it seems like grails doesn't save the entities and I can't see them in my application.
I've already tried save(failOnError:true), but it compiles and saves without any errors.
Here is the code of BootStrap.groovy
package racetrack
import grails.util.GrailsUtil
class BootStrap {
def init = { servletContext ->
switch(GrailsUtil.environment){
case "development":
def jane = new Runner(
firstName:"Jane",
lastName:"Doe",
dateOfBirth:(new Date() - 365*30),
gender:"F",
address:"123 Main St",
city:"Goose",
state:"NC",
zipcode:"12345",
email:"jane#whereever.com"
)
jane.save()
if(jane.hasErrors()){
println jane.errors
}
def trot = new Race(
name:"Turkey Trot",
startDate:(new Date() + 90),
city:"Duck",
state:"NC",
distance:5.0,
cost:20.0,
maxRunners:350
)
trot.save()
if(trot.hasErrors()){
println trot.errors
}
def reg = new Registration(
paid:false,
runner:jane,
race:trot
)
reg.save()
if(reg.hasErrors()){
println reg.errors
}
break
case "production" : break
}
}
def destroy = { }
}
Thank you very much
are you in development mode?
Mybe you should add a log.debug or println statement to see if your code gets executed.
and have your tried a .save(flush:true, failOnError:true)? the flush might help
Use enums instead of Strings. Enums fit best in switch-case scenario and you can avoid mistakes. Maybe GrailsUtil.environment returns DEVELOPMENT not development? Instead of:
case "development"
use
case Environment.DEVELOPMENT
Using the grails.util.Environment enum doesn't work as is. Because the grails.util.GrailsUtil.environment returns a string, not an Environment.
You are more or less forced using strings.
Though old I thought it might help if I posted something I just found :)
if (GrailsUtil.developmentEnv){
// do dev stuff
}
else {
// do other stuff
}

Resources