Questions regarding JSP & servlet & MongoDB Mlab - java

I am new to MongoDB Mlab, which means not familiar with how to use it and how to connect it with a DAO file. And I encounter a technical issue on SERVLET. Firstly, I try to extract data from MongoDB mlab to get an email & password of a user for my login page. And I also capture the email & password entered by a user on login JSP page by using "request.getParameter("")" method. These two points work fine because I already tested them. More info about my issue is that when I try to extract email and password from MongoDB mlab, I store these two parameters into a user object, and store the user object into an ArrayList. Then return this Arraylist to the login Servlet. Using for-each loop to traversal this list. I put the codes below.
When I try to enter an email and password on the login page, this is the result I encountered
how can I solve it
FDao.java
package Dao;
import static com.sun.corba.se.spi.presentation.rmi.StubAdapter.request;
import java.net.UnknownHostException;
import java.sql.*;
import java.util.*;
import javax.servlet.RequestDispatcher;
import model.Book;
import model.Staff;
import model.User;
import org.bson.Document;
public class FDao {
public List<User> checkLogin() throws UnknownHostException {
Iterator it = DB.getDB().getCollection("users").find().iterator();
List<User> aUser = new ArrayList();
while(it.hasNext()){
Document o = (Document) it.next();
aUser.add(new User(o.getString("email"), o.getString("password")));
}
return aUser;
}
}
LoginServlet.java(I capture string email and string password from login JSP page)
#WebServlet("/Login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
FDao userDao = new FDao();
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String email = request.getParameter("email");
String password = request.getParameter("pass");
List<User> users = new ArrayList();
users = userDao.checkLogin();
for (User user : users) {
if (email.equals(user.getEmail()) && password.equals(user.getPassword()) ) {
//HttpSession session = request.getSession();
//session.setAttribute("user", user);
request.getRequestDispatcher("/home.jsp").include(request, response); //the problem looks like appeared in this line of code
//out.println("Hello World");
} else {
//String message = "Your account does not exist in out database!";
//request.setAttribute("message", message); //message is object
request.getRequestDispatcher("/Login.jsp").include(request, response);//the problem looks like appeared in this line of code
//out.println("Nothing");
}
break;
}
}
}

Related

Authenticate GET request from html extensions in AEM

