Play change Language dynamallicy - java

Fairly new to Play trying to change the language dynamically.
route
GET /language/:lang controllers.Index.setLanguage(lang: String)
Tried so far (but none of them work)
Lang.apply(language);
Lang.change(language); // <-- doesn't even compile
Lang.apply(language);
ctx().changeLang(language);
view
#import play.i18n.Messages
...
#Messages.get("message")
#messages.at("message")
...
Both not working..
application.config
messages
Method with some logging
public Result setLanguage(String language) {
Http.Context context = Http.Context.current();
String langFromHttpContext = context.lang().language();
String langFromCtx = ctx().lang().language();
String playLangCookieVal = request().cookies().get("PLAY_LANG").value();
boolean changed = ctx().changeLang(language);
Logger.info("Request param: " + language);
Logger.info("Http context language: " + langFromHttpContext);
Logger.info("ctx language: " + langFromHttpContext);
Logger.info("PLAY_LANG cookie value: " + langFromCtx);
Logger.info("Changed: " + changed);
return ok(index.render("Index"));
}
Result
application - Request param: en
application - Http context language: nl
application - ctx language: nl
application - PLAY_LANG cookie value: nl
application - Changed: false

You need to delete the application.langs="nl" from the configuration. It's deprecated and replaced by the play.i18n.langs.
You must leave only play.i18n.langs=["en","nl"]
You code does not work because Play reads the application.langs="nl" and ignore play.i18n.langs=["en","nl"] (because langs already read from the application.langs), so it suggest your application use only "nl" language and, of course could not set it to "en", so ctx().changeLang(language) method return false

Try this:
ctx().changeLang(language);

Related

Use of OMI_IGNORE_NOTFOUND flag in OpenMetadata interface

In SAS Open Metadata reference (page 126), it says:
The UpdateMetadata method enables you to update the properties of existing metadata objects. It returns an error if the metadata object to be updated does not exist, unless the OMI_IGNORE_NOTFOUND (134217728) flag is set.
Here is my problem, if I specify the flag or I don't specify the flag, I still get the same error: ("SASLibrary : A5X8AHW1.B40000SQ cannot be found in the wlibrary container in the Foundation repository.")
Here is a snippet that reproduces the error:
import com.sas.meta.SASOMI.IOMI;
import com.sas.metadata.MetadataUtil;
import org.omg.CORBA.StringHolder;
IOMI iOMI = ... // an instance of IOMI connection
StringHolder outputMeta = new StringHolder();
String request = ""
+ "<UpdateMetadata>"
+ " <Metadata>"
+ " <SASLibrary Id=\"A5X8AHW1.B40000SQ\"/>"
+ " </Metadata>"
+ " <NS>SAS</NS>"
+ " <Flags>" + (MetadataUtil.OMI_IGNORE_NOTFOUND | MetadataUtil.OMI_TRUSTED_CLIENT | MetadataUtil.OMI_RETURN_LIST) + "</Flags>"
+ " <Options/>"
+ "</UpdateMetadata>"
;
iOMI.DoRequest(request, outputMeta);
Any ideas what is going wrong?
Contrary to what that document states, I have only seen OMI_IGNORE_NOTFOUND flag work with the DeleteMetadata method.
The javadoc also seems to support this by stating
OMI_IGNORE_NOTFOUND (134217728) This flag is for DeleteMetadata to tell it to ignore objects not found so that it will not return on error.
com.sas.metadata.remote.MdOMIUtil Interface Field Summery

What is configuartion required to get data from object storage by SWIFT in Spark

