Grails 2.5.4: Get all logged in users with HttpSessionListener - grails

I'm trying to get all the current user sessions using the app-info plugin but it doesn't compile in Grails 2.5.4. Is there another way to get this information? I'm new to Grails.
This link has some information including a reference to the app-info plugin but it's old and I wasn't able to get anything to compile.
UPDATE
I've added this custom class in src\groovy\UserSessions:
package usersessions
import javax.servlet.http.HttpSessionEvent
import javax.servlet.http.HttpSessionListener
//import org.apache.shiro.subject.PrincipalCollection
//import org.apache.shiro.subject.SimplePrincipalCollection;
//import org.apache.shiro.subject.support.DefaultSubjectContext
class MyHttpSessionListener implements HttpSessionListener {
private static List activeUsers = Collections.synchronizedList(new ArrayList());
#Override
public void sessionCreated(HttpSessionEvent event) { }
#Override
public void sessionDestroyed(HttpSessionEvent event) {
String userName = getCurrentUserName(event)
if (userName == null) {
return
}
MyHttpSessionListener.userLoggedOut(userName)
}
public static void userLoggedIn(String userName) {
if (!activeUsers.contains(userName)) {
activeUsers.add(userName)
}
}
public static void userLoggedOut(String userName) {
activeUsers.remove(userName)
}
public static List getCurrentUserNames() {
return Collections.unmodifiableList(activeUsers);
}
/*
private String getCurrentUserName(HttpSessionEvent event) {
PrincipalCollection currentUser = (PrincipalCollection) event.getSession().getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (currentUser == null) {
return null
}
return (String) currentUser.getPrimaryPrincipal();
}
*/
}
Added this to /scripts/_Events.groovy
import groovy.xml.StreamingMarkupBuilder
eventWebXmlEnd = {String tmpfile ->
def root = new XmlSlurper().parse(webXmlFile)
root.appendNode {
'listener' {
'listener-class' (
'usersessions.MyHttpSessionListener'
)
}
}
webXmlFile.text = new StreamingMarkupBuilder().bind {
mkp.declareNamespace(
"": "http://java.sun.com/xml/ns/javaee")
mkp.yield(root)
}
}
Added this to resources.groovy
myHttpSessionListener(usersessions.MyHttpSessionListener)
/* shiroAuthenticator(ModularRealmAuthenticator) {
authenticationStrategy = ref("shiroAuthenticationStrategy")
authenticationListeners = [ ref("authListener") ]
}
*/
Added this to my controller:
package usersessions
class NewController extends MyHttpSessionListener {
def index() {
myHttpSessionListener.userLoggedIn("user1")
render "Users "+ getCurrentUserNames()
}
}
It compiles and the app runs but I don't see how to get sessions in the listener? The controller gives an error when I load it:
No such property: myHttpSessionListener for class: usersessions.NewController
UPDATE 2
I changed the controller to use this code to test creating a sessions and it works:
def index() {
String randomString = org.apache.commons.lang.RandomStringUtils.random(3, true, true)
userLoggedIn(randomString)
render "Users "+ getCurrentUserNames()
}

Related

Why isn't an custom implemented VaadinServiceInitListener is listening in vaadin 13.0.2?

