Refactored lot of code about dispatcher with catcher concept. Improved

the lib folder. Added tests.
This commit is contained in:
Christian P. MOMON 2016-09-12 05:09:54 +02:00
parent e120c640fa
commit b03dec79ee
41 changed files with 2571 additions and 1246 deletions

View file

@ -3,20 +3,32 @@
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="test"/>
<classpathentry kind="lib" path="lib/servlet-api.jar" sourcepath="/KIWA/resources/extra-jars/servlet-api-2.4-sources.jar"/>
<classpathentry kind="lib" path="lib/hamcrest-core-1.3.jar"/>
<classpathentry kind="lib" path="lib/junit-4.11.jar"/>
<classpathentry kind="lib" path="lib/log4j-1.2.17.jar"/>
<classpathentry kind="lib" path="lib/slf4j-api-1.7.5.jar"/>
<classpathentry kind="lib" path="lib/slf4j-log4j12-1.7.5.jar"/>
<classpathentry kind="lib" path="lib/commons-codec-1.8.jar" sourcepath="lib/commons-codec-1.8-sources.jar"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="lib" path="lib/commons-fileupload-1.3.jar" sourcepath="lib/commons-fileupload-1.3-sources.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6">
<classpathentry kind="lib" path="lib/devinsy-utils-0.3.1-sources.zip"/>
<classpathentry kind="lib" path="lib/devinsy-utils-0.3.1.jar"/>
<classpathentry kind="lib" path="lib/commons-lang3-3.1-sources.jar"/>
<classpathentry kind="lib" path="lib/commons-lang3-3.1.jar" sourcepath="lib/commons-lang3-3.1-sources.jar"/>
<classpathentry kind="lib" path="lib/Logs/log4j-1.2.17-source.zip"/>
<classpathentry kind="lib" path="lib/Logs/log4j-1.2.17.jar"/>
<classpathentry kind="lib" path="lib/Logs/slf4j-api-1.7.5-sources.jar"/>
<classpathentry kind="lib" path="lib/Logs/slf4j-api-1.7.5.jar"/>
<classpathentry kind="lib" path="lib/Logs/slf4j-log4j12-1.7.5-sources.jar"/>
<classpathentry kind="lib" path="lib/Logs/slf4j-log4j12-1.7.5.jar"/>
<classpathentry kind="lib" path="lib/UnitTesting/hamcrest-core-1.3-sources.jar"/>
<classpathentry kind="lib" path="lib/UnitTesting/hamcrest-core-1.3.jar"/>
<classpathentry kind="lib" path="lib/UnitTesting/junit-4.11-sources.jar"/>
<classpathentry kind="lib" path="lib/UnitTesting/junit-4.11.jar"/>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v7.0">
<attributes>
<attribute name="owner.project.facets" value="jst.utility"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jdk1.6.0_45">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="lib/devinsy-utils-0.3.1-sources.zip"/>
<classpathentry kind="lib" path="lib/devinsy-utils-0.3.1.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<runtime name="Apache Tomcat v7.0"/>
<fixed facet="java"/>
<fixed facet="jst.utility"/>
<installed facet="java" version="1.6"/>

Binary file not shown.

BIN
lib/commons-lang3-3.1.jar Normal file

Binary file not shown.

View file

