Clean code.

This commit is contained in:
Christian P. MOMON 2013-06-20 03:04:07 +02:00
parent e96e9ddf13
commit 2fb862090f
16 changed files with 721 additions and 758 deletions

View file

@ -4,35 +4,17 @@ import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
/** /**
* *
*/ */
public class CookieHelper public class CookieHelper
{ {
static protected org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger (CookieHelper.class); static protected org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(CookieHelper.class);
/** /**
* *
*/ */
static public Cookie buildCookie (String name, String value, int duration, boolean isSecure) static public Cookie buildCookie(final String name, final String value, final int duration)
{
Cookie result;
result = new Cookie (name, value);
result.setMaxAge (duration);
result.setPath ("/");
result.setSecure (isSecure);
//
return (result);
}
/**
*
*/
static public Cookie buildCookie (String name, String value, int duration)
{ {
Cookie result; Cookie result;
@ -42,11 +24,46 @@ public class CookieHelper
return (result); return (result);
} }
/**
*
*/
static public Cookie buildCookie(final String name, final String value, final int duration, final boolean isSecure)
{
Cookie result;
result = new Cookie(name, value);
result.setMaxAge(duration);
result.setPath("/");
result.setSecure(isSecure);
//
return (result);
}
/** /**
* *
*/ */
static public Cookie getCookie (Cookie[] cookies, String key) static public boolean exists(final HttpServletRequest request, final String key)
{
boolean result;
if (getCookieValue(request, key) == null)
{
result = false;
}
else
{
result = true;
}
//
return (result);
}
/**
*
*/
static public Cookie getCookie(final Cookie[] cookies, final String key)
{ {
Cookie result = null; Cookie result = null;
@ -62,7 +79,7 @@ public class CookieHelper
{ {
if (cookieCounter < cookies.length) if (cookieCounter < cookies.length)
{ {
if (key.equals (cookies[cookieCounter].getName ())) if (key.equals(cookies[cookieCounter].getName()))
{ {
ended = true; ended = true;
result = cookies[cookieCounter]; result = cookies[cookieCounter];
@ -84,25 +101,23 @@ public class CookieHelper
return (result); return (result);
} }
/** /**
* *
*/ */
static public Cookie getCookie (HttpServletRequest request, String key) static public Cookie getCookie(final HttpServletRequest request, final String key)
{ {
Cookie result = null; Cookie result = null;
result = getCookie(request.getCookies (), key); result = getCookie(request.getCookies(), key);
// //
return(result); return (result);
} }
/** /**
* *
*/ */
static public Object getCookieValue (Cookie[] cookies, String key) static public Object getCookieValue(final Cookie[] cookies, final String key)
{ {
Object result; Object result;
@ -118,59 +133,35 @@ public class CookieHelper
} }
// //
return(result); return (result);
} }
/** /**
* *
*/ */
static public Object getCookieValue (HttpServletRequest request, String key) static public Object getCookieValue(final HttpServletRequest request, final String key)
{ {
Object result; Object result;
result = getCookieValue (request.getCookies (), key); result = getCookieValue(request.getCookies(), key);
// //
return(result); return (result);
} }
/** /**
* *
*/ */
static public boolean exists(HttpServletRequest request, String key) static public void reset(final HttpServletResponse response, final String key)
{
boolean result;
if (getCookieValue(request, key) == null)
{
result = false;
}
else
{
result = true;
}
//
return(result);
}
/**
*
*/
static public void set (HttpServletResponse response, String name, String value, int duration)
{
response.addCookie (buildCookie(name, value, duration));
}
/**
*
*/
static public void reset (HttpServletResponse response, String key)
{ {
response.addCookie(buildCookie(key, "", 0)); response.addCookie(buildCookie(key, "", 0));
} }
/**
*
*/
static public void set(final HttpServletResponse response, final String name, final String value, final int duration)
{
response.addCookie(buildCookie(name, value, duration));
}
} }

View file

@ -1,9 +1,10 @@
package fr.devinsy.kiss4web; package fr.devinsy.kiss4web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** /**
* *
@ -13,6 +14,5 @@ public interface Page
/** /**
* *
*/ */
public void doIt (HttpServletRequest request, HttpServletResponse response) public void doIt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
throws ServletException, IOException;
} }

View file

@ -1,9 +1,16 @@
package fr.devinsy.kiss4web; package fr.devinsy.kiss4web;
import java.io.*; import java.io.IOException;
import javax.servlet.*; import java.io.PrintWriter;
import javax.servlet.http.*;
import fr.devinsy.kiss4web.security.*; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import fr.devinsy.kiss4web.security.SecurityAgent;
import fr.devinsy.kiss4web.security.User;
/** /**
* *
@ -14,19 +21,98 @@ public class PageManager extends HttpServlet
private static PageManager instance = null; private static PageManager instance = null;
protected SecurityAgent securityAgent; protected SecurityAgent securityAgent;
static private org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger (PageManager.class); static private org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(PageManager.class);
/** /**
* *
*/ */
public void init () throws ServletException @Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
{
logger.info("==================================================");
logger.info("getContextPath=[" + request.getContextPath() + "]");
logger.info("getPathInfo=[" + request.getPathInfo() + "]");
logger.info("getPathTranslated=[" + request.getPathTranslated() + "]");
logger.info("getQueryString=[" + request.getQueryString() + "]");
logger.info("getRequestURI=[" + request.getRequestURI() + "]");
logger.info("getRequestURL=[" + request.getRequestURL() + "]");
logger.info("getServletPath=[" + request.getServletPath() + "]");
String className = buildClassName(request.getPathInfo());
logger.info("className=" + className);
Page page = this.instanciatePage("site." + className);
if (page == null)
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Unknow page.");
}
else
{
HttpSession session = request.getSession(false);
String login;
if (session == null)
{
login = null;
}
else
{
login = (String) session.getAttribute("login");
}
if (this.securityAgent.checkPermission(request.getPathInfo(), login))
{
page.doIt(request, response);
logger.info("securityAgent say 'permission OK': (" + login + ", " + request.getPathInfo() + ")");
}
else
{
logger.info("securityAgent say 'permission KO': (" + login + ", " + request.getPathInfo() + ")");
if (login == null)
{
response.sendRedirect("/gestion/login.xhtml");
}
else
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head></head><body>");
out.println("Permission denied.");
out.println("<form method='get' action='javascript:window.back ();'>");
out.println(" <input type='submit' name='retour' value='Retour' />");
out.println("</form>");
out.println("</body></html>");
}
}
}
}
/**
*
*/
@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
/**
*
*/
@Override
public void init() throws ServletException
{ {
// //
instance = this; instance = this;
try try
{ {
this.securityAgent = new SecurityAgent (getInitParameter ("securityDataPath")); this.securityAgent = new SecurityAgent(getInitParameter("securityDataPath"));
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -35,46 +121,44 @@ public class PageManager extends HttpServlet
} }
/** /**
*
*/ */
public static PageManager instance () public Page instanciatePage(final String className)
{ {
return instance; Page result;
Class<Page> pageClass = null;
try
{
pageClass = (Class<Page>) Class.forName(className);
}
catch (java.lang.ClassNotFoundException exception)
{
result = null;
} }
/** logger.info("class=" + pageClass);
*
*/
static public String buildClassName (String pathInfo)
{
String result;
result = null;
if ( pathInfo.equals ("/")) if (pageClass == null)
{ {
result = "Accueil"; result = null;
logger.error("Unknow page: (" + className + ")");
} }
else else
{ {
String[] tokens = pathInfo.split ("/"); try
StringBuffer name = new StringBuffer ();
for (int tokenCounter = 1; tokenCounter < tokens.length - 1; tokenCounter++)
{ {
name.append (tokens[tokenCounter]); result = pageClass.newInstance();
name.append ('.');
} }
catch (java.lang.InstantiationException exception)
if (pathInfo.endsWith ("/"))
{ {
name.append (tokens[tokens.length - 1]); logger.error("Can't instanciate page (" + className + ")");
name.append ('.'); result = null;
}
catch (java.lang.IllegalAccessException exception)
{
logger.error("(2) Can't instanciate page (" + className + ")");
result = null;
} }
logger.info ("==>[" + tokens[tokens.length - 1] + "]");
name.append (formatClassName (tokens[tokens.length - 1]));
result = name.toString ();
} }
// //
@ -84,20 +168,72 @@ public class PageManager extends HttpServlet
/** /**
* *
*/ */
static public String buildClassName2 (String pathInfo) public SecurityAgent securityAgent()
{
SecurityAgent result;
result = this.securityAgent;
//
return (result);
}
/**
*
*/
static public String buildClassName(final String pathInfo)
{
String result;
result = null;
if (pathInfo.equals("/"))
{
result = "Accueil";
}
else
{
String[] tokens = pathInfo.split("/");
StringBuffer name = new StringBuffer();
for (int tokenCounter = 1; tokenCounter < tokens.length - 1; tokenCounter++)
{
name.append(tokens[tokenCounter]);
name.append('.');
}
if (pathInfo.endsWith("/"))
{
name.append(tokens[tokens.length - 1]);
name.append('.');
}
logger.info("==>[" + tokens[tokens.length - 1] + "]");
name.append(formatClassName(tokens[tokens.length - 1]));
result = name.toString();
}
//
return (result);
}
/**
*
*/
static public String buildClassName2(final String pathInfo)
{ {
String result; String result;
if (pathInfo.endsWith (".xhtml")) if (pathInfo.endsWith(".xhtml"))
{ {
char[] source = pathInfo.toCharArray (); char[] source = pathInfo.toCharArray();
StringBuffer out = new StringBuffer (); StringBuffer out = new StringBuffer();
for (char c : source) for (char c : source)
{ {
out.append ("[" + c + "]"); out.append("[" + c + "]");
} }
logger.debug (out.toString ()); logger.debug(out.toString());
char[] target = new char[source.length - 7]; char[] target = new char[source.length - 7];
int lastStartToken = 0; int lastStartToken = 0;
@ -112,7 +248,7 @@ public class PageManager extends HttpServlet
break; break;
case '.': case '.':
target[lastStartToken] = Character.toUpperCase (target[lastStartToken]); target[lastStartToken] = Character.toUpperCase(target[lastStartToken]);
break; break;
default: default:
@ -120,29 +256,29 @@ public class PageManager extends HttpServlet
} }
} }
out = new StringBuffer (); out = new StringBuffer();
for (char c : target) for (char c : target)
{ {
out.append ("[" + c + "]"); out.append("[" + c + "]");
} }
logger.debug (out.toString ()); logger.debug(out.toString());
result = new String (target); result = new String(target);
} }
else if (pathInfo.equals ("/")) else if (pathInfo.equals("/"))
{ {
result = "Accueil"; result = "Accueil";
} }
else if (pathInfo.endsWith ("/")) else if (pathInfo.endsWith("/"))
{ {
char[] source = pathInfo.toCharArray (); char[] source = pathInfo.toCharArray();
StringBuffer out = new StringBuffer (); StringBuffer out = new StringBuffer();
for (char c : source) for (char c : source)
{ {
out.append ("[" + c + "]"); out.append("[" + c + "]");
} }
logger.debug (out.toString ()); logger.debug(out.toString());
char[] target = new char[source.length - 2]; char[] target = new char[source.length - 2];
int lastStartToken = 0; int lastStartToken = 0;
@ -161,9 +297,9 @@ public class PageManager extends HttpServlet
} }
} }
char[] targetPlus = new char [source.length - lastStartToken]; char[] targetPlus = new char[source.length - lastStartToken];
targetPlus[0] = '.'; targetPlus[0] = '.';
targetPlus[1] = Character.toUpperCase (source[lastStartToken]); targetPlus[1] = Character.toUpperCase(source[lastStartToken]);
int index = 2; int index = 2;
for (int nChar = lastStartToken + 1; nChar < source.length - 1; nChar++) for (int nChar = lastStartToken + 1; nChar < source.length - 1; nChar++)
{ {
@ -171,24 +307,24 @@ public class PageManager extends HttpServlet
index += 1; index += 1;
} }
out = new StringBuffer (); out = new StringBuffer();
for (char c : target) for (char c : target)
{ {
out.append ("[" + c + "]"); out.append("[" + c + "]");
} }
logger.debug (out.toString ()); logger.debug(out.toString());
out = new StringBuffer (); out = new StringBuffer();
for (char c : targetPlus) for (char c : targetPlus)
{ {
out.append ("[" + c + "]"); out.append("[" + c + "]");
} }
logger.debug (out.toString ()); logger.debug(out.toString());
result = new String (target) + new String (targetPlus); result = new String(target) + new String(targetPlus);
} }
else else
{ {
logger.debug ("unknow case"); logger.debug("unknow case");
result = null; result = null;
} }
@ -196,180 +332,39 @@ public class PageManager extends HttpServlet
return (result); return (result);
} }
/**
*/
public Page instanciatePage (String className)
{
Page result;
Class<Page> pageClass = null;
try
{
pageClass = (Class<Page>) Class.forName (className);
}
catch (java.lang.ClassNotFoundException exception)
{
result = null;
}
logger.info ("class=" + pageClass);
if (pageClass == null)
{
result = null;
logger.error ("Unknow page: (" + className + ")");
}
else
{
try
{
result = pageClass.newInstance ();
}
catch (java.lang.InstantiationException exception)
{
logger.error ("Can't instanciate page (" + className + ")");
result = null;
}
catch (java.lang.IllegalAccessException exception)
{
logger.error ("(2) Can't instanciate page (" + className + ")");
result = null;
}
}
//
return (result);
}
/** /**
* *
*/ */
public void doGet (HttpServletRequest request, HttpServletResponse response) static public String formatClassName(final String name)
throws IOException, ServletException
{
logger.info ("==================================================");
logger.info ("getContextPath=[" + request.getContextPath () + "]");
logger.info ("getPathInfo=[" + request.getPathInfo () + "]");
logger.info ("getPathTranslated=[" + request.getPathTranslated () + "]");
logger.info ("getQueryString=[" + request.getQueryString () + "]");
logger.info ("getRequestURI=[" + request.getRequestURI () + "]");
logger.info ("getRequestURL=[" + request.getRequestURL () + "]");
logger.info ("getServletPath=[" + request.getServletPath () + "]");
String className = buildClassName (request.getPathInfo ());
logger.info ("className=" + className);
Page page = this.instanciatePage ("site." + className);
if (page == null)
{
response.setContentType ("text/html");
PrintWriter out = response.getWriter();
out.println ("Unknow page.");
}
else
{
HttpSession session = request.getSession (false);
String login;
if (session == null)
{
login = null;
}
else
{
login = (String) session.getAttribute ("login");
}
if (this.securityAgent.checkPermission (request.getPathInfo (), login))
{
page.doIt (request, response);
logger.info ("securityAgent say 'permission OK': (" + login + ", " + request.getPathInfo () + ")");
}
else
{
logger.info ("securityAgent say 'permission KO': (" + login + ", " + request.getPathInfo () + ")");
if (login == null)
{
response.sendRedirect ("/gestion/login.xhtml");
}
else
{
response.setContentType ("text/html");
PrintWriter out = response.getWriter();
out.println ("<html><head></head><body>");
out.println ("Permission denied.");
out.println ("<form method='get' action='javascript:window.back ();'>");
out.println (" <input type='submit' name='retour' value='Retour' />");
out.println ("</form>");
out.println ("</body></html>");
}
}
}
}
/**
*
*/
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet (request, response);
}
/**
*
*/
static public String formatClassName (String name)
{ {
String result; String result;
result = null; result = null;
String[] splittedLastToken = name.split ("\\."); String[] splittedLastToken = name.split("\\.");
String last = splittedLastToken[0]; String last = splittedLastToken[0];
//logger.info ("last=" + last); // logger.info ("last=" + last);
String[] tokens = last.split ("_"); String[] tokens = last.split("_");
StringBuffer all = new StringBuffer (); StringBuffer all = new StringBuffer();
for (String token : tokens) for (String token : tokens)
{ {
//logger.info ("tok=" + token); // logger.info ("tok=" + token);
all.append (Character.toUpperCase (token.charAt (0))); all.append(Character.toUpperCase(token.charAt(0)));
all.append (token.substring (1)); all.append(token.substring(1));
} }
result = all.toString (); result = all.toString();
// //
return (result); return (result);
} }
/** /**
* *
*/ */
public SecurityAgent securityAgent () static public User getUserFromSession(final HttpServletRequest request)
{
SecurityAgent result;
result = this.securityAgent;
//
return (result);
}
/**
*
*/
static public User getUserFromSession (HttpServletRequest request)
{ {
User result; User result;
@ -379,7 +374,7 @@ public class PageManager extends HttpServlet
} }
else else
{ {
HttpSession session = request.getSession (false); HttpSession session = request.getSession(false);
String login; String login;
if (session == null) if (session == null)
@ -388,12 +383,20 @@ public class PageManager extends HttpServlet
} }
else else
{ {
login = (String) session.getAttribute ("login"); login = (String) session.getAttribute("login");
result = PageManager.instance ().securityAgent ().users ().getByLogin (login); result = PageManager.instance().securityAgent().users().getByLogin(login);
} }
} }
// //
return (result); return (result);
} }
/**
*
*/
public static PageManager instance()
{
return instance;
}
} }