I would like to validate user is signed in or not to achieve it i found something called VaadinServiceInitListener in vaadin 13.0.2 This class is used to listen to BeforeEnter event of all UIs in order to check whether a user is signed in or not before allowing entering any page.
I have created an vaadin 13.0.2 project with app-layout-addon by appreciated implemented login functionality and VaadinServiceInitListener to check whether a user is signed in or not.
public class AAACATInitListener implements VaadinServiceInitListener {
private static final long serialVersionUID = 1L;
private static InAppSessionContextImpl appContextImpl;
#Override
public void serviceInit(ServiceInitEvent event) {
System.out.println("in service init event");
event.getSource().addUIInitListener(new UIInitListener() {
private static final long serialVersionUID = 1L;
#Override
public void uiInit(UIInitEvent event) {
event.getUI().addBeforeEnterListener(new BeforeEnterListener() {
private static final long serialVersionUID = 1L;
#Override
public void beforeEnter(BeforeEnterEvent event) {
appContextImpl = (InAppSessionContextImpl)VaadinSession.getCurrent().getAttribute("context");
if (appContextImpl == null) {
WebBrowser webBrowser = UI.getCurrent().getSession().getBrowser();
String address = webBrowser.getAddress();
if(RememberAuthService.isAuthenticated(address) != null && !RememberAuthService.isAuthenticated(address).isEmpty()) {
//System.out.println("Found Remembered User....");
IBLSessionContext iblSessionContext = null;
try {
iblSessionContext = new UserBLManager().doRememberedStaffUserLogin(RememberAuthService.isAuthenticated(address), "");
if(iblSessionContext != null) {
InAppSessionContextImpl localAppContextImpl = new InAppSessionContextImpl();
localAppContextImpl.setBLSessionContext(iblSessionContext);
localAppContextImpl.setModuleGroupList(iblSessionContext.getSessionAccessControl().getPermittedModuleGroups());
appContextImpl = localAppContextImpl;
event.rerouteTo(ApplicationMainView.class);
}else {
Notification.show("Your access has been expired, Please contact your administrator", 5000, Position.BOTTOM_CENTER);
}
} catch (AuthenticationFailedException e) {
Notification.show("Authentication Failed, Please Reset Cookies And Try Again", 5000, Position.BOTTOM_CENTER);
} catch (Exception e){
e.printStackTrace();
Notification.show("Unexpected Error Occurred, Please Reset Cookies And Try Again", 5000, Position.BOTTOM_CENTER);
}
}else {
System.out.println("Session context is null, creating new context");
appContextImpl = new InAppSessionContextImpl();
VaadinSession.getCurrent().setAttribute("context", appContextImpl);
event.rerouteTo(LoginView.class);
}
} else {
System.out.println("Session context is not null");
InAppSessionContextImpl localAppContextImpl = new InAppSessionContextImpl();
localAppContextImpl.setBLSessionContext(appContextImpl.getBLSessionContext());
localAppContextImpl.setModuleGroupList(appContextImpl.getModuleGroupList());
appContextImpl = localAppContextImpl;
event.rerouteTo(ApplicationMainView.class);
}
}
});
}
});
}
public static void setBLSessionContext(IBLSessionContext iblSessionContext) {
appContextImpl.setBLSessionContext(iblSessionContext);
}
public static void setModuleGroupList(List<ModuleGroupVO> moduleGroupList) {
appContextImpl.setModuleGroupList(moduleGroupList);
}
private class InAppSessionContextImpl implements InAppSessionContext {
private static final long serialVersionUID = 1L;
private List<ModuleGroupVO> moduleGroupList;
private IBLSessionContext iblSessionContext;
private Map<String, Object> attributeMap;
public InAppSessionContextImpl() {
this.attributeMap = new HashMap<String, Object>();
}
#Override
public List<ModuleGroupVO> getModuleGroupList() {
return moduleGroupList;
}
public void setModuleGroupList(List<ModuleGroupVO> moduleGroupList) {
this.moduleGroupList = moduleGroupList;
}
#Override
public IBLSessionContext getBLSessionContext() {
return iblSessionContext;
}
public void setBLSessionContext(IBLSessionContext iblSessionContext) {
this.iblSessionContext = iblSessionContext;
}
#Override
public IBLSession getBLSession() {
if(iblSessionContext != null)
return iblSessionContext.getBLSession();
return null;
}
#Override
public boolean isPermittedAction(String actionAlias) {
if (getBLSessionContext() != null) {
if (getBLSessionContext().getSessionAccessControl() != null) {
return getBLSessionContext().getSessionAccessControl().isPermittedAction(actionAlias);
}
}
return false;
}
#Override
public void setAttribute(String key, Object attribute) {
attributeMap.put(key, attribute);
}
#Override
public Object getAttribute(String key) {
return attributeMap.get(key);
}
}
}
Expected results redirect to login page if user not signed in or else to main application page but AAACATInitListener is not listening.
If you are using Spring, simply add a #Component annotation to the class and it should work. If youre not using Spring, follow #codinghaus' answer.
To make Vaadin recognize the VaadinServiceInitListener you have to create a file called com.vaadin.flow.server.VaadinServiceInitListener and put it under src/main/resources/META-INF/services. Its content should be the full path to the class that implements the VaadinServiceInitListener interface. Did you do that?
You can also find a description on that in the tutorial.
The correct pattern to use beforeEnter(..) is not do it via VaadinServiceInitListener , instead you should implement BeforeEnterObserver interface in the view where you need use it and override beforeEnter(..) method with your implementation.
public class MainView extends VerticalLayout implements RouterLayout, BeforeEnterObserver {
...
#Override
public void beforeEnter(BeforeEnterEvent event) {
...
}
}

