fixes several warnings

Sat, 09 May 2020 15:19:21 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 09 May 2020 15:19:21 +0200
changeset 33
fd8c40ff78c3
parent 32
63a31871189e
child 34
824d4042c857

fixes several warnings

src/main/java/de/uapcore/lightpit/AbstractLightPITServlet.java file | annotate | diff | comparison | revisions
src/main/java/de/uapcore/lightpit/DatabaseFacade.java file | annotate | diff | comparison | revisions
src/main/java/de/uapcore/lightpit/Functions.java file | annotate | diff | comparison | revisions
src/main/java/de/uapcore/lightpit/ModuleManager.java file | annotate | diff | comparison | revisions
src/main/java/de/uapcore/lightpit/dao/CoreDAOFactory.java file | annotate | diff | comparison | revisions
src/main/java/de/uapcore/lightpit/dao/ModuleDao.java file | annotate | diff | comparison | revisions
src/main/java/de/uapcore/lightpit/dao/UserDao.java file | annotate | diff | comparison | revisions
src/main/java/de/uapcore/lightpit/entities/User.java file | annotate | diff | comparison | revisions
--- a/src/main/java/de/uapcore/lightpit/AbstractLightPITServlet.java	Sat May 09 14:58:41 2020 +0200
+++ b/src/main/java/de/uapcore/lightpit/AbstractLightPITServlet.java	Sat May 09 15:19:21 2020 +0200
@@ -28,22 +28,18 @@
  */
 package de.uapcore.lightpit;
 
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Optional;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.*;
 
 /**
  * A special implementation of a HTTPServlet which is focused on implementing
@@ -54,21 +50,21 @@
     private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
     
     private static final String HTML_FULL_DISPATCHER = Functions.jspPath("html_full");
-    
+
     /**
      * Store a reference to the annotation for quicker access.
      */
-    private Optional<LightPITModule> moduleInfo = Optional.empty();
+    private LightPITModule moduleInfo = null;
 
     /**
      * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
      */
-    private Optional<LightPITModule.ELProxy> moduleInfoELProxy = Optional.empty();
-    
-    
+    private LightPITModule.ELProxy moduleInfoELProxy = null;
+
+
     @FunctionalInterface