View file

@ -6,11 +6,13 @@
package fr.devinsy.kiss4web; package fr.devinsy.kiss4web;
import java.io.*; import java.io.IOException;
import javax.servlet.*; import java.io.PrintWriter;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** /**
* *
@ -19,47 +21,37 @@ public class ServletDispatcher extends SimpleServletDispatcher
{ {
private static final long serialVersionUID = -3471226305721330069L; private static final long serialVersionUID = -3471226305721330069L;
protected org.apache.log4j.Logger logger; protected org.apache.log4j.Logger logger;
//protected Servlets servlets;
// protected Servlets servlets;
/** /**
* *
*/ */
public void init () throws ServletException @Override
public void doIt(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
{ {
super.init(); logger.info("==================================================");
this.logger = org.apache.log4j.Logger.getLogger (this.getClass()); logger.info("getContextPath=[" + request.getContextPath() + "]");
//this.servlets = new Servlets(); logger.info("getPathInfo=[" + request.getPathInfo() + "]");
} logger.info("getPathTranslated=[" + request.getPathTranslated() + "]");
logger.info("getQueryString=[" + request.getQueryString() + "]");
logger.info("getRequestURI=[" + request.getRequestURI() + "]");
logger.info("getRequestURL=[" + request.getRequestURL() + "]");
logger.info("getServletPath=[" + request.getServletPath() + "]");
String className = pathInfoToClassName(request.getPathInfo());
logger.info("className=" + className);
/** HttpServlet servlet = instanciateServlet(className);
*
*/
public void doIt (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
logger.info ("==================================================");
logger.info ("getContextPath=[" + request.getContextPath () + "]");
logger.info ("getPathInfo=[" + request.getPathInfo () + "]");
logger.info ("getPathTranslated=[" + request.getPathTranslated () + "]");
logger.info ("getQueryString=[" + request.getQueryString () + "]");
logger.info ("getRequestURI=[" + request.getRequestURI () + "]");
logger.info ("getRequestURL=[" + request.getRequestURL () + "]");
logger.info ("getServletPath=[" + request.getServletPath () + "]");
String className = pathInfoToClassName (request.getPathInfo ());
logger.info ("className=" + className);
HttpServlet servlet = instanciateServlet (className);
if (servlet == null) if (servlet == null)
{ {
response.setContentType ("text/html"); response.setContentType("text/html");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.println ("<html><head></head><body>"); out.println("<html><head></head><body>");
out.println ("Unknow page."); out.println("Unknow page.");
out.println ("</body></html>"); out.println("</body></html>");
out.close(); out.close();
} }
@ -68,4 +60,15 @@ public class ServletDispatcher extends SimpleServletDispatcher
servlet.service(request, response); servlet.service(request, response);
} }
} }
/**
*
*/
@Override
public void init() throws ServletException
{
super.init();
this.logger = org.apache.log4j.Logger.getLogger(this.getClass());
// this.servlets = new Servlets();
}
} }