Jersy2 inject slf4j Logger

I'm trying to understand Jersey 2 development and context-dependency injection.
I don't understand how to inject into a resource an object that needs initialization parameters in the constructor.
For example: I'd like to #Inject slf4j Logger, built using LoggerFactory.
My resource class is:
#Path("/myresource")
public class MyResource {
#Inject
private Logger log;
#GET
#Produces(MediaType.APPLICATION_JSON)
public Answer status() {
log.info("STATUS");
return new Answer(200, "Server up and running # "+ ZonedDateTime.now());
}
}
My Resource config is:
public class MyAppextends ResourceConfig {
public MyApp() {
register(new MyBinder());
packages(true, "my.packages");
}
}
public class MyBinder extends AbstractBinder {
#Override
protected void configure() {
bindFactory(MyLoggerFactory.class).to(org.slf4j.Logger.class);
}
}
Finally, the Factory is:
public class MyLoggerFactory implements Factory<Logger> {
#Override
public Logger provide() {
return LoggerFactory.getLogger(TYPE_FOR_LOGGING.class);
}
#Override
public void dispose(Logger logger) {
}
}
How can I specify TYPE_FOR_LOGGING as argument, in order to Inject the correctly initialized Logger in every resource I want?
Thanks
What you are looking for is called the InstantiationService. You can inject it into Factories to find out who is calling the factory inside of the provide method.
Below find a code sample from the hk2 tests that illustrate the use of the InstantiationService.
#Singleton
public class CorrelationFactory implements Factory<PerLookupServiceWithName> {
private final static PerLookupServiceWithName NULL_SERVICE = new PerLookupServiceWithName() {
#Override
public String getName() {
return null;
}
};
#Inject
private InstantiationService instantiationService;
/* (non-Javadoc)
* #see org.glassfish.hk2.api.Factory#provide()
*/
#Override #PerLookup
public PerLookupServiceWithName provide() {
InstantiationData data = instantiationService.getInstantiationData();
if (data == null) {
return NULL_SERVICE;
}
Injectee parent = data.getParentInjectee();
if (parent == null) {
return NULL_SERVICE;
}
Class<?> parentClass = parent.getInjecteeClass();
if (parentClass == null) {
return NULL_SERVICE;
}
Correlator correlator = parentClass.getAnnotation(Correlator.class);
if (correlator == null) {
return NULL_SERVICE;
}
final String fName = correlator.value();
return new PerLookupServiceWithName() {
#Override
public String getName() {
return fName;
}
};
}
/* (non-Javadoc)
* #see org.glassfish.hk2.api.Factory#dispose(java.lang.Object)
*/
#Override
public void dispose(PerLookupServiceWithName instance) {
// DO nothing
}
}

Where can I find the source code for ActivityTestRule?

