externalize properties in grails - grails

I am trying to just externalize some custom properties in grails.
I cannot find a clear way on how to externalize some string properties and use them in my code.
Can any one please help me out.

You have to specify the location of the external configuration file in the config.groovy.
For example like this:
if (!grails.config.locations || !(grails.config.locations instanceof List)) {
grails.config.locations = []
}
// Internal Jetty: config-files are locates inside the /web-app/WEB-INF directory
if( GrailsUtil.isDevelopmentEnv() ) {
def dir = System.properties["base.dir"]
def f1 = "${dir}" + File.separator + "web-app" + File.separator + "WEB-INF" + File.separator + "${appName}-config.groovy"
grails.config.locations << "file:${f1}"
}
// TIER Tomcat: config-files are locates inside Tomcat's conf-directory
else if( System.properties["catalina.home"] ) {
def dir = System.properties["catalina.home"]
def f1 = "${dir}" + File.separator + "conf" + File.separator + "${appName}-config.groovy"
grails.config.locations << "file:${f1}"
}
// JBOSS, Glassfish etc
else {
//
}
// Further choices: command line argument (-D{$appName}.config.location=xxx)
if( System.properties["${appName}.config.location"] ) {
grails.config.locations << "file:" + System.properties["${appName}.config.location"]
}
So on local development the config file is locate under the WEB-INF directory.
While going life you have various choices of where to put your configuration file.
You can adapt, if needed, the code to works for config.properties in the same way.

Related

Screenshot is not attached to the extend report when ran in Jenkins only

When using remote-webdriver instance of BrowserStack, only when ran in Jenkins, the failed screenshot is not attached to the report. please help. folder structure is ExtentReport\Screenshots
I tried Extent Report: Not able to see the screenshots on other machine
this but it's not resolve the issue.
public void onTestFailure(ITestResult result) {
testMap.get().fail(result.getThrowable());
//add screenshot for failed test.
WebDriver driver= WebDriverFactory.getDriver();
//experimental to get screenshot
driver = new Augmenter().augment(driver);
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String destination = System.getProperty("user.dir") + "/ExtentReport/" + "/Screenshots/" + result.getMethod().getMethodName() + dateName + ".png";
File finalDestination = new File(destination);
try {
FileUtils.copyFile(source, finalDestination);
} catch (IOException e) {
e.printStackTrace();
}
testMap.get().addScreenCaptureFromPath(destination,result.getMethod().getMethodName());
}
Different operating systems use different characters as file and path separators. When our application has to run on multiple platforms, we need to handle these correctly.
To handle this issue Java provide File.separator.
So, instead of
String destination = System.getProperty("user.dir") + "/ExtentReport/" + "/Screenshots/" + result.getMethod().getMethodName() + dateName + ".png";
Try this:
String destination = System.getProperty("user.dir") + File.separator + "ExtentReport" + File.separator +"Screenshots" + File.separator + result.getMethod().getMethodName() + dateName + ".png";
To use it you will have to add this import
import java.io.File;
Based on the answer of ravi creed,
HTML : Unable to view the base64 image in html report
String base64Screenshot ="data:image/png;base64," + ((TakesScreenshot) Objects.requireNonNull(driver)).getScreenshotAs(OutputType.BASE64);
testMap.get().addScreenCaptureFromBase64String(base64Screenshot).getModel().getMedia().get(0);
I managed to solve this using above code.Once click on base64 img, it opens the actual screenshot.

How to read resource file in Play Framework >2.6?

All the answers to this problem relate to pre-2.6 play framework. Now, it seems that I need to inject an Environment into my Application, but even then, I get nothing.
I want to read in files from conf/i18n in my application root directory. I'm doing the following:
#Singleton
class Application #Inject() (configuration: play.api.Configuration, assets: AssetsFinder, env: play.api.Environment) extends InjectedController {
var root = System.getProperty("user.dir")
var folder = new File(root + "/conf/i18n");
var listOfFiles = folder.listFiles();
val i18n = for {
file <- listOfFiles
filename = file.getName if filename.endsWith(".json")
content = env.resourceAsStream("/conf/i18n/" + filename) match {
case Some(stream) => Source.fromInputStream(stream).getLines.mkString
case None => ""
}
} yield Map(filename.dropRight(".json".length) -> Json.parse(content))
}
but the result of resourceAsStream is always None.
It works if I do it this way:
val i18n = for {
file <- listOfFiles
filename = file.getName if filename.endsWith(".json")
content = Source.fromFile(folder + "/" + filename)("UTF-8").getLines.mkString
} yield Map(filename.dropRight(".json".length) -> Json.parse(content))
Any ideas?

MVC 5, globalize, validate german date: How to bundle the js-scripts?