View file

@ -55,16 +55,12 @@ public class SimpleServletDispatcher extends HttpServlet
/* 30 */'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '-', '-', '-', '-', '-', /* 30 */'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '-', '-', '-', '-', '-',
/* 40 */'\u0040', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', /* 40 */'\u0040', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
/* 50 */'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '-', '-', '-', '-', '-', /* 50 */'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '-', '-', '-', '-', '-',
/* 60 */'-', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', /* 60 */'-', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F',
'\u006F', /* 70 */'\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '-', '-',
/* 70 */'\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'-', '-',
/* 80 */NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, /* 80 */NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
/* 90 */NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, /* 90 */NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
/* A0 */'\u00A0', '\u00A1', '\u00A2', '\u00A3', '\u00A4', '\u00A5', '\u00A6', '\u00A7', '\u00A8', '\u00A9', '\u00AA', '\u00AB', '\u00AC', '\u00AD', /* A0 */'\u00A0', '\u00A1', '\u00A2', '\u00A3', '\u00A4', '\u00A5', '\u00A6', '\u00A7', '\u00A8', '\u00A9', '\u00AA', '\u00AB', '\u00AC', '\u00AD', '\u00AE', '\u00AF',
'\u00AE', '\u00AF', /* B0 */'-', '\u00B1', '\u00B2', '\u00B3', '\u00B4', '\u00B5', '\u00B6', '\u00B7', '\u00B8', '\u00B9', '\u00BA', '\u00BB', '\u00BC', '\u00BD', '\u00BE', '\u00BF',
/* B0 */'-', '\u00B1', '\u00B2', '\u00B3', '\u00B4', '\u00B5', '\u00B6', '\u00B7', '\u00B8', '\u00B9', '\u00BA', '\u00BB', '\u00BC', '\u00BD',
'\u00BE', '\u00BF',
/* C0 */'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', /* C0 */'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i',
/* D0 */'\u00D0', '\u00D1', 'o', 'o', 'o', 'o', 'o', 'o', '\u00D8', 'u', 'u', 'u', 'u', 'y', '\u00DE', '\u00DF', /* D0 */'\u00D0', '\u00D1', 'o', 'o', 'o', 'o', 'o', 'o', '\u00D8', 'u', 'u', 'u', 'u', 'y', '\u00DE', '\u00DF',
/* E0 */'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', /* E0 */'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i',
@ -250,8 +246,14 @@ public class SimpleServletDispatcher extends HttpServlet
} }
/** /**
* Extract values from a path. Example: "/article-/123/doors/open.xhtml" => * Extract values from a path.
* "123", "doors" and "open". *
* Example:
*
* <pre>
* "/article-/123/doors/open.xhtml";
* => "123", "doors" and "open".
* </pre>
*/ */
static public String[] longRewritedUrlParameters(final String path) static public String[] longRewritedUrlParameters(final String path)
{ {
@ -266,13 +268,18 @@ public class SimpleServletDispatcher extends HttpServlet
/** /**
* Convert a path in a class name, using easy conventions. * Convert a path in a class name, using easy conventions.
* *
* "/" => "Index_xhtml" "/good/" => "good.Good_xhtml" "/good/morning.xhtml" * <pre>
* => "good.Morning_xhtml" "/good/morning_girl.xhtml" => * "/"
* "good.Morning_girl_xhtml" "/good/morning-123.xhtml" => * => "Index_xhtml" "/good/"
* "good.Morning_xhtml" ('123' is detected as a parameter, it will be * => "good.Good_xhtml" "/good/morning.xhtml"
* decoded in the class called later). "/good/morning-/12/toto.jpg" => * => "good.Morning_xhtml" "/good/morning_girl.xhtml"
* "good.Morning" ('12' and 'toto.jpg" are detected as a parameter, they * => "good.Morning_girl_xhtml" "/good/morning-123.xhtml"
* => "good.Morning_xhtml" ('123' is detected as a parameter, it will be
* decoded in the class called later). "/good/morning-/12/toto.jpg"
* => "good.Morning" ('12' and 'toto.jpg" are detected as a parameter, they
* will be decoded in the class called later). * will be decoded in the class called later).
* </pre>
*
*/ */
static public String pathInfoToClassName(final String pathInfo) static public String pathInfoToClassName(final String pathInfo)
{ {
@ -480,9 +487,13 @@ public class SimpleServletDispatcher extends HttpServlet
* Sometimes, URL has to be rewrited because we need to put parameter in the * Sometimes, URL has to be rewrited because we need to put parameter in the
* page name. * page name.
* *
* Example: "/good/give_file?id=123&filename=foo.jpg" => * Example:
* rewriteShorturl("/good/give_file", "123", "foo.jpg"); => *
* "/good/give_file-/123/foo.jpg" * <pre>
* "/good/give_file?id=123&filename=foo.jpg"
* => rewriteShorturl("/good/give_file", "123", "foo.jpg");
* => "/good/give_file-/123/foo.jpg"
* </pre>
* *
* Note: "-/" is used to indicate the start of parameters. * Note: "-/" is used to indicate the start of parameters.
* *
@ -557,9 +568,13 @@ public class SimpleServletDispatcher extends HttpServlet
* Sometimes, URL has to be rewrited because we need to put parameter in the * Sometimes, URL has to be rewrited because we need to put parameter in the
* page name. * page name.
* *
* Example: "/good/article.xhtm?id=123&class=today&title=story's about me" * Example:
*
* <pre>
* "/good/article.xhtm?id=123&class=today&title=story's about me"
* => rewriteShorturl("/good/article", "xhtml", "123", "Story's aboute me"); * => rewriteShorturl("/good/article", "xhtml", "123", "Story's aboute me");
* => "/good/article-123-today-story-s-about-me.xhtml" * => "/good/article-123-today-story-s-about-me.xhtml"
* </pre>
*/ */
static public String rewriteShortUrl(final String uri, final String extension, final String... parameters) static public String rewriteShortUrl(final String uri, final String extension, final String... parameters)
{ {

View file

@ -1,7 +1,6 @@
package fr.devinsy.kiss4web.security; package fr.devinsy.kiss4web.security;
import java.util.Vector;
import java.util.*;
/** /**
* *
@ -11,47 +10,43 @@ public class Group
protected String name; protected String name;
protected Vector<String> members; protected Vector<String> members;
/** /**
* *
*/ */
public Group () public Group()
{ {
this.name = null; this.name = null;
this.members = new Vector<String> (); this.members = new Vector<String>();
} }
/** /**
* *
*/ */
public void addMember (String login) public void addMember(final String login)
{ {
if ((login != null) && (login.length () != 0)) if ((login != null) && (login.length() != 0))
{ {
this.members.add (login); this.members.add(login);
} }
} }
/** /**
* *
*/ */
public boolean contains (String name) public boolean contains(final String name)
{ {
boolean result = false; boolean result = false;
result = this.members.contains (name); result = this.members.contains(name);
// //
return (result); return (result);
} }
/** /**
* *
*/ */
public Vector<String> members () public Vector<String> members()
{ {
Vector<String> result; Vector<String> result;
@ -61,11 +56,10 @@ public class Group
return (result); return (result);
} }
/** /**
* *
*/ */
public String name () public String name()
{ {
String result; String result;
@ -75,11 +69,10 @@ public class Group
return (result); return (result);
} }
/** /**
* *
*/ */
public Group setName (String name) public Group setName(final String name)
{ {
this.name = name; this.name = name;
@ -87,11 +80,11 @@ public class Group
return (this); return (this);
} }
/** /**
* *
*/ */
public String toString () @Override
public String toString()
{ {
String result; String result;

View file

@ -1,7 +1,7 @@
package fr.devinsy.kiss4web.security; package fr.devinsy.kiss4web.security;
import java.util.Iterator;
import java.util.*; import java.util.Vector;
/** /**
* *
@ -13,16 +13,35 @@ public class Groups extends Vector<Group>
/** /**
* *
*/ */
public Groups () public Groups()
{ {
super (); super();
} }
/*
*
*/
public boolean contains(final String name)
{
boolean result;
if (get(name) == null)
{
result = false;
}
else
{
result = true;
}
//
return (result);
}
/** /**
* *
*/ */
public Group get (String name) public Group get(final String name)
{ {
Group result; Group result;
@ -34,13 +53,13 @@ public class Groups extends Vector<Group>
{ {
result = null; result = null;
boolean ended = false; boolean ended = false;
Iterator<Group> iterator = this.iterator (); Iterator<Group> iterator = this.iterator();
while (!ended) while (!ended)
{ {
if (iterator.hasNext ()) if (iterator.hasNext())
{ {
Group group = iterator.next (); Group group = iterator.next();
if (group.name ().equals (name)) if (group.name().equals(name))
{ {
ended = true; ended = true;
result = group; result = group;
@ -58,45 +77,23 @@ public class Groups extends Vector<Group>
return (result); return (result);
} }
/*
*
*/
public boolean contains (String name)
{
boolean result;
if (get (name) == null)
{
result = false;
}
else
{
result = true;
}
//
return (result);
}
/** /**
* *
*/ */
public Vector<String> getLoginGroups (String login) public Vector<String> getLoginGroups(final String login)
{ {
Vector<String> result; Vector<String> result;
result = new Vector<String> (); result = new Vector<String>();
Iterator<Group> iterator = this.iterator (); Iterator<Group> iterator = this.iterator();
while (iterator.hasNext ()) while (iterator.hasNext())
{ {
Group group = iterator.next (); Group group = iterator.next();
if (group.members ().contains (login)) if (group.members().contains(login))
{ {
result.add (group.name ()); result.add(group.name());
} }
} }
@ -104,56 +101,55 @@ public class Groups extends Vector<Group>
return (result); return (result);
} }
/** /**
* *
*/ */
public String getLoginGroupsString (String login) public String getLoginGroupsString(final String login)
{ {
String result; String result;
Vector<String> groups = getLoginGroups (login); Vector<String> groups = getLoginGroups(login);
StringBuffer string = new StringBuffer (); StringBuffer string = new StringBuffer();
for (String group : groups) for (String group : groups)
{ {
if (string.length () == 0) if (string.length() == 0)
{ {
string.append (group); string.append(group);
} }
else else
{ {
string.append (","); string.append(",");
string.append (group); string.append(group);
} }
} }
result = string.toString (); result = string.toString();
// //
return (result); return (result);
} }
/** /**
* *
*/ */
public String toString () @Override
public String toString()
{ {
String result; String result;
StringBuffer out; StringBuffer out;
out = new StringBuffer (); out = new StringBuffer();
Iterator<Group> iterator = this.iterator (); Iterator<Group> iterator = this.iterator();
while (iterator.hasNext ()) while (iterator.hasNext())
{ {
out.append (iterator.next ().toString () + "\n"); out.append(iterator.next().toString() + "\n");
} }
result = out.toString (); result = out.toString();
// //
return (result); return (result);

View file

@ -1,8 +1,8 @@
package fr.devinsy.kiss4web.security; package fr.devinsy.kiss4web.security;
import java.io.*; import java.io.FileInputStream;
import java.util.*; import java.util.Iterator;
import java.util.Properties;
/** /**
* *
@ -12,39 +12,39 @@ public class GroupsFileReader
/** /**
* *
*/ */
static public Groups load (String fileName) throws Exception static public Groups load(final String fileName) throws Exception
{ {
Groups result; Groups result;
result = new Groups (); result = new Groups();
Properties properties = new Properties(); Properties properties = new Properties();
try try
{ {
properties.load (new FileInputStream(fileName)); properties.load(new FileInputStream(fileName));
Iterator<Object> iterator = properties.keySet ().iterator (); Iterator<Object> iterator = properties.keySet().iterator();
while (iterator.hasNext ()) while (iterator.hasNext())
{ {
String key = (String) iterator.next (); String key = (String) iterator.next();
String valueLine = (String) properties.get (key); String valueLine = (String) properties.get(key);
// //
String[] values = valueLine.split (","); String[] values = valueLine.split(",");
Group group = new Group (); Group group = new Group();
group.setName (key); group.setName(key);
for (String value : values) for (String value : values)
{ {
group.addMember (value.trim ()); group.addMember(value.trim());
} }
result.add (group); result.add(group);
} }
} }
catch (Exception exception) catch (Exception exception)
{ {
throw new Exception ("can't load (" + fileName + ")", exception); throw new Exception("can't load (" + fileName + ")", exception);
} }
// //

View file

@ -1,9 +1,6 @@
package fr.devinsy.kiss4web.security; package fr.devinsy.kiss4web.security;
import java.util.Iterator;
import java.util.*;
/** /**
* *
@ -14,22 +11,104 @@ public class SecurityAgent
protected Groups groups; protected Groups groups;
protected Groups permissions; protected Groups permissions;
/** /**
* *
*/ */
public SecurityAgent (String path) throws Exception public SecurityAgent(final String path) throws Exception
{ {
this.users = UsersFileReader.load (path + "users.conf"); this.users = UsersFileReader.load(path + "users.conf");
this.groups = GroupsFileReader.load (path + "groups.conf"); this.groups = GroupsFileReader.load(path + "groups.conf");
this.permissions = GroupsFileReader.load (path + "permissions.conf"); this.permissions = GroupsFileReader.load(path + "permissions.conf");
} }
/**
*
*/
public boolean authenticate(final String login, final String password)
{
boolean result;
User user = this.users.getByLogin(login);
if (user == null)
{
result = false;
}
else if (user.password().equals(password))
{
result = true;
}
else
{
result = false;
}
//
return (result);
}
/** /**
* *
*/ */
public Groups groups () public boolean checkPermission(final String url, final String login)
{
boolean result = false;
Group permitGroups = this.permissions.get(url);
if (permitGroups == null)
{
result = false;
}
else
{
//
boolean ended = false;
Iterator<String> iterator = permitGroups.members().iterator();
while (!ended)
{
if (!iterator.hasNext())
{
ended = true;
result = false;
}
else
{
String groupName = iterator.next();
if (groupName.equals("*"))
{
result = true;
ended = true;
}
else
{
Group members = this.groups.get(groupName);
if (members == null)
{
result = false;
}
else
{
if (members.contains(login))
{
ended = true;
result = true;
}
}
}
}
}
}
//
return (result);
}
/**
*
*/
public Groups groups()
{ {
Groups result; Groups result;
@ -42,7 +121,7 @@ public class SecurityAgent
/** /**
* *
*/ */
public Groups permissions () public Groups permissions()
{ {
Groups result; Groups result;
@ -55,7 +134,7 @@ public class SecurityAgent
/** /**
* *
*/ */
public Users users () public Users users()
{ {
Users result; Users result;
@ -64,88 +143,4 @@ public class SecurityAgent
// //
return (result); return (result);
} }
/**
*
*/
public boolean authenticate (String login, String password)
{
boolean result;
User user = this.users.getByLogin (login);
if (user == null)
{
result = false;
}
else if (user.password ().equals (password))
{
result = true;
}
else
{
result = false;
}
//
return (result);
}
/**
*
*/
public boolean checkPermission (String url, String login)
{
boolean result = false;
Group permitGroups = this.permissions.get (url);
if (permitGroups == null)
{
result = false;
}
else
{
//
boolean ended = false;
Iterator<String> iterator = permitGroups.members ().iterator ();
while (!ended)
{
if (!iterator.hasNext ())
{
ended = true;
result = false;
}
else
{
String groupName = iterator.next ();
if (groupName.equals ("*"))
{
result = true;
ended = true;
}
else
{
Group members = this.groups.get (groupName);
if (members == null)
{
result = false;
}
else
{
if (members.contains (login))
{
ended = true;
result = true;
}
}
}
}
}
}
//
return (result);
}
} }

View file

@ -1,8 +1,5 @@
package fr.devinsy.kiss4web.security; package fr.devinsy.kiss4web.security;
/** /**
* *
*/ */
@ -13,11 +10,10 @@ public class User
protected String realName; protected String realName;
protected String email; protected String email;
/** /**
* *
*/ */
public User () public User()
{ {
this.login = null; this.login = null;
this.password = null; this.password = null;
@ -25,11 +21,10 @@ public class User
this.email = null; this.email = null;
} }
/** /**
* *
*/ */
public String email () public String email()
{ {
String result; String result;
@ -42,7 +37,7 @@ public class User
/** /**
* *
*/ */
public String login () public String login()
{ {
String result; String result;
@ -55,7 +50,7 @@ public class User
/** /**
* *
*/ */
public String password () public String password()
{ {
String result; String result;
@ -68,7 +63,7 @@ public class User
/** /**
* *
*/ */
public String realName () public String realName()
{ {
String result; String result;
@ -78,11 +73,10 @@ public class User
return (result); return (result);
} }
/** /**
* *
*/ */
public User setEmail (String email) public User setEmail(final String email)
{ {
this.email = email; this.email = email;
@ -93,7 +87,7 @@ public class User
/** /**
* *
*/ */
public User setLogin (String login) public User setLogin(final String login)
{ {
this.login = login; this.login = login;
@ -104,7 +98,7 @@ public class User
/** /**
* *
*/ */
public User setPassword (String password) public User setPassword(final String password)
{ {
this.password = password; this.password = password;
@ -115,7 +109,7 @@ public class User
/** /**
* *
*/ */
public User setRealName (String realName) public User setRealName(final String realName)
{ {
this.realName = realName; this.realName = realName;
@ -126,7 +120,8 @@ public class User
/** /**
* *
*/ */
public String toString () @Override
public String toString()
{ {
String result; String result;
@ -136,4 +131,3 @@ public class User
return (result); return (result);
} }
} }

View file

@ -1,8 +1,7 @@
package fr.devinsy.kiss4web.security; package fr.devinsy.kiss4web.security;
import java.util.Iterator;
import java.util.*; import java.util.Vector;
/** /**
* *
@ -11,20 +10,38 @@ public class Users extends Vector<User>
{ {
private static final long serialVersionUID = 6140538630004281217L; private static final long serialVersionUID = 6140538630004281217L;
/** /**
* *
*/ */
public Users () public Users()
{ {
super (); super();
} }
/*
*
*/
public boolean contains(final String login)
{
boolean result;
if (getByLogin(login) == null)
{
result = false;
}
else
{
result = true;
}
//
return (result);
}
/** /**
* *
*/ */
public User getByLogin (String login) public User getByLogin(final String login)
{ {
User result; User result;
@ -36,13 +53,13 @@ public class Users extends Vector<User>
{ {
result = null; result = null;
boolean ended = false; boolean ended = false;
Iterator<User> iterator = this.iterator (); Iterator<User> iterator = this.iterator();
while (!ended) while (!ended)
{ {
if (iterator.hasNext ()) if (iterator.hasNext())
{ {
User user = iterator.next (); User user = iterator.next();
if (user.login ().equals (login)) if (user.login().equals(login))
{ {
ended = true; ended = true;
result = user; result = user;
@ -60,46 +77,25 @@ public class Users extends Vector<User>
return (result); return (result);
} }
/*
*
*/
public boolean contains (String login)
{
boolean result;
if (getByLogin (login) == null)
{
result = false;
}
else
{
result = true;
}
//
return (result);
}
/** /**
* *
*/ */
public String toString () @Override
public String toString()
{ {
String result; String result;
StringBuffer out; StringBuffer out;
out = new StringBuffer (); out = new StringBuffer();
Iterator<User> iterator = this.iterator (); Iterator<User> iterator = this.iterator();
while (iterator.hasNext ()) while (iterator.hasNext())
{ {
out.append (iterator.next ().toString () + "\n"); out.append(iterator.next().toString() + "\n");
} }
result = out.toString (); result = out.toString();
// //
return (result); return (result);

View file

@ -1,8 +1,8 @@
package fr.devinsy.kiss4web.security; package fr.devinsy.kiss4web.security;
import java.io.*; import java.io.FileInputStream;
import java.util.*; import java.util.Iterator;
import java.util.Properties;
/** /**
* *
@ -12,42 +12,41 @@ public class UsersFileReader
/** /**
* *
*/ */
static public Users load (String fileName) throws Exception static public Users load(final String fileName) throws Exception
{ {
Users result; Users result;
result = new Users (); result = new Users();
Properties properties = new Properties(); Properties properties = new Properties();
try try
{ {
properties.load (new FileInputStream(fileName)); properties.load(new FileInputStream(fileName));
Iterator<Object> iterator = properties.keySet ().iterator (); Iterator<Object> iterator = properties.keySet().iterator();
while (iterator.hasNext ()) while (iterator.hasNext())
{ {
String key = (String) iterator.next (); String key = (String) iterator.next();
String valueLine = (String) properties.get (key); String valueLine = (String) properties.get(key);
// //
String[] values = valueLine.split (","); String[] values = valueLine.split(",");
User user = new User (); User user = new User();
user.setLogin (key); user.setLogin(key);
user.setPassword (values[0]); user.setPassword(values[0]);
user.setRealName (values[1]); user.setRealName(values[1]);
user.setEmail (values[2]); user.setEmail(values[2]);
result.add (user); result.add(user);
// //
} }
} }
catch (Exception exception) catch (Exception exception)
{ {
throw new Exception ("can't load (" + fileName + ")", exception); throw new Exception("can't load (" + fileName + ")", exception);
} }
// //
return (result); return (result);
} }

View file

@ -4,41 +4,18 @@ import java.util.List;
import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItem;
/** /**
* *
*/ */
public class FileItemHelper public class FileItemHelper
{ {
//static private org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger (FileItemHelper.class); // static private org.apache.log4j.Logger logger =
// org.apache.log4j.Logger.getLogger (FileItemHelper.class);
/** /**
* List FileItem * List FileItem
*/ */
static public String getItemValue (List items, String name) static public FileItem getItem(final List items, final String name)
{
String result;
FileItem item = getItem(items, name);
if (item == null)
{
result = null;
}
else
{
result = item.getString();
}
//
return(result);
}
/**
* List FileItem
*/
static public FileItem getItem (List items, String name)
{ {
FileItem result; FileItem result;
@ -76,7 +53,29 @@ public class FileItemHelper
} }
// //
return(result); return (result);
}
/**
* List FileItem
*/
static public String getItemValue(final List items, final String name)
{
String result;
FileItem item = getItem(items, name);
if (item == null)
{
result = null;
}
else
{
result = item.getString();
}
//
return (result);
} }
} }

View file

@ -2,24 +2,22 @@ package fr.devinsy.util.web;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
/** /**
* *
*/ */
public class Redirector public class Redirector
{ {
static private org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger (Redirector.class); static private org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Redirector.class);
/** /**
* *
*/ */
static public void redirect (HttpServletResponse response, String destination) static public void redirect(final HttpServletResponse response, final String destination)
{ {
logger.info ("Redirect to <" + destination + ">"); logger.info("Redirect to <" + destination + ">");
response.setHeader ("Location", destination); response.setHeader("Location", destination);
response.setStatus (HttpServletResponse.SC_MOVED_TEMPORARILY); response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
} }
} }

View file

@ -1,18 +1,16 @@
package fr.devinsy.util.web; package fr.devinsy.util.web;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import fr.devinsy.kiss4web.CookieHelper; import fr.devinsy.kiss4web.CookieHelper;
/** /**
* *
*/ */
public class SimpleSecurityAgent public class SimpleSecurityAgent
{ {
static protected org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger (SimpleSecurityAgent.class); static protected org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(SimpleSecurityAgent.class);
final static public String USERID_LABEL = "securityAgent.userId"; final static public String USERID_LABEL = "securityAgent.userId";
final static public String ACCOUNTID_LABEL = "securityAgent.accountId"; final static public String ACCOUNTID_LABEL = "securityAgent.accountId";
final static public String AUTH_LABEL = "securityAgent.auth"; final static public String AUTH_LABEL = "securityAgent.auth";
@ -21,82 +19,47 @@ public class SimpleSecurityAgent
protected String authLabel; protected String authLabel;
protected String secretKey; protected String secretKey;
/** /**
* *
*/ */
public SimpleSecurityAgent(String prefix, String secretKey) public SimpleSecurityAgent(final String prefix, final String secretKey)
{ {
this.userIdLabel = prefix + "." + USERID_LABEL; this.userIdLabel = prefix + "." + USERID_LABEL;
this.accountIdLabel = prefix + "." + ACCOUNTID_LABEL; this.accountIdLabel = prefix + "." + ACCOUNTID_LABEL;
this.authLabel= prefix + "." + AUTH_LABEL; this.authLabel = prefix + "." + AUTH_LABEL;
this.secretKey = secretKey; this.secretKey = secretKey;
} }
/** /**
* *
*/ */
static String md5sum(String source) public String accountId(final HttpServletRequest request)
{
String result;
result = org.apache.commons.codec.digest.DigestUtils.md5Hex(source);
//
return(result);
}
/**
*
*/
public String userId(HttpServletRequest request)
{
String result;
result = (String) CookieHelper.getCookieValue(request, this.userIdLabel);
//
return(result);
}
/**
*
*/
public String accountId(HttpServletRequest request)
{ {
String result; String result;
result = (String) CookieHelper.getCookieValue(request, this.accountIdLabel); result = (String) CookieHelper.getCookieValue(request, this.accountIdLabel);
// //
return(result); return (result);
} }
/** /**
* *
*/ */
public String auth(HttpServletRequest request) public String auth(final HttpServletRequest request)
{ {
String result; String result;
result = (String) CookieHelper.getCookieValue(request, this.authLabel); result = (String) CookieHelper.getCookieValue(request, this.authLabel);
// //
return(result); return (result);
} }
/** /**
* Check authentication and refresh it (reset countdown). * Check authentication and refresh it (reset countdown).
*/ */
public boolean isAuthenticated (HttpServletRequest request, HttpServletResponse response) public boolean isAuthenticated(final HttpServletRequest request, final HttpServletResponse response)
{ {
boolean result; boolean result;
@ -125,44 +88,68 @@ public class SimpleSecurityAgent
return (result); return (result);
} }
/** /**
* *
*/ */
static public String computeAuth(String key1, String key2, String key3, String key4) public void reset(final HttpServletRequest request, final HttpServletResponse response)
{
String result;
result = md5sum(key1 + key2 + key3+ key4);
//
return(result);
}
/**
*
*/
public void setAuthenticated (HttpServletRequest request, HttpServletResponse response, String accountId, String userId)
{
// Refresh cookie.
int duration = 60*60;
String auth = computeAuth(String.valueOf(accountId), userId, request.getRemoteAddr(), this.secretKey);
response.addCookie (CookieHelper.buildCookie(this.authLabel, auth, duration));
response.addCookie (CookieHelper.buildCookie(this.accountIdLabel, accountId, duration));
response.addCookie (CookieHelper.buildCookie(this.userIdLabel, userId, duration));
logger.info("set [" + auth + "," + accountId + "," + userId + "," + request.getRemoteAddr() + ")");
}
/**
*
*/
public void reset(HttpServletRequest request, HttpServletResponse response)
{ {
CookieHelper.reset(response, this.authLabel); CookieHelper.reset(response, this.authLabel);
CookieHelper.reset(response, this.accountIdLabel); CookieHelper.reset(response, this.accountIdLabel);
CookieHelper.reset(response, this.userIdLabel); CookieHelper.reset(response, this.userIdLabel);
} }
/**
*
*/
public void setAuthenticated(final HttpServletRequest request, final HttpServletResponse response, final String accountId, final String userId)
{
// Refresh cookie.
int duration = 60 * 60;
String auth = computeAuth(String.valueOf(accountId), userId, request.getRemoteAddr(), this.secretKey);
response.addCookie(CookieHelper.buildCookie(this.authLabel, auth, duration));
response.addCookie(CookieHelper.buildCookie(this.accountIdLabel, accountId, duration));
response.addCookie(CookieHelper.buildCookie(this.userIdLabel, userId, duration));
logger.info("set [" + auth + "," + accountId + "," + userId + "," + request.getRemoteAddr() + ")");
}
/**
*
*/
public String userId(final HttpServletRequest request)
{
String result;
result = (String) CookieHelper.getCookieValue(request, this.userIdLabel);
//
return (result);
}
/**
*
*/
static public String computeAuth(final String key1, final String key2, final String key3, final String key4)
{
String result;
result = md5sum(key1 + key2 + key3 + key4);
//
return (result);
}
/**
*
*/
static String md5sum(final String source)
{
String result;
result = org.apache.commons.codec.digest.DigestUtils.md5Hex(source);
//
return (result);
}
} }

View file

@ -2,8 +2,7 @@
* Kiss4Web tests. * Kiss4Web tests.
*/ */
import fr.devinsy.kiss4web.*; import fr.devinsy.kiss4web.ServletDispatcher;
/** /**
* *
@ -17,74 +16,69 @@ class FooTester
// Initialize logger. // Initialize logger.
org.apache.log4j.Logger logger = null; org.apache.log4j.Logger logger = null;
org.apache.log4j.BasicConfigurator.configure (); org.apache.log4j.BasicConfigurator.configure();
logger = org.apache.log4j.Logger.getRootLogger();
// logger.setLevel (org.apache.log4j.Level.INFO);
logger.setLevel(org.apache.log4j.Level.INFO);
logger = org.apache.log4j.Logger.getRootLogger (); logger.info("Enter");
//logger.setLevel (org.apache.log4j.Level.INFO);
logger.setLevel (org.apache.log4j.Level.INFO);
logger.info ("Enter");
// //
logger.info ("Set the log file format..."); logger.info("Set the log file format...");
// log =
// org.apache.log4j.Category.getInstance(Application.class.getName());
logger.info("... done.");
// log = org.apache.log4j.Category.getInstance(Application.class.getName()); logger.debug("Exit");
logger.info ("... done."); logger = org.apache.log4j.Logger.getLogger(FooTester.class.getName());
logger.debug ("Exit");
logger = org.apache.log4j.Logger.getLogger (FooTester.class.getName ());
} }
/** /**
* *
*/ */
public static String check (String title, StringBuffer source, String model) public static String check(final String title, final StringBuffer source, final String model)
{ {
String result; String result;
if (source.indexOf (model) == -1) if (source.indexOf(model) == -1)
{ {
result = String.format ("%-40s -> KO <-", title) + "\nGet:\n" + source + "\nWaiting:\n" + model; result = String.format("%-40s -> KO <-", title) + "\nGet:\n" + source + "\nWaiting:\n" + model;
} }
else else
{ {
result = String.format ("%-40s [ OK ] ", title); result = String.format("%-40s [ OK ] ", title);
} }
// //
return (result); return (result);
} }
/** /**
* *
*/ */
public static String testCaller (String pathInfo, String prefix) public static void main(final String[] args)
{ {
String result; System.out.println("----------------------------");
result = "[" + pathInfo + "]=>[" + ServletDispatcher.pathInfoToClassName(pathInfo, prefix) + "]";
//
return(result);
}
/**
*
*/
public static void main(String[] args)
{
System.out.println ("----------------------------");
System.out.println(testCaller("/", "fr.devinsy.website")); System.out.println(testCaller("/", "fr.devinsy.website"));
System.out.println(testCaller("/good/", "fr.devinsy.website")); System.out.println(testCaller("/good/", "fr.devinsy.website"));
System.out.println(testCaller("/good/morning", "fr.devinsy.website")); System.out.println(testCaller("/good/morning", "fr.devinsy.website"));
System.out.println(testCaller("/good/day_day", "fr.devinsy.website")); System.out.println(testCaller("/good/day_day", "fr.devinsy.website"));
System.out.println(testCaller("/good/day.xhtml", "fr.devinsy.website")); System.out.println(testCaller("/good/day.xhtml", "fr.devinsy.website"));
} }
/**
*
*/
public static String testCaller(final String pathInfo, final String prefix)
{
String result;
result = "[" + pathInfo + "]=>[" + ServletDispatcher.pathInfoToClassName(pathInfo, prefix) + "]";
//
return (result);
}
} }