Where can I find the source code for ActivityTestRule?
You can find it at
https://android.googlesource.com/platform/frameworks/testing/+/android-support-test/rules/src/main/java/android/support/test/rule/ActivityTestRule.java
You have to use branch android-support-test instead of master on platform/frameworks/testing project in AOSP.
You can add ActivityTestRule in code, import library and CTRL+Left Click to decompile.
If you can't import this class, you need to add it to dependencies in your build.gradle
androidTestCompile 'com.android.support.test:rules:0.3'
EDIT:
My result of decompiling:
package android.support.test.rule;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.test.InstrumentationRegistry;
import android.support.test.annotation.Beta;
import android.support.test.internal.util.Checks;
import android.support.test.rule.UiThreadTestRule;
import android.util.Log;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
#Beta
public class ActivityTestRule<T extends Activity> extends UiThreadTestRule {
private static final String TAG = "ActivityInstrumentationRule";
private final Class<T> mActivityClass;
private Instrumentation mInstrumentation;
private boolean mInitialTouchMode;
private boolean mLaunchActivity;
private T mActivity;
public ActivityTestRule(Class<T> activityClass) {
this(activityClass, false);
}
public ActivityTestRule(Class<T> activityClass, boolean initialTouchMode) {
this(activityClass, initialTouchMode, true);
}
public ActivityTestRule(Class<T> activityClass, boolean initialTouchMode, boolean launchActivity) {
this.mInitialTouchMode = false;
this.mLaunchActivity = false;
this.mActivityClass = activityClass;
this.mInitialTouchMode = initialTouchMode;
this.mLaunchActivity = launchActivity;
this.mInstrumentation = InstrumentationRegistry.getInstrumentation();
}
protected Intent getActivityIntent() {
return new Intent("android.intent.action.MAIN");
}
protected void beforeActivityLaunched() {
}
protected void afterActivityLaunched() {
}
protected void afterActivityFinished() {
}
public T getActivity() {
if(this.mActivity == null) {
Log.w("ActivityInstrumentationRule", "Activity wasn\'t created yet");
}
return this.mActivity;
}
public Statement apply(Statement base, Description description) {
return new ActivityTestRule.ActivityStatement(super.apply(base, description));
}
public T launchActivity(#Nullable Intent startIntent) {
this.mInstrumentation.setInTouchMode(this.mInitialTouchMode);
String targetPackage = this.mInstrumentation.getTargetContext().getPackageName();
if(null == startIntent) {
startIntent = this.getActivityIntent();
if(null == startIntent) {
Log.w("ActivityInstrumentationRule", "getActivityIntent() returned null using default: Intent(Intent.ACTION_MAIN)");
startIntent = new Intent("android.intent.action.MAIN");
}
}
startIntent.setClassName(targetPackage, this.mActivityClass.getName());
startIntent.addFlags(268435456);
Log.d("ActivityInstrumentationRule", String.format("Launching activity %s", new Object[]{this.mActivityClass.getName()}));
this.beforeActivityLaunched();
this.mActivity = (Activity)this.mActivityClass.cast(this.mInstrumentation.startActivitySync(startIntent));
this.mInstrumentation.waitForIdleSync();
this.afterActivityLaunched();
return this.mActivity;
}
void setInstrumentation(Instrumentation instrumentation) {
this.mInstrumentation = (Instrumentation)Checks.checkNotNull(instrumentation, "instrumentation cannot be null!");
}
void finishActivity() {
if(this.mActivity != null) {
this.mActivity.finish();
this.mActivity = null;
}
}
private class ActivityStatement extends Statement {
private final Statement mBase;
public ActivityStatement(Statement base) {
this.mBase = base;
}
public void evaluate() throws Throwable {
try {
if(ActivityTestRule.this.mLaunchActivity) {
ActivityTestRule.this.mActivity = ActivityTestRule.this.launchActivity(ActivityTestRule.this.getActivityIntent());
}
this.mBase.evaluate();
} finally {
ActivityTestRule.this.finishActivity();
ActivityTestRule.this.afterActivityFinished();
}
}
}
}