@ -51,7 +51,7 @@ public class CookieHelper
result = buildCookie(name, value, duration, Scope.HTTP_AND_HTTPS);
//
return (result);
return result;
}
/**
@ -61,14 +61,12 @@ public class CookieHelper
{
Cookie result;
//
try
{
result = new Cookie(name, java.net.URLEncoder.encode(value, "UTF-8"));
result.setMaxAge(duration);
result.setPath("/");
//
boolean secureValue;
if (secure == Scope.HTTPS_ONLY)
{
@ -87,7 +85,7 @@ public class CookieHelper
}
//
return (result);
return result;
}
/**
@ -107,7 +105,7 @@ public class CookieHelper
}
//
return (result);
return result;
}
/**
@ -148,7 +146,7 @@ public class CookieHelper
}
//
return (result);
return result;
}
/**
@ -161,13 +159,13 @@ public class CookieHelper
result = getCookie(request.getCookies(), key);
//
return (result);
return result;
}
/**
* Note: value is UTF-8 decoded.
*/
static public Object getCookieValue(final Cookie[] cookies, final String key)
public static Object getCookieValue(final Cookie[] cookies, final String key)
{
Object result;
@ -191,7 +189,7 @@ public class CookieHelper
}
//
return (result);
return result;
}
/**
@ -204,7 +202,7 @@ public class CookieHelper
result = getCookieValue(request.getCookies(), key);
//
return (result);
return result;
}
/**

View file

@ -1,100 +0,0 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Devinsy-utils.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
/**
*
*/
public class FileItemHelper
{
// static private final Logger logger =
// LoggerFactory.getLogger(FileItemHelper.class);
/**
* List FileItem
*/
public static FileItem getItem(final List items, final String name)
{
FileItem result;
if (name == null)
{
result = null;
}
else
{
result = null;
boolean ended = false;
int itemIndex = 0;
while (!ended)
{
if (itemIndex < items.size())
{
FileItem item = (FileItem) items.get(itemIndex);
if (name.equals(item.getFieldName()))
{
ended = true;
result = item;
}
else
{
itemIndex += 1;
}
}
else
{
ended = true;
result = null;
}
}
}
//
return (result);
}
/**
* List FileItem
*/
public static 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

@ -0,0 +1,33 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web;
/**
*
* @author Christian Pierre MOMON (christian.momon@devinsy.fr)
*/
public class Kiss4webUtils
{
/**
*
*/
public Kiss4webUtils()
{
}
}

View file

@ -18,15 +18,10 @@
*/
package fr.devinsy.kiss4web;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.regex.Matcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -34,42 +29,50 @@ import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.util.strings.StringList;
import fr.devinsy.kiss4web.catchers.BlankCatcher;
import fr.devinsy.kiss4web.catchers.FolderCatcher;
import fr.devinsy.kiss4web.catchers.LongURLCatcher;
import fr.devinsy.kiss4web.catchers.RootCatcher;
import fr.devinsy.kiss4web.catchers.ShortURLCatcher;
import fr.devinsy.kiss4web.catchers.WebContentCatcher;
import fr.devinsy.kiss4web.catchers.WebInfCatcher;
import fr.devinsy.kiss4web.catchers.XHTMLCatcher;
/**
* Rename KissDispatcher?
*
* According that URL is under UTF-8 format. Set Tomcat connector if needs
* (<connector ... URIEncoding="UTF-8" ... />).
* (<connector URIEncoding="UTF-8" />).
*/
public class KissDispatcher extends HttpServlet
{
public enum ContentDispositionType
{
ATTACHMENT,
INLINE
}
private static final long serialVersionUID = -3471226305721330069L;
private static Logger logger = LoggerFactory.getLogger(KissDispatcher.class);
public static final int CACHE_AGE = 2 * 60 * 60;
private String webclassesRootPath;
/*
* "Code can be shortest, speedest and memory smallest, but not the three in same time, only two", unknow citation.
*
* Note: characters array avalaible here
* http://fr.wikipedia.org/wiki/Table_des_caract%C3%A8res_Unicode_%280000-0FFF%29
*/
protected static char NONE = (char) 0;
public static final int DEFAULT_CACHE_AGE = 2 * 60 * 60;
private String webclassesRootPackage;
/**
*
*
*/
*
*/
public KissDispatcher()
{
this.webclassesRootPackage = null;
}
/**
* <pre>
* "/" => "Index_xhtml"
* "/good/" => "good.Good_xhtml"
* "/good/morning.xhtml" => "good.Morning_xhtml"
* "/good/morning_girl.xhtml" => "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).
* </pre>
*
*/
public void dispatch(final HttpServletRequest request, final HttpServletResponse response, final String webClassesRootPath) throws IOException, ServletException
{
long startTime = new Date().getTime();
@ -133,74 +136,44 @@ public class KissDispatcher extends HttpServlet
*
*/
// String path = request.getRequestURI();
String path = request.getPathInfo();
String urlPath = request.getPathInfo();
if (path == null)
if (BlankCatcher.matches(request))
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head></head><body>");
out.println("Unknow path.");
out.println("</body></html>");
out.close();
BlankCatcher.doCatch(response, urlPath);
}
else if ((!path.endsWith("/")) && (!path.endsWith(".xhtml")) && (!path.contains("-/")))
else if (RootCatcher.matches(request))
{
// path = getServletContext().getRealPath("/") +
// request.getRequestURI();
// First, search file in the WebContent root.
path = getServletContext().getRealPath("/") + request.getPathInfo();
logger.debug("path1=" + path);
if (!new File(path).exists())
{
// If file is not in WebContent root, search it in packaged
// classes.
path = getServletContext().getRealPath("/") + "WEB-INF/classes/" + webClassesRootPath.replaceAll("\\.", "/") + request.getPathInfo();
}
logger.debug("path2=" + path);
returnInlineFile(response, new File(path), getServletContext().getMimeType(path));
logger.info("File returned directly [" + path + "] with mimetype [" + getServletContext().getMimeType(path) + "].");
RootCatcher.doCatch(this.getServletConfig(), request, response, webClassesRootPath);
}
else if (LongURLCatcher.matches(request))
{
LongURLCatcher.doCatch(this.getServletConfig(), request, response, webClassesRootPath);
}
else if (FolderCatcher.matches(request))
{
FolderCatcher.doCatch(this.getServletConfig(), request, response, webClassesRootPath);
}
else if (ShortURLCatcher.matches(request))
{
ShortURLCatcher.doCatch(this.getServletConfig(), request, response, webClassesRootPath);
}
else if (XHTMLCatcher.matches(request))
{
XHTMLCatcher.doCatch(this.getServletConfig(), request, response, webClassesRootPath);
}
else if (WebContentCatcher.matches(this.getServletContext(), request))
{
XHTMLCatcher.doCatch(this.getServletConfig(), request, response, webClassesRootPath);
}
else if (WebInfCatcher.matches(this.getServletContext(), request, webClassesRootPath))
{
WebInfCatcher.doCatch(this.getServletContext(), request, response, webClassesRootPath);
}
else
{
String className = pathInfoToClassName(path, webClassesRootPath);
logger.info("className=[" + className + "]");
HttpServlet servlet = instanciateServlet(className);
// servlet.getServletContext().setAttribute(arg0, arg1);
if (servlet == null)
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head></head><body>");
out.println("Unknow page.");
out.println("</body></html>");
out.close();
}
else if (isAuthorized(request, response))
{
servlet.init(this.getServletConfig());
servlet.service(request, response);
}
else
{
/*
* TODO
*
* response.setContentType ("text/html"); PrintWriter
* out = response.getWriter();
*
* out.println ("<html><head></head><body>"); out.println
* ("Not authorized page."); out.println ("</body></html>");
*/
}
logger.info("Request not satisfied [" + urlPath + "]");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
//
@ -212,26 +185,36 @@ public class KissDispatcher extends HttpServlet
*
*/
@Override
public void doDelete(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
{
dispatch(request, response, this.webclassesRootPackage);
}
/**
*
*/
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
{
dispatch(request, response, this.webclassesRootPath);
dispatch(request, response, this.webclassesRootPackage);
}
/**
* Backward compatibility.
*
*/
public void doIt(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
{
dispatch(request, response, this.webclassesRootPath);
dispatch(request, response, this.webclassesRootPackage);
}
/**
*
*/
*
*/
@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
public void doPut(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
{
dispatch(request, response, this.webclassesRootPath);
dispatch(request, response, this.webclassesRootPackage);
}
/**
@ -241,7 +224,11 @@ public class KissDispatcher extends HttpServlet
public void init() throws ServletException
{
super.init();
this.webclassesRootPath = getInitParameter("webClassesRootPath");
logger.info("KissDispatcher init called.");
//
this.webclassesRootPackage = getInitParameter("webClassesRootPackage");
logger.info("webClassesRootPackage loaded=[{}]", this.webclassesRootPackage);
// Set logger.
String logFilepathname = getInitParameter("log4j-init-file");
@ -262,342 +249,4 @@ public class KissDispatcher extends HttpServlet
logger.info("Log initialization done.");
}
}
/**
*
*/
public boolean isAuthorized(final HttpServletRequest request, final HttpServletResponse response)
{
boolean result;
result = true;
//
return (result);
}
/**
*
*/
public static HttpServlet instanciateServlet(final String className)
{
HttpServlet result;
Class<HttpServlet> servletClass = null;
try
{
servletClass = (Class<HttpServlet>) Class.forName(className);
}
catch (java.lang.ClassNotFoundException exception)
{
result = null;
}
logger.info("class=" + servletClass);
if (servletClass == null)
{
result = null;
logger.error("Unknow page: (" + className + ")");
}
else
{
try
{
result = servletClass.newInstance();
}
catch (java.lang.InstantiationException exception)
{
logger.error("Can't instanciate servlet (" + className + ")");
result = null;
}
catch (java.lang.IllegalAccessException exception)
{
logger.error("(2) Can't instanciate servlet (" + className + ")");
result = null;
}
}
//
return (result);
}
/**
* Convert a path in a class name, using easy conventions.
*
* <pre>
* "/" => "Index_xhtml"
* "/good/" => "good.Good_xhtml"
* "/good/morning.xhtml" => "good.Morning_xhtml"
* "/good/morning_girl.xhtml" => "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).
* </pre>
*
*/
public static String pathInfoToClassName(final String pathInfo)
{
String result;
if ((pathInfo == null) || (pathInfo.length() == 0))
{
result = null;
}
else
{
if (pathInfo.equals("/"))
{
result = "Index_xhtml";
}
else
{
int keywordIndex = pathInfo.lastIndexOf("-/");
if (keywordIndex != -1)
{
// Long rewrited URL case.
String[] tokens = pathInfo.substring(0, keywordIndex).split("/");
StringList name = new StringList();
// Note: as pathInfo starts always with a '/', the first
// good token index is 1.
for (int tokenCounter = 1; tokenCounter < (tokens.length - 1); tokenCounter++)
{
name.append(tokens[tokenCounter]);
name.append('.');
}
String lastToken = tokens[tokens.length - 1];
name.append(lastToken.substring(0, 1).toUpperCase()).append(lastToken.substring(1).replace('.', '_'));
result = name.toString();
}
else
{
String[] tokens = pathInfo.split("/");
StringList name = new StringList();
// Note: as pathInfo starts always with a '/', the first
// good token index is 1.
for (int tokenCounter = 1; tokenCounter < (tokens.length - 1); tokenCounter++)
{
name.append(tokens[tokenCounter]);
name.append('.');
}
String lastToken = tokens[tokens.length - 1];
if (pathInfo.endsWith("/"))
{
name.append(lastToken).append(".").append(lastToken.substring(0, 1).toUpperCase()).append(lastToken.substring(1)).append("_xhtml");
}
else
{
Matcher matcher = SHORT_REWRITED_URL_CLASS.matcher(lastToken);
if (matcher.matches())
{
// Short rewrited URL case.
// logger.debug("group 1=[" + matcher.group(1) +
// "]");
lastToken = matcher.group(1) + ".xhtml";
}
name.append(lastToken.substring(0, 1).toUpperCase()).append(lastToken.substring(1).replace('.', '_'));
}
result = name.toString();
logger.debug("==>[" + tokens[tokens.length - 1] + "]");
}
}
}
logger.info("[" + pathInfo + "] => [" + result + "]");
//
return (result);
}
/**
*
*/
public static String pathInfoToClassName(final String pathInfo, final String prefix)
{
String result;
String className = pathInfoToClassName(pathInfo);
if (prefix == null)
{
result = className;
}
else if (prefix.endsWith("."))
{
result = prefix + className;
}
else
{
result = prefix + "." + className;
}
//
return (result);
}
/**
*
*/
public static void returnAttachmentFile(final HttpServletResponse response, final File file, final String mimeType) throws IOException
{
returnFile(response, file, mimeType, ContentDispositionType.ATTACHMENT);
}
/**
*
*/
public static void returnFile(final HttpServletResponse response, final File file, final String mimeType, final ContentDispositionType contentDisposition) throws IOException
{
if ((file == null) || (!file.exists()))
{
logger.warn("File not found [" + file.getAbsolutePath() + "]");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
else
{
/*
* response.setContentType("application/" + extension);
* response.setContentLength((int) data.length);
* response.setHeader("Content-Disposition"
* ,"attachment; filename=\"" + filename + "\"");
* response.flushBuffer();
*/
response.reset();
response.setContentType(mimeType);
response.setContentLength((int) file.length());
String contentDispositionToken;
if (contentDisposition == ContentDispositionType.ATTACHMENT)
{
contentDispositionToken = "attachment";
}
else
{
contentDispositionToken = "inline";
}
response.setHeader("Content-Disposition", contentDispositionToken + "; filename=\"" + file.getName() + "\"");
response.setDateHeader("Expires", new Date().getTime() + CACHE_AGE * 1000);
response.setHeader("Cache-Control", "max-age=" + CACHE_AGE);
response.flushBuffer();
ServletOutputStream out = response.getOutputStream();
FileInputStream in = null;
try
// Only for the in.
{
byte[] buffer = new byte[64 * 1024];
in = new FileInputStream(file);
boolean ended = false;
while (!ended)
{
int count = in.read(buffer);
if (count == -1)
{
ended = true;
}
else
{
out.write(buffer, 0, count);
}
}
out.flush();
out.close();
}
catch (IOException exception)
{
response.sendError(HttpServletResponse.SC_PARTIAL_CONTENT);
}
finally
{
if (in != null)
{
in.close();
}
}
}
}
/**
*
*/
public static void returnFile(final HttpServletResponse response, final String fileName, final byte[] data, final String mimeType, final ContentDispositionType contentDisposition,
final int cacheAge) throws IOException
{
if (data == null)
{
logger.warn("data is null.");
}
/*
* response.setContentType("application/" + extension);
* response.setContentLength((int) data.length);
* response.setHeader("Content-Disposition"
* ,"attachment; filename=\"" + filename + "\"");
* response.flushBuffer();
*/
response.reset();
response.setContentType(mimeType);
response.setContentLength(data.length);
String contentDispositionToken;
if (contentDisposition == ContentDispositionType.ATTACHMENT)
{
contentDispositionToken = "attachment";
}
else
{
contentDispositionToken = "inline";
}
response.setHeader("Content-Disposition", contentDispositionToken + "; filename=\"" + fileName + "\"");
response.setDateHeader("Expires", new Date().getTime() + cacheAge * 1000);
response.setHeader("Cache-Control", "max-age=" + cacheAge);
response.flushBuffer();
ServletOutputStream out = response.getOutputStream();
try
{
out.write(data, 0, data.length);
}
catch (IOException exception)
{
exception.printStackTrace();
response.sendError(HttpServletResponse.SC_PARTIAL_CONTENT);
}
finally
{
try
{
out.flush();
out.close();
}
catch (IOException exception)
{
exception.printStackTrace();
}
}
}
/**
*
*/
public static void returnInlineFile(final HttpServletResponse response, final File file, final String mimeType) throws IOException
{
returnFile(response, file, mimeType, ContentDispositionType.INLINE);
}
}

View file

@ -0,0 +1,536 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.catchers.ShortURLRewriter;
import fr.devinsy.util.strings.StringList;
/**
*
*/
public class KissDispatcherUtils
{
public enum ContentDispositionType
{
ATTACHMENT,
INLINE
}
private static Logger logger = LoggerFactory.getLogger(KissDispatcherUtils.class);
/**
*
*/
@Deprecated
public static 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);
}
/**
*
*/
public static String concatenatePackage(final String path, final String className)
{
String result;
if (path == null)
{
result = className;
}
else if (path.endsWith("."))
{
result = path + className;
}
else
{
result = path + "." + className;
}
//
return result;
}
/**
*
* @param className
* @throws IOException
* @throws ServletException
*/
public static void dispatchToServlet(final ServletConfig servletConfig, final HttpServletRequest request, final HttpServletResponse response, final String className) throws IOException,
ServletException
{
HttpServlet servlet = instanciateServlet(className);
// servlet.getServletContext().setAttribute(arg0, arg1);
if (servlet == null)
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head></head><body>");
out.println("Unknown page.");
out.println("</body></html>");
out.close();
}
else
{
servlet.init(servletConfig);
servlet.service(request, response);
}
}
/**
*
*/
@Deprecated
public static String formatClassName(final String name)
{
String result;
result = null;
String[] splittedLastToken = name.split("\\.");
String last = splittedLastToken[0];
// logger.info ("last=" + last);
String[] tokens = last.split("_");
StringBuffer all = new StringBuffer();
for (String token : tokens)
{
// logger.info ("tok=" + token);
all.append(Character.toUpperCase(token.charAt(0)));
all.append(token.substring(1));
}
result = all.toString();
//
return (result);
}
/**
*
*/
public static HttpServlet instanciateServlet(final String className)
{
HttpServlet result;
Class<HttpServlet> servletClass = null;
try
{
servletClass = (Class<HttpServlet>) Class.forName(className);
}
catch (java.lang.ClassNotFoundException exception)
{
result = null;
}
logger.info("class=" + servletClass);
if (servletClass == null)
{
result = null;
logger.error("unknown page: (" + className + ")");
}
else
{
try
{
result = servletClass.newInstance();
}
catch (java.lang.InstantiationException exception)
{
logger.error("Can't instanciate servlet (" + className + ")", exception);
result = null;
}
catch (java.lang.IllegalAccessException exception)
{
logger.error("(2) Can't instanciate servlet (" + className + ")", exception);
result = null;
}
}
//
return result;
}
/**
* Convert a path in a class name, using kiss conventions.
*
* <pre>
* "/" => "Index_xhtml"
* "/good/" => "good.Good_xhtml"
* "/good/morning.xhtml" => "good.Morning_xhtml"
* "/good/morning_girl.xhtml" => "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).
* </pre>
*
*/
@Deprecated
public static String pathInfoToClassName(final String pathInfo)
{
String result;
if ((pathInfo == null) || (pathInfo.length() == 0))
{
result = null;
}
else if (pathInfo.equals("/"))
{
result = "Index_xhtml";
}
else
{
int keywordIndex = pathInfo.lastIndexOf("-/");
if (keywordIndex != -1)
{
// Long rewrited URL case.
String[] tokens = pathInfo.substring(0, keywordIndex).split("/");
StringList name = new StringList();
// Note: as pathInfo starts always with a '/', the first
// good token index is 1.
for (int tokenCounter = 1; tokenCounter < (tokens.length - 1); tokenCounter++)
{
name.append(tokens[tokenCounter]);
name.append('.');
}
String lastToken = tokens[tokens.length - 1];
name.append(lastToken.substring(0, 1).toUpperCase()).append(lastToken.substring(1).replace('.', '_'));
result = name.toString();
}
else
{
StringList name = new StringList();
String[] tokens = pathInfo.split("/");
// Note: as pathInfo starts always with a '/', the first
// good token index is 1.
for (int tokenCounter = 1; tokenCounter < (tokens.length - 1); tokenCounter++)
{
name.append(tokens[tokenCounter]);
name.append('.');
}
String lastToken = tokens[tokens.length - 1];
if (pathInfo.endsWith("/"))
{
name.append(lastToken).append(".").append(lastToken.substring(0, 1).toUpperCase()).append(lastToken.substring(1)).append("_xhtml");
}
else
{
String className = ShortURLRewriter.unrewrite(lastToken);
if (className == null)
{
name.append(lastToken.substring(0, 1).toUpperCase()).append(lastToken.substring(1).replace('.', '_'));
}
else
{
name.append(lastToken.substring(0, 1).toUpperCase()).append(className);
}
}
result = name.toString();
logger.debug("==>[" + tokens[tokens.length - 1] + "]");
}
}
logger.info("[" + pathInfo + "] => [" + result + "]");
//
return result;
}
/**
*
*/
@Deprecated
public static String pathInfoToClassName(final String pathInfo, final String prefix)
{
String result;
String className = pathInfoToClassName(pathInfo);
if (prefix == null)
{
result = className;
}
else if (prefix.endsWith("."))
{
result = prefix + className;
}
else
{
result = prefix + "." + className;
}
//
return result;
}
/**
*
*/
public static void returnAttachmentFile(final HttpServletResponse response, final File file, final String mimeType) throws IOException
{
returnFile(response, file, mimeType, ContentDispositionType.ATTACHMENT);
}
/**
*
*/
public static void returnFile(final HttpServletResponse response, final File file, final String mimeType, final ContentDispositionType contentDisposition) throws IOException
{
if ((file == null) || (!file.exists()))
{
logger.warn("File not found [" + file.getAbsolutePath() + "]");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
else
{
/*
* response.setContentType("application/" + extension);
* response.setContentLength((int) data.length);
* response.setHeader("Content-Disposition"
* ,"attachment; filename=\"" + filename + "\"");
* response.flushBuffer();
*/
response.reset();
response.setContentType(mimeType);
response.setContentLength((int) file.length());
String contentDispositionToken;
if (contentDisposition == ContentDispositionType.ATTACHMENT)
{
contentDispositionToken = "attachment";
}
else
{
contentDispositionToken = "inline";
}
response.setHeader("Content-Disposition", contentDispositionToken + "; filename=\"" + file.getName() + "\"");
response.setDateHeader("Expires", new Date().getTime() + KissDispatcher.DEFAULT_CACHE_AGE * 1000);
response.setHeader("Cache-Control", "max-age=" + KissDispatcher.DEFAULT_CACHE_AGE);
response.flushBuffer();
ServletOutputStream out = response.getOutputStream();
FileInputStream in = null;
try
// Only for the in.
{
byte[] buffer = new byte[64 * 1024];
in = new FileInputStream(file);
boolean ended = false;
while (!ended)
{
int count = in.read(buffer);
if (count == -1)
{
ended = true;
}
else
{
out.write(buffer, 0, count);
}
}
out.flush();
out.close();
}
catch (IOException exception)
{
response.sendError(HttpServletResponse.SC_PARTIAL_CONTENT);
}
finally
{
if (in != null)
{
in.close();
}
}
}
}
/**
*
*/
public static void returnFile(final HttpServletResponse response, final String fileName, final byte[] data, final String mimeType, final ContentDispositionType contentDisposition,
final int cacheAge) throws IOException
{
if (data == null)
{
logger.warn("data is null.");
}
/*
* response.setContentType("application/" + extension);
* response.setContentLength((int) data.length);
* response.setHeader("Content-Disposition"
* ,"attachment; filename=\"" + filename + "\"");
* response.flushBuffer();
*/
response.reset();
response.setContentType(mimeType);
response.setContentLength(data.length);
String contentDispositionToken;
if (contentDisposition == ContentDispositionType.ATTACHMENT)
{
contentDispositionToken = "attachment";
}
else
{
contentDispositionToken = "inline";
}
response.setHeader("Content-Disposition", contentDispositionToken + "; filename=\"" + fileName + "\"");
response.setDateHeader("Expires", new Date().getTime() + cacheAge * 1000);
response.setHeader("Cache-Control", "max-age=" + cacheAge);
response.flushBuffer();
ServletOutputStream out = response.getOutputStream();
try
{
out.write(data, 0, data.length);
}
catch (IOException exception)
{
exception.printStackTrace();
response.sendError(HttpServletResponse.SC_PARTIAL_CONTENT);
}
finally
{
try
{
out.flush();
out.close();
}
catch (IOException exception)
{
exception.printStackTrace();
}
}
}
/**
*
*/
public static void returnInlineFile(final HttpServletResponse response, final File file, final String mimeType) throws IOException
{
returnFile(response, file, mimeType, ContentDispositionType.INLINE);
}
/**
*
* @param request
* @return
*/
public static String showParameters(final HttpServletRequest request)
{
String result;
//
StringList buffer = new StringList();
//
boolean ended = false;
Enumeration<String> names = request.getParameterNames();
buffer.appendln("Parameter list:");
while (!ended)
{
if (names.hasMoreElements())
{
String name = names.nextElement();
buffer.append("[").append(name).append("]=[").append(request.getParameter(name)).appendln("]");
}
else
{
ended = true;
}
}
//
result = buffer.toString();
//
return result;
}
}

View file

@ -1,421 +0,0 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web;
import java.io.IOException;
import java.io.PrintWriter;
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;
/**
*
*/
public class PageManager extends HttpServlet
{
private static final long serialVersionUID = 1983715791417570578L;
private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(PageManager.class);
private static PageManager instance = null;
private SecurityAgent securityAgent;
/**
*
*/
@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;
try
{
this.securityAgent = new SecurityAgent(getInitParameter("securityDataPath"));
}
catch (Exception exception)
{
throw new ServletException("SecurityAgent initialization failed.", exception);
}
}
/**
*/
public Page instanciatePage(final 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 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);
}
/**
*
*/
public static String buildClassName2(final String pathInfo)
{
String result;
if (pathInfo.endsWith(".xhtml"))
{
char[] source = pathInfo.toCharArray();
StringBuffer out = new StringBuffer();
for (char c : source)
{
out.append("[" + c + "]");
}
logger.debug(out.toString());
char[] target = new char[source.length - 7];
int lastStartToken = 0;
for (int nChar = 1; nChar < source.length - 5; nChar++)
{
char charSource = source[nChar];
switch (charSource)
{
case '/':
target[nChar - 1] = '.';
lastStartToken = nChar;
break;
case '.':
target[lastStartToken] = Character.toUpperCase(target[lastStartToken]);
break;
default:
target[nChar - 1] = source[nChar];
}
}
out = new StringBuffer();
for (char c : target)
{
out.append("[" + c + "]");
}
logger.debug(out.toString());
result = new String(target);
}
else if (pathInfo.equals("/"))
{
result = "Accueil";
}
else if (pathInfo.endsWith("/"))
{
char[] source = pathInfo.toCharArray();
StringBuffer out = new StringBuffer();
for (char c : source)
{
out.append("[" + c + "]");
}
logger.debug(out.toString());
char[] target = new char[source.length - 2];
int lastStartToken = 0;
for (int nChar = 1; nChar < source.length - 1; nChar++)
{
char charSource = source[nChar];
switch (charSource)
{
case '/':
target[nChar - 1] = '.';
lastStartToken = nChar + 1;
break;
default:
target[nChar - 1] = source[nChar];
}
}
char[] targetPlus = new char[source.length - lastStartToken];
targetPlus[0] = '.';
targetPlus[1] = Character.toUpperCase(source[lastStartToken]);
int index = 2;
for (int nChar = lastStartToken + 1; nChar < source.length - 1; nChar++)
{
targetPlus[index] = source[nChar];
index += 1;
}
out = new StringBuffer();
for (char c : target)
{
out.append("[" + c + "]");
}
logger.debug(out.toString());
out = new StringBuffer();
for (char c : targetPlus)
{
out.append("[" + c + "]");
}
logger.debug(out.toString());
result = new String(target) + new String(targetPlus);
}
else
{
logger.debug("unknow case");
result = null;
}
//
return (result);
}
/**
*
*/
public static String formatClassName(final String name)
{
String result;
result = null;
String[] splittedLastToken = name.split("\\.");
String last = splittedLastToken[0];
// logger.info ("last=" + last);
String[] tokens = last.split("_");
StringBuffer all = new StringBuffer();
for (String token : tokens)
{
// logger.info ("tok=" + token);
all.append(Character.toUpperCase(token.charAt(0)));
all.append(token.substring(1));
}
result = all.toString();
//
return (result);
}
/**
*
*/
public static User getUserFromSession(final HttpServletRequest request)
{
User result;
if (request == null)
{
result = null;
}
else
{
HttpSession session = request.getSession(false);
String login;
if (session == null)
{
result = null;
}
else
{
login = (String) session.getAttribute("login");
result = PageManager.instance().securityAgent().users().getByLogin(login);
}
}
//
return (result);
}
/**
*
*/
public static PageManager instance()
{
return instance;
}
}

View file

@ -28,6 +28,29 @@ import org.slf4j.LoggerFactory;
*/
public class Redirector
{
public enum Type
{
MOVED_PERMANENTLY(HttpServletResponse.SC_MOVED_PERMANENTLY),
MOVED_TEMPORARILY(HttpServletResponse.SC_MOVED_TEMPORARILY);
private int statusCode;
private Type(final int value)
{
this.statusCode = value;
}
public int statusCode()
{
int result;
result = this.statusCode;
//
return result;
}
}
private static final Logger logger = LoggerFactory.getLogger(Redirector.class);
/**
@ -37,8 +60,38 @@ public class Redirector
{
logger.info("Redirect to <" + destination + ">");
response.setHeader("Location", destination);
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
redirect(response, destination, Type.MOVED_TEMPORARILY);
}
/**
*
* @param response
* @param destination
* if null then use the "/" value.
* @param type
*/
public static void redirect(final HttpServletResponse response, final String destination, final Type type)
{
logger.info("Redirect to <" + destination + ">");
if ((response == null) || (type == null))
{
throw new IllegalArgumentException("Null parameter.");
}
else
{
String target;
if (destination == null)
{
target = "/";
}
else
{
target = destination;
}
response.setHeader("Location", target);
response.setStatus(type.statusCode());
}
}
}

View file

@ -1,89 +0,0 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*/
public class ServletDispatcher extends KissDispatcher
{
private static final long serialVersionUID = -3471226305721330069L;
private static Logger logger;
// protected Servlets servlets;
/**
*
*/
@Override
public void doIt(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 = pathInfoToClassName(request.getPathInfo());
logger.info("className=" + className);
HttpServlet servlet = instanciateServlet(className);
if (servlet == null)
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head></head><body>");
out.println("Unknow page.");
out.println("</body></html>");
out.close();
}
else
{
servlet.service(request, response);
}
}
/**
*
*/
@Override
public void init() throws ServletException
{
super.init();
logger = LoggerFactory.getLogger(this.getClass());
// this.servlets = new Servlets();
}
}