-    private static interface HandlerMethod {
-        ResponseType apply(HttpServletRequest t, HttpServletResponse u) throws IOException, ServletException;
+    private interface HandlerMethod {
+        ResponseType apply(HttpServletRequest t, HttpServletResponse u) throws IOException;
     }
     
     /**
@@ -84,22 +80,27 @@
 
     /**
      * Gives implementing modules access to the {@link ModuleManager}.
+     *
      * @return the module manager
      */
     protected final ModuleManager getModuleManager() {
         return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
     }
-    
+
+    public final LightPITModule getModuleInfo() {
+        return moduleInfo;
+    }
+
     /**
      * Gives implementing modules access to the {@link DatabaseFacade}.
+     *
      * @return the database facade
      */
     protected final DatabaseFacade getDatabaseFacade() {
         return (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
     }
-    
-    private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp)
-            throws IOException, ServletException {
+
+    private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp) throws IOException {
         try {
             LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
             return (ResponseType) method.invoke(this, req, resp);
@@ -112,13 +113,13 @@
 
     @Override
     public void init() throws ServletException {
-        moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class));
-        moduleInfoELProxy = moduleInfo.map(LightPITModule.ELProxy::convert);
-        
-        if (moduleInfo.isPresent()) {
+        moduleInfo = this.getClass().getAnnotation(LightPITModule.class);
+        moduleInfoELProxy = moduleInfo == null ? null : LightPITModule.ELProxy.convert(moduleInfo);
+
+        if (moduleInfo != null) {
             scanForRequestMappings();
         }
-        
+
         LOG.trace("{} initialized", getServletName());
     }
 
@@ -270,7 +271,7 @@
         // set some internal request attributes
         req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
         req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
-        moduleInfoELProxy.ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
+        Optional.ofNullable(moduleInfoELProxy).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
         
         
         // call the handler, if available, or send an HTTP 404 error
--- a/src/main/java/de/uapcore/lightpit/DatabaseFacade.java	Sat May 09 14:58:41 2020 +0200
+++ b/src/main/java/de/uapcore/lightpit/DatabaseFacade.java	Sat May 09 15:19:21 2020 +0200
@@ -28,10 +28,9 @@
  */
 package de.uapcore.lightpit;
 
-import java.sql.Connection;
-import java.sql.DatabaseMetaData;
-import java.sql.SQLException;
-import java.util.Optional;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import javax.naming.Context;
 import javax.naming.InitialContext;
 import javax.naming.NamingException;
@@ -40,31 +39,33 @@
 import javax.servlet.ServletContextListener;
 import javax.servlet.annotation.WebListener;
 import javax.sql.DataSource;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.SQLException;
+import java.util.Optional;
 
 /**
  * Provides access to different privilege layers within the database.
  */
 @WebListener
 public final class DatabaseFacade implements ServletContextListener {
-    
+
     private static final Logger LOG = LoggerFactory.getLogger(DatabaseFacade.class);
-    
+
     /**
      * Timeout in seconds for the validation test.
      */
     private static final int DB_TEST_TIMEOUT = 10;
-    
-    public static enum Dialect {
-        Postgres;
+
+    public enum Dialect {
+        Postgres
     }
-    
+
     /**
      * The database dialect to use.
-     * 
+     * <p>
      * May be override by context parameter.
-     * 
+     *
      * @see Constants#CTX_ATTR_DB_DIALECT
      */
     private Dialect dialect = Dialect.Postgres;
@@ -82,10 +83,9 @@
      * The attribute name in the Servlet context under which an instance of this class can be found.
      */
     public static final String SC_ATTR_NAME = DatabaseFacade.class.getName();
-    private ServletContext sc;
-    
+
     private static final String DS_JNDI_NAME = "jdbc/lightpit/app";
-    private Optional<DataSource> dataSource;
+    private DataSource dataSource;
     
     /**
      * Returns the data source.
@@ -97,14 +97,15 @@
      * @return a data source
      */
     public Optional<DataSource> getDataSource() {
-        return dataSource;
+        // TODO: this should not be an optional, if an empty optional is actually an exception
+        return Optional.ofNullable(dataSource);
     }
     
     public Dialect getSQLDialect() {
         return dialect;
     }
-    
-    private static void checkConnection(DataSource ds, String testSchema, String errMsg) {
+
+    private static void checkConnection(DataSource ds, String testSchema) {
         try (Connection conn = ds.getConnection()) {
             if (!conn.isValid(DB_TEST_TIMEOUT)) {
                 throw new SQLException("Validation check failed.");
@@ -118,25 +119,25 @@
             DatabaseMetaData metaData = conn.getMetaData();
             LOG.info("Connections as {} to {}/{} ready to go.", metaData.getUserName(), metaData.getURL(), conn.getSchema());
         } catch (SQLException ex) {
-            LOG.error(errMsg, ex);
+            LOG.error("Checking database connection failed", ex);
         }
     }
-    
-    private static Optional<DataSource> retrieveDataSource(Context ctx) {
+
+    private static DataSource retrieveDataSource(Context ctx) {
         DataSource ret = null;
         try {
-            ret = (DataSource)ctx.lookup(DS_JNDI_NAME);
+            ret = (DataSource) ctx.lookup(DS_JNDI_NAME);
             LOG.info("Data source retrieved.");
         } catch (NamingException ex) {
             LOG.error("Data source {} not available.", DS_JNDI_NAME);
             LOG.error("Reason for the missing data source: ", ex);
         }
-        return Optional.ofNullable(ret);
+        return ret;
     }
 
     @Override
     public void contextInitialized(ServletContextEvent sce) {
-        sc = sce.getServletContext();
+        ServletContext sc = sce.getServletContext();
         
         dataSource = null;
         
@@ -159,10 +160,12 @@
             LOG.debug("Trying to access JNDI context {}...", contextName);
             Context initialCtx = new InitialContext();
             Context ctx = (Context) initialCtx.lookup(contextName);
-            
+
             dataSource = retrieveDataSource(ctx);
-            
-            dataSource.ifPresent((ds) -> checkConnection(ds, dbSchema, "Checking database connection failed"));
+
+            if (dataSource != null) {
+                checkConnection(dataSource, dbSchema);
+            }
         } catch (NamingException | ClassCastException ex) {
             LOG.error("Cannot access JNDI resources.", ex);
         }
--- a/src/main/java/de/uapcore/lightpit/Functions.java	Sat May 09 14:58:41 2020 +0200
+++ b/src/main/java/de/uapcore/lightpit/Functions.java	Sat May 09 15:19:21 2020 +0200
@@ -28,11 +28,12 @@
  */
 package de.uapcore.lightpit;
 
-import java.util.Optional;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.util.Optional;
 
 /**
  * Contains common static functions.
@@ -64,8 +65,8 @@
     public static String fqn(String base, String name) {
         return base+"."+name;
     }
-    
-    public static String fqn(Class clazz, String name) {
+
+    public static String fqn(Class<?> clazz, String name) {
         return fqn(clazz.getName(), name);
     }
     
--- a/src/main/java/de/uapcore/lightpit/ModuleManager.java	Sat May 09 14:58:41 2020 +0200
+++ b/src/main/java/de/uapcore/lightpit/ModuleManager.java	Sat May 09 15:19:21 2020 +0200
@@ -84,7 +84,7 @@
     
     private Optional<LightPITModule> getModuleInfo(Registration reg) {
         try {
-            final Class scclass = Class.forName(reg.getClassName());
+            final Class<?> scclass = Class.forName(reg.getClassName());
             
             final boolean lpservlet = AbstractLightPITServlet.class.isAssignableFrom(scclass);
             final boolean lpmodule = scclass.isAnnotationPresent(LightPITModule.class);
@@ -103,8 +103,7 @@
             }
             
             if (lpservlet && lpmodule) {
-                final Class<? extends AbstractLightPITServlet> clazz = scclass;
-                final LightPITModule moduleInfo = clazz.getAnnotation(LightPITModule.class);
+                final LightPITModule moduleInfo = scclass.getAnnotation(LightPITModule.class);
                 return Optional.of(moduleInfo);
             } else {
                 return Optional.empty();
--- a/src/main/java/de/uapcore/lightpit/dao/CoreDAOFactory.java	Sat May 09 14:58:41 2020 +0200
+++ b/src/main/java/de/uapcore/lightpit/dao/CoreDAOFactory.java	Sat May 09 15:19:21 2020 +0200
@@ -43,8 +43,7 @@
             case Postgres:
                 return moduleDao;
             default:
-                assert (false);
-                return null;
+                throw new AssertionError("Switch was not exhaustive.");
         }
     }
 }
--- a/src/main/java/de/uapcore/lightpit/dao/ModuleDao.java	Sat May 09 14:58:41 2020 +0200
+++ b/src/main/java/de/uapcore/lightpit/dao/ModuleDao.java	Sat May 09 15:19:21 2020 +0200
@@ -44,7 +44,7 @@
      *
      * @param result the database result set
      * @param mod    the POJO
-     * @throws SQLException
+     * @throws SQLException on any kind of SQL errors
      */
     protected void mapColumns(ResultSet result, Module mod) throws SQLException {
         mod.setModID(result.getInt("modid"));
@@ -52,19 +52,19 @@
         mod.setVisible(result.getBoolean("visible"));
         mod.setPriority(result.getInt("priority"));
     }
-            
-    
+
+
     /**
      * Must return a prepared statement for a single object query with the specified properties.
-     * 
+     *
      * <ul>
      * <li>Parameter 1: classname</li>
      * <li>Result field 1: visible</li>
      * </ul>
-     * 
+     *
      * @param conn the connection to use
      * @return the prepared statement
-     * @throws SQLException 
+     * @throws SQLException on any kind of SQL errors
      */
     protected PreparedStatement moduleCheckStatement(Connection conn) throws SQLException {
         return conn.prepareStatement("SELECT visible FROM lpitcore_module WHERE classname = ?");
@@ -81,7 +81,7 @@
      *
      * @param conn the connection to use
      * @return the prepared statement
-     * @throws SQLException
+     * @throws SQLException on any kind of SQL errors
      */
     protected PreparedStatement moduleInsertStatement(Connection conn) throws SQLException {
         return conn.prepareStatement("INSERT INTO lpitcore_module (classname, visible, priority) VALUES (?, ?, ?)");
@@ -89,13 +89,13 @@
     
     /**
      * Synchronizes a set of registered module classes with the database.
-     * 
+     *
      * Inserts module classes which are not known to the database and sets them to be visible by default.
      * Module classes known to the database, which are not in the given set, are ignored.
-     * 
+     *
      * @param conn the connection to use
      * @param moduleSet the module set to synchronize
-     * @throws SQLException
+     * @throws SQLException on any kind of SQL errors
      */
     public final void syncRegisteredModuleClasses(Connection conn, Set<Map.Entry<String, LightPITModule>> moduleSet) throws SQLException {
                 
@@ -121,12 +121,12 @@
 
     /**
      * Returns a list of all modules known by the database.
-     * 
+     *
      * Keep in mind, that system modules are never known to the database.
-     * 
+     *
      * @param conn the connection to use
      * @return a list of all modules known by the database
-     * @throws SQLException 
+     * @throws SQLException on any kind of SQL errors
      */
     public List<Module> listAll(Connection conn) throws SQLException {
         List<Module> list = new ArrayList<>();
--- a/src/main/java/de/uapcore/lightpit/dao/UserDao.java	Sat May 09 14:58:41 2020 +0200
+++ b/src/main/java/de/uapcore/lightpit/dao/UserDao.java	Sat May 09 15:19:21 2020 +0200
@@ -36,7 +36,6 @@
 import java.sql.Statement;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Optional;
 
 public class UserDao {
 
@@ -45,23 +44,23 @@
      *
      * @param result the database result set
      * @param user   the POJO
-     * @throws SQLException
+     * @throws SQLException on any kind of SQL errors
      */
     protected void mapColumns(ResultSet result, User user) throws SQLException {
         user.setUserID(result.getInt("userid"));
         user.setUsername(result.getString("username"));
-        user.setGivenname(Optional.ofNullable(result.getString("givenname")));
-        user.setLastname(Optional.ofNullable(result.getString("lastname"))); 
+        user.setGivenname(result.getString("givenname"));
+        user.setLastname(result.getString("lastname"));
     }
 
     /**
      * Returns a list of all users ordered by their username.
-     * 
+     * <p>
      * Does not return reserved system users with negative user IDs.
-     * 
+     *
      * @param conn the connection to use
      * @return a list of all users
-     * @throws SQLException 
+     * @throws SQLException on any kind of SQL errors
      */
     public List<User> listAll(Connection conn) throws SQLException {
         List<User> list = new ArrayList<>();
--- a/src/main/java/de/uapcore/lightpit/entities/User.java	Sat May 09 14:58:41 2020 +0200
+++ b/src/main/java/de/uapcore/lightpit/entities/User.java	Sat May 09 15:19:21 2020 +0200
@@ -1,8 +1,8 @@
 /*
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
- * 
+ *
  * Copyright 2018 Mike Becker. All rights reserved.
- * 
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are met:
  *
@@ -24,20 +24,18 @@
  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  * POSSIBILITY OF SUCH DAMAGE.
- * 
+ *
  */
 package de.uapcore.lightpit.entities;
 
-import java.util.Optional;
+public final class User {
 
-public final class User {
-    
     public static final int ANONYMOUS_USERID = -1;
-    
+
     private int userID;
     private String username;
-    private Optional<String> givenname;
-    private Optional<String> lastname;
+    private String givenname;
+    private String lastname;
 
     public int getUserID() {
         return userID;
@@ -55,19 +53,19 @@
         this.username = username;
     }
 
-    public Optional<String> getGivenname() {
+    public String getGivenname() {
         return givenname;
     }
 
-    public void setGivenname(Optional<String> givenname) {
+    public void setGivenname(String givenname) {
         this.givenname = givenname;
     }
 
-    public Optional<String> getLastname() {
+    public String getLastname() {
         return lastname;
     }
 
-    public void setLastname(Optional<String> lastname) {
+    public void setLastname(String lastname) {
         this.lastname = lastname;
     }
 
@@ -88,5 +86,5 @@
         } else {
             return this.userID == ((User) obj).userID;
         }
-    }    
+    }
 }

mercurial