In the answer to this question (MVC 5 - can not get globalisation running) I solve the problem with a bunch of "<sript src="..." declarations and some js.
What I not managed: I want to bundle the scripts. If I try it like this (excerpt from bundleConfig.cs):
bundles.Add(new ScriptBundle("~/bundles/jqueryvalDe").Include(
"~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/cldr.js",
"~/Scripts/cldr/event.js",
"~/Scripts/cldr/supplemental.js",
"~/Scripts/cldr/unresolved.js",
"~/Scripts/globalize.js",
"~/Scripts/globalize/currency.js",
"~/Scripts/globalize/number.js",
"~/Scripts/globalize/date.js",
"~/Scripts/globalize/plural.js",
"~/Scripts/globalize/relative-time.js",
"~/Scripts/globalize/unit.js",
"~/Scripts/jquery.validate.globalize.js"
));
But I get an error from JavaScript: "Globalize" is undefined
It seems, the order of scrpts is changed...
At the moment I use a Workaround: I wrote an custom HTM-Helper.
public static class GermanDateValidationExtension
{
public static MvcHtmlString ScriptsForGermanDateValidation(this HtmlHelper helper)
{
return new MvcHtmlString("<script src=\"~/ Scripts / jquery.validate.js\"></script>\n" +
"<script src = \"~/Scripts/jquery.validate.unobtrusive.js\"></script>\n" +
"<script src = \"~/Scripts/cldr.js\"></script>\n" +
"<script src = \"~/Scripts/cldr/event.js\"></ script>\n" +
"<script src = \"~/Scripts/cldr/supplemental.js\"></script>\n" +
"<script src = \"~/Scripts/cldr/unresolved.js\"></script>\n" +
"<script src = \"~/Scripts/globalize.js\"></script>\n" +
"<script src = \"~/Scripts/globalize/currency.js\" ></script>\n" +
"<script src = \"~/Scripts/globalize/number.js\"></script>\n" +
"<script src = \"~/Scripts/globalize/date.js\"></script>\n" +
"<script src = \"~/Scripts/globalize/plural.js\" ></script>\n" +
"<script src = \"~/Scripts/globalize/relative-time.js\"></script>\n" +
"<script src = \"~/Scripts/globalize/unit.js\"></script>\n" +
"<script src = \"~/Scripts/jquery.validate.globalize.js\"></script>\n" +
"<script>\n" +
"$.when(\n" +
"$.get(\"/Scripts/cldr/main/de/ca-gregorian.json\"),\n" +
"$.get(\"/Scripts/cldr/main/de/numbers.json\"),\n" +
"$.get(\"/Scripts/cldr/supplemental/likelySubtags.json\"),\n" +
"$.get(\"/Scripts/cldr/supplemental/timeData.json\"),\n" +
"$.get(\"/Scripts/cldr/supplemental/weekData.json\")\n" +
").then(function() {\n" +
"return [].slice.apply(arguments, [0]).map(function(result) {\n" +
"return result[0];\n" +
"});\n" +
"}).then(Globalize.load)\n" +
".then(function() {\n" +
"Globalize.locale(\"de-DE\");\n" +
"});\n" +
"</ script > ");
}
}
And use it in the view:
...
#section Scripts {
#Html.ScriptsForGermanDateValidation()
}
...
My question is: How to bundle the scripts correctly?
The problem seems originated from bundling order which rendered jquery.validate.globalize.js before globalize.js, which uses "dependency tree" established in favor of well-known libraries & their custom extensions will rendered before others. Hence, in order to set load order as you want, create a class which implements IBundleOrder interface & its corresponding extension method:
// from Sebastián Rojas (/a/26602075)
class UnorderedBundleOrderer : IBundleOrderer
{
public IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
{
return files;
}
}
static class BundleExtensions
{
public static Bundle UnorderedBundling(this Bundle bundle)
{
bundle.Orderer = new UnorderedBundleOrderer();
return bundle;
}
}
Then you can use custom bundling order above in BundleConfig.cs file:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jqueryvalDe")
.UnorderedBundling()
.Include(
"~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js",
...
...
"~/Scripts/globalize.js",
...
...
"~/Scripts/jquery.validate.globalize.js"
));
}
Related issue:
ASP.NET MVC - Bundle Config order
Ordering of Files within a bundle - What are the known libraries?
The solution is - how Tetsuya Yamamoto says: Write your own orderer.
public IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
{
return files;
}
and use it:
var qvDeBundle =new ScriptBundle("~/bundles/jqueryvalDe").Include(
"~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/cldr.js",
"~/Scripts/cldr/event.js",
"~/Scripts/cldr/supplemental.js",
"~/Scripts/cldr/unresolved.js",
"~/Scripts/globalize.js",
"~/Scripts/globalize/currency.js",
"~/Scripts/globalize/number.js",
"~/Scripts/globalize/date.js",
"~/Scripts/globalize/plural.js",
"~/Scripts/globalize/relative-time.js",
"~/Scripts/globalize/unit.js",
"~/Scripts/jquery.validate.globalize.js"
);
qvDeBundle.Orderer=new UnorderBundleOrderer();
bundles.Add(qvDeBundle);

