I'm using HttpSessionBindingListener to maintain a record of all active logged in users in a web application.The below code works well for WildFly server but throws NullPointerException on Tomcat in valueBound method while fetching the session attribute which was set before calling this method.
package com.abc.def.xyz.dto;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import com.abc.def.xyz.util.Logger;
public class ActiveLoginUserDetails implements Serializable,HttpSessionBindingListener {
private Logger log = Logger.getLogger(this.getClass());
private static final long serialVersionUID = 1L;
private long usrId;
private String usrCode;
private String usrShortName;
private static Map<ActiveLoginUserDetails, HttpSession> activeLoginDtls = new ConcurrentHashMap<ActiveLoginUserDetails, HttpSession>();
private static Map<ActiveLoginUserDetails, HttpSession> loggedInUserDtlsMap = new ConcurrentHashMap<ActiveLoginUserDetails, HttpSession>();
public long getUsrId() {
return usrId;
}
public void setUsrId(long usrId) {
this.usrId = usrId;
}
public String getUsrCode() {
return usrCode;
}
public void setUsrCode(String usrCode) {
this.usrCode = usrCode;
}
public String getUsrShortName() {
return usrShortName;
}
public void setUsrShortName(String usrShortName) {
this.usrShortName = usrShortName;
}
public static Map<ActiveLoginUserDetails, HttpSession> getActiveLoginDtls() {
return activeLoginDtls;
}
public static void setActiveLoginDtls(Map<ActiveLoginUserDetails, HttpSession> activeLoginDtls) {
ActiveLoginUserDetails.activeLoginDtls = activeLoginDtls;
}
public static Map<ActiveLoginUserDetails, HttpSession> getLoggedInUserDtlsMap() {
return loggedInUserDtlsMap;
}
public static void setLoggedInUserDtlsMap(
Map<ActiveLoginUserDetails, HttpSession> loggedInUserDtlsMap) {
ActiveLoginUserDetails.loggedInUserDtlsMap = loggedInUserDtlsMap;
}
#Override
public void valueBound(HttpSessionBindingEvent event) {
ActiveLoginUserDetails sessionUsrDtls = (ActiveLoginUserDetails) event.getSession().getAttribute("LoggedInUsers");
Boolean userHasSmInteractiveLoginAction = false;
Boolean multiLoginAllowed = false;
Boolean check = true;
log.info("sessionUsrDtls:::::"+ );
List<ActionDetails> actnDtlsList = (List<ActionDetails>) event.getSession().getAttribute("sessionActnList");
for(ActionDetails actnDtls : actnDtlsList){
if(actnDtls.getActionAccessValue().equalsIgnoreCase("smLogin")){
userHasSmInteractiveLoginAction = true;
}
}
if(userHasSmInteractiveLoginAction){
String amultiLoginAllowedUserCodeList = "adminUser";
String[] usrCodeArr = amultiLoginAllowedUserCodeList.split(",");
for(String tempUserCode : usrCodeArr){
if(sessionUsrDtls.getUsrCode().equalsIgnoreCase(tempUserCode)){
multiLoginAllowed = true;
}
}
}
if(!multiLoginAllowed){
for( Entry<ActiveLoginUserDetails, HttpSession> tempLoginDtls : activeLoginDtls.entrySet()){
ActiveLoginUserDetails temp = tempLoginDtls.getKey();
if(temp.getUsrCode().equals(sessionUsrDtls.getUsrCode())){
if (event.getSession() != null) {
check = false;
event.getSession().invalidate();
log.debug("After Invalidating duplicate session for "+sessionUsrDtls.getUsrCode());
}
}
}
}
if(check){
log.debug("Inside adding user from session:::");
activeLoginDtls.put(this, event.getSession());
}
}
#Override
public void valueUnbound(HttpSessionBindingEvent event) {
log.debug("Inside removing user from session:::");
activeLoginDtls.remove(this);
loggedInUserDtlsMap.remove(this);
}
}
It is throwing NullPointerException (for sessionUsrDtls object) at line
if(sessionUsrDtls.getUsrCode().equalsIgnoreCase(tempUserCode)){
which denotes that the attribute is not set into session. but this method will get called only after setting the value into session, so couldn't get what's the exact problem going on here.
Related
Help me in the following code and how to used the backup on the Hazelcast
migration of the hazelcast 3.x.x to 5.x.x
package com.hazelcast.map;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastInstanceAware;
import com.hazelcast.nio.serialization.impl.BinaryInterface;
import java.util.Map;
// Interface AbstractEntryProcessor
#BinaryInterface
public abstract class AbstractEntryProcessor<K,V> implements EntryProcessor<K,V> {
private final EntryBackupProcessor<K,V> entryBackupProcessor;
// Non Parameterize Constructor
public AbstractEntryProcessor() {
this(true);
}
// Parameterize Constructor AbstractEntryProcessor
public AbstractEntryProcessor(boolean applyOnBackup) {
if (applyOnBackup) {
entryBackupProcessor = new EntryBackupProcessorImpl();
} else {
entryBackupProcessor = null;
}
}
//EntryBackupProcessor
#Override
public final EntryBackupProcessor getBackupProcessor() {
return entryBackupProcessor;
}
// class EntryBackupProcessorImpl
private class EntryBackupProcessorImpl implements EntryBackupProcessor<k,V>, HazelcastInstanceAware {
// generated for EntryBackupProcessorImpl which doesn't implement HazelcastInstanceAware
static final long serialVersionUID = -5081502753526394129L;
#Override
public void processBackup(Map.Entry<K,V> entry) {
process(entry);
}
#Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
final AbstractEntryProcessor<k,V> outer = AbstractEntryProcessor.this;
if (outer instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) outer).setHazelcastInstance(hazelcastInstance);
}
}
}
}
How to used the backup methods in 5.x.x versons of series
how to used the backup in the above question ?
This should work:
public abstract class AbstractEntryProcessor implements EntryProcessor, HazelcastInstanceAware {
protected transient HazelcastInstance hazelcastInstance;
private final boolean applyOnBackup;
// Non Parameterize Constructor
public AbstractEntryProcessor() {
this(true);
}
// Parameterize Constructor AbstractEntryProcessor
public AbstractEntryProcessor(boolean applyOnBackup) {
this.applyOnBackup = applyOnBackup;
}
//EntryBackupProcessor
#Override
public final EntryProcessor getBackupProcessor() {
if (!applyOnBackup || this instanceof ReadOnly) {
return null;
}
return this;
}
#Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}
}
I am trying to work with PersistentActor in Akka.
I tried the basic example provided in the Akka documentation at https://doc.akka.io/docs/akka/current/persistence.html.
I am getting the following error at the starting of the actor:
Caused by: java.lang.IllegalArgumentException: Default journal plugin
is not configured, see 'reference.conf' at
akka.persistence.Persistence$.verifyPluginConfigIsDefined(Persistence.scala:193)
at
akka.persistence.Persistence.defaultJournalPluginId$lzycompute(Persistence.scala:228)
at
akka.persistence.Persistence.defaultJournalPluginId(Persistence.scala:226)
at
akka.persistence.Persistence.journalConfigFor(Persistence.scala:336)
at akka.persistence.Eventsourced.$init$(Eventsourced.scala:97) at
akka.persistence.AbstractPersistentActor.(PersistentActor.scala:455)
at
org.spituk.learning.akka.samples.ExamplePersistentActor.(ExamplePersistentActor.java:72)
The code I tried is like:
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.persistence.AbstractPersistentActor;
import akka.persistence.SnapshotOffer;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
class Cmd implements Serializable {
private static final long serialVersionUID = 1L;
private final String data;
public Cmd(String data) {
this.data = data;
}
public String getData() {
return data;
}
}
class Evt implements Serializable {
private static final long serialVersionUID = 1L;
private final String data;
public Evt(String data) {
this.data = data;
}
public String getData() {
return data;
}
}
class ExampleState implements Serializable {
private static final long serialVersionUID = 1L;
private final ArrayList<String> events;
public ExampleState() {
this(new ArrayList<>());
}
public ExampleState(ArrayList<String> events) {
this.events = events;
}
public ExampleState copy() {
return new ExampleState(new ArrayList<>(events));
}
public void update(Evt evt) {
events.add(evt.getData());
}
public int size() {
return events.size();
}
#Override
public String toString() {
return events.toString();
}
}
public class ExamplePersistentActor extends AbstractPersistentActor {
private int snapShotInterval = 1000;
private ExampleState state = new ExampleState();
public static Props props() {
return Props.create(ExamplePersistentActor.class);
}
public int getNumEvents() {
return state.size();
}
#Override
public String persistenceId() {
return "sample-id-1";
}
#Override
public Receive createReceiveRecover() {
return receiveBuilder()
.match(Evt.class, state::update)
.match(SnapshotOffer.class, ss -> state = (ExampleState) ss.snapshot())
.build();
}
#Override
public Receive createReceive() {
return receiveBuilder()
.match(
Cmd.class,
c -> {
final String data = c.getData();
final Evt evt = new Evt(data + "-" + getNumEvents());
System.out.println("Cmd received::" + c);
persist(
evt,
(Evt e) -> {
state.update(e);
getContext().getSystem().getEventStream().publish(e);
if (lastSequenceNr() % snapShotInterval == 0 && lastSequenceNr() != 0)
// IMPORTANT: create a copy of snapshot because ExampleState is mutable
saveSnapshot(state.copy());
});
})
.matchEquals("print", s -> System.out.println(state))
.build();
}
public static void main(String[] args) throws IOException {
ActorSystem persistentSystem = ActorSystem.create("persistent-system");
ActorRef persistentSystemActor = persistentSystem.actorOf(ExamplePersistentActor.props());
persistentSystemActor.tell(new Cmd("Hello"), ActorRef.noSender());
System.in.read();
persistentSystem.terminate();
}
}
I have not defined any configurations for the persistence intend to use the built-in default plugins. Can someone please help me with this?
I had to add the following to the application.conf file:
akka.persistence.journal.plugin = "akka.persistence.journal.leveldb"
akka.persistence.snapshot-store.plugin = "akka.persistence.snapshot-store.local"
akka.persistence.journal.leveldb.dir = "target/example/journal"
akka.persistence.snapshot-store.local.dir = "target/example/snapshots"
# DO NOT USE THIS IN PRODUCTION !!!
akka.persistence.journal.leveldb.native = false
Facing an issue with passing values from my html form to action class. Created a sample project to test the functionality and have the same issue here. I have the following classes:
TestBean
package com.struts2test.beans;
public class TestBean {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
TestBeanHolder
package com.struts2test.beans;
import java.util.List;
import java.util.Map;
public class TestBeanHolder {
private Map<Integer, TestBean> testBeanMap;
private List<TestBean> testBeanList;
private Map<Integer, List<TestBean>> testBeanListMap;
public Map<Integer, TestBean> getTestBeanMap() {
return testBeanMap;
}
public void setTestBeanMap(Map<Integer, TestBean> testBeanMap) {
this.testBeanMap = testBeanMap;
}
public Map<Integer, List<TestBean>> getTestBeanListMap() {
return testBeanListMap;
}
public void setTestBeanListMap(Map<Integer, List<TestBean>> testBeanListMap) {
this.testBeanListMap = testBeanListMap;
}
public List<TestBean> getTestBeanList() {
return testBeanList;
}
public void setTestBeanList(List<TestBean> testBeanList) {
this.testBeanList = testBeanList;
}
}
TestAction
package com.struts2test.action;
import com.opensymphony.xwork2.ActionSupport;
import com.struts2test.beans.TestBeanHolder;
public class TestAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private TestBeanHolder testBeanHolder;
public TestBeanHolder getTestBeanHolder() {
return testBeanHolder;
}
public void setTestBeanHolder(TestBeanHolder testBeanHolder) {
this.testBeanHolder = testBeanHolder;
}
public String execute() throws Exception {
return SUCCESS;
}
}
When my url is http://localhost:8080/Struts2Test/test?testBeanHolder.testBeanMap[0].value=1, testBeanHolder.testBeanMap of my action gets populated with key of 0 mapping to a TestBean instance with value=1.
When the url is http://localhost:8080/Struts2Test/test?testBeanHolder.testBeanList[0].value=1, testBeanHolder.testBeanList gets populated with single instance of TestBean with value=1.
I am try to populate testBeanListMap property of testBeanHolder and doesn't work. The testBeanListMap is created but empty. Here is the URL I am trying http://localhost:8080/Struts2Test/test?testBeanHolder.testBeanListMap[0][0].value=1
Here is the code which worked, adding modified classes:
TestBeanListHolder
package com.struts2test.beans;
import java.util.List;
public class TestBeanListHolder {
private List<TestBean> testBeans;
public List<TestBean> getTestBeans() {
return testBeans;
}
public void setTestBeans(List<TestBean> testBeans) {
this.testBeans = testBeans;
}
}
TestBeanHolder
package com.struts2test.beans;
import java.util.List;
import java.util.Map;
public class TestBeanHolder {
private Map<Integer, TestBean> testBeanMap;
private List<TestBean> testBeanList;
private Map<Integer, TestBeanListHolder> testBeanListMap;
public Map<Integer, TestBean> getTestBeanMap() {
return testBeanMap;
}
public void setTestBeanMap(Map<Integer, TestBean> testBeanMap) {
this.testBeanMap = testBeanMap;
}
public Map<Integer, TestBeanListHolder> getTestBeanListMap() {
return testBeanListMap;
}
public void setTestBeanListMap(
Map<Integer, TestBeanListHolder> testBeanListMap) {
this.testBeanListMap = testBeanListMap;
}
public List<TestBean> getTestBeanList() {
return testBeanList;
}
public void setTestBeanList(List<TestBean> testBeanList) {
this.testBeanList = testBeanList;
}
}
URL
http://localhost:8080/Struts2Test/test?testBeanHolder.testBeanListMap[1].testBeans[0].value=somevalue
The url http://localhost:8080/Struts2Test/test?testBeanHolder.testBeanListMap[0][0].value=1 won't work because you are using wrong parameter name. Thus testBeanHolder.testBeanListMap[0][0].value is a name of the parameter that maps to the object which has a property of complex type (collection of collections). Struts2 can't handle such scenarios, . But you can wrap a second collection with an object and use a collection of objects. The name would change to testBeanHolder.testBeanListMap[0].object[0].value.
The expression testBeanHolder.testBeanListMap[0][0].value is not a valid OGNL expression.
See here for a complete reference of what is allowed.
ResultContentExt extends HashMap and has it's own variable testInt.
In main method, I write the ResultContentExt been to json.but can't write the variable
testInt to json.
I also rewrite writeObject method in ResultContentExt, which seems not be called...
package test.open.serial;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class ResultContentExt extends HashMap<String, Object> implements
Serializable {
private static final long serialVersionUID = 628377769976336650L;
public ResultContentExt() {
}
private int testInt;
public int getTestInt() {
return testInt;
}
public void setTestInt(int testInt) {
this.testInt = testInt;
}
public List<String> getRef_hot_status() {
return (List<String>) this.get("ref_hot_status");
}
#Override
public String toString() {
return "ResultContentExt [ref_hot_status=" + this.getRef_hot_status()
+ "]" + "ref_new_status=" + this.getRef_new_status()
+ this.getTestInt();
}
public void setRef_hot_status(List<String> ref_hot_status) {
if (ref_hot_status != null) {
this.put("ref_hot_status", ref_hot_status);
} else {
this.put("ref_hot_status", new LinkedList<Map<String, Integer>>());
}
}
public void setRef_new_status(List ref_new_status) {
if (ref_new_status != null) {
this.put("ref_new_status", ref_new_status);
} else {
this.put("ref_new_status", new LinkedList<Map<String, Integer>>());
}
}
public List<String> getRef_new_status() {
return (List<String>) this.get("ref_new_status");
}
public void writeObject(ObjectOutputStream s) throws IOException {
System.out.println("ResultContentExt begin...");
s.defaultWriteObject();
System.out.println("ResultContentExt end");
}
}
the result is {"ref_new_status":["bbbb","cccc"],"ref_hot_status":["aaa","侠盗飞"]}
why the testInt can't be write to json.
the main class
public class SearilazizeTest implements Serializable{
private static final long serialVersionUID = 5767426158258564918L;
private static Logger logger = Logger.getLogger(SearilazizeTest.class);
public static void main(String[] args){
try {
jsonObjectTrans();
} catch (Exception e) {
logger.error("", e);
}
}
public static void jsonObjectTrans(){
ResultContentExt rce = new ResultContentExt();
List<String> refHostStatus = new ArrayList<String>();
refHostStatus.add("aaa");
refHostStatus.add("侠盗飞");
rce.setRef_hot_status(refHostStatus);
List<String> refNewStatus = new ArrayList<String>();
refNewStatus.add("bbbb");
refNewStatus.add("cccc");
rce.setRef_new_status(refNewStatus);
rce.setTestInt(22);
System.out.println(rce.getTestInt());
JSONObject jsonArray = JSONObject.fromObject(rce);
System.out.println(jsonArray);
ResultContentExt packageVersionMaps = new ResultContentExt();
try {
JSONObject jsonObject = JSONObject.fromObject(jsonArray);
packageVersionMaps = (ResultContentExt) JSONObject.toBean(jsonObject,ResultContentExt.class);
} catch (Exception e) {
logger.error("", e);
}
System.out.println(packageVersionMaps);
}}
I have been struggling to find a good way of implementing PubSub with Autobahn for android. I am currenty using the Singleton pattern to use the same AutobahnConnection in my whole app. I got the calls and subscribing working but when i unsubscribe and then come back to the same fragment and try to subscribe again it doesnt work. Below my current Autobahn Class:
package nl.w3s.hulpverlener.utils;
import nl.w3s.hulpverlener.helper.DebugHelper;
import android.util.Log;
import de.tavendo.autobahn.Autobahn;
import de.tavendo.autobahn.Autobahn.SessionHandler;
import de.tavendo.autobahn.AutobahnConnection;
import de.tavendo.autobahn.AutobahnOptions;
public final class AutobahnService{
private static AutobahnService INSTANCE;
private static AutobahnConnection connection;
private AutobahnOptions options;
private boolean connected = false;
private String url = "http://johelpen.w3s.nl/";
private String websocketUrl;
private AutobahnService() {
connection = new AutobahnConnection();
options = new AutobahnOptions();
options.setReceiveTextMessagesRaw(true);
websocketUrl = CommonUtilities.STAGING_WEBSOCKET_URL;
connect();
}
public static AutobahnService getInstance() {
if(INSTANCE == null)
INSTANCE = new AutobahnService();
else
INSTANCE.connect();
return INSTANCE;
}
public void connect() {
if(!connection.isConnected()) {
connection.connect(websocketUrl, new SessionHandler() {
#Override
public void onOpen() {
connected = true;
Log.i(DebugHelper.TAG_DEBUG, "CONNECTED");
}
#Override
public void onClose(int p_intCode, String p_strReason) {
connected = false;
Log.i(DebugHelper.TAG_DEBUG, "DISCONNECTED");
}
}, options);
}
}
public void doCall(final String callType, final Class<?> classRef, final Autobahn.CallHandler autobahnEventHandler, final Object... arguments) {
connection.call(url + "#" + callType, classRef, autobahnEventHandler, arguments);
}
public void doSubscribe(final String callType, final Class<?> classRef, final Autobahn.EventHandler autobahnEventHandler) {
connection.subscribe(url + callType, classRef, autobahnEventHandler);
}
public void doUnsubscribe(final String callType) {
connection.unsubscribe(url + callType);
}
}
When I look at my logs it doesnt disconnect while unsubscribing and resubscribing.