View file

@ -1,67 +0,0 @@
/**
* Copyright (C) 2006-2010, 2013-2014 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import fr.devinsy.util.strings.StringList;
/**
*
*/
public class ServletTools
{
/**
*
* @param request
* @return
*/
public static String showParameters(final HttpServletRequest request)
{
String result;
//
StringList buffer = new StringList();
//
boolean ended = false;
Enumeration<String> names = request.getParameterNames();
buffer.appendln("Parameter list:");
while (!ended)
{
if (names.hasMoreElements())
{
String name = names.nextElement();
buffer.append("[").append(name).append("]=[").append(request.getParameter(name)).appendln("]");
}
else
{
ended = true;
}
}
//
result = buffer.toString();
//
return result;
}
}

View file

@ -33,14 +33,16 @@ import fr.devinsy.util.strings.StringList;
public class SimpleSecurityAgent
{
private static final Logger logger = LoggerFactory.getLogger(SimpleSecurityAgent.class);
public static final String USERID_LABEL = "securityAgent.userId";
public static final String ACCOUNTID_LABEL = "securityAgent.accountId";
public static final String AUTH_LABEL = "securityAgent.auth";
private static final int DEFAULT_AUTHENTICATION_DURATION = 60 * 60;
private String userIdLabel;
private String accountIdLabel;
private String authLabel;
private String secretKey;
private static final int DEFAULT_AUTHENTICATION_DURATION = 60 * 60;
private int authenticationDuration;
/**
@ -65,7 +67,7 @@ public class SimpleSecurityAgent
result = (String) CookieHelper.getCookieValue(request, this.accountIdLabel);
//
return (result);
return result;
}
/**
@ -78,7 +80,7 @@ public class SimpleSecurityAgent
result = (String) CookieHelper.getCookieValue(request, this.authLabel);
//
return (result);
return result;
}
/**
@ -107,7 +109,30 @@ public class SimpleSecurityAgent
}
//
return (result);
return result;
}
/**
*
* @param source
* @return
*/
public String digestWithSecret(final String source)
{
String result;
if (source == null)
{
result = null;
}
else
{
String key = source + this.secretKey;
result = digest(key);
}
//
return result;
}
/**
@ -147,29 +172,6 @@ public class SimpleSecurityAgent
result = false;
}
//
return (result);
}
/**
*
* @param source
* @return
*/
public String md5sumWithSecret(final String source)
{
String result;
if (source == null)
{
result = null;
}
else
{
String key = source + this.secretKey;
result = digest(key);
}
//
return result;
}
@ -218,7 +220,7 @@ public class SimpleSecurityAgent
result = (String) CookieHelper.getCookieValue(request, this.userIdLabel);
//
return (result);
return result;
}
/**
@ -246,6 +248,6 @@ public class SimpleSecurityAgent
}
//
return (result);
return result;
}
}

View file

@ -0,0 +1,78 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*/
public class BlankCatcher
{
private static Logger logger = LoggerFactory.getLogger(BlankCatcher.class);
/**
* @throws IOException
*
*/
public static void doCatch(final HttpServletResponse response, final String urlPath) throws IOException
{
logger.debug("Doing catch.");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head></head><body>");
out.println("Null path.");
out.println("</body></html>");
out.close();
}
/**
*
* @param urlPath
* @return
*/
public static boolean matches(final HttpServletRequest request)
{
boolean result;
String urlPath = request.getPathInfo();
if ((urlPath == null) || (urlPath.length() == 0))
{
result = true;
}
else
{
result = false;
}
//
return result;
}
}