Creating an instance of a domain class inside a grails script

I am trying to create an instance of a domain class inside a grails 2.3.6 script:
def player = new Player(name:"Bob")
player.save()
But I keep getting an exception
java.lang.NoClassDefFoundError: gaming/Player
I've tried all the different bootstrapping tricks I've managed to find on the internet but they don't really change the result:
I've tried importing:
import gaming.Player
I've tried loading the bootstrap script:
includeTargets << grailsScript("_GrailsBootstrap")
I've tried depending on every task I managed to find:
depends(configureProxy, packageApp, classpath, loadApp, configureApp, compile, bootstrap)
I've even tried loading the class at runtime:
ApplicationHolder.application.getClassForName("gaming.Player")
Interestingly enough, this last line doesn't barf which suggests that grails can find my class, but chooses to ignore the find when I actually go to use it.
Edit. As requested, here is the current version of the script
import gaming.Player
import org.codehaus.groovy.grails.commons.ApplicationHolder
includeTargets << grailsScript("_GrailsInit")
includeTargets << grailsScript("_GrailsBootstrap")
includeTargets << grailsScript("_GrailsClasspath")
def handleHeaderLine(line) {
def retval = []
line.each {
if(!it.equals("Game Name") && !it.equals("Total # of Copies")) {
println("Creating Player: " + it)
def player = new Player(name:it)
player.save
retval << it
} else {
retval << null
}
}
return retval;
}
def handleGameLine(header, line) {
println("Creating Game: " + line[0])
for(int i = 1; i < line.length - 1; i++) {
if(!header[i].equals("Total # of Copies")) {
def count = line[i] == "" ? 0 : Integer.parseInt(line[i]);
for(int j = 0; j < count; j++) {
println "Creating copy of " + line[0] + " owned by " + header[i]
}
}
}
}
target(loadAssets: "The description of the script goes here!") {
depends(configureProxy, packageApp, classpath, loadApp, configureApp, compile, bootstrap)
ApplicationHolder.application.getClassForName("gaming.Player")
def tsv = new File("...")
def header = null;
tsv.eachLine {
def line = it.split("\t")
if(header == null) {
header = handleHeaderLine(line)
println header
} else {
handleGameLine(header, line)
}
}
}
setDefaultTarget(loadAssets)
You do not have to do all the boiler plate effort to bring up the environment while running your script. run-script does that for you. When grails run-script is used following targets are run by default: checkVersion, configureProxy, bootstrap. And finally the script run-script is run.
run-script runs your custom script in GroovyShell by providing ApplicationContext and grailsApplication as bindings to shell. So what you would end up with your script is shown below as if it is written in Groovy console/shell:
//scripts/player/PlayerScript.groovy
def handleHeaderLine(line) {
def retval = []
line.each {
if(!it.equals("Game Name") && !it.equals("Total # of Copies")) {
println("Creating Player: " + it)
def player = new Player(name: it)
player.save(flush: true)
retval << it
} else {
retval << null
}
}
return retval
}
def handleGameLine(header, line) {
println("Creating Game: " + line[0])
for(int i = 1; i < line.length - 1; i++) {
if(!header[i].equals("Total # of Copies")) {
def count = line[i] == "" ? 0 : Integer.parseInt(line[i]);
for(int j = 0; j < count; j++) {
println "Creating copy of " + line[0] + " owned by " + header[i]
}
}
}
}
def tsv = new File("...")
def header = null
tsv.eachLine {
def line = it.split("\t")
if(header == null) {
header = handleHeaderLine(line)
println header
} else {
handleGameLine(header, line)
}
}
And then use run-script as below:
grails run-script scripts/player/PlayerScript.groovy
which would by default run the script in dev environment. If you want for other envirnments then use as
grails test run-script scripts/player/PlayerScript.groovy
BUT
Due to a major bug in latest version of grails, you won't be able to run script the above mentioned way because run-script always depends on bootstrap target and would always try to bring tomcat up while running script as the plugin scope in build which would result in Error loading plugin manager: TomcatGrailsPlugin. The workaround is also mentioned in the defect but here is a groovier implementation. Change in BuildConfig.groovy as:
plugins {
if ( !System.getProperty("noTomcat") ) {
build ":tomcat:7.0.52.1"
}
....
}
and then issue run-script command as:
grails -DnoTomcat=true run-script scripts/player/PlayerScript.groovy
On a side note, the reason your script was not running is that the class Player will not be loaded at this time while running script, for use. It has to be loaded manually using classLoader and then create an instance off of it. Something like:
includeTargets << grailsScript("_GrailsInit")
includeTargets << grailsScript("_GrailsBootstrap")
target(playerScript: "The description of the script goes here!") {
depends configureProxy, packageApp, classpath, loadApp, configureApp
def playerClass = classLoader.loadClass("gaming.Player")
//Skeptical about how a domain class would behave
//But a normal POGO should be good being used this way
def player = playerClass.newInstance([[name: "Bob"]] as Object[])
player.save(flush: true)
println player
}
setDefaultTarget(playerScript)

