Class 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

public abstract class BaseHandler extends RouterNanoHTTPD.DefaultHandler implements Handler
Base handler - The "Heart" of beetRoot. A handler is mapped by a route defined in 'cfg/routing.xml'.

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 you usually need to overwrite the following methods: Depending on the handler, you might want to overwrite more methods. There are methods for everything, and you should be able to do anything with the template engine. For a good overview, see users as well system handler source codes.
  • Field Details

    • PRECISION_INPUT_TYPES

      protected static final List<String> PRECISION_INPUT_TYPES
    • TAG_PREFIX_LANG

      public static final String 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

      protected TreeMap<Integer,String> columns
    • initialValues

      protected Map<String,String> initialValues
    • uniqueFields

      protected String[] uniqueFields
    • transientFields

      protected List<String> transientFields
    • emptyBean

      protected Entity emptyBean
    • entity

      protected String entity
    • action

      protected String action
    • htmlHead

      protected String htmlHead
    • htmlData

      protected String htmlData
    • insertServletNameInTemplateRefs

      protected boolean insertServletNameInTemplateRefs
    • servletName

      protected String servletName
  • Constructor Details

    • BaseHandler

      protected BaseHandler()
      Base Handler.
    • BaseHandler

      protected BaseHandler(String entity)
      Base Handler.
      Parameters:
      entity - entity, plural & lower-case; e.g. 'roles, users or properties'
  • Method Details

    • initialize

      public void initialize(BeetRootHTTPSession session)
      Every handler MUST be initialized!
      Parameters:
      session - session
    • registerRoutes

      public static void registerRoutes(List<Route> routes)
      Routes registration method.
      Parameters:
      routes - all routes except default routes
    • getHandlerClass

      public final Class<?> getHandlerClass(String handlerName)
      Get a handler class by handler name.
      Parameters:
      handlerName - handler name
      Returns:
      handler class or null if not found
    • getBeanClass

      public Class<?> getBeanClass()
      Get bean entity class that has been generated trough PLANT, overwritten or null.
      Returns:
      bean entity class
    • getEmptyBean

      public final Entity 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

      public SortedMap<Integer,String> columns()
      Get columns map. Entries: '[1] [colName1=GUI Col Name 1]'. '[2] [colName2=GUI Col Name 2]'. ...
      Returns:
      colum map
    • uniqueFields

      public String[] uniqueFields()
      Get unique fields.
      Returns:
      unique fields
    • columnsSize

      public int columnsSize()
      Amount of columns,
      Returns:
      amount of columns
    • getColumn

      public String[] getColumn(int idx)
      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

      public String getColumnsForSql()
      Get SQL fields, e.g. 'col1, col2, col3' for queries (seleczs).
      Returns:
      SQL query fields
    • getColumnsForSql

      public String getColumnsForSql(boolean forModification)
      Get SQL fields, e.g. 'col1, col2, col3'.
      Parameters:
      forModification - true for updates/inserts
      Returns:
      SQL query fields
    • getTransientFields

      public List<String> getTransientFields()
      Get transient fields
      Returns:
      transient fields
    • getInsertValues

      public String getInsertValues(BeetRootHTTPSession session) throws Exception
      Get SQL insert values.
      Parameters:
      session - HTTP session
      Returns:
      SQL insert values
      Throws:
      Exception - exception
    • getUpdateSetClause

      public String getUpdateSetClause(BeetRootHTTPSession session) throws Exception
      Get SQL update set clause. Passwords will NOT be updated!
      Parameters:
      session - HTTP session
      Returns:
      SQL update clause
      Throws:
      Exception - exception
    • getUpdateSetClause

      public String getUpdateSetClause(BeetRootHTTPSession session, String onOffMapName) throws Exception
      Get SQL update set clause. Passwords will NOT be updated!
      Parameters:
      session - HTTP session
      onOffMapName - name of on/off value map if any, otherwise null.
      Returns:
      SQL update clause
      Throws:
      Exception - exception
    • isCurrentUserUpdate

      protected boolean isCurrentUserUpdate(BeetRootHTTPSession session)
      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 - sessions
      preSql - pre-parsed SQL without unique fields
      operation - saved or updated
      Returns:
      response or null, null means success, response's status must be checked!
      Throws:
      Exception - exception
    • refreshUserRoles

      protected final void refreshUserRoles(int currentUserId, BeetRootHTTPSession session)
      Refresh user roles and permissions for current user.
      Parameters:
      currentUserId - current user id of the currently logged-in user
      session - HTTP session
    • getText

      public String getText(BeetRootHTTPSession session, int origId) throws Exception
      Process handlers to get the whole HTML page.
      Parameters:
      session - beetRoot session
      origId - original DB id
      Returns:
      whole parsed HTML page
      Throws:
      Exception - exception
    • registerDisplayField

      public void registerDisplayField(String displayNameValue)
      Register a display name value to be show where defined in template.
      Parameters:
      displayNameValue - display name value
    • getLayout

      public String getLayout(Session userSession)
      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

      public String getTitle(Session userSession)
      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

      public String[] 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 snippet
      list - the list with the associated entities
      session - beetRoot session
    • parseUnassociatedEntities

      protected void parseUnassociatedEntities(StringBuilder snippet, List<Model> list, BeetRootHTTPSession session)
      Parse un-associated list.
      Parameters:
      snippet - buffered code snippet
      list - the list with the un-associated entities
      session - beetRoot session
    • getNewScanner

      protected Scanner getNewScanner(String resource) 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'
      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 file
      userSession - 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

      protected String initialValue(String colName)
      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:
      getStatus in class RouterNanoHTTPD.DefaultHandler
    • getMimeType

      public String getMimeType()
      Specified by:
      getMimeType in class RouterNanoHTTPD.DefaultStreamHandler
    • getText

      public final String getText()
      Specified by:
      getText in class RouterNanoHTTPD.DefaultHandler
    • getData

      public final InputStream getData()
      Overrides:
      getData in class RouterNanoHTTPD.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:
      get in interface RouterNanoHTTPD.UriResponder
      Overrides:
      get in class RouterNanoHTTPD.DefaultHandler
    • isRetryCall

      public boolean isRetryCall(BeetRootHTTPSession session)
      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

      protected String[] getCustomizedExceptionInformation(Session userSession)
      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

      protected String isNoContentResponseButRoute(Session userSession)
      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. If null is returned, nothing happens.
      Parameters:
      userSession - user session
      Returns:
      null or 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:
      true if 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:
      true if it is a custom response
    • hasNoColumnsConfig

      protected boolean hasNoColumnsConfig()
      Overwrite this if your handler has no columns config configuration.
      Returns:
      true if no columns configuration must be read
    • getTemplateEngineErrorTitle

      protected String getTemplateEngineErrorTitle(Session userSession, String resource)
      Get title for general template engine error.
      Parameters:
      userSession - user session
      resource - template resource
      Returns:
      title
    • getTemplateEngineErrorMessage

      protected String getTemplateEngineErrorMessage(Session userSession, String resource)
      Get message for general template engine error.
      Parameters:
      userSession - user session
      resource - 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

      public boolean hasAccess(Session userSession)
      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

      public HandlerResponse readData(BeetRootHTTPSession session, int id) throws Exception
      Read data from DB that must be filled when the template is parsed. Used by index and view handlers.
      Parameters:
      session - HTTP session
      id - 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

      public HandlerResponse saveData(BeetRootHTTPSession session) throws Exception
      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

      public HandlerResponse updateData(BeetRootHTTPSession session, int id) throws Exception
      Update data in DB. Override for edit handlers.
      Parameters:
      id - db record id
      session - HTTP session
      Returns:
      response or null, null means success, response's status must be checked!
      Throws:
      Exception - exception
    • deleteData

      public HandlerResponse deleteData(BeetRootHTTPSession session, int id) throws Exception
      Delete data from DB. Override for delete handlers.
      Parameters:
      id - db record id
      session - HTTP session
      Returns:
      response or null, null means success, response's status must be checked!
      Throws:
      Exception - exception
    • getRedirectHandler

      public Class<?> 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

      public final BeetRootHTTPSession getCurrentSession()
      Get current HTTP session process.
      Returns:
      HTTP session
    • getEntity

      public String getEntity()
      Get web entity (use plural, e.g. 'tasks', 'users'.
      Returns:
      web entity
    • getHtmlHead

      public String getHtmlHead()
      Get HTML head if there's any.
      Returns:
      HTML head
    • getHtmlData

      public String getHtmlData()
      Get HTML data.
      Returns:
      HTML data
    • addHtmlHeadLine

      public void addHtmlHeadLine(String line)
      Get HTML head if there's any.
      Parameters:
      line - HTML line
    • addHtmlDataLine

      public void addHtmlDataLine(String line)
      Get HTML data.
      Parameters:
      line - HTML line
    • patchInputValue

      public static String patchInputValue(String text, String id, String newValue)
      This replaces a value in a HTML element with a specific ID.
      Parameters:
      text - text to parse and return
      id - HTML element with specific ID
      Returns:
      patched HTML
    • render

      public void render(BeetRootHTTPSession session)
      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

      public void renderAll(BeetRootHTTPSession session)
      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

      public final void setVar(String variable, Object replacement)
      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

      public final void setVarAll(String variable, Object replacement)
      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

      public String getTableExport(BeetRootHTTPSession session)
      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

      public String getPaginator(BeetRootHTTPSession session)
      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

      public boolean showMenu(Session userSession)
      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

      public boolean showLangMenu(Session userSession)
      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

      public void addSuccessMessage(String message)
      Add a success message to show.
      Parameters:
      message - message
    • addWarningMessage

      public void addWarningMessage(String message)
      Add a warning message to show.
      Parameters:
      message - message
    • addErrorMessage

      public void addErrorMessage(String message)
      Add an error message to show.
      Parameters:
      message - message
    • getResource

      public abstract String getResource()
      Get web resource file as it lies on the file system relatively to the started server process.
      Specified by:
      getResource in interface Handler
      Returns:
      web resource
    • addCheckBox

      protected void addCheckBox(BeetRootHTTPSession session, String columnName)
      Add proper logic for check-boxes.
      Parameters:
      session - HTTP session
      columnName - column / input name
    • isPrecisionInputType

      protected boolean isPrecisionInputType(String inputType)
      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

      public String formatSingleValueForDB(BeetRootHTTPSession session, String val, String columnname)
      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 the DefaultAddHandler.getAddMandatoryFields() method when creating a new record. It is therefore only possible for updates.
      Parameters:
      session - HTTP session
      val - value
      columnname - column name
      Returns:
      formatted value
    • loginMarker

      protected void loginMarker(boolean redirectLogin)
      Login marker method.
      Parameters:
      redirectLogin - redirected from login?