I go through document but still it is very much confusing how to get data from swift.
I configured swift in my one linux machine. By using below command I am able to get container list,
swift -A https://acc.objectstorage.softlayer.net/auth/v1.0/ -U
username -K passwordkey list
I seen many blog for blumix(https://console.ng.bluemix.net/docs/services/AnalyticsforApacheSpark/index-gentopic1.html#genTopProcId2) and written the below code
sc.textFile("swift://container.myacct/file.xml")
I am looking to integrate in java spark. Where need to configure object storage credential in java code. Is there any sample code or blog?
This notebook illustrates a number of ways to load data using the Scala language. Scala runs on the JVM. Java and Scala classes can be freely mixed, no matter whether they reside in different projects or in the same. Looking at the mechanics of how Scala code interacts with Openstack Swift object storage should help guide you to craft a Java equivalent.
From the above notebook, here are some steps illustrating how to configure and extract data from an Openstack Swift Object Storage instance using the Stocator library using the Scala language. The swift url decomposes into:
swift2d :// container . myacct / filename.extension
^ ^ ^ ^
stocator name of namespace object storage
protocol container filename
Imports
import org.apache.spark.SparkContext
import scala.util.control.NonFatal
import play.api.libs.json.Json
val sqlctx = new SQLContext(sc)
val scplain = sqlctx.sparkContext
Sample Creds
// #hidden_cell
var credentials = scala.collection.mutable.HashMap[String, String](
"auth_url"->"https://identity.open.softlayer.com",
"project"->"object_storage_3xxxxxx3_xxxx_xxxx_xxxx_xxxxxxxxxxxx",
"project_id"->"6xxxxxxxxxx04fxxxxxxxxxx6xxxxxx7",
"region"->"dallas",
"user_id"->"cxxxxxxxxxxaxxxxxxxxxx1xxxxxxxxx",
"domain_id"->"cxxxxxxxxxxaxxyyyyyyxx1xxxxxxxxx",
"domain_name"->"853255",
"username"->"Admin_cxxxxxxxxxxaxxxxxxxxxx1xxxxxxxxx",
"password"->"""&M7372!FAKE""",
"container"->"notebooks",
"tenantId"->"undefined",
"filename"->"file.xml"
)
Helper Method
def setRemoteObjectStorageConfig(name:String, sc: SparkContext, dsConfiguration:String) : Boolean = {
try {
val result = scala.util.parsing.json.JSON.parseFull(dsConfiguration)
result match {
case Some(e:Map[String,String]) => {
val prefix = "fs.swift2d.service." + name
val hconf = sc.hadoopConfiguration
hconf.set("fs.swift2d.impl","com.ibm.stocator.fs.ObjectStoreFileSystem")
hconf.set(prefix + ".auth.url", e("auth_url") + "/v3/auth/tokens")
hconf.set(prefix + ".tenant", e("project_id"))
hconf.set(prefix + ".username", e("user_id"))
hconf.set(prefix + ".password", e("password"))
hconf.set(prefix + "auth.method", "keystoneV3")
hconf.set(prefix + ".region", e("region"))
hconf.setBoolean(prefix + ".public", true)
println("Successfully modified sparkcontext object with remote Object Storage Credentials using datasource name " + name)
println("")
return true
}
case None => println("Failed.")
return false
}
}
catch {
case NonFatal(exc) => println(exc)
return false
}
}
Load the Data
val setObjStor = setRemoteObjectStorageConfig("sparksql", scplain, Json.toJson(credentials.toMap).toString)
val data_rdd = scplain.textFile("swift2d://notebooks.sparksql/" + credentials("filename"))
data_rdd.take(5)

The browser console doesn't recognize js vars that were injected with selenium webdriver

I try to bowser to a page with selenium web-driver.
I then inject and execute some js via selenium web-driver.
I try to access these vars in this opened browser console,
but it seems they were not created. How come?
I have this code:
public void foo (){
String script =
"var aLocation = {};" +
"var aOffer = {};" +
"var aAdData = " +
"{ " +
"location: aLocation, " +
"offer: aOffer " +
" };" +
"var aClientEnv = " +
" { " +
" sessionid: \"\", " +
" cookie: \"\", " +
" lon: 34.847, " +
" lat: 32.123, " +
" venue: \"\", " +
" venue_context: \"\", " +
" source: \"\"," + // One of the following (string) values: ADS_PIN_INFO,
// ADS_0SPEED_INFO, ADS_LINE_SEARCH_INFO,
// ADS_ARROW_NEARBY_INFO, ADS_CATEGORY_AUTOCOMPLETE_INFO,
// ADS_HISTORY_LIST_INFO
// (this field is also called "channel")
" locale: \"\"" + // ISO639-1 language code (2-5 characters), supported formats:
" };" +
"W.setOffer(aAdData, aClientEnv);";
javascriptExecutor.executeScript(script);
}
which yields:
script =
var aLocation = {};
var aOffer = {};
var aAdData = {
location: aLocation,
offer: aOffer
};
var aClientEnv = {
sessionid: "",
cookie: "",
rtserver - id: 1,
lon: 34.847,
lat: 32.123,
venue: "",
venue_context: "",
source: "",
locale: ""
};
W.setOffer(aAdData, aClientEnv);
I evaluate aLocation in this browser console and get "variable not defined". How can this be?
It is important to know how Selenium executes the JavaScript that is executed in the browser.
Contrarily to what nilesh's answer implies slapping a var in front of a variable declaration does not take it out of the global space. For instance if var foo = 1 is executed outside of a function scope, it will declare a global variable named foo.
The key is how Selenium executes the script. It would be possible for Selenium to execute the script passed to executeScript in the global space. (There are ways.) However, it does not. What it does is wrap the script in a new function so any var that appears in the code passed to executeScript is going to declare a local variable.
Just dropping the var would work but I prefer to be explicit when I want to manipulate the global space. I explicitly access the window object (e.g. window.foo = 1). Dropping var looks like it could be a mistake, whereas using window. looks deliberate.
Because your variables are NOT global. As soon as you declare them with var they are scoped. If you want to test something out, just put nemo=100; in your script above and try printing out in console, it should work.
Edit #1
By the way, by no means I'm advocating global variables here. I'm just trying to explain what happened to your variables in JS executed by WebDriver. If you want to use global variables then more explicit declaration like window.foo makes more sense like others have suggested. However overall try to avoid using them. Moreover try to avoid executing JavaScript using WebDriver in the first place
unless you have no other choice. WebDriver is supposed to simulate a real user for you and your user is less likely to execute a JavaScript to interact with your web app.

JavaScript Cookie Creation Issue

I am currently trying to create a cookie in JavaScript. The idea is that when the user clicks the extension icon whilst watching a YouTube video it gets the tab name and saves it as a cookie. This is so that I can then access the cookie from my Java program.
I am using chrome and I can't see the cookie in the list when I have pressed it even though the alert successfully displays so I am wondering if anyone can see an issue with my code.
Also if anyone has a better idea of how to get the tab name to my Java program I would be happy to hear your ideas.
Thanks everyone, here's my code:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
createCookie(cookieName, cookieValue);
});
}
function createCookie(name, value)
{
var expires = new Date().getTime() + (1000 * 3600);
var domain = ";domain=.youtube.com";
document.cookie = name + "=" + value + ";expires=" + expires + domain + ";path=/";
alert(name + " = " + value + ". Date = " + expires);
}
EDIT: I have changed my code to use the chrome API's provided by Google, great success!
If anyone has the same problem I have used the Google API's for chrome concerning cookies.
My new code is the following:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue, cookieURL;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
cookieURL = tab.url;
createCookie(cookieName, cookieValue, cookieURL);
});
}
function createCookie(cookieName, cookieValue, cookieURL)
{
chrome.cookies.set({name: cookieName, value: cookieValue, domain: ".youtube.com", url: cookieURL});
}
Note: In the manifest file you will need permissions for tabs, cookies and the website domain. Furthermore I have not stated when the cookie expires thus it expires when the session is closed.