View file

@ -1,36 +1,37 @@
/**
* Copyright (C) 2006-2010, 2013-2014 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
public interface Page
{
/**
*
*/
public void doIt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
public interface Catcher
{
void dispatch(final HttpServletRequest request, final HttpServletResponse response) throws Exception;
/**
*
* @param source
* @return
*/
boolean matches(final String urlPath);
}

View file

@ -0,0 +1,38 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.util.ArrayList;
/**
*
*/
public class Catchers extends ArrayList<Catcher>
{
private static final long serialVersionUID = -5400120588573116300L;
/**
*
*/
public Catchers()
{
super();
}
}

View file

@ -0,0 +1,108 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.KissDispatcherUtils;
import fr.devinsy.util.strings.StringList;
/**
*
*/
public class FolderCatcher
{
private static Logger logger = LoggerFactory.getLogger(FolderCatcher.class);
/**
* @throws IOException
* @throws ServletException
*
*/
public static void doCatch(final ServletConfig servletConfig, final HttpServletRequest request, final HttpServletResponse response, final String webClassesRootPackage) throws IOException,
ServletException
{
logger.debug("Doing catch.");
String urlPath = request.getPathInfo();
String className;
String[] tokens = urlPath.split("/");
if (tokens.length == 1)
{
className = "Index_xhtml";
}
else
{
StringList buffer = new StringList();
// Note: as pathInfo starts always with a '/', the first
// good token index is 1.
for (int tokenCounter = 1; tokenCounter < tokens.length - 1; tokenCounter++)
{
buffer.append(tokens[tokenCounter]);
buffer.append('.');
}
String lastToken = tokens[tokens.length - 1];
buffer.append(StringUtils.capitalize(lastToken)).append("_xhtml");
className = buffer.toString();
}
className = KissDispatcherUtils.concatenatePackage(webClassesRootPackage, className);
logger.info("className=[" + className + "]");
KissDispatcherUtils.dispatchToServlet(servletConfig, request, response, className);
}
/**
*
* @param urlPath
* @return
*/
public static boolean matches(final HttpServletRequest request)
{
boolean result;
String urlPath = request.getPathInfo();
if ((urlPath != null) && (urlPath.endsWith("/")))
{
result = true;
}
else
{
result = false;
}
//
return result;
}
}