Blackberry: Command line build and application auto-start

I have an application which is built from command line (ANT) using J2ME Polish. As such, this application is defined through a build.xml, not from Blackberry JDE project files.
What I need to do is have this application auto-start. This is easy enough to do once the application has been run for the first time (example). However, this does require the application to be manually run by the user (which I want to avoid).
The JDE provides options which you can check to enable auto-start, and from ANT:
<cldc runonstartup=="true"...
Will do the trick. The question is, how do I integrate this into a Polish buiild (i.e. into a Polish build.xml which is also building for other platforms)?
Anyone know what the auto-start option in the JDE actually does / what it changes?
So, the way to do this is, unfortunately, to change the J2ME-Polish source! As outlined in this bug report the J2ME Polish build framework (at version 2.1.4) doesn't pass on the RIM-MIDlet-Flags-x JAD attribute to RAPC.
The changes are relatively simple - merely passing on the RIM-MIDlet-Flags-1 value if defined in the JAD, otherwise setting it to zero (as the original 2.1.4 source does).
The diff (from 2.1.4) source:
Index: /enough-polish-build/source/extensions/de/enough/polish/blackberry/JarToCodFinalizer.java
===================================================================
--- /enough-polish-build/source/extensions/de/enough/polish/blackberry/JarToCodFinalizer.java (revision 315)
+++ /enough-polish-build/source/extensions/de/enough/polish/blackberry/JarToCodFinalizer.java (revision 316)
## -36,6 +36,7 ##
import java.util.Calendar;
import java.util.Locale;
import java.util.Map;
+import java.util.List;
import java.util.Properties;
import org.apache.tools.ant.BuildException;
## -185,6 +186,13 ##
}
}
File iconFile = null;
+ Map jadProperties;
+ try {
+ jadProperties = FileUtil.readPropertiesFile( jadFile, ':' );
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new BuildException("Unable to read JAD file " + e.toString() );
+ }
if (mainClassName != null) {
try {
/*
## -230,12 +238,26 ##
"MicroEdition-Configuration: CLDC-1.1",
//"MIDlet-1: Demo," + iconUrl + ",",
"MIDlet-1: " + env.getVariable("MIDlet-Name") + "," + iconUrl + ",",
- //"MIDlet-Icon: " + iconUrl,
- "RIM-MIDlet-Flags-1: 0"
+ //"MIDlet-Icon: " + iconUrl
};
+ /* Ensure that if RIM-MIDlet-Flags is defined in the JAD, it is
+ * passed on to RAPC to create the COD file.
+ * See https://developer.berlios.de/bugs/?func=detailbug&group_id=1246&bug_id=16901
+ * for details.
+ */
+ ArrayList newEntriesList = new ArrayList(Arrays.asList(newEntries));
+ final String flagsKey = "RIM-MIDlet-Flags-1";
+ String flagString = (String)jadProperties.get(flagsKey);
+ if (flagString == null) {
+ flagString = "0";
+ }
+ flagString = flagString.trim();
+ System.out.println("JarToCodFinalizer setting " + flagsKey + ": " + flagString);
+ newEntriesList.add(flagsKey+ ": " + flagString);
+
File rapcFile = new File( jadFile.getParent(), codName + ".rapc");
- FileUtil.writeTextFile( rapcFile, newEntries );
+ FileUtil.writeTextFile( rapcFile, newEntriesList );
} catch ( IOException e ) {
// this shouldn't happen
e.printStackTrace();
## -367,7 +389,6 ##
// now rewrite JAD file so that it is ready for OTA download:
// (first backup JAD file:)
//FileUtil.copy(jadFile, new File(jadFile.getParent(), jadFile.getName() + ".bak") );
- Map jadProperties = FileUtil.readPropertiesFile( jadFile, ':' );
Object[] keys = jadProperties.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
String key = (String) keys[i];
Another polish user :)
Take a look at BB forums the 2nd post. Then using what we know about polish and jad attributes
Add this to your jad section of your build.xml
<jad>
<attribute name="RIM-MIDlet-Flags"
value="1"
if="polish.vendor == BlackBerry" />
</jad>
I haven't tested this but the logic seems to be valid :) Let me know if it works or not.

Resources