Package ch.autumo.beetroot.handler
Class BaseHandler
java.lang.Object
org.nanohttpd.router.RouterNanoHTTPD.DefaultStreamHandler
org.nanohttpd.router.RouterNanoHTTPD.DefaultHandler
ch.autumo.beetroot.handler.BaseHandler
- All Implemented Interfaces:
Handler,RouterNanoHTTPD.UriResponder
- Direct Known Subclasses:
ChangeHandler,CustomResponseHandler,DefaultAddHandler,DefaultDeleteHandler,DefaultEditHandler,DefaultIndexHandler,DefaultRESTIndexHandler,DefaultViewHandler,Error404Handler,ErrorHandler,ExampleDownloadHandler,ExampleUploadHandler,HomeHandler,LoginHandler,LogoutHandler,NewQRCodeHandler,NoConfigHandler,NoContentButRouteHandler,NoContentHandler,NotImplementedHandler,OtpHandler,ResetHandler
Base handler - The "Heart" of beetRoot. A handler is mapped by a route
defined in 'cfg/routing.xml'.
Use
Use
Beside the CRUD methods
Use
setVar(String, Object) in your overwritten methods render(BeetRootHTTPSession)
to replace template variables.
Use
setVarAll(String, Object) in your overwritten methods renderAll(BeetRootHTTPSession)
to replace variables within the whole HTML document.
Beside the CRUD methods
readData(BeetRootHTTPSession, int)(index,view,edit),saveData(BeetRootHTTPSession)(add),updateData(BeetRootHTTPSession, int)(edit) anddeleteData(BeetRootHTTPSession, int)(delete)
getBeanClass()(when serving entities),getTitle(Session)(Show specific title)getRedirectHandler()(for redirecting)hasAccess(Session)(authorization)
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected final classState handler for role, entity and action "IFs" for the overall, the template and the template sub-resource layer. -
Field Summary
Fields -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedBase Handler.protectedBaseHandler(String entity) Base Handler. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddCheckBox(BeetRootHTTPSession session, String columnName) Add proper logic for check-boxes.voidaddErrorMessage(String message) Add an error message to show.voidaddHtmlDataLine(String line) Get HTML data.voidaddHtmlHeadLine(String line) Get HTML head if there's any.voidaddSuccessMessage(String message) Add a success message to show.voidaddWarningMessage(String message) Add a warning message to show.columns()Get columns map.intAmount of columns,deleteData(BeetRootHTTPSession session, int id) Delete data from DB.formatSingleValueForDB(BeetRootHTTPSession session, String val, String columnname) Format single value before update / insert into DB.final org.nanohttpd.protocols.http.response.Responseget(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, org.nanohttpd.protocols.http.IHTTPSession session) MAIN method for base handler.Class<?>Get bean entity class that has been generated trough PLANT, overwritten or null.String[]getColumn(int idx) Access column values. '[1] [colName=GUI Col Name 1]', index starts with 1 in 'columns.cfg'!Get SQL fields, e.g.getColumnsForSql(boolean forModification) Get SQL fields, e.g.final intGet current DB id of entity processed, for 'index.html' pages or other pages not showing an existing entity it is '-1'.final BeetRootHTTPSessionGet current HTTP session process.protected String[]getCustomizedExceptionInformation(Session userSession) Overwrite this method, if you want to have a customized handler exception title and message.final InputStreamgetData()final EntityGet an ampty bean of the entity type that is processed in this handler.Get web entity (use plural, e.g.final Class<?>getHandlerClass(String handlerName) Get a handler class by handler name.Get HTML data.Get HTML head if there's any.getInsertValues(BeetRootHTTPSession session) Get SQL insert values.Overwrite if you want to have a special layout for this handler.intGet set message type, default it is info/success type.protected ScannergetNewScanner(String resource) Getting a new scanner for a web resource (HTML template) to parse.protected ScannergetNewScanner(String resource, String originalResource) Getting a new scanner for a web resource (HTML template) to parse.getPaginator(BeetRootHTTPSession session) Get HTML paginator code.Class<?>Overwrite to get the right re-route/redirect index handler after modifying data.abstract StringGet web resource file as it lies on the file system relatively to the started server process.String[]Retrieve user roles for simple user role management.org.nanohttpd.protocols.http.response.IStatusgetTableExport(BeetRootHTTPSession session) Get HTML table export code.protected StringgetTemplateEngineErrorMessage(Session userSession, String resource) Get message for general template engine error.protected StringgetTemplateEngineErrorTitle(Session userSession, String resource) Get title for general template engine error.final StringgetText()getText(BeetRootHTTPSession session, int origId) Process handlers to get the whole HTML page.Page title show left above the navigation area.Get transient fieldsgetUpdateSetClause(BeetRootHTTPSession session) Get SQL update set clause.getUpdateSetClause(BeetRootHTTPSession session, String onOffMapName) Get SQL update set clause.booleanOverwrite this method, to specifically extend handler authorization, e.g. with more app user roles.booleanOverwrite if this handler serves templates with external links (starting with 'http' or 'https').protected booleanOverwrite this if your handler has no columns config configuration.voidinitialize(BeetRootHTTPSession session) Every handler MUST be initialized!protected StringinitialValue(String colName) Holds initial add values from 'columns.cfg'.protected intReturn size of initial value list for add template.protected booleanisCurrentUserUpdate(BeetRootHTTPSession session) Is the current user being updated?protected booleanOverwrite this if your handler has a custom response; e.g., a JSON response without any further HTML content.protected booleanOverwrite this if your handler doesn't have an output.protected StringisNoContentResponseButRoute(Session userSession) Overwrite this if your handler doesn't have an output.protected booleanisPrecisionInputType(String inputType) Is the given HTML input type a precision input type?booleanisRetryCall(BeetRootHTTPSession session) Is it a retry call?protected voidloginMarker(boolean redirectLogin) Login marker method.protected voidparseAssociatedEntities(StringBuilder snippet, List<Model> list, BeetRootHTTPSession session) Parse associated list.protected voidparseUnassociatedEntities(StringBuilder snippet, List<Model> list, BeetRootHTTPSession session) Parse un-associated list.static StringpatchInputValue(String text, String id, String newValue) This replaces a value in a HTML element with a specific ID.readData(BeetRootHTTPSession session, int id) Read data from DB that must be filled when the template is parsed.protected StringBuilderreadSnippetResource(String resource, Session userSession) Read snippet resource; e.g., 'web/html/:lang/users/snippets/roles.html'.protected voidredirectedMarker(boolean redirected) Mark this handler as it has been redirected from a data modifying handler.protected final voidrefreshUserRoles(int currentUserId, BeetRootHTTPSession session) Refresh user roles and permissions for current user.voidregisterDisplayField(String displayNameValue) Register a display name value to be show where defined in template.static voidregisterRoutes(List<Route> routes) Routes registration method.voidrender(BeetRootHTTPSession session) Overwrite to set your template variables.voidrenderAll(BeetRootHTTPSession session) Overwrite to set your variables for the whole HTML page.saveData(BeetRootHTTPSession session) Save data to DB.final voidsetCurrentEntityDbId(int origId) Set current DB id of entity processed, for 'index.html' pages or other pages not showing an existing entity it is '-1'.voidsetMessageType(int messageType) Set message type.final voidSet a template variable.final voidSet a global variable.booleanshowLangMenu(Session userSession) Show language menu?booleanShow template menu?String[]Get unique fields.uniqueTest(BeetRootHTTPSession session, String preSql, String operation) Check if unique fields are unique.updateData(BeetRootHTTPSession session, int id) Update data in DB.Methods inherited from class org.nanohttpd.router.RouterNanoHTTPD.DefaultStreamHandler
delete, other, post, put
-
Field Details
-
PRECISION_INPUT_TYPES
-
TAG_PREFIX_LANG
- See Also:
-
MSG_TYPE_INFO
public static final int MSG_TYPE_INFO- See Also:
-
MSG_TYPE_WARN
public static final int MSG_TYPE_WARN- See Also:
-
MSG_TYPE_ERR
public static final int MSG_TYPE_ERR- See Also:
-
columns
-
initialValues
-
uniqueFields
-
transientFields
-
emptyBean
-
entity
-
action
-
htmlHead
-
htmlData
-
insertServletNameInTemplateRefs
protected boolean insertServletNameInTemplateRefs -
servletName
-
-
Constructor Details
-
BaseHandler
protected BaseHandler()Base Handler. -
BaseHandler
Base Handler.- Parameters:
entity- entity, plural & lower-case; e.g. 'roles, users or properties'
-
-
Method Details
-
initialize
Every handler MUST be initialized!- Parameters:
session- session
-
registerRoutes
Routes registration method.- Parameters:
routes- all routes except default routes
-
getHandlerClass
Get a handler class by handler name.- Parameters:
handlerName- handler name- Returns:
- handler class or null if not found
-
getBeanClass
Get bean entity class that has been generated trough PLANT, overwritten or null.- Returns:
- bean entity class
-
getEmptyBean
Get an ampty bean of the entity type that is processed in this handler. Can be used to access static information that has been created by PLANT. (E.g. foreign related classes).- Returns:
- entity bean
-
getMessageType
public int getMessageType()Get set message type, default it is info/success type.- Returns:
- message type
-
setMessageType
public void setMessageType(int messageType) Set message type. Overwrites any message type set before, e.g. adding a message through constructor. But the original message is kept if any available.- Parameters:
messageType- message type
-
columns
Get columns map. Entries: '[1] [colName1=GUI Col Name 1]'. '[2] [colName2=GUI Col Name 2]'. ...- Returns:
- colum map
-
uniqueFields
Get unique fields.- Returns:
- unique fields
-
columnsSize
public int columnsSize()Amount of columns,- Returns:
- amount of columns
-
getColumn
Access column values. '[1] [colName=GUI Col Name 1]', index starts with 1 in 'columns.cfg'!- Parameters:
idx- columns index from 'columns.cfg'- Returns:
- column values
-
getColumnsForSql
Get SQL fields, e.g. 'col1, col2, col3' for queries (seleczs).- Returns:
- SQL query fields
-
getColumnsForSql
Get SQL fields, e.g. 'col1, col2, col3'.- Parameters:
forModification- true for updates/inserts- Returns:
- SQL query fields
-
getTransientFields
Get transient fields- Returns:
- transient fields
-
getInsertValues
Get SQL insert values.- Parameters:
session- HTTP session- Returns:
- SQL insert values
- Throws:
Exception- exception
-
getUpdateSetClause
Get SQL update set clause. Passwords will NOT be updated!- Parameters:
session- HTTP session- Returns:
- SQL update clause
- Throws:
Exception- exception
-
getUpdateSetClause
Get SQL update set clause. Passwords will NOT be updated!- Parameters:
session- HTTP sessiononOffMapName- name of on/off value map if any, otherwise null.- Returns:
- SQL update clause
- Throws:
Exception- exception
-
isCurrentUserUpdate
Is the current user being updated?- Parameters:
session- HTTP session- Returns:
- true is so
-
uniqueTest
public HandlerResponse uniqueTest(BeetRootHTTPSession session, String preSql, String operation) throws Exception Check if unique fields are unique.- Parameters:
session- sessionspreSql- pre-parsed SQL without unique fieldsoperation- saved or updated- Returns:
- response or null, null means success, response's status must be checked!
- Throws:
Exception- exception
-
refreshUserRoles
Refresh user roles and permissions for current user.- Parameters:
currentUserId- current user id of the currently logged-in usersession- HTTP session
-
getText
Process handlers to get the whole HTML page.- Parameters:
session- beetRoot sessionorigId- original DB id- Returns:
- whole parsed HTML page
- Throws:
Exception- exception
-
registerDisplayField
Register a display name value to be show where defined in template.- Parameters:
displayNameValue- display name value
-
getLayout
Overwrite if you want to have a special layout for this handler.- Parameters:
userSession- user session- Returns:
- layout file path; example: 'web/html/:lang/blocks/mylayout.html'
-
getTitle
Page title show left above the navigation area. If not overwritten, the entity name is shown starting with an upper-case letter!- Parameters:
userSession- user session- Returns:
- page title
-
hasExternalLinks
public boolean hasExternalLinks()Overwrite if this handler serves templates with external links (starting with 'http' or 'https').- Returns:
- true if
-
getSimpleManagementUserRoles
Retrieve user roles for simple user role management. These roles are read from the application configuration (beetroog.cfg -> 'web_roles') and translated in the web masks if a translation is available. Not used by the extended role management. which is default! Note: The extended user roles management is activated by default, so these roles aren't used!- Returns:
- user roles
-
parseAssociatedEntities
protected void parseAssociatedEntities(StringBuilder snippet, List<Model> list, BeetRootHTTPSession session) Parse associated list.- Parameters:
snippet- buffered code snippetlist- the list with the associated entitiessession- beetRoot session
-
parseUnassociatedEntities
protected void parseUnassociatedEntities(StringBuilder snippet, List<Model> list, BeetRootHTTPSession session) Parse un-associated list.- Parameters:
snippet- buffered code snippetlist- the list with the un-associated entitiessession- beetRoot session
-
getNewScanner
Getting a new scanner for a web resource (HTML template) to parse.- Parameters:
resource- resource string, e.g. 'web/html/en/<entity>/index.html'- Returns:
- file scanner for reading lines
- Throws:
FileNotFoundException- if file is not found
-
getNewScanner
protected Scanner getNewScanner(String resource, String originalResource) throws FileNotFoundException Getting a new scanner for a web resource (HTML template) to parse.- Parameters:
resource- resource string, e.g. 'web/html/en/<entity>/index.html'originalResource- resource string, e.g. 'web/html/:lang/<entity>/index.html'; useful for looking up snippets- Returns:
- file scanner for reading lines
- Throws:
FileNotFoundException- if file is not found
-
readSnippetResource
protected StringBuilder readSnippetResource(String resource, Session userSession) throws FileNotFoundException Read snippet resource; e.g., 'web/html/:lang/users/snippets/roles.html'.- Parameters:
resource- resource fileuserSession- user session- Returns:
- buffer with resource
- Throws:
FileNotFoundException- if file is not found
-
initValuesSize
protected int initValuesSize()Return size of initial value list for add template.- Returns:
- initial values size
-
initialValue
Holds initial add values from 'columns.cfg'. Example init.colName1=0 init.colName2=Change this!- Parameters:
colName- column name- Returns:
- initial value for add template
-
getStatus
public org.nanohttpd.protocols.http.response.IStatus getStatus()- Specified by:
getStatusin classRouterNanoHTTPD.DefaultHandler
-
getMimeType
- Specified by:
getMimeTypein classRouterNanoHTTPD.DefaultStreamHandler
-
getText
- Specified by:
getTextin classRouterNanoHTTPD.DefaultHandler
-
getData
- Overrides:
getDatain classRouterNanoHTTPD.DefaultHandler
-
get
public final org.nanohttpd.protocols.http.response.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, org.nanohttpd.protocols.http.IHTTPSession session) MAIN method for base handler.- Specified by:
getin interfaceRouterNanoHTTPD.UriResponder- Overrides:
getin classRouterNanoHTTPD.DefaultHandler
-
isRetryCall
Is it a retry call?- Parameters:
session- HTTP session- Returns:
- true if so
-
setCurrentEntityDbId
public final void setCurrentEntityDbId(int origId) Set current DB id of entity processed, for 'index.html' pages or other pages not showing an existing entity it is '-1'.- Parameters:
origId- original DB id of entity
-
getCurrentEntityDbId
public final int getCurrentEntityDbId()Get current DB id of entity processed, for 'index.html' pages or other pages not showing an existing entity it is '-1'.- Returns:
- original DB id of entity
-
getCustomizedExceptionInformation
Overwrite this method, if you want to have a customized handler exception title and message.- Parameters:
userSession- user session- Returns:
- array of two values containing title[0] and text[1]
-
isNoContentResponseButRoute
Overwrite this if your handler doesn't have an output. When a new route (e.g. 'users/index') is returned, that new route is loaded by a script refresh. Ifnullis returned, nothing happens.- Parameters:
userSession- user session- Returns:
nullor a new route
-
isNoContentResponse
protected boolean isNoContentResponse()Overwrite this if your handler doesn't have an output. A no content response (HTTP 204) with no content will be generated and the current page will be refreshed!- Returns:
trueif a script refresh on the default index handler should be made.
-
isCustomResponse
protected boolean isCustomResponse()Overwrite this if your handler has a custom response; e.g., a JSON response without any further HTML content. Such a response is usually used for live searches, etc.- Returns:
trueif it is a custom response
-
hasNoColumnsConfig
protected boolean hasNoColumnsConfig()Overwrite this if your handler has no columns config configuration.- Returns:
trueif no columns configuration must be read
-
getTemplateEngineErrorTitle
Get title for general template engine error.- Parameters:
userSession- user sessionresource- template resource- Returns:
- title
-
getTemplateEngineErrorMessage
Get message for general template engine error.- Parameters:
userSession- user sessionresource- template resource- Returns:
- message
-
redirectedMarker
protected void redirectedMarker(boolean redirected) Mark this handler as it has been redirected from a data modifying handler.- Parameters:
redirected- true if redirected
-
hasAccess
Overwrite this method, to specifically extend handler authorization, e.g. with more app user roles.- Parameters:
userSession- user session- Returns:
- true if access is allowed, otherwise false
-
readData
Read data from DB that must be filled when the template is parsed. Used by index and view handlers.- Parameters:
session- HTTP sessionid- db record id > 0 if a single record should be read otherwise < 0;- Returns:
- response or null, null means success, response's status must be checked!
- Throws:
Exception- exception
-
saveData
Save data to DB. Override for add handlers.- Parameters:
session- HTTP session- Returns:
- response or null, null means success, response's status must be checked and must hold the id of the saved record!
- Throws:
Exception- exception
-
updateData
Update data in DB. Override for edit handlers.- Parameters:
id- db record idsession- HTTP session- Returns:
- response or null, null means success, response's status must be checked!
- Throws:
Exception- exception
-
deleteData
Delete data from DB. Override for delete handlers.- Parameters:
id- db record idsession- HTTP session- Returns:
- response or null, null means success, response's status must be checked!
- Throws:
Exception- exception
-
getRedirectHandler
Overwrite to get the right re-route/redirect index handler after modifying data. It must be of the same entity as the last executing handler!- Returns:
- redirect index handler
-
getCurrentSession
Get current HTTP session process.- Returns:
- HTTP session
-
getEntity
Get web entity (use plural, e.g. 'tasks', 'users'.- Returns:
- web entity
-
getHtmlHead
Get HTML head if there's any.- Returns:
- HTML head
-
getHtmlData
Get HTML data.- Returns:
- HTML data
-
addHtmlHeadLine
Get HTML head if there's any.- Parameters:
line- HTML line
-
addHtmlDataLine
Get HTML data.- Parameters:
line- HTML line
-
patchInputValue
This replaces a value in a HTML element with a specific ID.- Parameters:
text- text to parse and returnid- HTML element with specific ID- Returns:
- patched HTML
-
render
Overwrite to set your template variables. Only use the pure names without bracket-limiters and $-sign; e.g., In template '{$name}' -> 'name' as variable. Example:setVar("name", "Gandalf").- Parameters:
session- HTTP session
-
renderAll
Overwrite to set your variables for the whole HTML page. Only use the pure names without bracket-limiters and $-sign; e.g., In template '{$name}' -> 'name' as variable. Example:setVarAll("name", "The Almighty").- Parameters:
session- HTTP session
-
setVar
Set a template variable. Only use the pure names without bracket-limiters and $-sign; e.g., In template '{$name}' -> 'name' as variable.- Parameters:
variable- template variable without brackets and '$'.replacement- replacement text
-
setVarAll
Set a global variable. Variables are replace within the whole HTML page! Only use the pure names without bracket-limiters and $-sign; e.g., In template '{$name}' -> 'name' as variable.- Parameters:
variable- template variable without brackets and '$'.replacement- replacement text
-
getTableExport
Get HTML table export code. Must only be implemented by index handlers and is only called if there's a "{$tabelExport}" tag in a template.- Parameters:
session- HTTP session- Returns:
- HTML paginator code
-
getPaginator
Get HTML paginator code. Must only be implemented by index handlers and is only called if there's a "{$paginator}" tag in a template.- Parameters:
session- HTTP session- Returns:
- HTML paginator code
-
showMenu
Show template menu?- Parameters:
userSession- user session, possible even a temporary session from a not logged in user- Returns:
- true if a menu should be shown
-
showLangMenu
Show language menu?- Parameters:
userSession- user session, possible even a temporary session from a not logged in user- Returns:
- true if language menu should be shown
-
addSuccessMessage
Add a success message to show.- Parameters:
message- message
-
addWarningMessage
Add a warning message to show.- Parameters:
message- message
-
addErrorMessage
Add an error message to show.- Parameters:
message- message
-
getResource
Get web resource file as it lies on the file system relatively to the started server process.- Specified by:
getResourcein interfaceHandler- Returns:
- web resource
-
addCheckBox
Add proper logic for check-boxes.- Parameters:
session- HTTP sessioncolumnName- column / input name
-
isPrecisionInputType
Is the given HTML input type a precision input type? They are allowed to have a 'maxLength' attribute.- Parameters:
inputType- HTML input type- Returns:
- true, if it is a precision HTML input type
-
formatSingleValueForDB
Format single value before update / insert into DB. This method is useful if you want to store null values for date, time or time-stamp in the database. In the HTML user interface, the value would be displayed as '' (empty string), which is not a valid value in the database; in this case, it would need to be set to null. This is rarely the case, as date/time values are normally set or, if they are mandatory, should be set in theDefaultAddHandler.getAddMandatoryFields()method when creating a new record. It is therefore only possible for updates.- Parameters:
session- HTTP sessionval- valuecolumnname- column name- Returns:
- formatted value
-
loginMarker
protected void loginMarker(boolean redirectLogin) Login marker method.- Parameters:
redirectLogin- redirected from login?
-