Good day,
When a user hit specific url with an extension on html, I want to validate if user has logged in. If the user is not logged in, I want to redirect them to my custom login page (this part is done). Else, I want to do nothing - meaning the current page that they are on, should continue being displayed.
I want this to meet client requirements (the default AEM login page should stay as is.
Scenario
The page is /content/mysite/page.html
If I am not logged in, I should be redirected to /content/mysite/login.html
If I am logged in, I should still see this page : /content/mysite/page.html
Now, my problem comes when I am logged in. Instead of seeing content of the page : /content/mysite/page.html, there page is simply blank. There are no contents to be displayed.
Maybe I do not get the concepts of servlets or I do not know how to handle this kind of problem.
Please help resolve this or suggest another route to handle this
Here is my the code I have so far:
package com.company.patientsportal.core.auth;
import java.io.IOException;
import java.util.Map;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.engine.SlingRequestProcessor;
#Service
#SlingServlet(resourceTypes={"patientsportal/components/structure/page"}, selectors="html", methods = "GET", metatype=true, description="My Authentication Verifier")
#Properties
(
{
#Property(name="login.form", description="The form on which the user to enter authentication credentials.", value="")
}
)
public class CheckAuthentication extends SlingAllMethodsServlet
{
/**
*
*/
private static final long serialVersionUID = 8552708551560032677L;
private Map<String, Object> redirects;
#Reference
private Repository repository;
#Reference
private SlingRequestProcessor requestProcessor;
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException
{
ResourceResolver resolver = request.getResourceResolver();
Session session = resolver.adaptTo(Session.class);
String userId = session.getUserID();
String url = request.getRequestPathInfo().getResourcePath();
url = url.substring(0, url.lastIndexOf("/")) + ".html";
if (String.valueOf(userId) == null || (String.valueOf(userId) != null ? String.valueOf(userId).equals("anonymous") : false))
{
String loginForm = getLoginForm("login.form");
if (loginForm != null)
{
response.sendRedirect(loginForm + "?url=" + url);
}
else
{
response.sendRedirect("/content/patientsportal/login.html?url=" + url);
}
}
else
{
//Do nothing or something in the else
//So far, do nothing does not work. It returns blank page even if I do not include the else part
}
}
private String getLoginForm(String loginForm)
{
if (redirects != null)
{
loginForm = (String) redirects.get(loginForm);
return loginForm;
}
return null;
}
#Activate
protected void activate(Map<String, Object> properties)
{
redirects = properties;
}
}
The ideal way of implementing login functionality is to either use the OOTB AEM authentication handler or implement Sling AuthenticationHandler and extending DefaultAuthenticationFeedbackHandler. You can find the code references to implement in lot of blogs -
acs-aem-samples
How to Create Custom Authentication Handler in CQ
After you have implemented this and have created/configured your own login page /form, you need to setup CUG on the pages that are to be exposed only to a logged in user. The details around it are available in AEM documentation here

Retrieve Nested Groups for a user from LDAP using Java program

I searched on net, found similar issues. As I'm newbie to LDAP, had to reach out for help.
Right now code brings all the groups for a user. When user1 logins, it brings Group A.
New Requirement is:
If Group A is member of Group B, we need to retrieve Group B as well along with Group A.
I'm trying to achieve this by tweaking query. I read about some matching rules OID 1.2.840.113556.1.4.1941 & LDAP_MATCHING_RULE_IN_CHAIN. But couldn't figure out how to implement in my code.
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
public abstract class SAPSecurityFilter implements Filter {
protected abstract SAPPrincipal buildGroups(SAPPrincipal principal, NamingEnumeration<SearchResult> results) throws NamingException;
private static final String SECURE_ENTERPRISE_DIRECTORY = "ldaps://ldap.abc.com:636/o=abc.com";
private static final String PRINCIPAL_NAME = "SAPPrincipal";
private static final String ENTERPRISE_DIRECTORY = "ldap://ldap.abc.com:389/o=abc.com";
private static final String USER_KEY = "HTTP_SM_USER";
private static final String BASE = "ou=Groups";
private static final String GROUP_QUERY = "(member=uid=%s,ou=People,o=abc.com)";
private final CacheManager cacheManager;
private List<String> excludeUrlPatterns = new ArrayList<String>();
public SAPSecurityFilter() {
// Setup Cache for principals
// cache Manager
URL url = getClass().getResource("/data-cache.xml");
cacheManager = new CacheManager(url);
}
public void destroy() {
// TODO Auto-generated method stub
}
/**
* doFilter
* <p/>
* Read the request headers for the HTTP_SM_USER value
* This value is the users email address.
* Using the email address lookup the users values in Enterprise directory
* Populate the principal and place it in request scope.
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//SAPt the request into HttpServletRequest
String path = ((HttpServletRequest) request).getPathInfo();
if (patternExcluded(path) || "OPTIONS".equalsIgnoreSAPe(((HttpServletRequest) request).getMethod())) {
chain.doFilter(request, response);
} else {
String smUser = ((HttpServletRequest) request).getRemoteUser();
HttpSession session = ((HttpServletRequest) request).getSession();
if (smUser == null) throw new ServletException("USER TOKEN MISSING");
// use the smUser to get the data needed to build a principal
LdapContext ctx = null;
// build SAP principal //
SAPPrincipal principal = new SAPPrincipal();
principal.setName(smUser);
//Cache cache = cacheManager.getCache("principalCache");
//Element element = cache.get(smUser);
// Cache miss for user
if (session.getAttribute(PRINCIPAL_NAME) == null) {
try {
ctx = getLdapContext(smUser);
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrs = {"cn"};
constraints.setReturningAttributes(attrs);
String filter = String.format(GROUP_QUERY, smUser);
NamingEnumeration<SearchResult> results = ctx.search(BASE, filter, constraints);
principal = buildGroups(principal, results);
//cache.put(new Element(smUser, principal));
session.setAttribute(PRINCIPAL_NAME, principal);
} catch (NamingException ne) {
throw new ServletException(ne);
} finally {
try {
if (ctx != null) ctx.close();
} catch (NamingException ne) {
// swallow on purpose
}
}
// Cache Hit for user
} else {
principal = (SAPPrincipal) session.getAttribute(PRINCIPAL_NAME);
}
// add principal to securityContext and SAPContext//
SAPContext.setPrincipal(principal);
chain.doFilter(new SecurityRequestWrapper(principal, (HttpServletRequest) request), response);
}
}
Your filter needs to be something like:
(member:1.2.840.113556.1.4.1941:=(CN=UserName,CN=Users,DC=YOURDOMAIN,DC=NET))
form:http://ldapwiki.willeke.com/wiki/Active%20Directory%20User%20Related%20Searches
-jim

how to show online user using servlet mapping

i want to show online users using this servlet ......
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.chatapp.useroperation.Client;
#WebServlet(name = "onlineUsersServlet", urlPatterns = { "/getOnlineUsersList" })
public class ListOfOnlineUsers extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String commaSepeparatedStr ="";
ServletContext appScope = request.getServletContext();
String channel = request.getParameter("channel");
final Map<String, List<Client>> clients = (Map<String, List<Client>>) appScope.getAttribute(LoginServlet.CLIENTS);
System.out.println(clients);
if(clients.size()> 0){
final List<Client> onlineClients = clients.get(channel);
if(onlineClients !=null){
for (Client client : onlineClients) {
if(commaSepeparatedStr.equals("") ){
commaSepeparatedStr = client.getUserName();
}else{
commaSepeparatedStr =commaSepeparatedStr+","+ client.getUserName();
}
}
}
}
response.getWriter().write(commaSepeparatedStr);
response.flushBuffer();
}
}
how can i pass value to this servlet from a jsp so that it store the username in its list......is it possible to put value in that servlet from session.
in your jsp do something like this:
<form action="/YOURWEBAPPNAME/onlineUsersServlet/getOnlineUsersList" method="get">
<input type="text" name="test" value="Hello World">
<input type="submit" value="Send">
</form>
in you doGet method do this:
String userInput = request.getParameter("test");
and feel free using that stuff.
put that stuff in the session with:
request.getSession(false).setAttribute("input",userInput);
and read it with:
String lInput = (String) request.getSession(false).getAttribute("input");
If you want to Store a Value from a session to a servlet, just attach an attribute to the Session;
During Login, get the username and store the value into the Session;
HttpSession sess = request.getSession();//Create new Session
//Get the username from login input
String username = request.getParameter("name");
//Attach the name to the Session.
sess.setAttribute("username", username);
Get the value anytime as long as the session is active.
HttpSession sess = request.getSession(false);//Use the current Session
//Get the value fron the Session
String username = (String) sess.getAttribute("username");//get the Attribute Username
You need to have Attached the Attribute to the Session before you can get it this way.
There are variables with a different scope that you can, or not, access from different places in your code. In JavaEE there are variables with request, session and application scope.
The request scope means that you can set it and use it in all your classes for the current request and that's what you seem to need right now.
I'm sorry I can't help you more right now but with this info Google or the SO search box should be your friend. I'll add details later.
Edit -
Stefan beike's answer has these details I'm talking about.

Spring MVC 3.0 Getting Values Out From Sql Query

I am newbie in using Spring MVC 3.0. I am writing a custom authentication class and I would like to know how I can extract the values from a SQL query into variables? Here is an example of what I am trying to achieve, and some code, which I am asking about, is omitted;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.crimetrack.DAO.LoginDAO;
import com.crimetrack.business.Login;
public class JdbcLoginDAO extends JdbcDaoSupport implements LoginDAO {
private final Logger logger = Logger.getLogger(getClass());
String dbUserName;
String dbPassword;
public boolean AuthenticateUser(Login login) {
logger.debug("Authenticating User");
String sql = "SELECT userName, password FROM tblofficers WHERE userName = :userName AND password = :password ";
//code for parameters : userName and password using login.getPassword() and login.getUsername()
//and code to get vaules out from query for comparison
if (dbUserName == login.getUserName()) {
if (dbPassword == login.getPassword()){
return true;
}
}
return false;
}
public static class LoginMapper implements ParameterizedRowMapper<Login>{
public Login mapRow(ResultSet rs, int rowNum) throws SQLException {
Login dbLogin = new Login();
dbLogin.setUserName(rs.getString("userName"));
dbLogin.setPassword(rs.getString("password"));
return dbLogin;
}
}
}
Return the query as another instance of your "Login" class using JDBCTemplate and BeanPropertyRowMapper and then compare the objects.
You'll have to look into JDBCTemplate to define the database connection but eventually this would look like:
UserLogin authenticLogin = (UserLogin) db_connection.queryForObject(sql, new BeanPropertyRowMapper(UserLogin.class));
if (userLogin.getPassword() == authenticLogin.getPassword()) {
return true
}
Basically, BeanPropertRowMapper will create a new instance of a class settting any properties with the same names as columns returned from the query.

User (session) count in cluster

Is there a good way to get the logged in user count in a Java web application that is running in a cluster?
I wrote a simple HttpSessionListener with a static field, but I suppose this doesn't work in cluster. I can see there is a Spring Security solution, but I read in some forums that this is still not ok in cluster.
The product in which I have to implement this user count is trying to be application server independent, currently we support Tomcat, Weblogic and JBoss. At the moment I need a solution for Weblogic 10.3 clusters.
You can maintain the counter in database which will work in cluster env.
A simple tutorial to demonstrate how to determine active users / sessions in a Java Web Application.
package com.hubberspot.javaee.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
#WebListener
public class OnlineUsersCounter implements HttpSessionListener {
private static int numberOfUsersOnline;
public OnlineUsersCounter() {
numberOfUsersOnline = 0;
}
public static int getNumberOfUsersOnline() {
return numberOfUsersOnline;
}
public void sessionCreated(HttpSessionEvent event) {
System.out.println("Session created by Id : " + event.getSession().getId());
synchronized (this) {
numberOfUsersOnline++;
}
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.println("Session destroyed by Id : " + event.getSession().getId());
synchronized (this) {
numberOfUsersOnline--;
}
}
}
Running the below servlet on three different browsers will provide output as : (see fig below)
package com.hubberspot.javaee;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hubberspot.javaee.listener.OnlineUsersCounter;
// #WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// #WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.
#WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
, initParams = { #WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// sessionCreated method gets executed
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60);
try {
out.println("<html>");
out.println("<body>");
out.println("<h2>Number of Users Online : "
+ OnlineUsersCounter.getNumberOfUsersOnline()
+ "</h2>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
Output of the program :
Eclipse Browser ->
Firefox Browser ->
Internet Explorer Browser ->
Console Output ->
For more: http://www.hubberspot.com/2013/09/how-to-determine-active-users-sessions.html

Categories