View file

@ -0,0 +1,76 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.KissDispatcherUtils;
/**
*
*/
public class LongURLCatcher
{
private static Logger logger = LoggerFactory.getLogger(LongURLCatcher.class);
/**
* @throws IOException
* @throws ServletException
*
*/
public static void doCatch(final ServletConfig servletConfig, final HttpServletRequest request, final HttpServletResponse response, final String webClassesRootPackage) throws IOException,
ServletException
{
logger.debug("Doing catch.");
String urlPath = request.getPathInfo();
String rewritedURLPath = LongURLRewriter.unrewrite(urlPath);
String className = KissDispatcherUtils.concatenatePackage(webClassesRootPackage, rewritedURLPath);
logger.info("className=[" + className + "]");
KissDispatcherUtils.dispatchToServlet(servletConfig, request, response, className);
}
/**
*
* @param urlPath
* @return
*/
public static boolean matches(final HttpServletRequest request)
{
boolean result;
String urlPath = request.getPathInfo();
result = LongURLRewriter.matches(urlPath);
//
return result;
}
}

View file

@ -0,0 +1,167 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.util.strings.StringList;
/**
*
*/
public class LongURLRewriter
{
private static Logger logger = LoggerFactory.getLogger(LongURLRewriter.class);
private final static Pattern LONG_REWRITED_URL_CLASS = Pattern.compile("^([^-]+)-/.*$");
// static final protected Pattern LONG_REWRITED_URL_PARAMETERS =
// Pattern.compile("^.+-/(.)+*$");
private static final Pattern REWRITE_PARAMETER = Pattern.compile("[^%\\w\\d]");
/**
*
* @param urlPath
* @return
*/
public static boolean matches(final String urlPath)
{
boolean result;
Matcher matcher = LONG_REWRITED_URL_CLASS.matcher(urlPath);
result = matcher.matches();
//
return result;
}
/**
*
*/
public static String[] unrewriteParameters(final HttpServletRequest request)
{
String[] result;
result = unrewriteParameters(request.getRequestURI());
//
return result;
}
/**
* This method gives a way for a long rewriting URL format. Long as in REST.
*
* Sometimes, URL has to be rewrited because we need to put parameter in the
* page name.
*
* Example:
*
* <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 beginning of parameters.
*
*/
public static String rewriteLongUrl(final String path, final String... parameters)
{
String result;
StringList string = new StringList();
string.append(path).append("-");
if ((parameters == null) || (parameters.length == 0))
{
string.append("/");
}
else
{
for (String parameter : parameters)
{
string.append("/").append(parameter);
}
}
result = string.toString();
//
return result;
}
/**
*
* /catalog/article-/123/2016/12/14/resume.xhtml -> /catalog/article.xhtml
*
* @param source
* an URL path.
* @return
*/
public static String unrewrite(final String source)
{
String result;
Matcher matcher = LONG_REWRITED_URL_CLASS.matcher(source);
if (matcher.matches())
{
// Short rewrited URL case.
// logger.debug("group 1=[" + matcher.group(1) +
// "]");
result = matcher.group(1) + ".xhtml";
}
else
{
result = null;
}
//
return result;
}
/**
* Extract values from a path.
*
* Example:
*
* <pre>
* "/article-/123/doors/open.xhtml";
* => "123", "doors" and "open".
* </pre>
*
* @param source
* an URL path.
* @return
*/
public static String[] unrewriteParameters(final String source)
{
String[] result;
result = source.substring(source.indexOf("-/") + 2).split("/");
//
return result;
}
}