How add properties to the Vaadin Calendar BasicEvent?

I am implementing the Vaadin 7 Calendar and require to display more
event information than is contained in BasicEvent.
Below is some of the code I am using (events are not being displayed
on calendar):
please can you inform me what I need to add/change?
Thank you Steve...
public class CalEvent extends BasicEvent {
private java.lang.String customer = "";
public CalEvent() {
}
public java.lang.String getCustomer() {
return customer;
}
public void setCustomer(java.lang.String customer) {
this.customer = customer;
}
}
public class EvtProvider extends BasicEventProvider {
public void addEvent(CalEvent event) {
super.addEvent(event);
}
public void removeEvent(Event event) {
super.removeEvent(event);
}
}
public class Mgr {
Mgr() {
cal = new Calendar("My Calendar");
EvtProvider evtProvider = new EvtProvider();
cal.setEventProvider(evtProvider);
List<CalEvent> lst = getCalEvents();
for (CalEvent ev : lst) {
cal.addEvent(ev);
}
}
"more event information than is contained in BasicEvent."
For example?
BasicEvent can display a lot of content in event or Event description.
http://i.stack.imgur.com/uRlN4.png

How Can i show urls clicked by user in Primefaces+JSF2

I am using JSF2 with Prime faces. I will want to show all the previous links or Urls clicked by user in every page.How can i do this?
Here's a good link for you: How can I get the request URL from a Java Filter?
What I would do is use something like that example and do a set of three URLs.
//Using linked example
public class MyFilter implements Filter {
public void init(FilterConfig config) throws ServletException { }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
chain.doFilter(request, response);
String url = ((HttpServletRequest) request).getPathTranslated();
UrlBean urlBean = (UrlBean) FacesContext.getCurrentInstance()getApplication().getValueBinding("#{urlBean}");
urlBean.storeUrl(url);
}
public void destroy() { }
}
This is totally untested, but the idea should work. You would just need to implement some logic (probably a stack) for your component so it stores what you need. (Obviously you might end up at the same URL multiple times). I should note the UrlBean is just an abstract idea, you would have to implement it
Hi I have created this Singleton class to put the Url Browsed by a User.
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class UrlHistory {
#SuppressWarnings("rawtypes")
private static Map<String, List> store = new HashMap<String, List>();
private static UrlHistoryBean instance = null;
public static UrlHistoryBean getInstance() {
if (instance == null) {
instance = new UrlHistoryBean();
}
return instance;
}
LinkedList<UrlData> urlList = new LinkedList<UrlHistoryBean.UrlData>();
public void addUrl(String sessionId, String urlString, int urlId) {
UrlData data = new UrlData();
data.setUrlName(urlString);
data.setUrlId(companyId);
if (urlList.isEmpty()) {
urlList.add(data);
} else {
boolean isEqual = false;
for (UrlData urlDataObj : urlList) {
if (urlDataObj.equals(data))
isEqual = true;
}
if(!isEqual)
urlList.addFirst(data);
}
store.put(sessionId, urlList);
}
#SuppressWarnings("rawtypes")
public static Map<String, List> getStore() {
return store;
}
#SuppressWarnings("rawtypes")
public static void setStore(Map<String, List> store) {
UrlHistoryBean.store = store;
}
public class UrlData {
String urlName;
int urlId;
public String getUrlName() {
return UrlName;
}
public void setUrlName(String UrlName) {
this.UrlName = UrlName;
}
public int getUrlId() {
return urlId;
}
public void setUrlId(int urlId) {
this.urlId = urlId;
}
public boolean equals(UrlData rData) {
boolean bEqual = false;
if (this.getUrlId() > 0 && rData.getUrlId() > 0 && this.getUrlId() == rData.getUrlId()) {
bEqual = true;
}
return bEqual;
}
}
}

Resources