one more question:
I created an inputfield and added an AjaxFormComponentUpdatingBehavior ("onkeyup"). Now I want to execute some code only if the right key (space-key) is pressed.
How am I able to get the last pressed key? I thought it would be stored in the target attribute but I couldn't find it there... Is there any easy way to solve this problem?
Thx guys!
CU Sylvus
You should not use an AjaxFormComponentUpdatingBehavior if you want to capture keys. This behavior is reserved for actions that update the form component model. I would probably try to do it in javascript alone, especially if you are using a javascript framework like mootools or prototype. Here is some sample code for mootools (no need to send this to the server):
this.add(new TextField<String>("textField").add(new AbstractBehavior(){
private static final long serialVersionUID = 1L;
private Component component;
#Override
public void bind(final Component component){
this.component = component.setOutputMarkupId(true);
}
#Override
public void renderHead(final IHeaderResponse response){
response.renderOnDomReadyJavascript(
"$('" + this.component.getMarkupId() + "')" +
".addEvent('keyup',function(event){" +
"if(' '==event.key){" +
"alert('you pressed space!!!')" +
"}" +
"}" +
");");
};
}));
if no js library is available, here's a wicket-only solution:
#Override
public void renderHead(final IHeaderResponse response){
response.renderJavascriptReference(WicketEventReference.INSTANCE);
response.renderOnDomReadyJavascript("Wicket.Event.add('"
+ this.component.getMarkupId()
+ "',onkeyup',function(event){" + "if(' '==event.key){"
+ "alert('you pressed space!!!')" + "}" + "}" + ");");
};
but this does not deal with cross-browser issues in event handling
I found the solution, thanks to Google and Firebug.
searchInput.add(new AbstractBehavior() {
private static final long serialVersionUID = 1L;
private Component component;
#Override
public void bind(final Component component) {
this.component = component.setOutputMarkupId(true);
}
#Override
public void renderHead(final IHeaderResponse response) {
response.renderJavascriptReference(WicketEventReference.INSTANCE);
response.renderOnDomReadyJavascript("document.getElementById('" +
this.component.getMarkupId() + "').onkeyup=function(event){\n" +
"if(32==event.keyCode){\n" + "alert('you pressed space!!!')" + "\n}" +
"}");
}
});
Related
Is there some effective and accurate way to track the size of a particular session in a servlet based application?
Java doesn't have a sizeof() method like C (see this post for more information) so you generally can't get the size of anything in Java. However, you can track what goes into and is removed from the session with a HttpSessionAttributeListener (link is JavaEE 8 and below). This will give you some visibility into the number of attributes and, to an extent, the amount of memory being used. Something like:
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
#WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {
#Override
public void attributeAdded(HttpSessionBindingEvent event) {
System.out.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been added" );
}
#Override
public void attributeRemoved(HttpSessionBindingEvent event) {
System.our.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been removed" );
}
#Override
public void attributeReplaced(HttpSessionBindingEvent event) {
System.out.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been replaced" );
}
}
I'm playing w/ EE and want to persist a user session state. I have the session bean here:
#Stateful(mappedName = "UserSessionState")
#Named("UserSessionState")
#SessionScoped
#StatefulTimeout(value = 5, unit = TimeUnit.MINUTES)
public class UserSessionState implements Serializable
{
private boolean hasPlayerId = false;
private String playerId = "";
public void setRandomPlayerId()
{
playerId = UUID.uuid();
hasPlayerId = true;
}
public boolean hasPlayerId()
{
return hasPlayerId;
}
public String getPlayerId()
{
return playerId;
}
}
And a servlet here (GameState is an Application Scoped bean that is working as expected, CustomExtendedHttpServlet is just a simple extension of HttpServlet)
public class NewUserJoined extends CustomExtendedHttpServlet
{
#Inject
protected GameState gameState;
#Inject
protected UserSessionState user;
#Override
protected String doGetImpl(HttpServletRequest request, HttpServletResponse response, UserContext userLoginContext)
{
if (!user.hasPlayerId())
{
user.setRandomPlayerId();
}
String userId = user.getPlayerId();
if (!gameState.hasUser(userId))
{
gameState.addUser(userId, user);
return "Hi, your ID is: " + user.getPlayerId() + ", there are " + gameState.getUserCount() + " other players here";
}
else
{
return user.getPlayerId() + " you're already in the game, there are: " + gameState.getUserCount() + " other players here";
}
}
}
I'm not sure what's going on, but whenever I call the New User Joined servlet from the same HTTP session, I get this response on the first call (as expected):
"Hi, your ID is: , there are 1 other players here"
Repeating the same servlet call in the same session gives me the same message:
"Hi, your ID is: , there are 2 other players here"
...
It looks like a new instance of User Session State is getting created over and over. Am I doing this correctly?
EDIT 1: Here the code I use to send a request. It appears I'm getting a new session ID with each request, what could cause that?
RequestCallback callback = new RequestCallback()
{
#Override
public void onResponseReceived(Request request, Response response)
{
log(response.getText());
}
#Override
public void onError(Request request, Throwable exception)
{
log(
"Response Error | "
+ "Exception: " + exception);
}
};
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, SERVLET_URL);
rb.setCallback(callback);
try
{
rb.send();
}
catch (RequestException e)
{
log("Response Error | "
+ "Exception: " + e);
}
Figured out the issue,
Turns out I had an old workaround in the GWT client that was changing the host to get around a CORS issue. Because the response didn't match up to the origin, the cookie wasn't getting sent with future servlet GET calls.
Have you tried a call to request.getSession(true) to make sure an EE HTTPSession is established here?
-------EDIT 2--------
Still using the post of Davidgyoung and these comments, now I have a FatalException :
E/AndroidRuntime﹕ FATAL EXCEPTION:
IntentService[BeaconIntentProcessor]
Process: databerries.beaconapp, PID: 19180
java.lang.NullPointerException
at databerries.beaconapp.MyApplicationName.didEnterRegion(MyApplicationName.java:76)
at org.altbeacon.beacon.BeaconIntentProcessor.onHandleIntent(BeaconIntentProcessor.java:83)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
This error is due to the calling of setRangeNotifier()?
-------EDIT--------
After the post of Davidgyoung and these comments, I tried this method, but still not working :
public class MyApplicationName extends Application implements BootstrapNotifier {
private static final String TAG = ".MyApplicationName";
private RegionBootstrap regionBootstrap;
private BeaconManager beaconManager;
List region_list = new ArrayList();
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "App started up");
// wake up the app when any beacon is seen (you can specify specific id filers in the parameters below)
List region_list = myRegionList();
regionBootstrap = new RegionBootstrap(this, region_list);
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
beaconManager.setBackgroundScanPeriod(3000l);
beaconManager.setBackgroundBetweenScanPeriod(5000l);
}
#Override
public void didDetermineStateForRegion(int arg0, Region arg1) {
// Don't care
}
#Override
public void didEnterRegion(Region region) {
Log.d(TAG, "Got a didEnterRegion call");
// This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched)
// if you want the Activity to launch every single time beacons come into view, remove this call.
regionBootstrap.disable();
Intent intent = new Intent(this, MyActivity.class);
// IMPORTANT: in the AndroidManifest.xml definition of this activity, you must set android:launchMode="singleInstance" or you will get two instances
// created when a user launches the activity manually and it gets launched from here.
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
String zone = region.toString();
Log.d(TAG, "Enter in region");
String text = "Enter in " + zone;
Log.d(TAG, text);
String uuid = "UUID : " + region.getId1();
Log.d(TAG, uuid);
//This part is not working
beaconManager.setRangeNotifier(this);
beaconManager.startRangingBeaconsInRegion(region);
}
#Override
public void didExitRegion(Region arg0) {
// Don't care
}
The errors are about the input in setRangeNotifier and an exception for startRangingBeaconsInRegion
This isn't my main class, my main class :
public class MyActivity extends Activity{
public final static String EXTRA_MESSAGE = "com.example.myapp.MESSAGE";
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("myActivity","onCreate");
}
}
I want all the IDs of the beacons in the region. With this method if I understand, the app is wake-up in the background when she detected a region and normally the "startRangingBeaconsInRegion" can give me a list of beacons with this one I can take the Ids.
-------Original--------
I would like to know all the beacon around me. I know the UUID of this beacons and I can get it with 'region.toString();'. But, I need the others id of the beacons. And, I don't have "Beacon" on didRangeBeaconsInRegion.
How to know the beacons in the region?
And last question, it's possible to make that in the background?
Thanks
You can see an example of ranging for beacons in the "Ranging Sample Code" section here: http://altbeacon.github.io/android-beacon-library/samples.html
This will allow you to read all the identifiers by looking at each Beacon object returned in the Collection<Beacon> beacons in the callback. Like this:
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
for (Beacon beacon: beacons) {
Log.i(TAG, "This beacon has identifiers:"+beacon.getId1()+", "+beacon.getId2()+", "+beacon.getId3());
}
}
Once you start ranging, it will continue to do so in the background, provided you don't exit the activity that starts the ranging. Under some uses of the library, ranging slows down in the background, but this only happens if using the BackgroundPowerSaver class. If you don't want ranging to slow down in the background, simply don't enable background power saving with the library.
Code:
public static class Oya {
String name;
public Oya(String name) {
super();
this.name = name;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Oya [name=" + name + "]";
}
}
public static void main(String[] args) throws GridException {
try (Grid grid = GridGain.start(
System.getProperty("user.home") + "/gridgain-platform-os-6.1.9-nix/examples/config/example-cache.xml")) {
GridCache<Integer, Oya> cache = grid.cache("partitioned");
boolean success2 = cache.putxIfAbsent(3, new Oya("3"));
log.info("Current 3 value = {}", cache.get(3));
cache.transform(3, (it) -> new Oya(it.name + "-transformed"));
log.info("Transformed 3 value = {}", cache.get(3));
}
}
Start another GridGain node.
Run the code. It should print: 3-transformed
Comment the putxIfAbsent() code.
Run the code. I expected it to print: 3-transformed but got null instead
The code will work if I change the cache value to a String (like in GridGain Basic Operations video) or a Java builtin value, but not for my own custom class.
Peer-deployment for data grid is a development-only feature. The contract of a SHARED mode is that whenever last node which had original class definition leaves, all classes will be undeployed. For Data Grid it means that the cache will be cleared. This is useful for cases when you change class definitions.
In CONTINUOUS mode, cache classes never get undeployed, but in this case you must be careful not to change definitions of classes without restarting the grid nodes.
For more information see Deployment Modes documentation.
I have java method
void someMethod(String str, Map map) {
...
}
From JS call this method
var map = new Object()
map.key1 = "val1"
...someMethod(str, map)
Exception:
java.lang.NoSuchMethodException: None of the fixed arity signatures
[(java.lang.String, java.util.Map)] of method org.prjctor.shell.Bash.eval
match the argument types [java.lang.String, jdk.nashorn.internal.scripts.JO]
But in Nashorn docs "Mapping of Data Types Between Java and JavaScript" said "Every JavaScript object is also a java.util.Map so APIs receiving maps will receive them directly".
What am I doing wrong?
Agree with the previous answers that you cannot do this as the docs have implied.
However you could create and pass a map as follows
..
var HashMap = Java.type('java.util.HashMap');
var map = new HashMap();
map.put('1', 'val1');
...someMethod(str, map)
The doc says ""Every JavaScript object implements the java.util.Map interface". But this sample test program shows thats not the case.
public final class NashornTestMap {
public static void main(String args[]) throws Exception{
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine nashorn = factory.getEngineByName("nashorn");
nashorn.eval(""
+"load(\"nashorn:mozilla_compat.js\");"
+ "importClass(Packages.NashornTestMap);"
+ "var map={};"
+ "map[\"Key\"]=String(\"Val\"); "
+ "var test = new NashornTestMap();"
+ "test.test(map);"
+ "");
}
public void test(Map<String, String> obj){
System.out.println(obj);
}
}
The above code give exception "Exception in thread "main" java.lang.ClassCastException: Cannot cast jdk.nashorn.internal.scripts.JO4 to java.util.Map". This link confirms this.
However you can use Map inside your script and call the java objects directly, like this.
public final class NashornTestMap {
public static void main(String args[]) throws Exception{
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine nashorn = factory.getEngineByName("nashorn");
nashorn.eval(""
+"load(\"nashorn:mozilla_compat.js\");"
+ "importClass(Packages.NashornTestMap);"
+ "var HashMap = Java.type(\"java.util.HashMap\");"
+ "var map = new HashMap();"
+ "map.put(0, \"value1\");"
+ "var test = new NashornTestMap();"
+ "test.test(map);"
+ "");
}
public void test(Map<String, String> obj){
System.out.println(obj);
}
}
Returns "{0=value1}"