View file

@ -0,0 +1,79 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.KissDispatcherUtils;
/**
*
*/
public class RootCatcher
{
private static Logger logger = LoggerFactory.getLogger(RootCatcher.class);
/**
* @throws IOException
* @throws ServletException
*
*/
public static void doCatch(final ServletConfig servletConfig, final HttpServletRequest request, final HttpServletResponse response, final String webClassesRootPackage) throws IOException,
ServletException
{
logger.debug("Doing catch.");
String className = KissDispatcherUtils.concatenatePackage(webClassesRootPackage, "Index_xhtml");
logger.info("classPathname=[" + className + "]");
KissDispatcherUtils.dispatchToServlet(servletConfig, request, response, className);
}
/**
*
* @param urlPath
* @return
*/
public static boolean matches(final HttpServletRequest request)
{
boolean result;
String urlPath = request.getPathInfo();
if ((urlPath != null) && (urlPath.equals("/")))
{
result = true;
}
else
{
result = false;
}
//
return result;
}
}

View file

@ -0,0 +1,76 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.KissDispatcherUtils;
/**
*
*/
public class ShortURLCatcher
{
private static Logger logger = LoggerFactory.getLogger(ShortURLCatcher.class);
/**
* @throws IOException
* @throws ServletException
*
*/
public static void doCatch(final ServletConfig servletConfig, final HttpServletRequest request, final HttpServletResponse response, final String webClassesRootPackage) throws IOException,
ServletException
{
logger.debug("Doing catch.");
String urlPath = request.getPathInfo();
String rewritedURLPath = ShortURLRewriter.unrewrite(urlPath);
String className = KissDispatcherUtils.concatenatePackage(webClassesRootPackage, rewritedURLPath);
logger.info("className=[" + className + "]");
KissDispatcherUtils.dispatchToServlet(servletConfig, request, response, className);
}
/**
*
* @param urlPath
* @return
*/
public static boolean matches(final HttpServletRequest request)
{
boolean result;
String urlPath = request.getPathInfo();
result = ShortURLRewriter.matches(urlPath);
//
return result;
}
}

View file