DJ Native Swing javascript command problems

Using DJ Native Swing it is possible to show a web page within a java application. When you do this it is also possible to communicate from the browser to the java runtime environment using the "command" protocol. The documentation has a code snippet which demonstrates it's usage:
function sendCommand( command ){
var s = 'command://' + encodeURIComponent( command );
for( var i = 1; i < arguments.length; s+= '&' + encodeURIComponent( arguments[i++] ) );
window.location = s;
}
As it looks here it seems to be a regular GET request to an url using the command protocol instead of http. Although when I create and image, script tag or just and ajax get request there is no response and the breakpoint in the java runtime isn't triggered.
I don't want to set the window.location because I don't want to navigate away from the page I am currently at. Using the link to navigate to a command url does work though but it also navigates away from the current page. The page uses OpenLayers and dojo. (I have also tried dojo.io.script)
After some work I have found a neat way to communicate with the java runtime which doesn't trigger a refresh of the page every time there is communication. It is inspired on the way JSONP works to get around the cross domain restriction in most browsers these days. Because an iFrame will also trigger a command:// url it possible to do a JSONP like action using this technique. The code on the client side (browser):
dojo.provide( "nmpo.io.java" );
dojo.require( "dojo.io.script" );
nmpo.io.java = dojo.delegate( dojo.io.script, {
attach: function(/*String*/id, /*String*/url, /*Document?*/frameDocument){
// summary:
// creates a new tag pointing to the specified URL and
// adds it to the document.
// description:
// Attaches the script element to the DOM. Use this method if you
// just want to attach a script to the DOM and do not care when or
// if it loads.
var frame = dojo.create( "iframe", {
id: id,
frameborder: 0,
framespacing: 0
}, dojo.body( ) );
dojo.style( frame, { display: "none" } );
dojo.attr( frame, { src: url } );
return frame;
},
_makeScriptDeferred: function(/*Object*/args){
//summary:
// sets up a Deferred object for an IO request.
var dfd = dojo._ioSetArgs(args, this._deferredCancel, this._deferredOk, this._deferredError);
var ioArgs = dfd.ioArgs;
ioArgs.id = dojo._scopeName + "IoScript" + (this._counter++);
ioArgs.canDelete = false;
//Special setup for jsonp case
ioArgs.jsonp = args.callbackParamName || args.jsonp;
if(ioArgs.jsonp){
//Add the jsonp parameter.
ioArgs.query = ioArgs.query || "";
if(ioArgs.query.length > 0){
ioArgs.query += "&";
}
ioArgs.query += ioArgs.jsonp
+ "="
+ (args.frameDoc ? "parent." : "")
+ "nmpo.io.java.jsonp_" + ioArgs.id + "._jsonpCallback";
ioArgs.frameDoc = args.frameDoc;
//Setup the Deferred to have the jsonp callback.
ioArgs.canDelete = true;
dfd._jsonpCallback = this._jsonpCallback;
this["jsonp_" + ioArgs.id] = dfd;
}
return dfd; // dojo.Deferred
}
});
When a request is sent to the java runtime a callback argument will be supplied and a webBrowser.executeJavascript( callbackName + "(" + json + ");" ); action can be executed to trigger the callback in the browser.
Usage example client:
dojo.require( "nmpo.io.java" );
nmpo.io.java.get({
// For some reason the first paramater (the one after the '?') is never in the
// paramater array in the java runtime. As a work around we stick in a dummy.
url: "command://sum?_",
callbackParamName: "callback",
content: {
numbers: [ 1, 2, 3, 4, 5 ].join( "," )
},
load: function( result ){
console.log( "A result was returned, the sum was [ " + result.result + " ]" );
}
});
Usage example java:
webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
#Override
public void commandReceived(WebBrowserCommandEvent e) {
// Check if you have the right command here, left out for the example
// Parse the paramaters into a Hashtable or something, also left out for the example
int sum = 0;
for( String number : arguments.get( "numbers" ).split( "," ) ){
sum += Integer.parseInt( number );
}
// Execute the javascript callback like would happen with a regular JSONP call.
webBrowser.executeJavascript( arguments.get( "callback" ) + "({ result: " + sum + " });" );
}
});
Also with IE in the frame I can highly recommend using firebug lite, the dev tools for IE are not available.

Categories