i have struts2.0 in my project, i am storing username in session by implements SessionAware done as follows
public class NewProduct extends ActionSupport implements SessionAware{
private Map session;
public String execute() {
session.put("username", "Rangappa");
return "success"
}
public void setSession(Map session) {
this.session = session;
}
public Map getSession() {
return session;
}
here I am setting session variable here, i m not getting how to get this session variable in other class,
i done as below but its not working
public class NewProduct extends ActionSupport implements SessionAware{
public String execute() throws Exception {
String username = (String) session.get("username");
System.out.println("username: "+username );
return "success"
}
}
both class are in same packages, please let me know solution, Thanks i advance
Use this code after importing the appropriate packages
Map session = ActionContext.getContext().get("session");
String userName = (String)(session.get("username"));
Related
I have a class which extends SequenceStyleGenerator for generating custom primary key for the database.
I'm asked to write test cases for the whole application. While I think that code coverage on SonaqQube can't be 100%, still I'm being asked to write the test cases for the whole application.
I've gone through the source code for SequenceStyleGenerator but I'm unable to get it how to test the class.
Here is the code for the same.
public class BigIntegerSequenceGenerator extends SequenceStyleGenerator {
public static final String VALUE_PREFIX_PARAMETER = "valuePrefix";
public static final String VALUE_PREFIX_DEFAULT = "";
private String valuePrefix;
public static final String NUMBER_FORMAT_PARAMETER = "numberFormat";
public static final String NUMBER_FORMAT_DEFAULT = "%d";
private String numberFormat;
#Override
public Serializable generate(SharedSessionContractImplementor session,
Object object) {
return valuePrefix + String.format(numberFormat, super.generate(session, object));
}
#Override
public void configure(Type type, Properties params,
ServiceRegistry serviceRegistry) {
super.configure(LongType.INSTANCE, params, serviceRegistry);
valuePrefix = ConfigurationHelper.getString(VALUE_PREFIX_PARAMETER,
params, VALUE_PREFIX_DEFAULT);
numberFormat = ConfigurationHelper.getString(NUMBER_FORMAT_PARAMETER,
params, NUMBER_FORMAT_DEFAULT);
}
}
Here is the test for this file
class BigIntegerSequenceGeneratorTest {
SharedSessionContractImplementor session;
BigIntegerSequenceGenerator generator;
#BeforeEach
void setUp() {
generator = new BigIntegerSequenceGenerator();
session = mock(SharedSessionContractImplementor.class);
session = mock(Session.class);
}
#Test
void testGenerate() {
generator.generate(session,new Object());
}
}
I'm getting
java.lang.NullPointerException
at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:520)
I check it by using debug points and this is the code I'm getting.
#Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
return optimizer.generate( databaseStructure.buildCallback( session ) );
}
optimizer and databaseStructure are null.
For what I know, when the SpringBoot application runs, it automatically configures the hibernate and the optimizer and databaseStruictore are configured which will then be used for the models when saving the data.
I know that this will require the database connection mocking but it seems like I'm unable to do it.
NOTE : I'm using JUnit5 for testing
-Thank you
I defined a Logininfo class to store the email and password of a user in. I get the email and password from a Login GUI. There are put into the Logininfo class using setMethods. I'm connecting the programming to a mysql server (mysql is not an issue here). I need the the emailadres and password so I can use it for queries in other GUI's later on.
This is the Logininfo class
public class Logininfo {
public static Emailadres emailadres = new Emailadres();
public static Password password = new Password();
public static class Emailadres
{
private String emailadres;
public Emailadres()
{
emailadres = " ";
}
public void setEmailadres(String emailadres)
{
this.emailadres = emailadres;
}
public String getEmailadres()
{
return(emailadres);
}
}
public static class Password
{
private String password ;
public Password()
{
password = " ";
}
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return(password);
}
}
}
In the login GUI I use the setMethod to store the emailadress and password.
public class Login extends javax.swing.JFrame {
Logininfo logininfo;
Logininfo.Emailadres emailadres = new Logininfo.Emailadres();
Logininfo.Password password = new Logininfo.Password();
private boolean validate_login(String email,String wachtwoord) {
emailadres.setEmailadres(email);
wachtwoord.setPassword(password);
Later on I try to retrieve the emailadress and password in another class.
public class Account extends javax.swing.JFrame {
Logininfo logininfo;
Logininfo.EmailAdres emailadres;
Logininfo.WachtWoord password;
emailadres.getEmailadres(email);
password.getPassword(password);
I get a Nullpointerexception here. I know that you have to make a new instance of Logininfo in the Login GUI screen. However in the Account class you can't make another new instance. Are public class not supposed to be used for this and should I use something else?
Any help would be appreciated
email_adres in your Login class is an instance field of that class, and is completely unrelated to emailadres instance field of Account class. The two pointers point to different places in memory.
If you want the instance of Account to have that data from Login instance, you have to give it to it somehow.
i'm trying to observes a #SessionScoped component after change any property. HttpSessionAttributeListener not fire changes in cdi managed components.
#SuppressWarnings("serial")
#SessionScoped
public class TestSession implements Serializable {
private User user;
public TestSession() {
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
An example Servlet:
#SuppressWarnings("serial")
#WebServlet(name = "demo", urlPatterns = "/demo")
public class DemoServlet extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(DemoServlet.class);
#Inject
private TestSession testSession;
#Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
User user = new User(1L,new Role(1L));
user.setId(RandomUtils.nextLong());
testSession.setUser(user); //listen that component change something
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/demo.jsp");
dispatcher.forward(httpServletRequest, httpServletResponse);
}
}
Is the a way to listen when component change any attribute ? Anyone has some approach to do that ?
Important : I dont have access to rewrite or add code on TestSession java class or servlet .
You can place an interceptor in the setUser() method that creates an event then catch it.
I am using Dropwizard and wrote a Security Provider that should check the session. If a user is available, it should return it. Otherwise it should throw an exception. How can I get the Session from an HttpRequestContext?
public class SecurityProvider<T> implements InjectableProvider<Auth, Parameter> {
private static class Injectable<T> extends AbstractHttpContextInjectable<T> {
#Override
public T getValue(HttpContext c) {
//Here, get somehow the session,
//then check if user is in session,
//if so, proceed
return null;
}
}
#Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}
#Override
public com.sun.jersey.spi.inject.Injectable getInjectable(ComponentContext ic, Auth auth, Parameter parameter) {
return new Injectable<T>();
}
}
I have followed a tutorial on dynamic datasource routing tutorial in Spring. For that I have to extend AbstractRoutingDataSource to tell spring which datasource to get, so I do:
public class CustomRouter extends AbstractRoutingDataSource {
#Override
protected Object determineCurrentLookupKey() {
return CustomerContextHolder.getCustomerType();
}
}
Everything goes fine till I find the class responsible for keeping the value of the customerType (it should be the same during the whole session):
public class CustomerContextHolder {
private static final ThreadLocal<Integer> contextHolder = new ThreadLocal<Integer>();
public static void setCustomerType(Integer customerType) {
contextHolder.set(customerType);
}
public static Integer getCustomerType() {
return (Integer) contextHolder.get();
}
public static void clearCustomerType() {
contextHolder.remove();
}
}
This creates a thread-bound variable customerType, but I have a web application with spring and JSF I don't think with threads but with sessions. So I set it in the login page with thread A (View), but then thread B (Hibernate) request the value to know what datasource to use, it is null indeed, because it has a new value for this thread.
Is there any way to do it Session-bounded instead of Thread-bounded?
Things I have tried so far:
Inject the CustomRouter in the view to set it in the session: Not working, it causes a cycle in dependecies
Replace the ThreadLocal with an Integer: Not working, the value is always set by the last user logged in
Is FacesContext.getCurrentInstance() working? If so then you may try with this:
public class CustomerContextHolder {
private static HttpSession getCurrentSession(){
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
return request.getSession();
}
public static void setCustomerType(Integer customerType) {
CustomerContextHolder.getCurrentSession().setAttribute("userType", customerType);
}
public static Integer getCustomerType() {
return (Integer) CustomerContextHolder.getCurrentSession().getAttribute("userType");
}
public static void clearCustomerType() {
contextHolder.remove(); // You may want to remove the attribute in session, dunno
}
}