@ -0,0 +1,280 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.util.strings.StringList;
/**
*
*/
public class ShortURLRewriter
{
private static Logger logger = LoggerFactory.getLogger(ShortURLRewriter.class);
private static final Pattern SHORT_REWRITED_URL_CLASS = Pattern.compile("^([^-]+)-.+\\.xhtml$");
private static final Pattern SHORT_REWRITED_URL_PARAMETERS = Pattern.compile("^[^-]+-(.+)\\.xhtml$");
private static final Pattern REWRITE_PARAMETER = Pattern.compile("[^%\\w\\d]");
/*
* "Code can be shortest, speedest and memory smallest, but not the three in same time, only two", unknow citation.
*
* Note: characters array avalaible here
* http://fr.wikipedia.org/wiki/Table_des_caract%C3%A8res_Unicode_%280000-0FFF%29
*/
private static char NONE = (char) 0;
private static int[] rewritingParameterMapping = {
/* 00 */NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
/* 10 */NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
/* 20 */'-', NONE, NONE, '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-',
/* 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',
/* 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', '\u006F',
/* 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,
/* 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', '\u00AE', '\u00AF',
/* 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',
/* 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',
/* F0 */'o', 'n', 'o', 'o', 'o', 'o', 'o', '\u00F7', '-', 'u', 'u', 'u', 'u', 'y', '-', 'y' };
/**
*
* @param url
* @return
*/
public static boolean matches(final String url)
{
boolean result;
Matcher matcher = SHORT_REWRITED_URL_CLASS.matcher(url);
result = matcher.matches();
//
return result;
}
/**
* This method gives a way for a short rewriting URL format.
*
* Sometimes, URL has to be rewrited because we need to put parameter in the
* page name.
*
* Example:
*
* <pre>
* "/good/article.xhtm?id=123&class=today&title=story's about me"
* => rewriteShorturl("/good/article", "xhtml", "123", "Story's aboute me");
* => "/good/article-123-today-story-s-about-me.xhtml"
* </pre>
*/
public static String rewrite(final String uri, final String extension, final String... parameters)
{
String result;
StringList buffer = new StringList();
buffer.append(uri);
for (String parameter : parameters)
{
// Not use of String.replaceAll() method in goal to optimize Pattern
// compile action.
// string.append("-").append(REWRITE_PARAMETER.matcher(parameter.toLowerCase()).replaceAll("-"));
buffer.append("-").append(rewriteParameter(parameter));
}
if ((extension != null) && (extension.length() != 0))
{
buffer.append(".").append(extension);
}
result = buffer.toString();
//
return result;
}
/**
*
* @param parameter
* @return
*/
public static String rewriteParameter(final String parameter)
{
String result;
StringBuffer buffer = new StringBuffer(parameter.length());
char previousCar = NONE;
for (int charIndex = 0; charIndex < parameter.length(); charIndex++)
{
// logger.info("" + charIndex + " " + parameter.charAt(charIndex) +
// " " + (char) tab[parameter.charAt(charIndex)]);
char sourceCar = parameter.charAt(charIndex);
char targetCar;
if (sourceCar > 255)
{
targetCar = '-';
}
else
{
targetCar = (char) rewritingParameterMapping[sourceCar];
}
if (targetCar != NONE)
{
if ((targetCar != '-') || ((targetCar == '-') && (previousCar != '-')))
{
buffer.append(targetCar);
previousCar = targetCar;
}
}
}
if (buffer.charAt(buffer.length() - 1) == '-')
{
buffer.setLength(buffer.length() - 1);
}
result = buffer.toString();
logger.info("[" + parameter + "] -> [" + result + "]");
//
return result;
}
/**
*
* article.xhtm?id=123 -> article.xhtml
*
* @param source
* @return
*/
public static String unrewrite(final String source)
{
String result;
Matcher matcher = SHORT_REWRITED_URL_CLASS.matcher(source);
if (matcher.matches())
{
// Short rewrited URL case.
// logger.debug("group 1=[" + matcher.group(1) +
// "]");
result = matcher.group(1) + ".xhtml";
}
else
{
result = null;
}
//
return result;
}
/**
*
*/
public static String unrewriteParameter(final HttpServletRequest request)
{
String result;
result = unrewriteParameter(request.getRequestURI());
//
return result;
}
/**
* Return value of the first parameter.
*/
public static String unrewriteParameter(final String path)
{
String result;
String[] results = unrewriteParameters(path);
if ((results == null) || (results.length == 0))
{
result = null;
}
else
{
result = results[0];
}
//
return result;
}
/**
*
*/
public static String[] unrewriteParameters(final HttpServletRequest request)
{
String[] result;
result = unrewriteParameters(request.getRequestURI());
//
return result;
}
/**
* Extract value from a path. Example: "/article-123.xhtml" => "123".
*/
public static String[] unrewriteParameters(final String path)
{
String[] result;
Matcher matcher = SHORT_REWRITED_URL_PARAMETERS.matcher(path);
if (matcher.matches())
{
if (matcher.groupCount() != 1)
{
result = null;
}
else
{
result = matcher.group(1).split("-");
}
}
else
{
result = null;
}
//
return result;
}
}

View file

@ -0,0 +1,81 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.KissDispatcherUtils;
/**
*
*/
public class WebContentCatcher
{
private static Logger logger = LoggerFactory.getLogger(WebContentCatcher.class);
/**
* @throws IOException
* @throws ServletException
*
*/
public static void doCatch(final ServletContext servletContext, final HttpServletRequest request, final HttpServletResponse response, final String webClassesRootPackage) throws IOException,
ServletException
{
logger.debug("Doing catch.");
String path = servletContext.getRealPath("/") + request.getPathInfo();
logger.info("path=[{}]", path);
String mimeType = servletContext.getMimeType(path);
KissDispatcherUtils.returnInlineFile(response, new File(path), mimeType);
logger.info("File returned directly [{}] with mimetype [{}].", path, servletContext.getMimeType(path));
}
/**
*
* @param urlPath
* @return
*/
public static boolean matches(final ServletContext servletContext, final HttpServletRequest request)
{
boolean result;
if (new File(servletContext.getRealPath("/") + request.getPathInfo()).exists())
{
result = true;
}
else
{
result = false;
}
//
return result;
}
}

View file

@ -0,0 +1,82 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.KissDispatcherUtils;
/**
*
*/
public class WebInfCatcher
{
private static Logger logger = LoggerFactory.getLogger(WebInfCatcher.class);
/**
* @throws IOException
* @throws ServletException
*
*/
public static void doCatch(final ServletContext servletContext, final HttpServletRequest request, final HttpServletResponse response, final String webClassesRootPackage) throws IOException,
ServletException
{
logger.debug("Doing catch.");
String path = servletContext.getRealPath("/") + "WEB-INF/classes/" + webClassesRootPackage.replaceAll("\\.", "/") + request.getPathInfo();
logger.info("path=[{}]", path);
String mimeType = servletContext.getMimeType(path);
KissDispatcherUtils.returnInlineFile(response, new File(path), mimeType);
logger.info("File returned directly [{}] with mimetype [{}].", path, servletContext.getMimeType(path));
}
/**
*
* @param urlPath
* @return
*/
public static boolean matches(final ServletContext servletContext, final HttpServletRequest request, final String webClassesRootPackage)
{
boolean result;
if (new File(servletContext.getRealPath("/") + "WEB-INF/classes/" + webClassesRootPackage.replaceAll("\\.", "/") + request.getPathInfo()).exists())
{
result = true;
}
else
{
result = false;
}
//
return result;
}
}

View file

@ -0,0 +1,106 @@
/**
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.KissDispatcherUtils;
import fr.devinsy.util.strings.StringList;
/**
*
*/
public class XHTMLCatcher
{
private static Logger logger = LoggerFactory.getLogger(XHTMLCatcher.class);
/**
* @throws IOException
* @throws ServletException
*/
public static void doCatch(final ServletConfig servletConfig, final HttpServletRequest request, final HttpServletResponse response, final String webClassesRootPackage) throws IOException,
ServletException
{
logger.debug("Doing catch.");
String urlPath = request.getPathInfo();
String className;
String[] tokens = urlPath.split("/");
if (tokens.length == 1)
{
className = "Index_xhtml";
}
else
{
StringList buffer = new StringList();
// Note: as pathInfo starts always with a '/', the first
// good token index is 1.
for (int tokenCounter = 1; tokenCounter < tokens.length - 1; tokenCounter++)
{
buffer.append(tokens[tokenCounter]);
buffer.append('.');
}
String lastToken = tokens[tokens.length - 1];
buffer.append(StringUtils.capitalize(lastToken).replace('.', '_')).append("_xhtml");
className = buffer.toString();
}
className = KissDispatcherUtils.concatenatePackage(webClassesRootPackage, className);
logger.info("className=[" + className + "]");
KissDispatcherUtils.dispatchToServlet(servletConfig, request, response, className);
}
/**
*
* @param urlPath
* @return
*/
public static boolean matches(final HttpServletRequest request)
{
boolean result;
String urlPath = request.getPathInfo();
if ((urlPath != null) && (urlPath.endsWith(".xhtml")))
{
result = true;
}
else
{
result = false;
}
//
return result;
}
}

