diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs index 7ced310..ade7550 100644 --- a/.settings/org.eclipse.jdt.core.prefs +++ b/.settings/org.eclipse.jdt.core.prefs @@ -282,7 +282,7 @@ org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.tabulation.char=space org.eclipse.jdt.core.formatter.tabulation.size=4 org.eclipse.jdt.core.formatter.use_on_off_tags=false org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs index fe89f28..9a2c605 100644 --- a/.settings/org.eclipse.jdt.ui.prefs +++ b/.settings/org.eclipse.jdt.ui.prefs @@ -1,2 +1,109 @@ +cleanup.add_default_serial_version_id=false +cleanup.add_generated_serial_version_id=true +cleanup.add_missing_annotations=true +cleanup.add_missing_deprecated_annotations=true +cleanup.add_missing_methods=false +cleanup.add_missing_nls_tags=false +cleanup.add_missing_override_annotations=true +cleanup.add_missing_override_annotations_interface_methods=true +cleanup.add_serial_version_id=true +cleanup.always_use_blocks=true +cleanup.always_use_parentheses_in_expressions=false +cleanup.always_use_this_for_non_static_field_access=true +cleanup.always_use_this_for_non_static_method_access=false +cleanup.convert_to_enhanced_for_loop=false +cleanup.correct_indentation=false +cleanup.format_source_code=true +cleanup.format_source_code_changes_only=false +cleanup.make_local_variable_final=false +cleanup.make_parameters_final=true +cleanup.make_private_fields_final=false +cleanup.make_type_abstract_if_missing_method=false +cleanup.make_variable_declarations_final=true +cleanup.never_use_blocks=false +cleanup.never_use_parentheses_in_expressions=true +cleanup.organize_imports=false +cleanup.qualify_static_field_accesses_with_declaring_class=false +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +cleanup.qualify_static_member_accesses_with_declaring_class=true +cleanup.qualify_static_method_accesses_with_declaring_class=false +cleanup.remove_private_constructors=true +cleanup.remove_trailing_whitespaces=true +cleanup.remove_trailing_whitespaces_all=true +cleanup.remove_trailing_whitespaces_ignore_empty=false +cleanup.remove_unnecessary_casts=true +cleanup.remove_unnecessary_nls_tags=true +cleanup.remove_unused_imports=true +cleanup.remove_unused_local_variables=false +cleanup.remove_unused_private_fields=true +cleanup.remove_unused_private_members=false +cleanup.remove_unused_private_methods=true +cleanup.remove_unused_private_types=true +cleanup.sort_members=true +cleanup.sort_members_all=false +cleanup.use_blocks=true +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.use_parentheses_in_expressions=false +cleanup.use_this_for_non_static_field_access=true +cleanup.use_this_for_non_static_field_access_only_if_necessary=false +cleanup.use_this_for_non_static_method_access=false +cleanup.use_this_for_non_static_method_access_only_if_necessary=true +cleanup_profile=_Kiss4web +cleanup_settings_version=2 eclipse.preferences.version=1 +editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true +formatter_profile=_Kiss4web formatter_settings_version=12 +sp_cleanup.add_default_serial_version_id=true +sp_cleanup.add_generated_serial_version_id=false +sp_cleanup.add_missing_annotations=true +sp_cleanup.add_missing_deprecated_annotations=true +sp_cleanup.add_missing_methods=false +sp_cleanup.add_missing_nls_tags=false +sp_cleanup.add_missing_override_annotations=true +sp_cleanup.add_missing_override_annotations_interface_methods=true +sp_cleanup.add_serial_version_id=false +sp_cleanup.always_use_blocks=true +sp_cleanup.always_use_parentheses_in_expressions=false +sp_cleanup.always_use_this_for_non_static_field_access=true +sp_cleanup.always_use_this_for_non_static_method_access=false +sp_cleanup.convert_to_enhanced_for_loop=false +sp_cleanup.correct_indentation=true +sp_cleanup.format_source_code=true +sp_cleanup.format_source_code_changes_only=false +sp_cleanup.make_local_variable_final=false +sp_cleanup.make_parameters_final=true +sp_cleanup.make_private_fields_final=false +sp_cleanup.make_type_abstract_if_missing_method=false +sp_cleanup.make_variable_declarations_final=true +sp_cleanup.never_use_blocks=false +sp_cleanup.never_use_parentheses_in_expressions=true +sp_cleanup.on_save_use_additional_actions=true +sp_cleanup.organize_imports=true +sp_cleanup.qualify_static_field_accesses_with_declaring_class=false +sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_with_declaring_class=false +sp_cleanup.qualify_static_method_accesses_with_declaring_class=false +sp_cleanup.remove_private_constructors=true +sp_cleanup.remove_trailing_whitespaces=false +sp_cleanup.remove_trailing_whitespaces_all=true +sp_cleanup.remove_trailing_whitespaces_ignore_empty=false +sp_cleanup.remove_unnecessary_casts=true +sp_cleanup.remove_unnecessary_nls_tags=true +sp_cleanup.remove_unused_imports=true +sp_cleanup.remove_unused_local_variables=false +sp_cleanup.remove_unused_private_fields=true +sp_cleanup.remove_unused_private_members=false +sp_cleanup.remove_unused_private_methods=true +sp_cleanup.remove_unused_private_types=true +sp_cleanup.sort_members=true +sp_cleanup.sort_members_all=false +sp_cleanup.use_blocks=true +sp_cleanup.use_blocks_only_for_return_and_throw=false +sp_cleanup.use_parentheses_in_expressions=false +sp_cleanup.use_this_for_non_static_field_access=true +sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=false +sp_cleanup.use_this_for_non_static_method_access=false +sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/src/fr/devinsy/kiss4web/CookieHelper.java b/src/fr/devinsy/kiss4web/CookieHelper.java index e385366..c626679 100644 --- a/src/fr/devinsy/kiss4web/CookieHelper.java +++ b/src/fr/devinsy/kiss4web/CookieHelper.java @@ -33,193 +33,193 @@ import org.slf4j.LoggerFactory; */ public class CookieHelper { - public enum Scope - { - HTTP_AND_HTTPS, - HTTPS_ONLY - } + public enum Scope + { + HTTP_AND_HTTPS, + HTTPS_ONLY + } - private static final Logger logger = LoggerFactory.getLogger(CookieHelper.class); + private static final Logger logger = LoggerFactory.getLogger(CookieHelper.class); - /** + /** * */ - public static Cookie buildCookie(final String name, final String value, final int duration) - { - Cookie result; + public static Cookie buildCookie(final String name, final String value, final int duration) + { + Cookie result; - result = buildCookie(name, value, duration, Scope.HTTP_AND_HTTPS); + result = buildCookie(name, value, duration, Scope.HTTP_AND_HTTPS); - // - return (result); - } + // + return (result); + } - /** - * Warning: value is UTF-8 URLEncoded! - */ - public static Cookie buildCookie(final String name, final String value, final int duration, final Scope secure) - { - Cookie result; + /** + * Warning: value is UTF-8 URLEncoded! + */ + public static Cookie buildCookie(final String name, final String value, final int duration, final Scope secure) + { + Cookie result; - // - try - { - result = new Cookie(name, java.net.URLEncoder.encode(value, "UTF-8")); - result.setMaxAge(duration); - result.setPath("/"); + // + try + { + result = new Cookie(name, java.net.URLEncoder.encode(value, "UTF-8")); + result.setMaxAge(duration); + result.setPath("/"); - // - boolean secureValue; - if (secure == Scope.HTTPS_ONLY) - { - secureValue = true; - } - else - { - secureValue = false; - } - result.setSecure(secureValue); - } - catch (UnsupportedEncodingException exception) - { - exception.printStackTrace(); - throw new IllegalArgumentException("value is unsupported encoding."); - } + // + boolean secureValue; + if (secure == Scope.HTTPS_ONLY) + { + secureValue = true; + } + else + { + secureValue = false; + } + result.setSecure(secureValue); + } + catch (UnsupportedEncodingException exception) + { + exception.printStackTrace(); + throw new IllegalArgumentException("value is unsupported encoding."); + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static boolean exists(final HttpServletRequest request, final String key) - { - boolean result; + public static boolean exists(final HttpServletRequest request, final String key) + { + boolean result; - if (getCookieValue(request, key) == null) - { - result = false; - } - else - { - result = true; - } + if (getCookieValue(request, key) == null) + { + result = false; + } + else + { + result = true; + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static Cookie getCookie(final Cookie[] cookies, final String key) - { - Cookie result = null; + public static Cookie getCookie(final Cookie[] cookies, final String key) + { + Cookie result = null; - if (cookies == null) - { - result = null; - } - else - { - boolean ended = false; - int cookieCounter = 0; - while (!ended) - { - if (cookieCounter < cookies.length) - { - if (key.equals(cookies[cookieCounter].getName())) - { - ended = true; - result = cookies[cookieCounter]; - } - else - { - cookieCounter += 1; - } - } - else - { - ended = true; - result = null; - } - } - } + if (cookies == null) + { + result = null; + } + else + { + boolean ended = false; + int cookieCounter = 0; + while (!ended) + { + if (cookieCounter < cookies.length) + { + if (key.equals(cookies[cookieCounter].getName())) + { + ended = true; + result = cookies[cookieCounter]; + } + else + { + cookieCounter += 1; + } + } + else + { + ended = true; + result = null; + } + } + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static Cookie getCookie(final HttpServletRequest request, final String key) - { - Cookie result = null; + public static Cookie getCookie(final HttpServletRequest request, final String key) + { + Cookie result = null; - result = getCookie(request.getCookies(), key); + 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) - { - Object result; + /** + * Note: value is UTF-8 decoded. + */ + static public Object getCookieValue(final Cookie[] cookies, final String key) + { + Object result; - try - { - Cookie cookie = getCookie(cookies, key); + try + { + Cookie cookie = getCookie(cookies, key); - if (cookie == null) - { - result = null; - } - else - { - result = java.net.URLDecoder.decode(cookie.getValue(), "UTF-8"); - } - } - catch (UnsupportedEncodingException exception) - { - exception.printStackTrace(); - throw new IllegalArgumentException(); - } + if (cookie == null) + { + result = null; + } + else + { + result = java.net.URLDecoder.decode(cookie.getValue(), "UTF-8"); + } + } + catch (UnsupportedEncodingException exception) + { + exception.printStackTrace(); + throw new IllegalArgumentException(); + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static Object getCookieValue(final HttpServletRequest request, final String key) - { - Object result; + public static Object getCookieValue(final HttpServletRequest request, final String key) + { + Object result; - result = getCookieValue(request.getCookies(), key); + result = getCookieValue(request.getCookies(), key); - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static void reset(final HttpServletResponse response, final String key) - { - response.addCookie(buildCookie(key, "", 0)); - } + public static void reset(final HttpServletResponse response, final String key) + { + response.addCookie(buildCookie(key, "", 0)); + } - /** + /** * */ - public static void set(final HttpServletResponse response, final String name, final String value, final int duration) - { - response.addCookie(buildCookie(name, value, duration)); - } + public static void set(final HttpServletResponse response, final String name, final String value, final int duration) + { + response.addCookie(buildCookie(name, value, duration)); + } } diff --git a/src/fr/devinsy/kiss4web/FileItemHelper.java b/src/fr/devinsy/kiss4web/FileItemHelper.java index d9b49c6..8abbd42 100644 --- a/src/fr/devinsy/kiss4web/FileItemHelper.java +++ b/src/fr/devinsy/kiss4web/FileItemHelper.java @@ -27,74 +27,74 @@ import org.apache.commons.fileupload.FileItem; */ public class FileItemHelper { - // static private final Logger logger = - // LoggerFactory.getLogger(FileItemHelper.class); + // static private final Logger logger = + // LoggerFactory.getLogger(FileItemHelper.class); - /** - * List FileItem - */ - public static FileItem getItem(final List items, final String name) - { - FileItem result; + /** + * 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 == 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; - } - } - } + if (name.equals(item.getFieldName())) + { + ended = true; + result = item; + } + else + { + itemIndex += 1; + } + } + else + { + ended = true; + result = null; + } + } + } - // - return (result); - } + // + return (result); + } - /** - * List FileItem - */ - public static String getItemValue(final List items, final String name) - { - String result; + /** + * List FileItem + */ + public static String getItemValue(final List items, final String name) + { + String result; - FileItem item = getItem(items, name); + FileItem item = getItem(items, name); - if (item == null) - { - result = null; - } - else - { - result = item.getString(); - } + if (item == null) + { + result = null; + } + else + { + result = item.getString(); + } - // - return (result); - } + // + return (result); + } } // //////////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/src/fr/devinsy/kiss4web/KissDispatcher.java b/src/fr/devinsy/kiss4web/KissDispatcher.java index 024f11e..3bf73e1 100755 --- a/src/fr/devinsy/kiss4web/KissDispatcher.java +++ b/src/fr/devinsy/kiss4web/KissDispatcher.java @@ -44,560 +44,560 @@ import fr.devinsy.util.StringList; */ public class KissDispatcher extends HttpServlet { - public enum ContentDispositionType - { - ATTACHMENT, - INLINE - } + public enum ContentDispositionType + { + ATTACHMENT, + INLINE + } - private static final long serialVersionUID = -3471226305721330069L; + private static final long serialVersionUID = -3471226305721330069L; - private static Logger logger = LoggerFactory.getLogger(KissDispatcher.class); + private static Logger logger = LoggerFactory.getLogger(KissDispatcher.class); - public static final int CACHE_AGE = 2 * 60 * 60; + public static final int CACHE_AGE = 2 * 60 * 60; - private String webclassesRootPath; + 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; + /* + * "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 void dispatch(final HttpServletRequest request, final HttpServletResponse response, final String webClassesRootPath) throws IOException, ServletException - { - long startTime = new Date().getTime(); + public void dispatch(final HttpServletRequest request, final HttpServletResponse response, final String webClassesRootPath) throws IOException, ServletException + { + long startTime = new Date().getTime(); - 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() + "]"); + 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() + "]"); - // - /* - * In past, possibility to use the servlet path was enable. It is too - * complexe, not kiss mind. - * - * String path; - * if (request.getPathInfo() == null) - * { - * // web.xml url-pattern= *.xhtml - * path = request.getServletPath(); - * } - * else - * { - * // web.xml url-pattern = - * path = request.getPathInfo(); - * } - * - * https://issues.apache.org/bugzilla/show_bug.cgi?id=11318 - * A number of features have been introduced in later versions of Tomcat - * that relate to URI encoding. This includes a URIEncoding attribute - * on the Coyote HTTP/1.1 connector which defaults to ISO-8859-1. - * - * According to the servlet specification: - * HttpServletRequest.getPathInfo() should be decoded by the web container; - * HttpServletRequest.getRequestURI() should not be decoded by the web container. - * - * - * http://stackoverflow.com/questions/15278512/safe-html-form-accept-charset/15587140#15587140 - * The standard URL encoding must use UTF-8 yet servlets not only default to ISO-8859-1 but don't offer - * any way to change that with code. - * Sure you can req.setRequestEncoding("UTF-8") before you read anything, but for some ungodly reason this only affects request body, - * not query string parameters. There is nothing in the servlet request interface to specify the encoding used for query string parameters. - * Using ISO-8859-1 in your form is a hack. Using this ancient encoding will cause more problems than solve for sure. - * Especially since browsers do not support ISO-8859-1 and always treat it as Windows-1252. Whereas servlets treat ISO-8859-1 as ISO-8859-1, - * so you will be screwed beyond belief if you go with this. - * To change this in Tomcat for example, you can use the URIEncoding attribute in your element: - * - * - * If you don't use a container that has these settings, can't change its settings or some other issue, - * you can still make it work because ISO-8859-1 decoding retains full information from the original binary. - * String correct = new String(request.getParameter("test").getBytes("ISO-8859-1"), "UTF-8") - * - * - * http://tomcat.apache.org/tomcat-5.5-doc/config/http.html - * URIEncoding - * This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. - * If not specified, ISO-8859-1 will be used. - * - */ - // String path = request.getRequestURI(); - String path = request.getPathInfo(); + // + /* + * In past, possibility to use the servlet path was enable. It is too + * complexe, not kiss mind. + * + * String path; + * if (request.getPathInfo() == null) + * { + * // web.xml url-pattern= *.xhtml + * path = request.getServletPath(); + * } + * else + * { + * // web.xml url-pattern = + * path = request.getPathInfo(); + * } + * + * https://issues.apache.org/bugzilla/show_bug.cgi?id=11318 + * A number of features have been introduced in later versions of Tomcat + * that relate to URI encoding. This includes a URIEncoding attribute + * on the Coyote HTTP/1.1 connector which defaults to ISO-8859-1. + * + * According to the servlet specification: + * HttpServletRequest.getPathInfo() should be decoded by the web container; + * HttpServletRequest.getRequestURI() should not be decoded by the web container. + * + * + * http://stackoverflow.com/questions/15278512/safe-html-form-accept-charset/15587140#15587140 + * The standard URL encoding must use UTF-8 yet servlets not only default to ISO-8859-1 but don't offer + * any way to change that with code. + * Sure you can req.setRequestEncoding("UTF-8") before you read anything, but for some ungodly reason this only affects request body, + * not query string parameters. There is nothing in the servlet request interface to specify the encoding used for query string parameters. + * Using ISO-8859-1 in your form is a hack. Using this ancient encoding will cause more problems than solve for sure. + * Especially since browsers do not support ISO-8859-1 and always treat it as Windows-1252. Whereas servlets treat ISO-8859-1 as ISO-8859-1, + * so you will be screwed beyond belief if you go with this. + * To change this in Tomcat for example, you can use the URIEncoding attribute in your element: + * + * + * If you don't use a container that has these settings, can't change its settings or some other issue, + * you can still make it work because ISO-8859-1 decoding retains full information from the original binary. + * String correct = new String(request.getParameter("test").getBytes("ISO-8859-1"), "UTF-8") + * + * + * http://tomcat.apache.org/tomcat-5.5-doc/config/http.html + * URIEncoding + * This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. + * If not specified, ISO-8859-1 will be used. + * + */ + // String path = request.getRequestURI(); + String path = request.getPathInfo(); - if (path == null) - { - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); + if (path == null) + { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); - out.println(""); - out.println("Unknow path."); - out.println(""); + out.println(""); + out.println("Unknow path."); + out.println(""); - out.close(); - } - else if ((!path.endsWith("/")) && (!path.endsWith(".xhtml")) && (!path.contains("-/"))) - { - // 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); + out.close(); + } + else if ((!path.endsWith("/")) && (!path.endsWith(".xhtml")) && (!path.contains("-/"))) + { + // 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) + "]."); - } - else - { - String className = pathInfoToClassName(path, webClassesRootPath); - logger.info("className=[" + className + "]"); + returnInlineFile(response, new File(path), getServletContext().getMimeType(path)); + logger.info("File returned directly [" + path + "] with mimetype [" + getServletContext().getMimeType(path) + "]."); + } + else + { + String className = pathInfoToClassName(path, webClassesRootPath); + logger.info("className=[" + className + "]"); - HttpServlet servlet = instanciateServlet(className); + HttpServlet servlet = instanciateServlet(className); - // servlet.getServletContext().setAttribute(arg0, arg1); + // servlet.getServletContext().setAttribute(arg0, arg1); - if (servlet == null) - { - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); + if (servlet == null) + { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); - out.println(""); - out.println("Unknow page."); - out.println(""); + out.println(""); + out.println("Unknow page."); + out.println(""); - 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 (""); out.println - * ("Not authorized page."); out.println (""); - */ - } - } + 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 (""); out.println + * ("Not authorized page."); out.println (""); + */ + } + } - // - long endTime = new Date().getTime(); - logger.debug("TIME: {}ms {}", endTime - startTime, request.getPathInfo()); - } + // + long endTime = new Date().getTime(); + logger.debug("TIME: {}ms {}", endTime - startTime, request.getPathInfo()); + } - /** + /** * */ - @Override - public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException - { - dispatch(request, response, this.webclassesRootPath); - } + @Override + public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException + { + dispatch(request, response, this.webclassesRootPath); + } - /** - * Backward compatibility. - */ - public void doIt(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException - { - dispatch(request, response, this.webclassesRootPath); - } + /** + * Backward compatibility. + */ + public void doIt(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException + { + dispatch(request, response, this.webclassesRootPath); + } - /** + /** * */ - @Override - public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException - { - dispatch(request, response, this.webclassesRootPath); - } + @Override + public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException + { + dispatch(request, response, this.webclassesRootPath); + } - /** + /** * */ - @Override - public void init() throws ServletException - { - super.init(); - this.webclassesRootPath = getInitParameter("webClassesRootPath"); + @Override + public void init() throws ServletException + { + super.init(); + this.webclassesRootPath = getInitParameter("webClassesRootPath"); - // Set logger. - String logFilepathname = getInitParameter("log4j-init-file"); - if (logFilepathname != null) - { - try - { - System.out.println("Log configuration found (" + logFilepathname + "), will use it."); - org.apache.log4j.PropertyConfigurator.configure(getServletContext().getRealPath("/") + logFilepathname); - } - catch (Exception exception) - { - System.out.println("Log configuration FILE NOT FOUND (" + logFilepathname + "), use of the basic configurator."); - org.apache.log4j.BasicConfigurator.configure(); - } + // Set logger. + String logFilepathname = getInitParameter("log4j-init-file"); + if (logFilepathname != null) + { + try + { + System.out.println("Log configuration found (" + logFilepathname + "), will use it."); + org.apache.log4j.PropertyConfigurator.configure(getServletContext().getRealPath("/") + logFilepathname); + } + catch (Exception exception) + { + System.out.println("Log configuration FILE NOT FOUND (" + logFilepathname + "), use of the basic configurator."); + org.apache.log4j.BasicConfigurator.configure(); + } - logger = LoggerFactory.getLogger(this.getClass()); - logger.info("Log initialization done."); - } - } + logger = LoggerFactory.getLogger(this.getClass()); + logger.info("Log initialization done."); + } + } - /** + /** * */ - public boolean isAuthorized(final HttpServletRequest request, final HttpServletResponse response) - { - boolean result; + public boolean isAuthorized(final HttpServletRequest request, final HttpServletResponse response) + { + boolean result; - result = true; + result = true; - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static HttpServlet instanciateServlet(final String className) - { - HttpServlet result; + public static HttpServlet instanciateServlet(final String className) + { + HttpServlet result; - Class servletClass = null; - try - { - servletClass = (Class) Class.forName(className); - } - catch (java.lang.ClassNotFoundException exception) - { - result = null; - } + Class servletClass = null; + try + { + servletClass = (Class) Class.forName(className); + } + catch (java.lang.ClassNotFoundException exception) + { + result = null; + } - logger.info("class=" + servletClass); + 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; - } - } + 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); - } + // + return (result); + } - /** - * Convert a path in a class name, using easy conventions. - * - *
-	 * "/" => "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).
-	 * 
+ /** + * Convert a path in a class name, using easy conventions. + * + *
+     * "/" => "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).
+     * 
+ * + */ + 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) - { - String result; + public static String pathInfoToClassName(final String pathInfo, final String prefix) + { + String result; - if ((pathInfo == null) || (pathInfo.length() == 0)) - { - result = null; - } - else - { - if (pathInfo.equals("/")) - { - result = "Index_xhtml"; - } - else - { - int keywordIndex = pathInfo.lastIndexOf("-/"); + String className = pathInfoToClassName(pathInfo); - if (keywordIndex != -1) - { - // Long rewrited URL case. - String[] tokens = pathInfo.substring(0, keywordIndex).split("/"); + if (prefix == null) + { + result = className; + } + else if (prefix.endsWith(".")) + { + result = prefix + className; + } + else + { + result = prefix + "." + className; + } - 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('.'); - } + // + return (result); + } - 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; + public static void returnAttachmentFile(final HttpServletResponse response, final File file, final String mimeType) throws IOException + { + returnFile(response, file, mimeType, ContentDispositionType.ATTACHMENT); + } - 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 File file, final String mimeType, final ContentDispositionType contentDisposition) throws IOException - { + 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 ((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() + "\""); + if (data == null) + { + logger.warn("data is null."); + } - response.setDateHeader("Expires", new Date().getTime() + CACHE_AGE * 1000); - response.setHeader("Cache-Control", "max-age=" + CACHE_AGE); + /* + * 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.flushBuffer(); + response.setDateHeader("Expires", new Date().getTime() + cacheAge * 1000); + response.setHeader("Cache-Control", "max-age=" + cacheAge); - ServletOutputStream out = response.getOutputStream(); + response.flushBuffer(); - FileInputStream in = null; - try - // Only for the in. - { - byte[] buffer = new byte[64 * 1024]; + ServletOutputStream out = response.getOutputStream(); - in = new FileInputStream(file); - boolean ended = false; - while (!ended) - { - int count = in.read(buffer); + 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(); + } + } + } - 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); - } + public static void returnInlineFile(final HttpServletResponse response, final File file, final String mimeType) throws IOException + { + returnFile(response, file, mimeType, ContentDispositionType.INLINE); + } } diff --git a/src/fr/devinsy/kiss4web/Page.java b/src/fr/devinsy/kiss4web/Page.java index 5016150..e9b6ba0 100644 --- a/src/fr/devinsy/kiss4web/Page.java +++ b/src/fr/devinsy/kiss4web/Page.java @@ -29,8 +29,8 @@ import javax.servlet.http.HttpServletResponse; */ public interface Page { - /** + /** * */ - public void doIt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; + public void doIt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; } diff --git a/src/fr/devinsy/kiss4web/PageManager.java b/src/fr/devinsy/kiss4web/PageManager.java index b370cd0..b403d63 100644 --- a/src/fr/devinsy/kiss4web/PageManager.java +++ b/src/fr/devinsy/kiss4web/PageManager.java @@ -35,387 +35,387 @@ import fr.devinsy.kiss4web.security.User; */ public class PageManager extends HttpServlet { - private static final long serialVersionUID = 1983715791417570578L; + private static final long serialVersionUID = 1983715791417570578L; - private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(PageManager.class); + private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(PageManager.class); - private static PageManager instance = null; - private SecurityAgent securityAgent; + 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() + "]"); + @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); + String className = buildClassName(request.getPathInfo()); + logger.info("className=" + className); - Page page = this.instanciatePage("site." + className); + Page page = this.instanciatePage("site." + className); - if (page == null) - { - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); + 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"); - } + 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 (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(); + if (login == null) + { + response.sendRedirect("/gestion/login.xhtml"); + } + else + { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); - out.println(""); - out.println("Permission denied."); - out.println("
"); - out.println(" "); - out.println("
"); - out.println(""); - } - } - } - } + out.println(""); + out.println("Permission denied."); + out.println("
"); + out.println(" "); + out.println("
"); + out.println(""); + } + } + } + } - /** + /** * */ - @Override - public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException - { - doGet(request, response); - } + @Override + public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException + { + doGet(request, response); + } - /** + /** * */ - @Override - public void init() throws ServletException - { - // - instance = this; + @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); - } - } + 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; + public Page instanciatePage(final String className) + { + Page result; - Class pageClass = null; - try - { - pageClass = (Class) Class.forName(className); - } - catch (java.lang.ClassNotFoundException exception) - { - result = null; - } + Class pageClass = null; + try + { + pageClass = (Class) Class.forName(className); + } + catch (java.lang.ClassNotFoundException exception) + { + result = null; + } - logger.info("class=" + pageClass); + 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; - } - } + 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); - } + // + return (result); + } - /** + /** * */ - public SecurityAgent securityAgent() - { - SecurityAgent result; + public SecurityAgent securityAgent() + { + SecurityAgent result; - result = this.securityAgent; + result = this.securityAgent; - // - return (result); - } + // + return (result); + } - /** + /** * */ - static public String buildClassName(final String pathInfo) - { - String result; - result = null; + 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(); + 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('.'); - } + 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('.'); - } + if (pathInfo.endsWith("/")) + { + name.append(tokens[tokens.length - 1]); + name.append('.'); + } - logger.info("==>[" + tokens[tokens.length - 1] + "]"); - name.append(formatClassName(tokens[tokens.length - 1])); + logger.info("==>[" + tokens[tokens.length - 1] + "]"); + name.append(formatClassName(tokens[tokens.length - 1])); - result = name.toString(); - } + result = name.toString(); + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static String buildClassName2(final String pathInfo) - { - String result; + public static String buildClassName2(final String pathInfo) + { + String result; - if (pathInfo.endsWith(".xhtml")) - { - char[] source = pathInfo.toCharArray(); + if (pathInfo.endsWith(".xhtml")) + { + char[] source = pathInfo.toCharArray(); - StringBuffer out = new StringBuffer(); - for (char c : source) - { - out.append("[" + c + "]"); - } - logger.debug(out.toString()); + 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; + 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; + case '.': + target[lastStartToken] = Character.toUpperCase(target[lastStartToken]); + break; - default: - target[nChar - 1] = source[nChar]; - } - } + default: + target[nChar - 1] = source[nChar]; + } + } - out = new StringBuffer(); - for (char c : target) - { - out.append("[" + c + "]"); - } - logger.debug(out.toString()); + 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(); + 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()); + 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; + 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]; - } - } + 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; - } + 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()); + 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; - } + result = new String(target) + new String(targetPlus); + } + else + { + logger.debug("unknow case"); + result = null; + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static String formatClassName(final String name) - { - String result; + public static String formatClassName(final String name) + { + String result; - result = null; + result = null; - String[] splittedLastToken = name.split("\\."); - String last = splittedLastToken[0]; - // logger.info ("last=" + last); + 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); + 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)); - } + all.append(Character.toUpperCase(token.charAt(0))); + all.append(token.substring(1)); + } - result = all.toString(); + result = all.toString(); - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static User getUserFromSession(final HttpServletRequest request) - { - User result; + public static User getUserFromSession(final HttpServletRequest request) + { + User result; - if (request == null) - { - result = null; - } - else - { - HttpSession session = request.getSession(false); + 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); - } - } + String login; + if (session == null) + { + result = null; + } + else + { + login = (String) session.getAttribute("login"); + result = PageManager.instance().securityAgent().users().getByLogin(login); + } + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static PageManager instance() - { - return instance; - } + public static PageManager instance() + { + return instance; + } } diff --git a/src/fr/devinsy/kiss4web/Redirector.java b/src/fr/devinsy/kiss4web/Redirector.java index 81d4342..c0c23b3 100644 --- a/src/fr/devinsy/kiss4web/Redirector.java +++ b/src/fr/devinsy/kiss4web/Redirector.java @@ -28,18 +28,18 @@ import org.slf4j.LoggerFactory; */ public class Redirector { - private static final Logger logger = LoggerFactory.getLogger(Redirector.class); + private static final Logger logger = LoggerFactory.getLogger(Redirector.class); - /** + /** * */ - public static void redirect(final HttpServletResponse response, final String destination) - { - logger.info("Redirect to <" + destination + ">"); + public static void redirect(final HttpServletResponse response, final String destination) + { + logger.info("Redirect to <" + destination + ">"); - response.setHeader("Location", destination); - response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); - } + response.setHeader("Location", destination); + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + } } // //////////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/src/fr/devinsy/kiss4web/ServletDispatcher.java b/src/fr/devinsy/kiss4web/ServletDispatcher.java index f01a02a..a328f8a 100755 --- a/src/fr/devinsy/kiss4web/ServletDispatcher.java +++ b/src/fr/devinsy/kiss4web/ServletDispatcher.java @@ -34,56 +34,56 @@ import org.slf4j.LoggerFactory; */ public class ServletDispatcher extends KissDispatcher { - private static final long serialVersionUID = -3471226305721330069L; - private static Logger logger; + private static final long serialVersionUID = -3471226305721330069L; + private static Logger logger; - // protected Servlets servlets; + // 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() + "]"); + @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); + String className = pathInfoToClassName(request.getPathInfo()); + logger.info("className=" + className); - HttpServlet servlet = instanciateServlet(className); + HttpServlet servlet = instanciateServlet(className); - if (servlet == null) - { - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); + if (servlet == null) + { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); - out.println(""); - out.println("Unknow page."); - out.println(""); + out.println(""); + out.println("Unknow page."); + out.println(""); - out.close(); - } - else - { - servlet.service(request, response); - } - } + out.close(); + } + else + { + servlet.service(request, response); + } + } - /** + /** * */ - @Override - public void init() throws ServletException - { - super.init(); - logger = LoggerFactory.getLogger(this.getClass()); - // this.servlets = new Servlets(); - } + @Override + public void init() throws ServletException + { + super.init(); + logger = LoggerFactory.getLogger(this.getClass()); + // this.servlets = new Servlets(); + } } diff --git a/src/fr/devinsy/kiss4web/ServletTools.java b/src/fr/devinsy/kiss4web/ServletTools.java index 2f23e95..a3534e0 100644 --- a/src/fr/devinsy/kiss4web/ServletTools.java +++ b/src/fr/devinsy/kiss4web/ServletTools.java @@ -29,39 +29,39 @@ import fr.devinsy.util.StringList; */ public class ServletTools { - /** - * - * @param request - * @return - */ - public static String showParameters(final HttpServletRequest request) - { - String result; + /** + * + * @param request + * @return + */ + public static String showParameters(final HttpServletRequest request) + { + String result; - // - StringList buffer = new StringList(); + // + StringList buffer = new StringList(); - // - boolean ended = false; - Enumeration 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; - } - } + // + boolean ended = false; + Enumeration 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(); + // + result = buffer.toString(); - // - return result; - } + // + return result; + } } \ No newline at end of file diff --git a/src/fr/devinsy/kiss4web/SimpleSecurityAgent.java b/src/fr/devinsy/kiss4web/SimpleSecurityAgent.java index 50200e2..766eab2 100644 --- a/src/fr/devinsy/kiss4web/SimpleSecurityAgent.java +++ b/src/fr/devinsy/kiss4web/SimpleSecurityAgent.java @@ -32,220 +32,220 @@ import fr.devinsy.util.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 String userIdLabel; - private String accountIdLabel; - private String authLabel; - private String secretKey; - private static final int DEFAULT_AUTHENTICATION_DURATION = 60 * 60; - private int authenticationDuration; + 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 String userIdLabel; + private String accountIdLabel; + private String authLabel; + private String secretKey; + private static final int DEFAULT_AUTHENTICATION_DURATION = 60 * 60; + private int authenticationDuration; - /** + /** * */ - public SimpleSecurityAgent(final String prefix, final String secretKey) - { - this.userIdLabel = prefix + "." + USERID_LABEL; - this.accountIdLabel = prefix + "." + ACCOUNTID_LABEL; - this.authLabel = prefix + "." + AUTH_LABEL; - this.secretKey = secretKey; - this.authenticationDuration = DEFAULT_AUTHENTICATION_DURATION; - } + public SimpleSecurityAgent(final String prefix, final String secretKey) + { + this.userIdLabel = prefix + "." + USERID_LABEL; + this.accountIdLabel = prefix + "." + ACCOUNTID_LABEL; + this.authLabel = prefix + "." + AUTH_LABEL; + this.secretKey = secretKey; + this.authenticationDuration = DEFAULT_AUTHENTICATION_DURATION; + } - /** + /** * */ - public String accountId(final HttpServletRequest request) - { - String result; + public String accountId(final HttpServletRequest request) + { + String result; - result = (String) CookieHelper.getCookieValue(request, this.accountIdLabel); + result = (String) CookieHelper.getCookieValue(request, this.accountIdLabel); - // - return (result); - } + // + return (result); + } - /** + /** * */ - public String auth(final HttpServletRequest request) - { - String result; + public String auth(final HttpServletRequest request) + { + String result; - result = (String) CookieHelper.getCookieValue(request, this.authLabel); + result = (String) CookieHelper.getCookieValue(request, this.authLabel); - // - return (result); - } + // + return (result); + } - /** - * This method builds a key from keys and a secret key. - */ - public String computeAuth(final String... keys) - { - String result; + /** + * This method builds a key from keys and a secret key. + */ + public String computeAuth(final String... keys) + { + String result; - if (keys == null) - { - result = null; - } - else - { - // Add a secret key to the key list. - String[] targetKeys = new String[keys.length + 1]; - for (int keyIndex = 0; keyIndex < keys.length; keyIndex++) - { - targetKeys[keyIndex] = keys[keyIndex]; - } - targetKeys[keys.length] = this.secretKey; + if (keys == null) + { + result = null; + } + else + { + // Add a secret key to the key list. + String[] targetKeys = new String[keys.length + 1]; + for (int keyIndex = 0; keyIndex < keys.length; keyIndex++) + { + targetKeys[keyIndex] = keys[keyIndex]; + } + targetKeys[keys.length] = this.secretKey; - // - result = digest(targetKeys); - } + // + result = digest(targetKeys); + } - // - return (result); - } + // + return (result); + } - /** - * - * @return - */ - public int getAuthenticationDuration() - { - return this.authenticationDuration; - } + /** + * + * @return + */ + public int getAuthenticationDuration() + { + return this.authenticationDuration; + } - /** - * Check authentication and refresh it (reset countdown). - */ - public boolean isAuthenticated(final HttpServletRequest request, final HttpServletResponse response) - { - boolean result; + /** + * Check authentication and refresh it (reset countdown). + */ + public boolean isAuthenticated(final HttpServletRequest request, final HttpServletResponse response) + { + boolean result; - String accountId = accountId(request); - String userId = userId(request); - String auth = auth(request); - logger.info("cook=[" + auth + "]"); + String accountId = accountId(request); + String userId = userId(request); + String auth = auth(request); + logger.info("cook=[" + auth + "]"); - if (auth == null) - { - result = false; - } - else if (auth.equals(computeAuth(accountId, userId, request.getRemoteAddr()))) - { - result = true; + if (auth == null) + { + result = false; + } + else if (auth.equals(computeAuth(accountId, userId, request.getRemoteAddr()))) + { + result = true; - // Refresh cookies. - setAuthenticated(request, response, accountId, userId); - } - else - { - result = false; - } + // Refresh cookies. + setAuthenticated(request, response, accountId, userId); + } + else + { + result = false; + } - // - return (result); - } + // + return (result); + } - /** - * - * @param source - * @return - */ - public String md5sumWithSecret(final String source) - { - String 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); - } + if (source == null) + { + result = null; + } + else + { + String key = source + this.secretKey; + result = digest(key); + } - // - return result; - } + // + return result; + } - /** + /** * */ - public void reset(final HttpServletRequest request, final HttpServletResponse response) - { - CookieHelper.reset(response, this.authLabel); - CookieHelper.reset(response, this.accountIdLabel); - CookieHelper.reset(response, this.userIdLabel); - } + public void reset(final HttpServletRequest request, final HttpServletResponse response) + { + CookieHelper.reset(response, this.authLabel); + CookieHelper.reset(response, this.accountIdLabel); + CookieHelper.reset(response, this.userIdLabel); + } - /** + /** * */ - public void setAuthenticated(final HttpServletRequest request, final HttpServletResponse response, final String accountId, final String userId) - { - // Refresh cookie. - String auth = computeAuth(String.valueOf(accountId), userId, request.getRemoteAddr()); + public void setAuthenticated(final HttpServletRequest request, final HttpServletResponse response, final String accountId, final String userId) + { + // Refresh cookie. + String auth = computeAuth(String.valueOf(accountId), userId, request.getRemoteAddr()); - response.addCookie(CookieHelper.buildCookie(this.authLabel, auth, this.authenticationDuration)); - response.addCookie(CookieHelper.buildCookie(this.accountIdLabel, accountId, this.authenticationDuration)); - response.addCookie(CookieHelper.buildCookie(this.userIdLabel, userId, this.authenticationDuration)); + response.addCookie(CookieHelper.buildCookie(this.authLabel, auth, this.authenticationDuration)); + response.addCookie(CookieHelper.buildCookie(this.accountIdLabel, accountId, this.authenticationDuration)); + response.addCookie(CookieHelper.buildCookie(this.userIdLabel, userId, this.authenticationDuration)); - logger.info("set [" + auth + "," + accountId + "," + userId + "," + request.getRemoteAddr() + ")"); - } + logger.info("set [" + auth + "," + accountId + "," + userId + "," + request.getRemoteAddr() + ")"); + } - /** - * - * @param duration - */ - public void setAuthenticationDuration(final int duration) - { - this.authenticationDuration = duration; - } + /** + * + * @param duration + */ + public void setAuthenticationDuration(final int duration) + { + this.authenticationDuration = duration; + } - /** + /** * */ - public String userId(final HttpServletRequest request) - { - String result; + public String userId(final HttpServletRequest request) + { + String result; - result = (String) CookieHelper.getCookieValue(request, this.userIdLabel); + result = (String) CookieHelper.getCookieValue(request, this.userIdLabel); - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static String digest(final String... keys) - { - String result; + public static String digest(final String... keys) + { + String result; - if (keys == null) - { - result = null; - } - else - { - // - StringList targetKey = new StringList(); - for (String key : keys) - { - targetKey.append(key); - } + if (keys == null) + { + result = null; + } + else + { + // + StringList targetKey = new StringList(); + for (String key : keys) + { + targetKey.append(key); + } - // - result = DigestUtils.sha256Hex(targetKey.toString()); - } + // + result = DigestUtils.sha256Hex(targetKey.toString()); + } - // - return (result); - } + // + return (result); + } } \ No newline at end of file diff --git a/src/fr/devinsy/kiss4web/security/Group.java b/src/fr/devinsy/kiss4web/security/Group.java index 1ecd53d..db62ccd 100644 --- a/src/fr/devinsy/kiss4web/security/Group.java +++ b/src/fr/devinsy/kiss4web/security/Group.java @@ -25,92 +25,92 @@ import java.util.Vector; */ public class Group { - private String name; - private Vector members; + private String name; + private Vector members; - /** + /** * */ - public Group() - { - this.name = null; - this.members = new Vector(); - } + public Group() + { + this.name = null; + this.members = new Vector(); + } - /** + /** * */ - public void addMember(final String login) - { - if ((login != null) && (login.length() != 0)) - { - this.members.add(login); - } - } + public void addMember(final String login) + { + if ((login != null) && (login.length() != 0)) + { + this.members.add(login); + } + } - /** + /** * */ - public boolean contains(final String name) - { - boolean result = false; + public boolean contains(final String name) + { + boolean result = false; - result = this.members.contains(name); + result = this.members.contains(name); - // - return (result); - } + // + return (result); + } - /** + /** * */ - public Vector members() - { - Vector result; + public Vector members() + { + Vector result; - result = this.members; + result = this.members; - // - return (result); - } + // + return (result); + } - /** + /** * */ - public String name() - { - String result; + public String name() + { + String result; - result = this.name; + result = this.name; - // - return (result); - } + // + return (result); + } - /** + /** * */ - public Group setName(final String name) - { - this.name = name; + public Group setName(final String name) + { + this.name = name; - // - return (this); - } + // + return (this); + } - /** + /** * */ - @Override - public String toString() - { - String result; + @Override + public String toString() + { + String result; - result = "|" + this.name + "|" + this.members + "|"; + result = "|" + this.name + "|" + this.members + "|"; - // - return (result); - } + // + return (result); + } } // //////////////////////////////////////////////////////////////////////// diff --git a/src/fr/devinsy/kiss4web/security/Groups.java b/src/fr/devinsy/kiss4web/security/Groups.java index 1ae2d32..b4e969a 100644 --- a/src/fr/devinsy/kiss4web/security/Groups.java +++ b/src/fr/devinsy/kiss4web/security/Groups.java @@ -26,152 +26,152 @@ import java.util.Vector; */ public class Groups extends Vector { - private static final long serialVersionUID = 6238581648850758903L; + private static final long serialVersionUID = 6238581648850758903L; - /** + /** * */ - public Groups() - { - super(); - } + public Groups() + { + super(); + } - /* + /* + * + */ + public boolean contains(final String name) + { + boolean result; + + if (get(name) == null) + { + result = false; + } + else + { + result = true; + } + + // + return (result); + } + + /** * */ - public boolean contains(final String name) - { - boolean result; + public Group get(final String name) + { + Group result; - if (get(name) == null) - { - result = false; - } - else - { - result = true; - } + if (name == null) + { + result = null; + } + else + { + result = null; + boolean ended = false; + Iterator iterator = this.iterator(); + while (!ended) + { + if (iterator.hasNext()) + { + Group group = iterator.next(); + if (group.name().equals(name)) + { + ended = true; + result = group; + } + } + else + { + ended = true; + result = null; + } + } + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public Group get(final String name) - { - Group result; + public Vector getLoginGroups(final String login) + { + Vector result; - if (name == null) - { - result = null; - } - else - { - result = null; - boolean ended = false; - Iterator iterator = this.iterator(); - while (!ended) - { - if (iterator.hasNext()) - { - Group group = iterator.next(); - if (group.name().equals(name)) - { - ended = true; - result = group; - } - } - else - { - ended = true; - result = null; - } - } - } + result = new Vector(); + Iterator iterator = this.iterator(); - // - return (result); - } + while (iterator.hasNext()) + { + Group group = iterator.next(); - /** - * - */ - public Vector getLoginGroups(final String login) - { - Vector result; + if (group.members().contains(login)) + { + result.add(group.name()); + } + } - result = new Vector(); - Iterator iterator = this.iterator(); + // + return (result); + } - while (iterator.hasNext()) - { - Group group = iterator.next(); - - if (group.members().contains(login)) - { - result.add(group.name()); - } - } - - // - return (result); - } - - /** + /** * */ - public String getLoginGroupsString(final String login) - { - String result; + public String getLoginGroupsString(final String login) + { + String result; - Vector groups = getLoginGroups(login); + Vector groups = getLoginGroups(login); - StringBuffer string = new StringBuffer(); + StringBuffer string = new StringBuffer(); - for (String group : groups) - { - if (string.length() == 0) - { - string.append(group); - } - else - { - string.append(","); - string.append(group); - } - } + for (String group : groups) + { + if (string.length() == 0) + { + string.append(group); + } + else + { + string.append(","); + string.append(group); + } + } - result = string.toString(); + result = string.toString(); - // - return (result); - } + // + return (result); + } - /** + /** * */ - @Override - public String toString() - { - String result; + @Override + public String toString() + { + String result; - StringBuffer out; - out = new StringBuffer(); + StringBuffer out; + out = new StringBuffer(); - Iterator iterator = this.iterator(); + Iterator iterator = this.iterator(); - while (iterator.hasNext()) - { - out.append(iterator.next().toString() + "\n"); - } + while (iterator.hasNext()) + { + out.append(iterator.next().toString() + "\n"); + } - result = out.toString(); + result = out.toString(); - // - return (result); - } + // + return (result); + } } // //////////////////////////////////////////////////////////////////////// diff --git a/src/fr/devinsy/kiss4web/security/GroupsFileReader.java b/src/fr/devinsy/kiss4web/security/GroupsFileReader.java index 6badaaf..797a665 100644 --- a/src/fr/devinsy/kiss4web/security/GroupsFileReader.java +++ b/src/fr/devinsy/kiss4web/security/GroupsFileReader.java @@ -27,47 +27,47 @@ import java.util.Properties; */ public class GroupsFileReader { - /** + /** * */ - public static Groups load(final String fileName) throws Exception - { - Groups result; + public static Groups load(final String fileName) throws Exception + { + Groups result; - result = new Groups(); + result = new Groups(); - Properties properties = new Properties(); - try - { - properties.load(new FileInputStream(fileName)); + Properties properties = new Properties(); + try + { + properties.load(new FileInputStream(fileName)); - Iterator iterator = properties.keySet().iterator(); - while (iterator.hasNext()) - { - String key = (String) iterator.next(); - String valueLine = (String) properties.get(key); + Iterator iterator = properties.keySet().iterator(); + while (iterator.hasNext()) + { + String key = (String) iterator.next(); + String valueLine = (String) properties.get(key); - // - String[] values = valueLine.split(","); + // + String[] values = valueLine.split(","); - Group group = new Group(); - group.setName(key); - for (String value : values) - { - group.addMember(value.trim()); - } + Group group = new Group(); + group.setName(key); + for (String value : values) + { + group.addMember(value.trim()); + } - result.add(group); - } - } - catch (Exception exception) - { - throw new Exception("can't load (" + fileName + ")", exception); - } + result.add(group); + } + } + catch (Exception exception) + { + throw new Exception("can't load (" + fileName + ")", exception); + } - // - return (result); - } + // + return (result); + } } // //////////////////////////////////////////////////////////////////////// diff --git a/src/fr/devinsy/kiss4web/security/SecurityAgent.java b/src/fr/devinsy/kiss4web/security/SecurityAgent.java index 1cbd469..0e2c816 100644 --- a/src/fr/devinsy/kiss4web/security/SecurityAgent.java +++ b/src/fr/devinsy/kiss4web/security/SecurityAgent.java @@ -25,140 +25,140 @@ import java.util.Iterator; */ public class SecurityAgent { - private Users users; - private Groups groups; - private Groups permissions; + private Users users; + private Groups groups; + private Groups permissions; - /** + /** * */ - public SecurityAgent(final String path) throws Exception - { - this.users = UsersFileReader.load(path + "users.conf"); - this.groups = GroupsFileReader.load(path + "groups.conf"); - this.permissions = GroupsFileReader.load(path + "permissions.conf"); - } + public SecurityAgent(final String path) throws Exception + { + this.users = UsersFileReader.load(path + "users.conf"); + this.groups = GroupsFileReader.load(path + "groups.conf"); + this.permissions = GroupsFileReader.load(path + "permissions.conf"); + } - /** + /** * */ - public boolean authenticate(final String login, final String password) - { - boolean result; + public boolean authenticate(final String login, final String password) + { + boolean result; - User user = this.users.getByLogin(login); + User user = this.users.getByLogin(login); - if (user == null) - { - result = false; - } - else if (user.password().equals(password)) - { - result = true; - } - else - { - result = false; - } + if (user == null) + { + result = false; + } + else if (user.password().equals(password)) + { + result = true; + } + else + { + result = false; + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public boolean checkPermission(final String url, final String login) - { - boolean result = false; + public boolean checkPermission(final String url, final String login) + { + boolean result = false; - Group permitGroups = this.permissions.get(url); + Group permitGroups = this.permissions.get(url); - if (permitGroups == null) - { - result = false; - } - else - { - // - boolean ended = false; - Iterator iterator = permitGroups.members().iterator(); - while (!ended) - { - if (!iterator.hasNext()) - { - ended = true; - result = false; - } - else - { - String groupName = iterator.next(); - if (groupName.equals("*")) - { - result = true; - ended = true; - } - else - { - Group members = this.groups.get(groupName); + if (permitGroups == null) + { + result = false; + } + else + { + // + boolean ended = false; + Iterator iterator = permitGroups.members().iterator(); + while (!ended) + { + if (!iterator.hasNext()) + { + ended = true; + result = false; + } + else + { + String groupName = iterator.next(); + if (groupName.equals("*")) + { + result = true; + ended = true; + } + else + { + Group members = this.groups.get(groupName); - if (members == null) - { - result = false; - } - else - { - if (members.contains(login)) - { - ended = true; - result = true; - } - } - } - } - } - } + if (members == null) + { + result = false; + } + else + { + if (members.contains(login)) + { + ended = true; + result = true; + } + } + } + } + } + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public Groups groups() - { - Groups result; + public Groups groups() + { + Groups result; - result = this.groups; + result = this.groups; - // - return (result); - } + // + return (result); + } - /** + /** * */ - public Groups permissions() - { - Groups result; + public Groups permissions() + { + Groups result; - result = this.permissions; + result = this.permissions; - // - return (result); - } + // + return (result); + } - /** + /** * */ - public Users users() - { - Users result; + public Users users() + { + Users result; - result = this.users; + result = this.users; - // - return (result); - } + // + return (result); + } } diff --git a/src/fr/devinsy/kiss4web/security/User.java b/src/fr/devinsy/kiss4web/security/User.java index 14de8b2..c1f9b43 100644 --- a/src/fr/devinsy/kiss4web/security/User.java +++ b/src/fr/devinsy/kiss4web/security/User.java @@ -23,129 +23,129 @@ package fr.devinsy.kiss4web.security; */ public class User { - private String login; - private String password; - private String realName; - private String email; + private String login; + private String password; + private String realName; + private String email; - /** + /** * */ - public User() - { - this.login = null; - this.password = null; - this.realName = null; - this.email = null; - } + public User() + { + this.login = null; + this.password = null; + this.realName = null; + this.email = null; + } - /** + /** * */ - public String email() - { - String result; + public String email() + { + String result; - result = this.email; + result = this.email; - // - return (result); - } + // + return (result); + } - /** + /** * */ - public String login() - { - String result; + public String login() + { + String result; - result = this.login; + result = this.login; - // - return (result); - } + // + return (result); + } - /** + /** * */ - public String password() - { - String result; + public String password() + { + String result; - result = this.password; + result = this.password; - // - return (result); - } + // + return (result); + } - /** + /** * */ - public String realName() - { - String result; + public String realName() + { + String result; - result = this.realName; + result = this.realName; - // - return (result); - } + // + return (result); + } - /** + /** * */ - public User setEmail(final String email) - { - this.email = email; + public User setEmail(final String email) + { + this.email = email; - // - return (this); - } + // + return (this); + } - /** + /** * */ - public User setLogin(final String login) - { - this.login = login; + public User setLogin(final String login) + { + this.login = login; - // - return (this); - } + // + return (this); + } - /** + /** * */ - public User setPassword(final String password) - { - this.password = password; + public User setPassword(final String password) + { + this.password = password; - // - return (this); - } + // + return (this); + } - /** + /** * */ - public User setRealName(final String realName) - { - this.realName = realName; + public User setRealName(final String realName) + { + this.realName = realName; - // - return (this); - } + // + return (this); + } - /** + /** * */ - @Override - public String toString() - { - String result; + @Override + public String toString() + { + String result; - result = "|" + this.login + "|" + this.password + "|" + this.realName + "|"; + result = "|" + this.login + "|" + this.password + "|" + this.realName + "|"; - // - return (result); - } + // + return (result); + } } diff --git a/src/fr/devinsy/kiss4web/security/Users.java b/src/fr/devinsy/kiss4web/security/Users.java index aa26d75..04f4f46 100644 --- a/src/fr/devinsy/kiss4web/security/Users.java +++ b/src/fr/devinsy/kiss4web/security/Users.java @@ -26,98 +26,98 @@ import java.util.Vector; */ public class Users extends Vector { - private static final long serialVersionUID = 6140538630004281217L; + private static final long serialVersionUID = 6140538630004281217L; - /** + /** * */ - public Users() - { - super(); - } + public Users() + { + super(); + } - /* + /* + * + */ + public boolean contains(final String login) + { + boolean result; + + if (getByLogin(login) == null) + { + result = false; + } + else + { + result = true; + } + + // + return (result); + } + + /** * */ - public boolean contains(final String login) - { - boolean result; + public User getByLogin(final String login) + { + User result; - if (getByLogin(login) == null) - { - result = false; - } - else - { - result = true; - } + if (login == null) + { + result = null; + } + else + { + result = null; + boolean ended = false; + Iterator iterator = this.iterator(); + while (!ended) + { + if (iterator.hasNext()) + { + User user = iterator.next(); + if (user.login().equals(login)) + { + ended = true; + result = user; + } + } + else + { + ended = true; + result = null; + } + } + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public User getByLogin(final String login) - { - User result; + @Override + public String toString() + { + String result; - if (login == null) - { - result = null; - } - else - { - result = null; - boolean ended = false; - Iterator iterator = this.iterator(); - while (!ended) - { - if (iterator.hasNext()) - { - User user = iterator.next(); - if (user.login().equals(login)) - { - ended = true; - result = user; - } - } - else - { - ended = true; - result = null; - } - } - } + StringBuffer out; + out = new StringBuffer(); - // - return (result); - } + Iterator iterator = this.iterator(); - /** - * - */ - @Override - public String toString() - { - String result; + while (iterator.hasNext()) + { + out.append(iterator.next().toString() + "\n"); + } - StringBuffer out; - out = new StringBuffer(); + result = out.toString(); - Iterator iterator = this.iterator(); - - while (iterator.hasNext()) - { - out.append(iterator.next().toString() + "\n"); - } - - result = out.toString(); - - // - return (result); - } + // + return (result); + } } // //////////////////////////////////////////////////////////////////////// diff --git a/src/fr/devinsy/kiss4web/security/UsersFileReader.java b/src/fr/devinsy/kiss4web/security/UsersFileReader.java index e150867..72a7db2 100644 --- a/src/fr/devinsy/kiss4web/security/UsersFileReader.java +++ b/src/fr/devinsy/kiss4web/security/UsersFileReader.java @@ -27,47 +27,47 @@ import java.util.Properties; */ public class UsersFileReader { - /** + /** * */ - public static Users load(final String fileName) throws Exception - { - Users result; + public static Users load(final String fileName) throws Exception + { + Users result; - result = new Users(); + result = new Users(); - Properties properties = new Properties(); - try - { - properties.load(new FileInputStream(fileName)); + Properties properties = new Properties(); + try + { + properties.load(new FileInputStream(fileName)); - Iterator iterator = properties.keySet().iterator(); - while (iterator.hasNext()) - { - String key = (String) iterator.next(); - String valueLine = (String) properties.get(key); + Iterator iterator = properties.keySet().iterator(); + while (iterator.hasNext()) + { + String key = (String) iterator.next(); + String valueLine = (String) properties.get(key); - // - String[] values = valueLine.split(","); + // + String[] values = valueLine.split(","); - User user = new User(); - user.setLogin(key); - user.setPassword(values[0]); - user.setRealName(values[1]); - user.setEmail(values[2]); + User user = new User(); + user.setLogin(key); + user.setPassword(values[0]); + user.setRealName(values[1]); + user.setEmail(values[2]); - result.add(user); - // - } - } - catch (Exception exception) - { - throw new Exception("can't load (" + fileName + ")", exception); - } + result.add(user); + // + } + } + catch (Exception exception) + { + throw new Exception("can't load (" + fileName + ")", exception); + } - // - return (result); - } + // + return (result); + } } // //////////////////////////////////////////////////////////////////////// diff --git a/test/FooSandbox.java b/test/FooSandbox.java index f43112b..fa3e9dc 100644 --- a/test/FooSandbox.java +++ b/test/FooSandbox.java @@ -16,6 +16,7 @@ * You should have received a copy of the GNU General Public License * along with Kiss4web. If not, see */ +import fr.devinsy.kiss4web.KissDispatcher; import fr.devinsy.kiss4web.ServletDispatcher; /** @@ -23,76 +24,76 @@ import fr.devinsy.kiss4web.ServletDispatcher; */ class FooSandbox { - static private org.apache.log4j.Logger logger; + static private org.apache.log4j.Logger logger; - static - { - // Initialize logger. - org.apache.log4j.Logger logger = null; + static + { + // Initialize logger. + org.apache.log4j.Logger logger = null; - org.apache.log4j.BasicConfigurator.configure(); + org.apache.log4j.BasicConfigurator.configure(); - logger = org.apache.log4j.Logger.getRootLogger(); - // logger.setLevel (org.apache.log4j.Level.INFO); - logger.setLevel(org.apache.log4j.Level.INFO); + logger = org.apache.log4j.Logger.getRootLogger(); + // logger.setLevel (org.apache.log4j.Level.INFO); + logger.setLevel(org.apache.log4j.Level.INFO); - logger.info("Enter"); + logger.info("Enter"); - // - logger.info("Set the log file format..."); + // + logger.info("Set the log file format..."); - // log = - // org.apache.log4j.Category.getInstance(Application.class.getName()); - logger.info("... done."); + // log = + // org.apache.log4j.Category.getInstance(Application.class.getName()); + logger.info("... done."); - logger.debug("Exit"); - logger = org.apache.log4j.Logger.getLogger(FooSandbox.class.getName()); - } + logger.debug("Exit"); + logger = org.apache.log4j.Logger.getLogger(FooSandbox.class.getName()); + } - /** + /** * */ - public static String check(final String title, final StringBuffer source, final String model) - { - String result; + public static String check(final String title, final StringBuffer source, final String model) + { + String result; - if (source.indexOf(model) == -1) - { - result = String.format("%-40s -> KO <-", title) + "\nGet:\n" + source + "\nWaiting:\n" + model; + if (source.indexOf(model) == -1) + { + result = String.format("%-40s -> KO <-", title) + "\nGet:\n" + source + "\nWaiting:\n" + model; - } - else - { - result = String.format("%-40s [ OK ] ", title); - } + } + else + { + result = String.format("%-40s [ OK ] ", title); + } - // - return (result); - } + // + return (result); + } - /** + /** * */ - public static void main(final String[] args) - { - System.out.println("----------------------------"); - System.out.println(testCaller("/", "fr.devinsy.website")); - System.out.println(testCaller("/good/", "fr.devinsy.website")); - System.out.println(testCaller("/good/morning", "fr.devinsy.website")); - System.out.println(testCaller("/good/day_day", "fr.devinsy.website")); - System.out.println(testCaller("/good/day.xhtml", "fr.devinsy.website")); - } + public static void main(final String[] args) + { + System.out.println("----------------------------"); + System.out.println(testCaller("/", "fr.devinsy.website")); + System.out.println(testCaller("/good/", "fr.devinsy.website")); + System.out.println(testCaller("/good/morning", "fr.devinsy.website")); + System.out.println(testCaller("/good/day_day", "fr.devinsy.website")); + System.out.println(testCaller("/good/day.xhtml", "fr.devinsy.website")); + } - /** + /** * */ - public static String testCaller(final String pathInfo, final String prefix) - { - String result; + public static String testCaller(final String pathInfo, final String prefix) + { + String result; - result = "[" + pathInfo + "]=>[" + ServletDispatcher.pathInfoToClassName(pathInfo, prefix) + "]"; + result = "[" + pathInfo + "]=>[" + KissDispatcher.pathInfoToClassName(pathInfo, prefix) + "]"; - // - return (result); - } + // + return (result); + } } diff --git a/test/one/Foo2Test.java b/test/one/Foo2Test.java index 158a988..b5b6bc0 100644 --- a/test/one/Foo2Test.java +++ b/test/one/Foo2Test.java @@ -22,18 +22,18 @@ import org.junit.Test; public class Foo2Test { - // private Logger logger = - // LoggerFactory.getLogger(PdfGenerationAmqpServiceInjectedTest.class); + // private Logger logger = + // LoggerFactory.getLogger(PdfGenerationAmqpServiceInjectedTest.class); - /** + /** * */ - @Test - public void test2a() - { - // logger.debug("===== test starting..."); + @Test + public void test2a() + { + // logger.debug("===== test starting..."); - // logger.debug("===== test done."); - } + // logger.debug("===== test done."); + } }