View file

@ -1,30 +1,29 @@
/**
* Copyright (C) 2006-2010, 2013-2014 Christian Pierre MOMON
* Copyright (C) 2006-2010, 2013-2016 Christian Pierre MOMON
*
* This file is part of Devinsy-utils.
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
import fr.devinsy.kiss4web.KissDispatcher;
import fr.devinsy.kiss4web.ServletDispatcher;
import fr.devinsy.kiss4web.KissDispatcherUtils;
/**
* Kiss4Web tests.
*/
class FooSandbox
{
static private org.apache.log4j.Logger logger;
private static org.apache.log4j.Logger logger;
static
{
@ -91,7 +90,7 @@ class FooSandbox
{
String result;
result = "[" + pathInfo + "]=>[" + KissDispatcher.pathInfoToClassName(pathInfo, prefix) + "]";
result = "[" + pathInfo + "]=>[" + KissDispatcherUtils.pathInfoToClassName(pathInfo, prefix) + "]";
//
return (result);

View file

@ -0,0 +1,71 @@
/**
* Copyright (C) 2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.mocks.HttpServletRequestMock;
/**
*
* @author Christian Pierre MOMON (christian.momon@devinsy.fr)
*/
public class BlankCatcherTest
{
private static Logger logger = LoggerFactory.getLogger(ShortURLCatcher.class);
/**
*
*/
@Test
public void testMatches01()
{
HttpServletRequestMock source = new HttpServletRequestMock();
source.setPathInfo(null);
Assert.assertTrue(BlankCatcher.matches(source));
}
/**
*
*/
@Test
public void testMatches02()
{
HttpServletRequestMock source = new HttpServletRequestMock();
source.setPathInfo("");
Assert.assertTrue(BlankCatcher.matches(source));
}
/**
*
*/
@Test
public void testMatches03()
{
HttpServletRequestMock source = new HttpServletRequestMock();
source.setPathInfo("/");
Assert.assertFalse(BlankCatcher.matches(source));
}
}

View file

@ -0,0 +1,83 @@
/**
* Copyright (C) 2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package fr.devinsy.kiss4web.catchers;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.mocks.HttpServletRequestMock;
/**
*
* @author Christian Pierre MOMON (christian.momon@devinsy.fr)
*/
public class RootCatcherTest
{
private static Logger logger = LoggerFactory.getLogger(ShortURLCatcher.class);
/**
*
*/
@Test
public void testMatches01()
{
HttpServletRequestMock source = new HttpServletRequestMock();
source.setPathInfo(null);
Assert.assertFalse(RootCatcher.matches(source));
}
/**
*
*/
@Test
public void testMatches02()
{
HttpServletRequestMock source = new HttpServletRequestMock();
source.setPathInfo("");
Assert.assertFalse(RootCatcher.matches(source));
}
/**
*
*/
@Test
public void testMatches03()
{
HttpServletRequestMock source = new HttpServletRequestMock();
source.setPathInfo("/");
Assert.assertTrue(RootCatcher.matches(source));
}
/**
*
*/
@Test
public void testMatches04()
{
HttpServletRequestMock source = new HttpServletRequestMock();
source.setPathInfo("/toto");
Assert.assertFalse(RootCatcher.matches(source));
}
}

View file

@ -0,0 +1,432 @@
package fr.devinsy.kiss4web.mocks;
/**
* Copyright (C) 2016 Christian Pierre MOMON
*
* This file is part of Kiss4web.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.devinsy.kiss4web.catchers.ShortURLCatcher;
/**
*
* @author Christian Pierre MOMON (christian.momon@devinsy.fr)
*/
public class HttpServletRequestMock implements HttpServletRequest
{
private static Logger logger = LoggerFactory.getLogger(ShortURLCatcher.class);
private String pathInfo;
@Override
public Object getAttribute(final String name)
{
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getAttributeNames()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getAuthType()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getCharacterEncoding()
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getContentLength()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public String getContentType()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getContextPath()
{
// TODO Auto-generated method stub
return null;
}
@Override
public Cookie[] getCookies()
{
// TODO Auto-generated method stub
return null;
}
@Override
public long getDateHeader(final String name)
{
// TODO Auto-generated method stub
return 0;
}
@Override
public String getHeader(final String name)
{
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getHeaderNames()
{
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getHeaders(final String name)
{
// TODO Auto-generated method stub
return null;
}
@Override
public ServletInputStream getInputStream() throws IOException
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getIntHeader(final String name)
{
// TODO Auto-generated method stub
return 0;
}
@Override
public String getLocalAddr()
{
// TODO Auto-generated method stub
return null;
}
@Override
public Locale getLocale()
{
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getLocales()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getLocalName()
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getLocalPort()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public String getMethod()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getParameter(final String name)
{
// TODO Auto-generated method stub
return null;
}
@Override
public Map getParameterMap()
{
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getParameterNames()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String[] getParameterValues(final String name)
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getPathInfo()
{
return this.pathInfo;
}
@Override
public String getPathTranslated()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getProtocol()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getQueryString()
{
// TODO Auto-generated method stub
return null;
}
@Override
public BufferedReader getReader() throws IOException
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getRealPath(final String path)
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getRemoteAddr()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getRemoteHost()
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getRemotePort()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public String getRemoteUser()
{
// TODO Auto-generated method stub
return null;
}
@Override
public RequestDispatcher getRequestDispatcher(final String path)
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getRequestedSessionId()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getRequestURI()
{
// TODO Auto-generated method stub
return null;
}
@Override
public StringBuffer getRequestURL()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getScheme()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getServerName()
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getServerPort()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public String getServletPath()
{
// TODO Auto-generated method stub
return null;
}
@Override
public HttpSession getSession()
{
// TODO Auto-generated method stub
return null;
}
@Override
public HttpSession getSession(final boolean create)
{
// TODO Auto-generated method stub
return null;
}
@Override
public Principal getUserPrincipal()
{
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isRequestedSessionIdFromCookie()
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isRequestedSessionIdFromUrl()
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isRequestedSessionIdFromURL()
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isRequestedSessionIdValid()
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isSecure()
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isUserInRole(final String role)
{
// TODO Auto-generated method stub
return false;
}
@Override
public void removeAttribute(final String name)
{
// TODO Auto-generated method stub
}
@Override
public void setAttribute(final String name, final Object o)
{
// TODO Auto-generated method stub
}
@Override
public void setCharacterEncoding(final String env) throws UnsupportedEncodingException
{
// TODO Auto-generated method stub
}
public void setPathInfo(final String pathInfo)
{
this.pathInfo = pathInfo;
}
}

View file

@ -1,39 +0,0 @@
/**
* Copyright (C) 2006-2010, 2013-2014 Christian Pierre MOMON
*
* This file is part of Devinsy-utils.
*
* Kiss4web is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kiss4web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Kiss4web. If not, see <http://www.gnu.org/licenses/>
*/
package one;
import org.junit.Test;
public class Foo2Test
{
// private Logger logger =
// LoggerFactory.getLogger(PdfGenerationAmqpServiceInjectedTest.class);
/**
*
*/
@Test
public void test2a()
{
// logger.debug("===== test starting...");
// logger.debug("===== test done.");
}
}