diff --git a/.gitignore b/.gitignore index 50b2ed416..40ee6833d 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,6 @@ bin/ *.ipr *.iws *.db + +*.swp +*.log diff --git a/alitheia/core/pom.xml b/alitheia/core/pom.xml index 4203d2dda..e96d8fd67 100644 --- a/alitheia/core/pom.xml +++ b/alitheia/core/pom.xml @@ -1,202 +1,198 @@ - + - - alitheia - eu.sqooss - 0.95-SNAPSHOT - + + alitheia + eu.sqooss + 0.95-SNAPSHOT + - 4.0.0 - eu.sqooss.alitheia - core - Alitheia Core + 4.0.0 + eu.sqooss.alitheia + core + Alitheia Core - bundle + bundle - 0.95-SNAPSHOT - - - - - org.apache.felix - maven-bundle-plugin - 2.2.0 - true - - - - *;scope=compile|runtime;artifactId=!core|org.osgi.core|org.osgi.compendium|servlet-api|junit - - - eu.sqooss.core, eu.sqooss.service.*, - com.mws.squal.service.* - - - com.mysql.jdbc;resolution:=optional, org.h2;resolution:=optional, - javassist.util, javassist.util.proxy, - org.hibernate, org.hibernate.cfg, org.hibernate.classic, org.hibernate.exception, - org.hibernate.proxy, org.hibernate.type, org.hibernate.connection, - org.hibernate.cache, org.hsqldb;resolution:=optional, - com.sun.source.*;resolution:=optional, *;resolution:=optional - - eu.sqooss.core.CoreActivator - eu.sqooss.alitheia.core - 1.0 - Athens University Of Economics and Business - The Alitheia Core Platform - org.hibernate.core, org.apache.velocity - - - - - + 0.95-SNAPSHOT + + + + + org.apache.felix + maven-bundle-plugin + 2.2.0 + true + + + + *;scope=compile|runtime;artifactId=!core|org.osgi.core|org.osgi.compendium|servlet-api|junit + + + eu.sqooss.core, eu.sqooss.service.*, + com.mws.squal.service.* + + + com.mysql.jdbc;resolution:=optional, org.h2;resolution:=optional, + javassist.util, javassist.util.proxy, + org.hibernate, org.hibernate.cfg, org.hibernate.classic, + org.hibernate.exception, + org.hibernate.proxy, org.hibernate.type, org.hibernate.connection, + org.hibernate.cache, org.hsqldb;resolution:=optional, + com.sun.source.*;resolution:=optional, *;resolution:=optional + + eu.sqooss.core.CoreActivator + eu.sqooss.alitheia.core + 1.0 + Athens University Of Economics and Business + The Alitheia Core Platform + org.hibernate.core, org.apache.velocity + + + + + - - - org.osgi - org.osgi.core - 4.2.0 - true - - - org.osgi - org.osgi.compendium - 4.2.0 - true - - - org.apache.velocity - velocity - 1.6 - - - dom4j - dom4j - 1.6 - - - javax.mail - mail - 1.4 - - - commons-codec - commons-codec - 1.3 - - - log4j - log4j - 1.2.16 - - - junit - junit - 4.6 - provided - - - org.powermock - powermock-module-junit4 - 1.5.2 - test - - - org.powermock - powermock-api-mockito - 1.5.2 - test - - - org.hibernate - hibernate-annotations - 3.5.1-Final - - - javax.servlet - servlet-api - 2.5 - - - org.jboss.resteasy - resteasy-jaxrs - 1.2.1.GA - - - org.jboss.resteasy - resteasy-jaxb-provider - 1.2.GA - - - org.jboss.resteasy - resteasy-jettison-provider - 1.2.GA - - - org.scannotation - scannotation - 1.0.2 - - - javax.ws.rs - jsr311-api - 1.1.1 - - - org.slf4j - slf4j-log4j12 - 1.6.1 - jar - compile - - - org.codehaus.jettison - jettison - 1.2 - compile - - - org.mockito - mockito-core - 1.9.5 - test - - - - - - tools.jar - - - java.vendor - Sun Microsystems Inc. - - - - - com.sun - tools - 1.6 - system - true - ${java.home}/../lib/tools.jar - - - - + + + org.osgi + org.osgi.core + 4.2.0 + true + + + org.osgi + org.osgi.compendium + 4.2.0 + true + + + org.apache.velocity + velocity + 1.6 + + + dom4j + dom4j + 1.6 + + + javax.mail + mail + 1.4 + + + commons-codec + commons-codec + 1.3 + + + log4j + log4j + 1.2.16 + + + junit + junit + 4.6 + provided + + + org.powermock + powermock-module-junit4 + 1.5.2 + test + + + org.powermock + powermock-api-mockito + 1.5.2 + test + + + org.hibernate + hibernate-annotations + 3.5.1-Final + + + javax.servlet + servlet-api + 2.5 + + + org.jboss.resteasy + resteasy-jaxrs + 1.2.1.GA + + + org.jboss.resteasy + resteasy-jaxb-provider + 1.2.GA + + + org.jboss.resteasy + resteasy-jettison-provider + 1.2.GA + + + org.scannotation + scannotation + 1.0.2 + + + javax.ws.rs + jsr311-api + 1.1.1 + + + org.slf4j + slf4j-log4j12 + 1.6.1 + jar + compile + + + org.codehaus.jettison + jettison + 1.2 + compile + + + org.mockito + mockito-core + 1.9.5 + test + + + org.jsoup + jsoup + 1.8.1 + + + + + + tools.jar + + + java.vendor + Sun Microsystems Inc. + + + + + com.sun + tools + 1.6 + system + true + ${java.home}/../lib/tools.jar + + + + diff --git a/alitheia/core/src/main/java/eu/sqooss/core/AlitheiaCore.java b/alitheia/core/src/main/java/eu/sqooss/core/AlitheiaCore.java index 63610d55f..3e7f16fd8 100644 --- a/alitheia/core/src/main/java/eu/sqooss/core/AlitheiaCore.java +++ b/alitheia/core/src/main/java/eu/sqooss/core/AlitheiaCore.java @@ -162,6 +162,10 @@ public static AlitheiaCore testInstance() { return instance; } + public static void setTestInstance(AlitheiaCore instance) { + AlitheiaCore.instance = instance; + } + /** * Register an external implementation of an AlitheiaCore service. It * will override any internally defined implementation. diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/cluster/ClusterNodeServiceImpl.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/cluster/ClusterNodeServiceImpl.java index 5f8f77478..9da15e13b 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/cluster/ClusterNodeServiceImpl.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/cluster/ClusterNodeServiceImpl.java @@ -55,6 +55,7 @@ import eu.sqooss.service.cluster.ClusterNodeService; import eu.sqooss.service.db.ClusterNode; import eu.sqooss.service.db.DBService; +import eu.sqooss.service.db.Project; import eu.sqooss.service.db.StoredProject; import eu.sqooss.service.logging.Logger; import eu.sqooss.service.updater.UpdaterService; @@ -347,10 +348,10 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) bcontent = new StringBuilder(); dbs.startDBSession(); - Set assignments = ClusterNode.thisNode().getProjects(); + Set assignments = ClusterNode.thisNode().getProjects(); if ((assignments!=null) && (assignments.size()>0) ){ bcontent.append("\n"); - for (StoredProject sp : assignments) { + for (Project sp : assignments) { bcontent.append(" boolean addRecords(List records) { + public boolean addRecords(List records) { if( !checkSession() ) return false; - DAObject lastRecord = null; + IDAObject lastRecord = null; try { Session s = sessionFactory.getCurrentSession(); - for (DAObject record : records) { + for (IDAObject record : records) { lastRecord = record; s.save(record); } @@ -723,7 +724,7 @@ public boolean isDBSessionActive() { } @SuppressWarnings("unchecked") - public T attachObjectToDBSession(T obj) { + public T attachObjectToDBSession(T obj) { if( !checkSession() ) return null; diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/fds/FDSServiceImpl.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/fds/FDSServiceImpl.java index e28fb7ea3..737b05b6e 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/fds/FDSServiceImpl.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/fds/FDSServiceImpl.java @@ -36,20 +36,17 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Random; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; -import eu.sqooss.service.util.FileUtils; -import org.apache.commons.codec.binary.Hex; import org.osgi.framework.BundleContext; import eu.sqooss.core.AlitheiaCore; import eu.sqooss.service.db.DBService; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.db.StoredProject; @@ -67,6 +64,7 @@ import eu.sqooss.service.tds.Revision; import eu.sqooss.service.tds.SCMAccessor; import eu.sqooss.service.tds.TDSService; +import eu.sqooss.service.util.FileUtils; /** {@inheritDoc} */ public class FDSServiceImpl implements FDSService, Runnable { @@ -187,7 +185,7 @@ private OnDiskCheckout createCheckout(SCMAccessor scm, ProjectVersion pv, String * @return The SCM revision for the project or null if the project file is * deleted or otherwise unavailable. */ - private Revision projectFileRevision(ProjectFile pf) { + private Revision projectFileRevision(IProjectFile pf) { // Make sure that the file exists in the specified project version String fileStatus = pf.getState().toString(); if (PathChangeType.valueOf(fileStatus) == PathChangeType.DELETED) { @@ -246,7 +244,7 @@ private File projectFileLocal(ProjectFile pf, Revision r) { * The project file to look up. * @return The accessor or null on failure. */ - private SCMAccessor projectFileAccessor(ProjectFile pf) { + private SCMAccessor projectFileAccessor(IProjectFile pf) { // Retrieve the project ID long projectId = pf.getProjectVersion().getProject().getId(); @@ -465,7 +463,7 @@ public synchronized File getFile(ProjectFile pf) { } /** {@inheritDoc} */ - public InputStream getFileContents(ProjectFile pf) { + public InputStream getFileContents(IProjectFile pf) { Revision projectRevision = projectFileRevision(pf); if (projectRevision == null) { diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/fds/InMemoryCheckoutImpl.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/fds/InMemoryCheckoutImpl.java index 1b72274a0..5569e04cd 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/fds/InMemoryCheckoutImpl.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/fds/InMemoryCheckoutImpl.java @@ -36,6 +36,7 @@ import java.util.List; import java.util.regex.Pattern; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.fds.InMemoryCheckout; @@ -64,9 +65,9 @@ class InMemoryCheckoutImpl implements InMemoryCheckout { protected void createCheckout() { root = new InMemoryDirectory(this); - List projectFiles = revision.getFiles(); + List projectFiles = revision.getFiles(); if (projectFiles != null && projectFiles.size() != 0) { - for (ProjectFile f : projectFiles) { + for (IProjectFile f : projectFiles) { if (pattern.matcher(f.getFileName()).matches()) { if (!f.getIsDirectory()) { root.createSubDirectory(f.getDir().getPath()).addFile(f.getName()); diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/metricactivator/MetricActivatorImpl.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/metricactivator/MetricActivatorImpl.java index 4487e5202..9299d8bb7 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/metricactivator/MetricActivatorImpl.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/metricactivator/MetricActivatorImpl.java @@ -33,15 +33,26 @@ package eu.sqooss.impl.service.metricactivator; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import java.util.concurrent.atomic.AtomicLong; -import eu.sqooss.service.abstractmetric.InvocationOrder; import org.osgi.framework.BundleContext; import eu.sqooss.core.AlitheiaCore; import eu.sqooss.service.abstractmetric.AbstractMetric; import eu.sqooss.service.abstractmetric.AlitheiaPlugin; +import eu.sqooss.service.abstractmetric.InvocationOrder; import eu.sqooss.service.abstractmetric.SchedulerHints; import eu.sqooss.service.cluster.ClusterNodeActionException; import eu.sqooss.service.cluster.ClusterNodeService; @@ -51,6 +62,7 @@ import eu.sqooss.service.db.DBService; import eu.sqooss.service.db.EncapsulationUnit; import eu.sqooss.service.db.ExecutionUnit; +import eu.sqooss.service.db.IDAObject; import eu.sqooss.service.db.MailMessage; import eu.sqooss.service.db.MailingList; import eu.sqooss.service.db.MailingListThread; @@ -89,8 +101,8 @@ public class MetricActivatorImpl implements MetricActivator { public MetricActivatorImpl() { } @Override - public void runMetric(T resource, AlitheiaPlugin ap) { - Class activator = resource.getClass(); + public void runMetric(T resource, AlitheiaPlugin ap) { + Class activator = resource.getClass(); Job j = new MetricActivatorJob((AbstractMetric)ap, resource.getId(), logger, metricTypesToActivators.get(activator), priority.incrementAndGet(), diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/tds/TDSServiceImpl.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/tds/TDSServiceImpl.java index 9635be25d..70a32a002 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/tds/TDSServiceImpl.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/tds/TDSServiceImpl.java @@ -42,6 +42,7 @@ import eu.sqooss.core.AlitheiaCoreService; import eu.sqooss.service.db.ClusterNode; import eu.sqooss.service.db.DBService; +import eu.sqooss.service.db.Project; import eu.sqooss.service.db.StoredProject; import eu.sqooss.service.logging.Logger; import eu.sqooss.service.tds.DataAccessor; @@ -148,7 +149,7 @@ private void stuffer() { if (db != null && db.startDBSession()) { - for (StoredProject p : ClusterNode.thisNode().getProjects()) { + for (Project p : ClusterNode.thisNode().getProjects()) { addAccessor(p.getId(), p.getName(), p.getBtsUrl(), p.getMailUrl(), p.getScmUrl()); } diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/AbstractView.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/AbstractView.java index f79c95031..bb0b0fa2d 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/AbstractView.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/AbstractView.java @@ -33,7 +33,6 @@ package eu.sqooss.impl.service.webadmin; -import java.net.URI; import java.util.Enumeration; import java.util.Locale; import java.util.MissingResourceException; @@ -43,6 +42,7 @@ import javax.servlet.http.HttpServletRequest; import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; @@ -58,485 +58,503 @@ import eu.sqooss.service.updater.UpdaterService; public abstract class AbstractView { - // Core components - protected static AlitheiaCore sobjCore = null; - protected static ServiceReference srefCore = null; - - // Critical logging components - protected static LogManager sobjLogManager = null; - protected static Logger sobjLogger = null; - - // Service components - protected static DBService sobjDB = null; - protected static MetricActivator compMA = null; - protected static PluginAdmin sobjPA = null; - protected static Scheduler sobjSched = null; - protected static TDSService sobjTDS = null; - protected static UpdaterService sobjUpdater = null; - protected static ClusterNodeService sobjClusterNode = null; - protected static SecurityManager sobjSecurity = null; - - // Velocity stuff - protected static VelocityContext vc = null; - protected BundleContext bc = null; - - // Names of the various resource files - private static String RES_LABELS_FILE = "ResourceLabels"; - private static String RES_ERRORS_FILE = "ResourceErrors"; - private static String RES_MESSAGES_FILE = "ResourceMessages"; - - // Resource bundles - private static ResourceBundle resLbl = null; - private static ResourceBundle resMsg = null; - private static ResourceBundle resErr = null; - - // Debug flag - global for all views - protected static boolean DEBUG = false; - - // Some constants that are used internally - private static String NULL_PARAM_NAME = "Undefined parameter name!"; - - /** - * Instantiates a new AbstractView object. - * - * @param bundlecontext the parent bundle's context - * @param vc the Velocity instance's context - */ - public AbstractView(BundleContext bundlecontext, VelocityContext vc) { - // Keep the Velocity context instance - this.vc = vc; - this.bc = bundlecontext; - - sobjCore = AlitheiaCore.getInstance(); - - // Retrieve the instances of the core components - if (sobjCore != null) { - //Get the log manager's instance - sobjLogManager = sobjCore.getLogManager(); - if (sobjLogManager != null) { - // Instantiate a dedicated logger - sobjLogger = sobjLogManager.createLogger( - Logger.NAME_SQOOSS_WEBADMIN); - } - - // Get the database component's instance - sobjDB = sobjCore.getDBService(); - if ((sobjDB == null) && (sobjLogger != null)) - sobjLogger.debug("Could not get the database component's instance."); - - // Get the plug-in admin's instance - sobjPA = sobjCore.getPluginAdmin(); - if ((sobjPA == null) && (sobjLogger != null)) - sobjLogger.debug("Could not get the plug-in admin's instance."); - - // Get the scheduler's instance - sobjSched = sobjCore.getScheduler(); - if ((sobjSched == null) && (sobjLogger != null)) - sobjLogger.debug("Could not get the scheduler's instance."); - - // Get the metric activator's instance - compMA = sobjCore.getMetricActivator(); - if ((compMA == null) && (sobjLogger != null)) - sobjLogger.debug("Could not get the metric activator's instance."); - - // Get the TDS component's instance - sobjTDS = sobjCore.getTDSService(); - if ((sobjTDS == null) && (sobjLogger != null)) - sobjLogger.debug("Could not get the TDS component's instance."); - - // Get the updater component's instance - sobjUpdater = sobjCore.getUpdater(); - if ((sobjUpdater == null) && (sobjLogger != null)) - sobjLogger.debug("Could not get the updater component's instance."); - - // Get the ClusterNodeService component's instance - sobjClusterNode = sobjCore.getClusterNodeService(); - if ((sobjClusterNode != null) && (sobjLogger != null)) - sobjLogger.debug("Got the ClusterNodeService component's instance."); - - - // Get the security manager's instance - sobjSecurity = sobjCore.getSecurityManager(); - if ((sobjSecurity == null) && (sobjLogger != null)) - sobjLogger.debug("Could not get the security manager's instance."); - } - } - - /** - * Initializes the various resource bundle with the specified locale. - * - * @param locale the user's locale - */ - public static void initResources (Locale locale) { - resLbl = getLabelsBundle(locale); - resErr = getErrorsBundle(locale); - resMsg = getMessagesBundle(locale); - } - - /** - * Retrieves the value of the given resource property from the - * resource bundle that stores all label strings. - * - * @param name the name of the resource property - * - * @return The property's value, when that property can be found in the - * corresponding resource bundle, OR the provided property name's - * parameter, when such property is missing. - */ - public static String getLbl (String name) { - if (resLbl != null) { - try { - return resLbl.getString(name); - } - catch (NullPointerException ex) { - return NULL_PARAM_NAME; - } - catch (MissingResourceException ex) { - return name; - } - } - return name; - } - - /** - * Retrieves the value of the given resource property from the - * resource bundle that stores all error strings. - * - * @param name the name of the resource property - * - * @return The property's value, when that property can be found in the - * corresponding resource bundle, OR the provided property name's - * parameter, when such property is missing. - */ - public static String getErr (String name) { - if (resErr != null) { - try { - return resErr.getString(name); - } - catch (NullPointerException ex) { - return NULL_PARAM_NAME; - } - catch (MissingResourceException ex) { - return name; - } - } - return name; - } - - /** - * Retrieves the value of the given resource property from the - * resource bundle that stores all message strings. - * - * @param name the name of the resource property - * - * @return The property's value, when that property can be found in the - * corresponding resource bundle, OR the provided property name's - * parameter, when such property is missing. - */ - public static String getMsg (String name) { - if (resMsg != null) { - try { - return resMsg.getString(name); - } - catch (NullPointerException ex) { - return NULL_PARAM_NAME; - } - catch (MissingResourceException ex) { - return name; - } - } - return name; - } - - // TODO: Move this method's logic in the initResources() once all views - // are using the new methods. + // Core components + protected static AlitheiaCore sobjCore = null; + protected static ServiceReference srefCore = null; + + // Critical logging components + protected static LogManager sobjLogManager = null; + protected static Logger sobjLogger = null; + + // Service components + protected static DBService sobjDB = null; + protected static MetricActivator compMA = null; + protected static PluginAdmin sobjPA = null; + protected static Scheduler sobjSched = null; + protected static TDSService sobjTDS = null; + protected static UpdaterService sobjUpdater = null; + protected static ClusterNodeService sobjClusterNode = null; + protected static SecurityManager sobjSecurity = null; + + // Velocity stuff + protected static VelocityContext vc = null; + protected static VelocityEngine ve = null; + protected BundleContext bc = null; + + // Names of the various resource files + private static String RES_LABELS_FILE = "ResourceLabels"; + private static String RES_ERRORS_FILE = "ResourceErrors"; + private static String RES_MESSAGES_FILE = "ResourceMessages"; + + // Resource bundles + private static ResourceBundle resLbl = null; + private static ResourceBundle resMsg = null; + private static ResourceBundle resErr = null; + + // Debug flag - global for all views + protected static boolean DEBUG = false; + + // Some constants that are used internally + private static String NULL_PARAM_NAME = "Undefined parameter name!"; + + /** + * Instantiates a new AbstractView object. + * + * @param bundlecontext + * the parent bundle's context + * @param vc + * the Velocity instance's context + */ + public AbstractView(BundleContext bundlecontext, VelocityContext vc, + VelocityEngine ve) { + // Keep the Velocity context instance + AbstractView.vc = vc; + AbstractView.ve = ve; + this.bc = bundlecontext; + + sobjCore = AlitheiaCore.getInstance(); + + // Retrieve the instances of the core components + if (sobjCore != null) { + // Get the log manager's instance + sobjLogManager = sobjCore.getLogManager(); + if (sobjLogManager != null) { + // Instantiate a dedicated logger + sobjLogger = sobjLogManager + .createLogger(Logger.NAME_SQOOSS_WEBADMIN); + } + + // Get the database component's instance + sobjDB = sobjCore.getDBService(); + if ((sobjDB == null) && (sobjLogger != null)) + sobjLogger + .debug("Could not get the database component's instance."); + + // Get the plug-in admin's instance + sobjPA = sobjCore.getPluginAdmin(); + if ((sobjPA == null) && (sobjLogger != null)) + sobjLogger.debug("Could not get the plug-in admin's instance."); + + // Get the scheduler's instance + sobjSched = sobjCore.getScheduler(); + if ((sobjSched == null) && (sobjLogger != null)) + sobjLogger.debug("Could not get the scheduler's instance."); + + // Get the metric activator's instance + compMA = sobjCore.getMetricActivator(); + if ((compMA == null) && (sobjLogger != null)) + sobjLogger + .debug("Could not get the metric activator's instance."); + + // Get the TDS component's instance + sobjTDS = sobjCore.getTDSService(); + if ((sobjTDS == null) && (sobjLogger != null)) + sobjLogger.debug("Could not get the TDS component's instance."); + + // Get the updater component's instance + sobjUpdater = sobjCore.getUpdater(); + if ((sobjUpdater == null) && (sobjLogger != null)) + sobjLogger + .debug("Could not get the updater component's instance."); + + // Get the ClusterNodeService component's instance + sobjClusterNode = sobjCore.getClusterNodeService(); + if ((sobjClusterNode != null) && (sobjLogger != null)) + sobjLogger + .debug("Got the ClusterNodeService component's instance."); + + // Get the security manager's instance + sobjSecurity = sobjCore.getSecurityManager(); + if ((sobjSecurity == null) && (sobjLogger != null)) + sobjLogger + .debug("Could not get the security manager's instance."); + } + } + + /** + * Initializes the various resource bundle with the specified locale. + * + * @param locale + * the user's locale + */ + public static void initResources(Locale locale) { + resLbl = getLabelsBundle(locale); + resErr = getErrorsBundle(locale); + resMsg = getMessagesBundle(locale); + } + + /** + * Retrieves the value of the given resource property from the resource + * bundle that stores all label strings. + * + * @param name + * the name of the resource property + * + * @return The property's value, when that property can be found in the + * corresponding resource bundle, OR the provided property name's + * parameter, when such property is missing. + */ + public static String getLbl(String name) { + if (resLbl != null) { + try { + return resLbl.getString(name); + } catch (NullPointerException ex) { + return NULL_PARAM_NAME; + } catch (MissingResourceException ex) { + return name; + } + } + return name; + } + + /** + * Retrieves the value of the given resource property from the resource + * bundle that stores all error strings. + * + * @param name + * the name of the resource property + * + * @return The property's value, when that property can be found in the + * corresponding resource bundle, OR the provided property name's + * parameter, when such property is missing. + */ + public static String getErr(String name) { + if (resErr != null) { + try { + return resErr.getString(name); + } catch (NullPointerException ex) { + return NULL_PARAM_NAME; + } catch (MissingResourceException ex) { + return name; + } + } + return name; + } + + /** + * Retrieves the value of the given resource property from the resource + * bundle that stores all message strings. + * + * @param name + * the name of the resource property + * + * @return The property's value, when that property can be found in the + * corresponding resource bundle, OR the provided property name's + * parameter, when such property is missing. + */ + public static String getMsg(String name) { + if (resMsg != null) { + try { + return resMsg.getString(name); + } catch (NullPointerException ex) { + return NULL_PARAM_NAME; + } catch (MissingResourceException ex) { + return name; + } + } + return name; + } + + // TODO: Move this method's logic in the initResources() once all views + // are using the new methods. public static ResourceBundle getLabelsBundle(Locale locale) { locale = Locale.ENGLISH; return ResourceBundle.getBundle(RES_LABELS_FILE, locale); } - // TODO: Move this method's logic in the initResources() once all views - // are using the new methods. + // TODO: Move this method's logic in the initResources() once all views + // are using the new methods. public static ResourceBundle getErrorsBundle(Locale locale) { locale = Locale.ENGLISH; return ResourceBundle.getBundle(RES_ERRORS_FILE, locale); } - // TODO: Move this method's logic in the initResources() once all views - // are using the new methods. - public static ResourceBundle getMessagesBundle (Locale locale) { - locale = Locale.ENGLISH; - return ResourceBundle.getBundle(RES_MESSAGES_FILE, locale); - } - - /** - * Construct an HTML-based list of all parameters and their values, that - * are contained in the given servlet's request object. Useful for debug - * of the views functionality. - * - * @param request the servlet's request object - * - * @return The list of request parameters. - */ - protected static String debugRequest (HttpServletRequest request) { - StringBuilder b = new StringBuilder(); - Enumeration e = request.getParameterNames(); - while (e.hasMoreElements()) { - String key = (String) e.nextElement(); - b.append(key + "=" + request.getParameter(key) + "
\n"); - } - return b.toString(); - } - - /** - * Generates a string that contains a 2*num spaces. - *
- * Used for indentation of the HTML content that is generated by the - * various views. - * - * @param num the indentation depth - * - * @return The indentation string. - */ - protected static String sp (long num) { - StringBuilder b = new StringBuilder(); - for (long i = 0; i < num; i++) - b.append(" "); - return b.toString(); - } - - /** - * Generates a simple table row (with two columns) that represents - * a single text input element with a title line. The title line will be - * stored in the first cell, while the text input will be placed in the - * second cell. - *
- * This method is used by the various views for generating simple input - * screens. - * - * @param title the title that will preceed the input element - * @param parName the input element's name - * @param parValue the input element's initial value - * @param in the indentation depth - * - * @return The string that contains the table's row, or an empty string - * upon invalid (null) name of the input element. - */ - protected static String normalInputRow ( - String title, String parName, String parValue, long in) { - // Stores the assembled HTML content - StringBuilder b = new StringBuilder("\n"); - - // Create the input field's row - if (parName != null) { - b.append(sp(in++) + "\n"); - b.append(sp(in) + "" - + "" + ((title != null) ? title : "") + "" - + "\n"); - b.append(sp(in++) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - } - - // Return the generated content - return b.toString(); - } - - /** - * Generates a simple table row (with two columns) that represents - * a single text message with a title line. The title line will be - * stored in the first cell, while the message will be placed in the - * second cell. - *
- * This method is used by the various views for generating simple info - * screens. - * - * @param title the title that will preceed the text message - * @param value the text message - * @param in the indentation depth - * - * @return The string that contains the table's row. - */ - protected static String normalInfoRow ( - String title, String value, long in) { - // Stores the assembled HTML content - StringBuilder b = new StringBuilder("\n"); - - // Create the info row - b.append(sp(in++) + "\n"); - b.append(sp(in) + "" - + "" + ((title != null) ? title : "") + "" - + "\n"); - b.append(sp(in++) + "\n"); - b.append(sp(in) + ((value != null) ? value : "") + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - - // Return the generated content - return b.toString(); - } - - /** - * Produces an HTML fieldset tag which encapsulates the HTML - * content that is stored in the given StringBuilder object. - * - * @param name the fieldset legend's name - * @param css the CSS class name to use - * @param content the HTML content - * @param in the indentation depth - * - * @return The HTML presentation. - */ - protected static String normalFieldset ( - String name, - String css, - StringBuilder content, - long in) { - if ((content != null) && (content.toString().length() > 0)) { - return (sp(in) + "\n" - + sp(++in) + "" - + ((name != null) ? name : "NONAME") - + "\n" - + content.toString() - + sp(--in) + "\n"); - } - return (""); - } - - // TODO: Remove this method, since it is not I18n compatible. - protected static String errorFieldset (StringBuilder errors, long in) { - return normalFieldset("Errors", null, errors, in); - } - - /** - * Creates a Long object from the content of the given - * String object, while handling internally any thrown - * exception. - * - * @param value the String value - * - * @return The Long value. - */ - protected static Long fromString (String value) { - try { - return (new Long(value)); - } - catch (NumberFormatException ex){ - return null; - } - } - - /** - * Method for validation of a simple name-based properties. - *
- * The validation will be successful on values that contain alphanumeric - * characters, plus the space character (as long as it does not appear - * as first or last character in the sequence). - * - * @param text the property value - * - * @return true upon successful validation, - * or false otherwise. - */ - protected static boolean checkName (String text) { - if (text == null) return false; - - // Check for head or foot occurrence of deprecated signs - Pattern p = Pattern.compile("^[ ]+.*"); - if (p.matcher(text).matches()) return false; - p = Pattern.compile(".*[ ]+$"); - if (p.matcher(text).matches()) return false; - // Check the name - p = Pattern.compile("[\\p{Alnum} ]+"); - return p.matcher(text).matches(); - } - - /** - * Method for validation of a project name-based properties. - *
- * The validation will be successful on values that contain alphanumeric - * characters, plus the space and the underscore characters - * (as long as they do not appear as first or last character in the - * sequence). - * - * @param text the property value - * - * @return true upon successful validation, - * or false otherwise. - */ - protected static boolean checkProjectName (String text) { - if (text == null) return false; - - // Check for head or foot occurrence of deprecated signs - Pattern p = Pattern.compile("^[ _\\-]+.*"); - if (p.matcher(text).matches()) return false; - p = Pattern.compile(".*[ _\\-]+$"); - if (p.matcher(text).matches()) return false; - // Check the name - p = Pattern.compile("[\\p{Alnum}_\\- ]+"); - return p.matcher(text).matches(); - } - - /** - * Method for validation of properties that hold an email address. - *
- * The validation will be successful on values that satisfy the email - * address specification from RFC 2822. - *
- * Note: this methods tries to follow RFC 2822 as much as possible, - * but is not yet fully compatible with it. - * - * @param text the property value - * - * @return true upon successful validation, - * or false otherwise. - */ - protected static boolean checkEmail (String text) { - if (text == null) return false; - - // Check for adjacent dot signs - Pattern p = Pattern.compile("\\.\\."); - if (p.matcher(text).matches()) return false; - // Split the email into local and domain part - String parts[] = text.split("@"); - if (parts.length != 2) return false; - // Check for head or foot occurrence of dot signs - p = Pattern.compile("^[.].*"); - if (p.matcher(parts[0]).matches()) return false; - if (p.matcher(parts[1]).matches()) return false; - p = Pattern.compile(".*[.]$"); - if (p.matcher(parts[0]).matches()) return false; - if (p.matcher(parts[1]).matches()) return false; - // Local part's regular expression - Pattern l = Pattern.compile("^[\\p{Alnum}!#$%*/?|^{}`~&'+-=_.]+$"); - // Domain part's regular expression - Pattern d = Pattern.compile("^[\\p{Alnum}.-]+[.][\\p{Alpha}]{2,4}$"); - // Match both parts - return ((l.matcher(parts[0]).matches()) - && (d.matcher(parts[1]).matches())); - } - - /** - * Check if the provided URL is supported by the TDS data accessor - * plug-ins. - * @param url The URL to check - * @return True if the URL is supported, false otherwise or if the - * provided string is not a URL. - */ - protected static boolean checkTDSUrl (String url) { - return sobjTDS.isURLSupported(url); - } + // TODO: Move this method's logic in the initResources() once all views + // are using the new methods. + public static ResourceBundle getMessagesBundle(Locale locale) { + locale = Locale.ENGLISH; + return ResourceBundle.getBundle(RES_MESSAGES_FILE, locale); + } + + /** + * Construct an HTML-based list of all parameters and their values, that are + * contained in the given servlet's request object. Useful for debug of the + * views functionality. + * + * @param request + * the servlet's request object + * + * @return The list of request parameters. + */ + protected static String debugRequest(HttpServletRequest request) { + StringBuilder b = new StringBuilder(); + Enumeration e = request.getParameterNames(); + while (e.hasMoreElements()) { + String key = (String) e.nextElement(); + b.append(key + "=" + request.getParameter(key) + "
\n"); + } + return b.toString(); + } + + /** + * Generates a string that contains a 2*num spaces.
+ * Used for indentation of the HTML content that is generated by the + * various views. + * + * @param num + * the indentation depth + * + * @return The indentation string. + */ + protected static String sp(long num) { + StringBuilder b = new StringBuilder(); + for (long i = 0; i < num; i++) + b.append(" "); + return b.toString(); + } + + /** + * Generates a simple table row (with two columns) that represents a + * single text input element with a title line. The title line will be + * stored in the first cell, while the text input will be placed in the + * second cell.
+ * This method is used by the various views for generating simple input + * screens. + * + * @param title + * the title that will preceed the input element + * @param parName + * the input element's name + * @param parValue + * the input element's initial value + * @param in + * the indentation depth + * + * @return The string that contains the table's row, or an empty string upon + * invalid (null) name of the input element. + */ + protected static String normalInputRow(String title, String parName, + String parValue, long in) { + // Stores the assembled HTML content + StringBuilder b = new StringBuilder("\n"); + + + + // Create the input field's row + if (parName != null) { + b.append(sp(in++) + "\n"); + b.append(sp(in) + "" + "" + + ((title != null) ? title : "") + "" + "\n"); + b.append(sp(in++) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + b.append(sp(--in) + "\n"); + } + + // Return the generated content + return b.toString(); + } + + /** + * Generates a simple table row (with two columns) that represents a + * single text message with a title line. The title line will be stored in + * the first cell, while the message will be placed in the second cell.
+ * This method is used by the various views for generating simple info + * screens. + * + * @param title + * the title that will preceed the text message + * @param value + * the text message + * @param in + * the indentation depth + * + * @return The string that contains the table's row. + */ + protected static String normalInfoRow(String title, String value, long in) { + // Stores the assembled HTML content + StringBuilder b = new StringBuilder("\n"); + + // Create the info row + b.append(sp(in++) + "\n"); + b.append(sp(in) + "" + "" + + ((title != null) ? title : "") + "" + "\n"); + b.append(sp(in++) + "\n"); + b.append(sp(in) + ((value != null) ? value : "") + "\n"); + b.append(sp(--in) + "\n"); + b.append(sp(--in) + "\n"); + + // Return the generated content + return b.toString(); + } + + /** + * Produces an HTML fieldset tag which encapsulates the HTML content that is + * stored in the given StringBuilder object. + * + * @param name + * the fieldset legend's name + * @param css + * the CSS class name to use + * @param content + * the HTML content + * @param in + * the indentation depth + * + * @return The HTML presentation. + */ + protected static String normalFieldset(String name, String css, + StringBuilder content, long in) { + if ((content != null) && (content.toString().length() > 0)) { + return (sp(in) + "\n" + + sp(++in) + "" + + ((name != null) ? name : "NONAME") + "\n" + + content.toString() + sp(--in) + "\n"); + } + return (""); + } + + // TODO: Remove this method, since it is not I18n compatible. + protected static String errorFieldset(StringBuilder errors, long in) { + return normalFieldset("Errors", null, errors, in); + } + + /** + * Creates a Long object from the content of the given + * String object, while handling internally any thrown + * exception. + * + * @param value + * the String value + * + * @return The Long value. + */ + protected static Long fromString(String value) { + try { + return (new Long(value)); + } catch (NumberFormatException ex) { + return null; + } + } + + /** + * Method for validation of a simple name-based properties.
+ * The validation will be successful on values that contain alphanumeric + * characters, plus the space character (as long as it does not appear as + * first or last character in the sequence). + * + * @param text + * the property value + * + * @return true upon successful validation, or + * false otherwise. + */ + protected static boolean checkName(String text) { + if (text == null) + return false; + + // Check for head or foot occurrence of deprecated signs + Pattern p = Pattern.compile("^[ ]+.*"); + if (p.matcher(text).matches()) + return false; + p = Pattern.compile(".*[ ]+$"); + if (p.matcher(text).matches()) + return false; + // Check the name + p = Pattern.compile("[\\p{Alnum} ]+"); + return p.matcher(text).matches(); + } + + /** + * Method for validation of a project name-based properties.
+ * The validation will be successful on values that contain alphanumeric + * characters, plus the space and the underscore characters (as long as + * they do not appear as first or last character in the sequence). + * + * @param text + * the property value + * + * @return true upon successful validation, or + * false otherwise. + */ + protected static boolean checkProjectName(String text) { + if (text == null) + return false; + + // Check for head or foot occurrence of deprecated signs + Pattern p = Pattern.compile("^[ _\\-]+.*"); + if (p.matcher(text).matches()) + return false; + p = Pattern.compile(".*[ _\\-]+$"); + if (p.matcher(text).matches()) + return false; + // Check the name + p = Pattern.compile("[\\p{Alnum}_\\- ]+"); + return p.matcher(text).matches(); + } + + /** + * Method for validation of properties that hold an email address.
+ * The validation will be successful on values that satisfy the email + * address specification from RFC 2822.
+ * Note: this methods tries to follow RFC 2822 as much as possible, but + * is not yet fully compatible with it. + * + * @param text + * the property value + * + * @return true upon successful validation, or + * false otherwise. + */ + protected static boolean checkEmail(String text) { + if (text == null) + return false; + + // Check for adjacent dot signs + Pattern p = Pattern.compile("\\.\\."); + if (p.matcher(text).matches()) + return false; + // Split the email into local and domain part + String parts[] = text.split("@"); + if (parts.length != 2) + return false; + // Check for head or foot occurrence of dot signs + p = Pattern.compile("^[.].*"); + if (p.matcher(parts[0]).matches()) + return false; + if (p.matcher(parts[1]).matches()) + return false; + p = Pattern.compile(".*[.]$"); + if (p.matcher(parts[0]).matches()) + return false; + if (p.matcher(parts[1]).matches()) + return false; + // Local part's regular expression + Pattern l = Pattern.compile("^[\\p{Alnum}!#$%*/?|^{}`~&'+-=_.]+$"); + // Domain part's regular expression + Pattern d = Pattern.compile("^[\\p{Alnum}.-]+[.][\\p{Alpha}]{2,4}$"); + // Match both parts + return ((l.matcher(parts[0]).matches()) && (d.matcher(parts[1]) + .matches())); + } + + /** + * Check if the provided URL is supported by the TDS data accessor plug-ins. + * + * @param url + * The URL to check + * @return True if the URL is supported, false otherwise or if the provided + * string is not a URL. + */ + protected static boolean checkTDSUrl(String url) { + return sobjTDS.isURLSupported(url); + } } -//vi: ai nosi sw=4 ts=4 expandtab +// vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/AdminServlet.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/AdminServlet.java index bde9ad0e3..a269693e5 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/AdminServlet.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/AdminServlet.java @@ -33,21 +33,10 @@ package eu.sqooss.impl.service.webadmin; -import eu.sqooss.core.AlitheiaCore; -import eu.sqooss.impl.service.webadmin.WebAdminRenderer; -import eu.sqooss.service.admin.AdminAction; -import eu.sqooss.service.admin.AdminService; -import eu.sqooss.service.admin.actions.AddProject; -import eu.sqooss.service.db.DBService; -import eu.sqooss.service.logging.Logger; -import eu.sqooss.service.util.Pair; -import eu.sqooss.service.webadmin.WebadminService; - -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; - import java.util.Hashtable; import java.util.Locale; @@ -57,295 +46,292 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; - +import org.apache.velocity.app.VelocityEngine; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; -import org.osgi.framework.ServiceReference; + +import eu.sqooss.core.AlitheiaCore; +import eu.sqooss.service.admin.AdminAction; +import eu.sqooss.service.admin.AdminService; +import eu.sqooss.service.admin.actions.AddProject; +import eu.sqooss.service.db.DBService; +import eu.sqooss.service.logging.Logger; +import eu.sqooss.service.util.Pair; +import eu.sqooss.service.webadmin.WebadminService; public class AdminServlet extends HttpServlet { - private static final long serialVersionUID = 1L; - private static BundleContext bc = null; - private static WebadminService webadmin = null; - - /// Logger given by our owner to write log messages to. - private Logger logger = null; - - private DBService db = null; - - // Content tables - private Hashtable dynamicContentMap = null; - private Hashtable> staticContentMap = null; - - // Dynamic substitutions - VelocityContext vc = null; - VelocityEngine ve = null; - - // Renderer of content - WebAdminRenderer adminView = null; - - // Plug-ins view - PluginsView pluginsView = null; - - // Projects view - ProjectsView projectsView = null; - - TranslationProxy tr = new TranslationProxy(); - - public AdminServlet(BundleContext bc, - WebadminService webadmin, - Logger logger, - VelocityEngine ve) { - AdminServlet.webadmin = webadmin; - AdminServlet.bc = bc; - this.ve = ve; - this.logger = logger; - - AlitheiaCore core = AlitheiaCore.getInstance(); - db = core.getDBService(); - - // Create the static content map - staticContentMap = new Hashtable>(); - addStaticContent("/screen.css", "text/css"); - addStaticContent("/webadmin.css", "text/css"); - addStaticContent("/sqo-oss.png", "image/x-png"); - addStaticContent("/queue.png", "image/x-png"); - addStaticContent("/uptime.png", "image/x-png"); - addStaticContent("/greyBack.jpg", "image/x-jpg"); - addStaticContent("/projects.png", "image/x-png"); - addStaticContent("/logs.png", "image/x-png"); - addStaticContent("/metrics.png", "image/x-png"); - addStaticContent("/gear.png", "image/x-png"); - addStaticContent("/header-repeat.png", "image/x-png"); - addStaticContent("/add_user.png", "image/x-png"); - addStaticContent("/edit.png", "image/x-png"); - addStaticContent("/jobs.png", "image/x-png"); - addStaticContent("/rules.png", "image/x-png"); - - // Create the dynamic content map - dynamicContentMap = new Hashtable(); - dynamicContentMap.put("/", "index.html"); - dynamicContentMap.put("/index", "index.html"); - dynamicContentMap.put("/projects", "projects.html"); - dynamicContentMap.put("/projectlist", "projectslist.html"); - dynamicContentMap.put("/logs", "logs.html"); - dynamicContentMap.put("/jobs", "jobs.html"); - dynamicContentMap.put("/alljobs", "alljobs.html"); - dynamicContentMap.put("/users", "users.html"); - dynamicContentMap.put("/rules", "rules.html"); - dynamicContentMap.put("/jobstat", "jobstat.html"); - - // Now the dynamic substitutions and renderer - vc = new VelocityContext(); - adminView = new WebAdminRenderer(bc, vc); - - // Create the various view objects - pluginsView = new PluginsView(bc, vc); - projectsView = new ProjectsView(bc, vc); - } - - /** - * Add content to the static map - */ - private void addStaticContent(String path, String type) { - Pair p = new Pair (path,type); - staticContentMap.put(path, p); - } - - protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, - IOException { - if (!db.isDBSessionActive()) { - db.startDBSession(); - } - - try { - String query = request.getPathInfo(); - - // Add the request to the log - logger.debug("GET:" + query); - - // This is static content - if (query.startsWith("/stop")) { - vc.put("RESULTS", "

Alitheia Core is now shutdown.

"); - sendPage(response, request, "/results.html"); - - // Now stop the system - logger.info("System stopped by user request to webadmin."); - try { - bc.getBundle(0).stop(); - } catch (BundleException be) { - logger.warn("Could not stop bundle 0."); - // And ignore - } - return; - } - if (query.startsWith("/restart")) { - vc.put("RESULTS", "

Alitheia Core is now restarting.

"); - sendPage(response, request, "/results.html"); - - //FIXME: How do we do a restart? - return; - } - else if ((query != null) && (staticContentMap.containsKey(query))) { - sendResource(response, staticContentMap.get(query)); - } - else if ((query != null) && (dynamicContentMap.containsKey(query))) { - sendPage(response, request, dynamicContentMap.get(query)); - } - } catch (NullPointerException e) { - logger.warn("Got a NPE while rendering a page.",e); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } finally { - if (db.isDBSessionActive()) { - db.commitDBSession(); - } - } - } - - protected void doPost(HttpServletRequest request, - HttpServletResponse response) throws ServletException, - IOException { - if (!db.isDBSessionActive()) { - db.startDBSession(); - } - - try { - String query = request.getPathInfo(); - logger.debug("POST:" + query); - - if (query.startsWith("/addproject")) { - //addProject(request); - sendPage(response, request, "/results.html"); - } else if (query.startsWith("/diraddproject")) { - AdminService as = AlitheiaCore.getInstance().getAdminService(); - AdminAction aa = as.create(AddProject.MNEMONIC); - aa.addArg("dir", request.getParameter("properties")); - as.execute(aa); - if (aa.hasErrors()) - vc.put("RESULTS", aa.errors()); - else - vc.put("RESULTS", aa.results()); - sendPage(response, request, "/results.html"); - } else { - doGet(request,response); - } - } catch (NullPointerException e) { - logger.warn("Got a NPE while handling POST data."); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } finally { - if (db.isDBSessionActive()) { - db.commitDBSession(); - } - } - } - - /** - * Sends a resource (stored in the jar file) as a response. The mime-type - * is set to @p mimeType . The @p path to the resource should start - * with a / . - * - * Test cases: - * - null mimetype, null path, bad path, relative path, path not found, - * - null response - * - * TODO: How to simulate conditions that will cause IOException - */ - protected void sendResource(HttpServletResponse response, Pair source) - throws ServletException, IOException { - - InputStream istream = getClass().getResourceAsStream(source.first); - if ( istream == null ) { - throw new IOException("Path not found: " + source.first); - } - - byte[] buffer = new byte[1024]; - int bytesRead = 0; - int totalBytes = 0; - - response.setContentType(source.second); - ServletOutputStream ostream = response.getOutputStream(); - while ((bytesRead = istream.read(buffer)) > 0) { - ostream.write(buffer,0,bytesRead); - totalBytes += bytesRead; - } - } - - protected void sendPage( - HttpServletResponse response, - HttpServletRequest request, - String path) - throws ServletException, IOException { - Template t = null; - try { - t = ve.getTemplate( path ); - } catch (Exception e) { - logger.warn("Failed to get template <" + path + ">"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - StringWriter writer = new StringWriter(); - PrintWriter print = response.getWriter(); - - // Do any substitutions that may be required - createSubstitutions(request); - response.setContentType("text/html"); - t.merge(vc, writer); - - print.print(writer.toString()); - } - - private void createSubstitutions(HttpServletRequest request) { - // Initialize the resource bundles with the provided locale - AbstractView.initResources(Locale.ENGLISH); - - // Simple string substitutions - vc.put("APP_NAME", AbstractView.getLbl("app_name")); - vc.put("COPYRIGHT", - "Copyright 2007-2008" - + "" - + " SQO-OSS Consortium Members" - + ""); - vc.put("LOGO", ""); - vc.put("UPTIME", WebAdminRenderer.getUptime()); - - // Object-based substitutions - vc.put("scheduler", adminView.sobjSched.getSchedulerStats()); - vc.put("tr",tr); // translations proxy - vc.put("admin",adminView); - vc.put("projects",projectsView); - vc.put("metrics",pluginsView); - vc.put("request", request); // The request can be used by the render() methods - } - - /** - * This is a class whose sole purpose is to provide a useful API from - * within Velocity templates for the translation functions offered by - * the AbstractView. Only one object needs to be created, and it - * forwards all the label(), message() and error() calls to the translation - * methods of the view. - */ - public class TranslationProxy { - public TranslationProxy() { - } - - /** Translate a label */ - public String label(String s) { - return AbstractView.getLbl(s); - } - - /** Translate a (multi-line, html formatted) message */ - public String message(String s) { - return AbstractView.getMsg(s); - } - - /** Translate an error message */ - public String error(String s) { - return AbstractView.getErr(s); - } - } + private static final long serialVersionUID = 1L; + private static BundleContext bc = null; + private static WebadminService webadmin = null; + + // / Logger given by our owner to write log messages to. + private Logger logger = null; + + private DBService db = null; + + // Content tables + private Hashtable dynamicContentMap = null; + private Hashtable> staticContentMap = null; + + // Dynamic substitutions + VelocityContext vc = null; + VelocityEngine ve = null; + + // Renderer of content + WebAdminRenderer adminView = null; + + // Plug-ins view + PluginsView pluginsView = null; + + // Projects view + ProjectsView projectsView = null; + + TranslationProxy tr = new TranslationProxy(); + + public AdminServlet(BundleContext bc, WebadminService webadmin, + Logger logger, VelocityEngine ve) { + AdminServlet.webadmin = webadmin; + AdminServlet.bc = bc; + this.ve = ve; + this.logger = logger; + + AlitheiaCore core = AlitheiaCore.getInstance(); + db = core.getDBService(); + + // Create the static content map + staticContentMap = new Hashtable>(); + addStaticContent("/screen.css", "text/css"); + addStaticContent("/webadmin.css", "text/css"); + addStaticContent("/sqo-oss.png", "image/x-png"); + addStaticContent("/queue.png", "image/x-png"); + addStaticContent("/uptime.png", "image/x-png"); + addStaticContent("/greyBack.jpg", "image/x-jpg"); + addStaticContent("/projects.png", "image/x-png"); + addStaticContent("/logs.png", "image/x-png"); + addStaticContent("/metrics.png", "image/x-png"); + addStaticContent("/gear.png", "image/x-png"); + addStaticContent("/header-repeat.png", "image/x-png"); + addStaticContent("/add_user.png", "image/x-png"); + addStaticContent("/edit.png", "image/x-png"); + addStaticContent("/jobs.png", "image/x-png"); + addStaticContent("/rules.png", "image/x-png"); + + // Create the dynamic content map + dynamicContentMap = new Hashtable(); + dynamicContentMap.put("/", "index.html"); + dynamicContentMap.put("/index", "index.html"); + dynamicContentMap.put("/projects", "projects.html"); + dynamicContentMap.put("/projectlist", "projectslist.html"); + dynamicContentMap.put("/logs", "logs.html"); + dynamicContentMap.put("/jobs", "jobs.html"); + dynamicContentMap.put("/alljobs", "alljobs.html"); + dynamicContentMap.put("/users", "users.html"); + dynamicContentMap.put("/rules", "rules.html"); + dynamicContentMap.put("/jobstat", "jobstat.html"); + + // Now the dynamic substitutions and renderer + vc = new VelocityContext(); + adminView = new WebAdminRenderer(bc, vc); + + // Create the various view objects + pluginsView = new PluginsView(bc, vc); + projectsView = new ProjectsView(bc, vc, ve); + } + + /** + * Add content to the static map + */ + private void addStaticContent(String path, String type) { + Pair p = new Pair(path, type); + staticContentMap.put(path, p); + } + + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + if (!db.isDBSessionActive()) { + db.startDBSession(); + } + + try { + String query = request.getPathInfo(); + + // Add the request to the log + logger.debug("GET:" + query); + + // This is static content + if (query.startsWith("/stop")) { + vc.put("RESULTS", "

Alitheia Core is now shutdown.

"); + sendPage(response, request, "/results.html"); + + // Now stop the system + logger.info("System stopped by user request to webadmin."); + try { + bc.getBundle(0).stop(); + } catch (BundleException be) { + logger.warn("Could not stop bundle 0."); + // And ignore + } + return; + } + if (query.startsWith("/restart")) { + vc.put("RESULTS", "

Alitheia Core is now restarting.

"); + sendPage(response, request, "/results.html"); + + // FIXME: How do we do a restart? + return; + } else if ((query != null) && (staticContentMap.containsKey(query))) { + sendResource(response, staticContentMap.get(query)); + } else if ((query != null) + && (dynamicContentMap.containsKey(query))) { + sendPage(response, request, dynamicContentMap.get(query)); + } + } catch (NullPointerException e) { + logger.warn("Got a NPE while rendering a page.", e); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } finally { + if (db.isDBSessionActive()) { + db.commitDBSession(); + } + } + } + + protected void doPost(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + if (!db.isDBSessionActive()) { + db.startDBSession(); + } + + try { + String query = request.getPathInfo(); + logger.debug("POST:" + query); + + if (query.startsWith("/addproject")) { + // addProject(request); + sendPage(response, request, "/results.html"); + } else if (query.startsWith("/diraddproject")) { + AdminService as = AlitheiaCore.getInstance().getAdminService(); + AdminAction aa = as.create(AddProject.MNEMONIC); + aa.addArg("dir", request.getParameter("properties")); + as.execute(aa); + if (aa.hasErrors()) + vc.put("RESULTS", aa.errors()); + else + vc.put("RESULTS", aa.results()); + sendPage(response, request, "/results.html"); + } else { + doGet(request, response); + } + } catch (NullPointerException e) { + logger.warn("Got a NPE while handling POST data."); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } finally { + if (db.isDBSessionActive()) { + db.commitDBSession(); + } + } + } + + /** + * Sends a resource (stored in the jar file) as a response. The mime-type is + * set to @p mimeType . The @p path to the resource should start with a / . + * + * Test cases: - null mimetype, null path, bad path, relative path, path not + * found, - null response + * + * TODO: How to simulate conditions that will cause IOException + */ + protected void sendResource(HttpServletResponse response, + Pair source) throws ServletException, IOException { + + InputStream istream = getClass().getResourceAsStream(source.first); + if (istream == null) { + throw new IOException("Path not found: " + source.first); + } + + byte[] buffer = new byte[1024]; + int bytesRead = 0; + int totalBytes = 0; + + response.setContentType(source.second); + ServletOutputStream ostream = response.getOutputStream(); + while ((bytesRead = istream.read(buffer)) > 0) { + ostream.write(buffer, 0, bytesRead); + totalBytes += bytesRead; + } + } + + protected void sendPage(HttpServletResponse response, + HttpServletRequest request, String path) throws ServletException, + IOException { + Template t = null; + try { + t = ve.getTemplate(path); + } catch (Exception e) { + logger.warn("Failed to get template <" + path + ">"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + StringWriter writer = new StringWriter(); + PrintWriter print = response.getWriter(); + + // Do any substitutions that may be required + createSubstitutions(request); + response.setContentType("text/html"); + t.merge(vc, writer); + + print.print(writer.toString()); + } + + private void createSubstitutions(HttpServletRequest request) { + // Initialize the resource bundles with the provided locale + AbstractView.initResources(Locale.ENGLISH); + + // Simple string substitutions + vc.put("APP_NAME", AbstractView.getLbl("app_name")); + vc.put("COPYRIGHT", "Copyright 2007-2008" + + "" + + " SQO-OSS Consortium Members" + ""); + vc.put("LOGO", ""); + vc.put("UPTIME", WebAdminRenderer.getUptime()); + + // Object-based substitutions + vc.put("scheduler", adminView.sobjSched.getSchedulerStats()); + vc.put("tr", tr); // translations proxy + vc.put("admin", adminView); + vc.put("projects", projectsView); + vc.put("metrics", pluginsView); + vc.put("request", request); // The request can be used by the render() + // methods + } + + /** + * This is a class whose sole purpose is to provide a useful API from within + * Velocity templates for the translation functions offered by the + * AbstractView. Only one object needs to be created, and it forwards all + * the label(), message() and error() calls to the translation methods of + * the view. + */ + public class TranslationProxy { + public TranslationProxy() { + } + + /** Translate a label */ + public String label(String s) { + return AbstractView.getLbl(s); + } + + /** Translate a (multi-line, html formatted) message */ + public String message(String s) { + return AbstractView.getMsg(s); + } + + /** Translate an error message */ + public String error(String s) { + return AbstractView.getErr(s); + } + } } // vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/PluginsView.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/PluginsView.java index 9a582edb4..20719fcd8 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/PluginsView.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/PluginsView.java @@ -51,935 +51,814 @@ import eu.sqooss.service.pa.PluginInfo.ConfigurationType; import eu.sqooss.service.util.StringUtils; -public class PluginsView extends AbstractView{ +public class PluginsView extends AbstractView { - public PluginsView(BundleContext bundlecontext, VelocityContext vc) { - super(bundlecontext, vc); - } + public PluginsView(BundleContext bundlecontext, VelocityContext vc) { + super(bundlecontext, vc, ve); + } - /** - * Renders the various plug-in's views. - * - * @param req the servlet's request object - * - * @return The HTML presentation of the generated view. - */ - public static String render(HttpServletRequest req) { - // Stores the assembled HTML content - StringBuilder b = new StringBuilder("\n"); - // Stores the accumulated error messages - StringBuilder e = new StringBuilder(); - // Indentation spacer - long in = 6; + /** + * Renders the various plug-in's views. + * + * @param req + * the servlet's request object + * + * @return The HTML presentation of the generated view. + */ + public static String render(HttpServletRequest req) { + // Stores the assembled HTML content + StringBuilder b = new StringBuilder("\n"); + // Stores the accumulated error messages + StringBuilder e = new StringBuilder(); + // Indentation spacer + long in = 6; - // Request parameters - String reqParAction = "action"; - String reqParHashcode = "pluginHashcode"; - String reqParPropName = "propertyName"; - String reqParPropDescr = "propertyDescription"; - String reqParPropType = "propertyType"; - String reqParPropValue = "propertyValue"; - String reqParShowProp = "showProperties"; - String reqParShowActv = "showActivators"; - // Recognized "action" parameter's values - String actValInstall = "installPlugin"; - String actValUninstall = "uninstallPlugin"; - String actValSync = "syncPlugin"; - String actValReqAddProp = "createProperty"; - String actValReqUpdProp = "updateProperty"; - String actValConAddProp = "confirmProperty"; - String actValConRemProp = "removeProperty"; - // Request values - String reqValAction = ""; - String reqValHashcode = null; - String reqValPropName = null; - String reqValPropDescr = null; - String reqValPropType = null; - String reqValPropValue = null; - boolean reqValShowProp = false; // Show plug-in properties - boolean reqValShowActv = false; // Show plug-in activators - // Info object of the selected plug-in - PluginInfo selPI = null; + // Request parameters + String reqParAction = "action"; + String reqParHashcode = "pluginHashcode"; + String reqParPropName = "propertyName"; + String reqParPropDescr = "propertyDescription"; + String reqParPropType = "propertyType"; + String reqParPropValue = "propertyValue"; + String reqParShowProp = "showProperties"; + String reqParShowActv = "showActivators"; + // Recognized "action" parameter's values + String actValInstall = "installPlugin"; + String actValUninstall = "uninstallPlugin"; + String actValSync = "syncPlugin"; + String actValReqAddProp = "createProperty"; + String actValReqUpdProp = "updateProperty"; + String actValConAddProp = "confirmProperty"; + String actValConRemProp = "removeProperty"; + // Request values + String reqValAction = ""; + String reqValHashcode = null; + String reqValPropName = null; + String reqValPropDescr = null; + String reqValPropType = null; + String reqValPropValue = null; + boolean reqValShowProp = false; // Show plug-in properties + boolean reqValShowActv = false; // Show plug-in activators + // Info object of the selected plug-in + PluginInfo selPI = null; - // Proceed only when at least one plug-in is registered - if (sobjPA.listPlugins().isEmpty()) { - b.append(normalFieldset( - "All plug-ins", - null, - new StringBuilder("" - + "No plug-ins found! " - + "" - + ""), - in)); - } - else { - // =============================================================== - // Parse the servlet's request object - // =============================================================== - if (req != null) { - // DEBUG: Dump the servlet's request parameter - if (DEBUG) { - b.append(debugRequest(req)); - } + // Proceed only when at least one plug-in is registered + if (sobjPA.listPlugins().isEmpty()) { + b.append(normalFieldset("All plug-ins", null, new StringBuilder( + "" + "No plug-ins found! " + + "" + + ""), in)); + } else { + // =============================================================== + // Parse the servlet's request object + // =============================================================== + if (req != null) { + // DEBUG: Dump the servlet's request parameter + if (DEBUG) { + b.append(debugRequest(req)); + } - // Retrieve the selected editor's action (if any) - reqValAction = req.getParameter(reqParAction); - if (reqValAction == null) { - reqValAction = ""; - }; - // Retrieve the various display flags - if ((req.getParameter(reqParShowProp) != null) - && (req.getParameter(reqParShowProp).equals("true"))) { - reqValShowProp = true; - } - if ((req.getParameter(reqParShowActv) != null) - && (req.getParameter(reqParShowActv).equals("true"))) { - reqValShowActv = true; - } - // Retrieve the selected configuration property's values - if ((reqValAction.equals(actValConAddProp)) - || (reqValAction.equals(actValReqUpdProp)) - || (reqValAction.equals(actValConRemProp))) { - // Name, description, type and value - reqValPropName = req.getParameter(reqParPropName); - reqValPropDescr = req.getParameter(reqParPropDescr); - reqValPropType = req.getParameter(reqParPropType); - reqValPropValue = req.getParameter(reqParPropValue); - } - // Retrieve the selected plug-in's hash code - reqValHashcode = req.getParameter(reqParHashcode); - // Plug-in based actions - if (reqValHashcode != null) { - // ======================================================= - // Plug-in install request - // ======================================================= - if (reqValAction.equals(actValInstall)) { - if (sobjPA.installPlugin(reqValHashcode) == false) { - e.append("Plug-in can not be installed!" - + " Check log for details."); - } - // Persist the DB changes - else { - PluginInfo pInfo = - sobjPA.getPluginInfo(reqValHashcode); - sobjPA.pluginUpdated(sobjPA.getPlugin(pInfo)); - } - } - // ======================================================= - // Plug-in un-install request - // ======================================================= - else if (reqValAction.equals(actValUninstall)) { - if (sobjPA.uninstallPlugin(reqValHashcode) == false) { - e.append("Plug-in can not be uninstalled." - + " Check log for details."); - } else { - e.append("A job was scheduled to remove the plug-in"); - } - } - } - // Retrieve the selected plug-in's info object - if (reqValHashcode != null) { - selPI = sobjPA.getPluginInfo(reqValHashcode); - } - // Plug-in info based actions - if ((selPI != null) && (selPI.installed)) { - // ======================================================= - // Plug-in synchronize (on all projects) request - // ======================================================= - if (reqValAction.equals(actValSync)) { - compMA.syncMetrics(sobjPA.getPlugin(selPI)); - } - // ======================================================= - // Plug-in's configuration property removal - // ======================================================= - else if (reqValAction.equals(actValConRemProp)) { - if (selPI.hasConfProp( - reqValPropName, reqValPropType)) { - try { - if (selPI.removeConfigEntry( - sobjDB, - reqValPropName, - reqValPropType)) { - // Update the Plug-in Admin's information - sobjPA.pluginUpdated( - sobjPA.getPlugin(selPI)); - // Reload the PluginInfo object - selPI = sobjPA.getPluginInfo( - reqValHashcode); - } - else { - e.append("Property removal" - + " has failed!" - + " Check log for details."); - } - } - catch (Exception ex) { - e.append(ex.getMessage()); - } - } - else { - e.append ("Unknown configuration property!"); - } - // Return to the update view upon error - if (e.toString().length() > 0) { - reqValAction = actValReqUpdProp; - } - } - // ======================================================= - // Plug-in's configuration property creation/update - // ======================================================= - else if (reqValAction.equals(actValConAddProp)) { - // Check for a property update - boolean update = selPI.hasConfProp( - reqValPropName, reqValPropType); - // Update configuration property - if (update) { - try { - if (selPI.updateConfigEntry( - sobjDB, - reqValPropName, - reqValPropValue)) { - // Update the Plug-in Admin's information - sobjPA.pluginUpdated( - sobjPA.getPlugin(selPI)); - // Reload the PluginInfo object - selPI = - sobjPA.getPluginInfo(reqValHashcode); - } - else { - e.append("Property update" - + " has failed!" - + " Check log for details."); - } - } - catch (Exception ex) { - e.append(ex.getMessage()); - } - } - // Create configuration property - else { - try { - if (selPI.addConfigEntry( - sobjDB, - reqValPropName, - reqValPropDescr, - reqValPropType, - reqValPropValue)) { - // Update the Plug-in Admin's information - sobjPA.pluginUpdated( - sobjPA.getPlugin(selPI)); - // Reload the PluginInfo object - selPI = - sobjPA.getPluginInfo(reqValHashcode); - } - else { - e.append("Property creation" - + " has failed!" - + " Check log for details."); - } - } - catch (Exception ex) { - e.append(ex.getMessage()); - } - } - // Return to the create/update view upon error - if (e.toString().length() > 0) { - if (update) reqValAction = actValReqUpdProp; - else reqValAction = actValReqAddProp; - } - } - } - } + // Retrieve the selected editor's action (if any) + reqValAction = req.getParameter(reqParAction); + if (reqValAction == null) { + reqValAction = ""; + } + ; + // Retrieve the various display flags + if ((req.getParameter(reqParShowProp) != null) + && (req.getParameter(reqParShowProp).equals("true"))) { + reqValShowProp = true; + } + if ((req.getParameter(reqParShowActv) != null) + && (req.getParameter(reqParShowActv).equals("true"))) { + reqValShowActv = true; + } + // Retrieve the selected configuration property's values + if ((reqValAction.equals(actValConAddProp)) + || (reqValAction.equals(actValReqUpdProp)) + || (reqValAction.equals(actValConRemProp))) { + // Name, description, type and value + reqValPropName = req.getParameter(reqParPropName); + reqValPropDescr = req.getParameter(reqParPropDescr); + reqValPropType = req.getParameter(reqParPropType); + reqValPropValue = req.getParameter(reqParPropValue); + } + // Retrieve the selected plug-in's hash code + reqValHashcode = req.getParameter(reqParHashcode); + // Plug-in based actions + if (reqValHashcode != null) { + // ======================================================= + // Plug-in install request + // ======================================================= + if (reqValAction.equals(actValInstall)) { + if (sobjPA.installPlugin(reqValHashcode) == false) { + e.append("Plug-in can not be installed!" + + " Check log for details."); + } + // Persist the DB changes + else { + PluginInfo pInfo = sobjPA + .getPluginInfo(reqValHashcode); + sobjPA.pluginUpdated(sobjPA.getPlugin(pInfo)); + } + } + // ======================================================= + // Plug-in un-install request + // ======================================================= + else if (reqValAction.equals(actValUninstall)) { + if (sobjPA.uninstallPlugin(reqValHashcode) == false) { + e.append("Plug-in can not be uninstalled." + + " Check log for details."); + } else { + e.append("A job was scheduled to remove the plug-in"); + } + } + } + // Retrieve the selected plug-in's info object + if (reqValHashcode != null) { + selPI = sobjPA.getPluginInfo(reqValHashcode); + } + // Plug-in info based actions + if ((selPI != null) && (selPI.installed)) { + // ======================================================= + // Plug-in synchronize (on all projects) request + // ======================================================= + if (reqValAction.equals(actValSync)) { + compMA.syncMetrics(sobjPA.getPlugin(selPI)); + } + // ======================================================= + // Plug-in's configuration property removal + // ======================================================= + else if (reqValAction.equals(actValConRemProp)) { + if (selPI.hasConfProp(reqValPropName, reqValPropType)) { + try { + if (selPI.removeConfigEntry(sobjDB, + reqValPropName, reqValPropType)) { + // Update the Plug-in Admin's information + sobjPA.pluginUpdated(sobjPA + .getPlugin(selPI)); + // Reload the PluginInfo object + selPI = sobjPA + .getPluginInfo(reqValHashcode); + } else { + e.append("Property removal" + + " has failed!" + + " Check log for details."); + } + } catch (Exception ex) { + e.append(ex.getMessage()); + } + } else { + e.append("Unknown configuration property!"); + } + // Return to the update view upon error + if (e.toString().length() > 0) { + reqValAction = actValReqUpdProp; + } + } + // ======================================================= + // Plug-in's configuration property creation/update + // ======================================================= + else if (reqValAction.equals(actValConAddProp)) { + // Check for a property update + boolean update = selPI.hasConfProp(reqValPropName, + reqValPropType); + // Update configuration property + if (update) { + try { + if (selPI.updateConfigEntry(sobjDB, + reqValPropName, reqValPropValue)) { + // Update the Plug-in Admin's information + sobjPA.pluginUpdated(sobjPA + .getPlugin(selPI)); + // Reload the PluginInfo object + selPI = sobjPA + .getPluginInfo(reqValHashcode); + } else { + e.append("Property update" + " has failed!" + + " Check log for details."); + } + } catch (Exception ex) { + e.append(ex.getMessage()); + } + } + // Create configuration property + else { + try { + if (selPI.addConfigEntry(sobjDB, + reqValPropName, reqValPropDescr, + reqValPropType, reqValPropValue)) { + // Update the Plug-in Admin's information + sobjPA.pluginUpdated(sobjPA + .getPlugin(selPI)); + // Reload the PluginInfo object + selPI = sobjPA + .getPluginInfo(reqValHashcode); + } else { + e.append("Property creation" + + " has failed!" + + " Check log for details."); + } + } catch (Exception ex) { + e.append(ex.getMessage()); + } + } + // Return to the create/update view upon error + if (e.toString().length() > 0) { + if (update) + reqValAction = actValReqUpdProp; + else + reqValAction = actValReqAddProp; + } + } + } + } - // =============================================================== - // Create the form - // =============================================================== - b.append(sp(in++) + "
\n"); + // =============================================================== + // Create the form + // =============================================================== + b.append(sp(in++) + "\n"); - // =============================================================== - // Display the accumulated error messages (if any) - // =============================================================== - b.append(errorFieldset(e, in)); + // =============================================================== + // Display the accumulated error messages (if any) + // =============================================================== + b.append(errorFieldset(e, in)); - // =============================================================== - // "Create/update configuration property" editor - // =============================================================== - if ((selPI != null) && (selPI.installed) - && ((reqValAction.equals(actValReqAddProp)) - || (reqValAction.equals(actValReqUpdProp)))) { - // Input field values are stored here - String value = null; - // Create the field-set - b.append(sp(in) + "
\n"); - // Check for a property update request - boolean update = selPI.hasConfProp( - reqValPropName, reqValPropType); - b.append(sp(++in) + "" - + ((update) - ? "Update property of " - : "Create property for ") - + selPI.getPluginName() - + "\n"); - b.append(sp(in) + ""); - // Property's name - value = ((reqValPropName != null) ? reqValPropName : ""); - b.append(sp(in) + "\n" - + sp(++in) - + "\n" - + sp(in) - + "\n" - + sp(--in) + "\n"); - // Property's description - value = ((reqValPropDescr != null) ? reqValPropDescr : ""); - b.append(sp(in) + "\n" - + sp(++in) - + "\n" - + sp(in) - + "\n" - + sp(--in) + "\n"); - // Property's type - value = ((reqValPropType != null) ? reqValPropType : ""); - b.append(sp(in) + "\n" - + sp(++in) - + "\n" - + sp(in) - + "\n" - + sp(--in) - + "\n"); - // Property's value - value = ((reqValPropValue != null) ? reqValPropValue : ""); - b.append(sp(in) + "\n" - + sp(++in) - + "\n" - + sp(in) - + "\n" - + sp(--in) - + "\n"); - // Command tool-bar - value = ((update) ? "Update" : "Create"); - b.append(sp(in) + "\n" - + sp(++in) - + "\n" - + sp(--in) - + "\n"); - b.append(sp(--in) + "
" - + "Name" - + "" - + ((update) ? value - : "") - + "
" - + "Description" - + "" - + ((update) ? value - : "") - + "
" - + "Type" - + "\n" - + sp(++in)); - if (update) { - b.append(value); - } - else { - b.append("\n"); - } - b.append(sp(--in) - + "
" - + "Value" - + "" - + "" - + "
" - + "" - + " "); - if (update) { - b.append(sp(in) + "" - + " "); - } - b.append(sp(in) + "" - + "
"); - b.append(sp(--in) + "
\n"); - } - // =============================================================== - // Plug-in editor - // =============================================================== - else if (selPI != null) { - // Create the plug-in field-set - b.append(sp(in) + "
\n"); - b.append(sp(++in) + "" - + selPI.getPluginName() - + "\n"); - //------------------------------------------------------------ - // Create the plug-in info table - //------------------------------------------------------------ - b.append(sp(in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - // Display the plug-in's info - b.append(sp(in) + "\n"); - b.append(sp(in++) + "\n"); - // Plug-in state - b.append(sp(++in) + "\n"); - // Plug-in name - b.append(sp(in) + "\n"); - // Plug-in class - b.append(sp(in) + "\n"); - // Plug-in version - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - // Plug-in tool-bar - b.append(sp(in++) + "\n"); - b.append(sp(in++) + "\n"); - b.append(sp(--in) + "\n"); - // Close the plug-in table - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "
" - + "Status" - + "Name" - + "ClassVersion
" - + ((selPI.installed) - ? "Installed" : "Registered") - + "" - + selPI.getPluginName() + "" - + StringUtils.join((String[]) ( - selPI.getServiceRef().getProperty( - Constants.OBJECTCLASS)),",") - + "" - + selPI.getPluginVersion() + "
\n"); - b.append(sp(in) + "\n"); - if (selPI.installed) { - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - } - else { - b.append(sp(in) + "\n"); - } - b.append(sp(--in) + "
\n"); + // =============================================================== + // "Create/update configuration property" editor + // =============================================================== + if ((selPI != null) + && (selPI.installed) + && ((reqValAction.equals(actValReqAddProp)) || (reqValAction + .equals(actValReqUpdProp)))) { + // Input field values are stored here + String value = null; + // Create the field-set + b.append(sp(in) + "
\n"); + // Check for a property update request + boolean update = selPI.hasConfProp(reqValPropName, + reqValPropType); + b.append(sp(++in) + + "" + + ((update) ? "Update property of " + : "Create property for ") + + selPI.getPluginName() + "\n"); + b.append(sp(in) + ""); + // Property's name + value = ((reqValPropName != null) ? reqValPropName : ""); + b.append(sp(in) + + "\n" + + sp(++in) + + "\n" + + sp(in) + + "\n" + + sp(--in) + "\n"); + // Property's description + value = ((reqValPropDescr != null) ? reqValPropDescr : ""); + b.append(sp(in) + + "\n" + + sp(++in) + + "\n" + + sp(in) + + "\n" + sp(--in) + "\n"); + // Property's type + value = ((reqValPropType != null) ? reqValPropType : ""); + b.append(sp(in) + "\n" + sp(++in) + + "\n" + sp(in) + + "\n" + sp(--in) + "\n"); + // Property's value + value = ((reqValPropValue != null) ? reqValPropValue : ""); + b.append(sp(in) + "\n" + sp(++in) + + "\n" + sp(in) + + "\n" + sp(--in) + "\n"); + // Command tool-bar + value = ((update) ? "Update" : "Create"); + b.append(sp(in) + "\n" + sp(++in) + + "\n" + + sp(--in) + "\n"); + b.append(sp(--in) + "
" + + "Name" + + "" + + ((update) ? value : "") + "
" + + "Description" + + "" + + ((update) ? value : "") + "
" + + "Type" + "\n" + sp(++in)); + if (update) { + b.append(value); + } else { + b.append("\n"); + } + b.append(sp(--in) + "
" + + "Value" + "" + "" + "
" + + "" + " "); + if (update) { + b.append(sp(in) + "" + " "); + } + b.append(sp(in) + "" + "
"); + b.append(sp(--in) + "
\n"); + } + // =============================================================== + // Plug-in editor + // =============================================================== + else if (selPI != null) { + // Create the plug-in field-set + b.append(sp(in) + "
\n"); + b.append(sp(++in) + "" + selPI.getPluginName() + + "\n"); + // ------------------------------------------------------------ + // Create the plug-in info table + // ------------------------------------------------------------ + b.append(sp(in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + b.append(sp(--in) + "\n"); + // Display the plug-in's info + b.append(sp(in) + "\n"); + b.append(sp(in++) + "\n"); + // Plug-in state + b.append(sp(++in) + "\n"); + // Plug-in name + b.append(sp(in) + "\n"); + // Plug-in class + b.append(sp(in) + + "\n"); + // Plug-in version + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + // Plug-in tool-bar + b.append(sp(in++) + "\n"); + b.append(sp(in++) + "\n"); + b.append(sp(--in) + "\n"); + // Close the plug-in table + b.append(sp(--in) + "\n"); + b.append(sp(--in) + "
" + "Status" + "Name" + "ClassVersion
" + + ((selPI.installed) ? "Installed" : "Registered") + + "" + selPI.getPluginName() + "" + + StringUtils.join((String[]) (selPI.getServiceRef() + .getProperty(Constants.OBJECTCLASS)), ",") + + "" + selPI.getPluginVersion() + "
\n"); + b.append(sp(in) + "\n"); + if (selPI.installed) { + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + } else { + b.append(sp(in) + "\n"); + } + b.append(sp(--in) + "
\n"); - //------------------------------------------------------------ - // Registered metrics, activators and configuration - //------------------------------------------------------------ - if (selPI.installed) { - //-------------------------------------------------------- - // Create the metrics field-set - //-------------------------------------------------------- - b.append(sp(++in) + "
\n"); - b.append(sp(++in) + "" - + "Supported metrics" - + "\n"); - // Create the metrics table - b.append(sp(in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - // Display the list of supported metrics - b.append(sp(in++) + "\n"); - // Get the list of supported metrics - List metrics = - sobjPA.getPlugin(selPI).getAllSupportedMetrics(); - if ((metrics == null) || (metrics.isEmpty())) { - b.append(sp(in++) + ""); - b.append(sp(in) + "\n"); - b.append(sp(--in)+ "\n"); - } - else { - for (Metric metric: metrics) { - b.append(sp(in++) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(--in)+ "\n"); - } - } - // Close the metrics table - b.append(sp(--in) + "\n"); - // Close the metrics table - b.append(sp(--in) + "
" - + "Id" - + "Name" - + "Type" - + "Description
" - + "This plug-in does not support metrics." - + "
" - + metric.getId() + "" - + metric.getMnemonic() + "" - + metric.getMetricType().getType() - + "" - + metric.getDescription() + "
\n"); - // Close the metric field-set - b.append(sp(--in) + "
\n"); - //-------------------------------------------------------- - // Create the properties field-set - //-------------------------------------------------------- - b.append(sp(++in) + "
\n"); - b.append(sp(++in) + "" - + "Configuration properties" - + "\n"); - // Create the properties table - b.append(sp(in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - // Display the set of configuration properties - b.append(sp(in++) + "\n"); - // Get the plug-in's configuration set - Set config = Plugin.getPluginByHashcode(selPI.getHashcode()).getConfigurations(); - if ((config == null) || (config.isEmpty())) { - b.append(sp(in++) + ""); - b.append(sp(in) + "\n"); - b.append(sp(--in)+ "\n"); - } - else { - for (PluginConfiguration param : config) { - b.append(sp(in++) + "\n"); - // Property's name and description - String description = param.getMsg(); - if (param.getMsg() == null) - description = "No description available."; - b.append(sp(in) + "\n"); - // Property's type - b.append(sp(in) + "\n"); - // Property's value - b.append(sp(in) + "\n"); - b.append(sp(--in)+ "\n"); - } - } - // Command tool-bar - b.append(sp(in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(--in) + "\n"); - // Close the properties table - b.append(sp(--in) + "\n"); - // Close the properties table - b.append(sp(--in) + "
" - + "Name" - + "Type" - + "Value
" - + "This plug-in has no configuration properties." - + "
" - + "\"[Edit]\"/" - + " " + param.getName() - + "" - + param.getType() - + "" - + param.getValue() - + "
\n"); - b.append(sp(++in) + "\n"); - b.append(sp(--in) + "
\n"); - // Close the properties field-set - b.append(sp(--in) + "
\n"); - } + // ------------------------------------------------------------ + // Registered metrics, activators and configuration + // ------------------------------------------------------------ + if (selPI.installed) { + // -------------------------------------------------------- + // Create the metrics field-set + // -------------------------------------------------------- + b.append(sp(++in) + "
\n"); + b.append(sp(++in) + "" + "Supported metrics" + + "\n"); + // Create the metrics table + b.append(sp(in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + b.append(sp(--in) + "\n"); + // Display the list of supported metrics + b.append(sp(in++) + "\n"); + // Get the list of supported metrics + List metrics = sobjPA.getPlugin(selPI) + .getAllSupportedMetrics(); + if ((metrics == null) || (metrics.isEmpty())) { + b.append(sp(in++) + ""); + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + } else { + for (Metric metric : metrics) { + b.append(sp(in++) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + } + } + // Close the metrics table + b.append(sp(--in) + "\n"); + // Close the metrics table + b.append(sp(--in) + "
" + "Id" + "Name" + "Type" + "Description
" + + "This plug-in does not support metrics." + + "
" + metric.getId() + + "" + metric.getMnemonic() + + "" + + metric.getMetricType().getType() + + "" + metric.getDescription() + + "
\n"); + // Close the metric field-set + b.append(sp(--in) + "
\n"); + // -------------------------------------------------------- + // Create the properties field-set + // -------------------------------------------------------- + b.append(sp(++in) + "
\n"); + b.append(sp(++in) + "" + "Configuration properties" + + "\n"); + // Create the properties table + b.append(sp(in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + b.append(sp(--in) + "\n"); + // Display the set of configuration properties + b.append(sp(in++) + "\n"); + // Get the plug-in's configuration set + Set config = Plugin + .getPluginByHashcode(selPI.getHashcode()) + .getConfigurations(); + if ((config == null) || (config.isEmpty())) { + b.append(sp(in++) + ""); + b.append(sp(in) + + "\n"); + b.append(sp(--in) + "\n"); + } else { + for (PluginConfiguration param : config) { + b.append(sp(in++) + "\n"); + // Property's name and description + String description = param.getMsg(); + if (param.getMsg() == null) + description = "No description available."; + b.append(sp(in) + "\n"); + // Property's type + b.append(sp(in) + "\n"); + // Property's value + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + } + } + // Command tool-bar + b.append(sp(in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(--in) + "\n"); + // Close the properties table + b.append(sp(--in) + "\n"); + // Close the properties table + b.append(sp(--in) + "
" + "Name" + "Type" + "Value
" + + "This plug-in has no configuration properties." + + "
" + + "\"[Edit]\"/" + + " " + param.getName() + "" + + param.getType() + "" + + param.getValue() + "
\n"); + b.append(sp(++in) + "\n"); + b.append(sp(--in) + "
\n"); + // Close the properties field-set + b.append(sp(--in) + "
\n"); + } - // Close the plug-in field-set - b.append(sp(--in) + "
\n"); - } - // =============================================================== - // Plug-ins list - // =============================================================== - else { - // Create the field-set - b.append(sp(in) + "
\n"); - b.append(sp(++in) + "All plug-ins\n"); - // Retrieve information for all registered metric plug-ins - Collection l = sobjPA.listPlugins(); - //------------------------------------------------------------ - // Create the header row - //------------------------------------------------------------ - b.append(sp(in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(++in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - //------------------------------------------------------------ - // Create the content row - //------------------------------------------------------------ - b.append(sp(in++) + "\n"); - //------------------------------------------------------------ - // Display not-installed plug-ins first - //------------------------------------------------------------ - for(PluginInfo i : l) { - if (i.installed == false) { - b.append(sp(in) + "\n"); - // Plug-in state - b.append(sp(++in) + "\n"); - // Plug-in name - b.append(sp(in) + "\n"); - // Plug-in class - b.append(sp(in) + "\n"); - // Plug-in version - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - // Extended plug-in information - b.append(renderPluginAttributes( - i, reqValShowProp, reqValShowActv, in)); - } - } - //------------------------------------------------------------ - // Installed plug-ins - //------------------------------------------------------------ - for(PluginInfo i : l) { - if (i.installed) { - b.append(sp(in) + "\n"); - // Plug-in state - b.append(sp(++in) + "\n"); - // Plug-in name - b.append(sp(in) + "\n"); - // Plug-in class - b.append(sp(in) + "\n"); - // Plug-in version - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - // Extended plug-in information - b.append(renderPluginAttributes( - i, reqValShowProp, reqValShowActv, in)); - } - } - //------------------------------------------------------------ - // Close the table - //------------------------------------------------------------ - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "
" - + "Status" - + "Name" - + "ClassVersion
" - + "\"[Edit]\"/" - + " Registered" - + i.getPluginName() - + "" - + StringUtils.join((String[]) ( - i.getServiceRef().getProperty( - Constants.OBJECTCLASS)),",") - + "" - + i.getPluginVersion() + "
" - + "\"[Edit]\"/" - + " Installed" - + i.getPluginName() - + "" - + StringUtils.join((String[]) ( - i.getServiceRef().getProperty( - Constants.OBJECTCLASS)),",") - + "" - + i.getPluginVersion() + "
\n"); - //------------------------------------------------------------ - // Display flags - //------------------------------------------------------------ - b.append(sp(in) + "\n"); - b.append(sp(++in) + "Display properties\n"); - b.append(sp(++in) + "Display activators\n"); - b.append(sp(--in) + "\n"); - // Close the field-set - b.append(sp(--in) + "
\n"); - } + // Close the plug-in field-set + b.append(sp(--in) + "
\n"); + } + // =============================================================== + // Plug-ins list + // =============================================================== + else { + // Create the field-set + b.append(sp(in) + "
\n"); + b.append(sp(++in) + "All plug-ins\n"); + // Retrieve information for all registered metric plug-ins + Collection l = sobjPA.listPlugins(); + // ------------------------------------------------------------ + // Create the header row + // ------------------------------------------------------------ + b.append(sp(in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(++in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + b.append(sp(--in) + "\n"); + // ------------------------------------------------------------ + // Create the content row + // ------------------------------------------------------------ + b.append(sp(in++) + "\n"); + // ------------------------------------------------------------ + // Display not-installed plug-ins first + // ------------------------------------------------------------ + for (PluginInfo i : l) { + if (i.installed == false) { + b.append(sp(in) + "\n"); + // Plug-in state + b.append(sp(++in) + "\n"); + // Plug-in name + b.append(sp(in) + "\n"); + // Plug-in class + b.append(sp(in) + + "\n"); + // Plug-in version + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + // Extended plug-in information + b.append(renderPluginAttributes(i, reqValShowProp, + reqValShowActv, in)); + } + } + // ------------------------------------------------------------ + // Installed plug-ins + // ------------------------------------------------------------ + for (PluginInfo i : l) { + if (i.installed) { + b.append(sp(in) + "\n"); + // Plug-in state + b.append(sp(++in) + "\n"); + // Plug-in name + b.append(sp(in) + "\n"); + // Plug-in class + b.append(sp(in) + + "\n"); + // Plug-in version + b.append(sp(in) + "\n"); + b.append(sp(--in) + "\n"); + // Extended plug-in information + b.append(renderPluginAttributes(i, reqValShowProp, + reqValShowActv, in)); + } + } + // ------------------------------------------------------------ + // Close the table + // ------------------------------------------------------------ + b.append(sp(--in) + "\n"); + b.append(sp(--in) + "
" + "Status" + "Name" + "ClassVersion
" + + "\"[Edit]\"/" + + " Registered" + + i.getPluginName() + "" + + StringUtils.join((String[]) (i + .getServiceRef() + .getProperty(Constants.OBJECTCLASS)), + ",") + "" + + i.getPluginVersion() + "
" + + "\"[Edit]\"/" + + " Installed" + + i.getPluginName() + "" + + StringUtils.join((String[]) (i + .getServiceRef() + .getProperty(Constants.OBJECTCLASS)), + ",") + "" + + i.getPluginVersion() + "
\n"); + // ------------------------------------------------------------ + // Display flags + // ------------------------------------------------------------ + b.append(sp(in) + "\n"); + b.append(sp(++in) + "Display properties\n"); + b.append(sp(++in) + "Display activators\n"); + b.append(sp(--in) + "\n"); + // Close the field-set + b.append(sp(--in) + "
\n"); + } - // =============================================================== - // INPUT FIELDS - // =============================================================== - // "Action type" input field - b.append(sp(in) + "\n"); - // "Selected plug-in's hash code" input field - b.append(sp(in) + "\n"); - // "Configuration attribute's name" input field - b.append(sp(in) + "\n"); - // "Configuration attribute's description" input field - b.append(sp(in) + "\n"); - // "Configuration attribute's type" input field - b.append(sp(in) + "\n"); - // "Configuration attribute's value" input field - b.append(sp(in) + "\n"); - // "Show configuration properties" input field - b.append(sp(in) + "\n"); - // "Show activators" input field - b.append(sp(in) + "\n"); + // =============================================================== + // INPUT FIELDS + // =============================================================== + // "Action type" input field + b.append(sp(in) + "\n"); + // "Selected plug-in's hash code" input field + b.append(sp(in) + "\n"); + // "Configuration attribute's name" input field + b.append(sp(in) + "\n"); + // "Configuration attribute's description" input field + b.append(sp(in) + "\n"); + // "Configuration attribute's type" input field + b.append(sp(in) + "\n"); + // "Configuration attribute's value" input field + b.append(sp(in) + "\n"); + // "Show configuration properties" input field + b.append(sp(in) + "\n"); + // "Show activators" input field + b.append(sp(in) + "\n"); - // =============================================================== - // Close the form - // =============================================================== - b.append(sp(--in) + "
\n"); - } + // =============================================================== + // Close the form + // =============================================================== + b.append(sp(--in) + "\n"); + } - return b.toString(); - } + return b.toString(); + } - /** - * Creates a set of table rows populated with the plug-in properties and - * activators, as found in the given PluginInfo object - * - * @param pluginInfo the plug-in's PluginInfo object - * @param showProperties display flag - * @param showActivators display flag - * @param in indentation value for the generated HTML content - * - * @return The table as HTML presentation. - */ - private static String renderPluginAttributes( - PluginInfo pluginInfo, - boolean showProperties, - boolean showActivators, - long in) { - // Stores the assembled HTML content - StringBuilder b = new StringBuilder(); - // List the metric plug-in's configuration properties - if (showProperties) { - Set l = - pluginInfo.getConfiguration(); - // Skip if this plug-ins has no configuration - if ((l != null) && (l.isEmpty() == false)) { - for (PluginConfiguration property : l) { - b.append(sp(in++) + ""); - b.append(sp(in) + " \n"); - b.append(sp(in) + "" - + "Property: " + property.getName() - + " Type: " + property.getType() - + " Value: " + property.getValue() - + "\n"); - b.append(sp(--in)+ "\n"); - } - } - } - // List the metric plug-in's activator types - if (showActivators) { - Set> activators = - pluginInfo.getActivationTypes(); - // Skip if this plug-ins has no activators - if (activators != null) { - for (Class activator : activators) { - b.append(""); - b.append(" \n"); - b.append("" - + "Activator: " - + activator.getName() - + ""); - b.append("\n"); - } - } - } - return b.toString(); - } + /** + * Creates a set of table rows populated with the plug-in properties and + * activators, as found in the given PluginInfo object + * + * @param pluginInfo + * the plug-in's PluginInfo object + * @param showProperties + * display flag + * @param showActivators + * display flag + * @param in + * indentation value for the generated HTML content + * + * @return The table as HTML presentation. + */ + private static String renderPluginAttributes(PluginInfo pluginInfo, + boolean showProperties, boolean showActivators, long in) { + // Stores the assembled HTML content + StringBuilder b = new StringBuilder(); + // List the metric plug-in's configuration properties + if (showProperties) { + Set l = pluginInfo.getConfiguration(); + // Skip if this plug-ins has no configuration + if ((l != null) && (l.isEmpty() == false)) { + for (PluginConfiguration property : l) { + b.append(sp(in++) + ""); + b.append(sp(in) + " \n"); + b.append(sp(in) + "" + + "Property: " + property.getName() + + " Type: " + property.getType() + + " Value: " + property.getValue() + + "\n"); + b.append(sp(--in) + "\n"); + } + } + } + // List the metric plug-in's activator types + if (showActivators) { + Set> activators = pluginInfo + .getActivationTypes(); + // Skip if this plug-ins has no activators + if (activators != null) { + for (Class activator : activators) { + b.append(""); + b.append(" \n"); + b.append("" + + "Activator: " + activator.getName() + + ""); + b.append("\n"); + } + } + } + return b.toString(); + } } -//vi: ai nosi sw=4 ts=4 expandtab +// vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/ProjectDeleteJob.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/ProjectDeleteJob.java index dcdda445d..fea0edd6a 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/ProjectDeleteJob.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/ProjectDeleteJob.java @@ -43,6 +43,7 @@ import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.db.StoredProject; import eu.sqooss.service.db.StoredProjectConfig; +import eu.sqooss.service.db.Version; import eu.sqooss.service.scheduler.Job; public class ProjectDeleteJob extends Job { @@ -91,14 +92,14 @@ protected void run() throws Exception { boolean success = true; // Delete project version's parents. - List versions = sp.getProjectVersions(); + List versions = sp.getProjectVersions(); - for (ProjectVersion pv : versions) { + for (Version pv : versions) { /* Set parents = pv.getParents(); for (ProjectVersionParent pvp : parents) { }*/ - pv.getParents().clear(); + pv.clearParents(); } //Delete the project's config options diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/ProjectsView.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/ProjectsView.java index 2975b36d6..fb7406a7a 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/ProjectsView.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/ProjectsView.java @@ -33,14 +33,22 @@ package eu.sqooss.impl.service.webadmin; +import java.io.IOException; +import java.io.StringWriter; +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; - import javax.servlet.http.HttpServletRequest; +import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.exception.MethodInvocationException; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; import org.osgi.framework.BundleContext; import eu.sqooss.core.AlitheiaCore; @@ -52,140 +60,164 @@ import eu.sqooss.service.db.Bug; import eu.sqooss.service.db.ClusterNode; import eu.sqooss.service.db.MailMessage; +import eu.sqooss.service.db.Project; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.db.StoredProject; import eu.sqooss.service.pa.PluginInfo; import eu.sqooss.service.scheduler.SchedulerException; -import eu.sqooss.service.updater.Updater; import eu.sqooss.service.updater.UpdaterService.UpdaterStage; public class ProjectsView extends AbstractView { - // Script for submitting this page - private static String SUBMIT = "document.projects.submit();"; - - // Action parameter's values - private static String ACT_REQ_ADD_PROJECT = "reqAddProject"; - private static String ACT_CON_ADD_PROJECT = "conAddProject"; - private static String ACT_REQ_REM_PROJECT = "reqRemProject"; - private static String ACT_CON_REM_PROJECT = "conRemProject"; - private static String ACT_REQ_SHOW_PROJECT = "conShowProject"; - private static String ACT_CON_UPD_ALL = "conUpdateAll"; - private static String ACT_CON_UPD = "conUpdate"; - private static String ACT_CON_UPD_ALL_NODE = "conUpdateAllOnNode"; - - // Servlet parameters - private static String REQ_PAR_ACTION = "reqAction"; - private static String REQ_PAR_PROJECT_ID = "projectId"; - private static String REQ_PAR_PRJ_NAME = "projectName"; - private static String REQ_PAR_PRJ_WEB = "projectHomepage"; - private static String REQ_PAR_PRJ_CONT = "projectContact"; - private static String REQ_PAR_PRJ_BUG = "projectBL"; - private static String REQ_PAR_PRJ_MAIL = "projectML"; - private static String REQ_PAR_PRJ_CODE = "projectSCM"; - private static String REQ_PAR_SYNC_PLUGIN = "reqParSyncPlugin"; - private static String REQ_PAR_UPD = "reqUpd"; - - /** - * Instantiates a new projects view. - * - * @param bundlecontext the BundleContext object - * @param vc the VelocityContext object - */ - public ProjectsView(BundleContext bundlecontext, VelocityContext vc) { - super(bundlecontext, vc); - } - - /** - * Renders the various project's views. - * - * @param req the servlet's request object - * - * @return The HTML presentation of the generated view. - */ - public static String render(HttpServletRequest req) { - // Stores the assembled HTML content - StringBuilder b = new StringBuilder("\n"); - // Stores the accumulated error messages - StringBuilder e = new StringBuilder(); - // Indentation spacer - int in = 6; - - // Initialize the resource bundles with the request's locale - initResources(req.getLocale()); - - // Request values - String reqValAction = ""; - Long reqValProjectId = null; - - // Selected project - StoredProject selProject = null; - - // =============================================================== - // Parse the servlet's request object - // =============================================================== - if (req != null) { - // DEBUG: Dump the servlet's request parameter - if (DEBUG) { - b.append(debugRequest(req)); - } - - // Retrieve the selected editor's action (if any) - reqValAction = req.getParameter(REQ_PAR_ACTION); - - // Retrieve the selected project's DAO (if any) - reqValProjectId = fromString(req.getParameter(REQ_PAR_PROJECT_ID)); - if (reqValProjectId != null) { - selProject = sobjDB.findObjectById( - StoredProject.class, reqValProjectId); - } - - if (reqValAction == null) { - reqValAction = ""; - } else if (reqValAction.equals(ACT_CON_ADD_PROJECT)) { - selProject = addProject(e, req, in); - } else if (reqValAction.equals(ACT_CON_REM_PROJECT)) { - selProject = removeProject(e, selProject, in); - } else if (reqValAction.equals(ACT_CON_UPD)) { - triggerUpdate(e, selProject, in, req.getParameter(REQ_PAR_UPD)); - } else if (reqValAction.equals(ACT_CON_UPD_ALL)) { - triggerAllUpdate(e, selProject, in); - } else if (reqValAction.equals(ACT_CON_UPD_ALL_NODE)) { - triggerAllUpdateNode(e, selProject, in); - } else { - // Retrieve the selected plug-in's hash-code - String reqValSyncPlugin = req.getParameter(REQ_PAR_SYNC_PLUGIN); - syncPlugin(e, selProject, reqValSyncPlugin); - } - } - createFrom(b, e, selProject, reqValAction , in); - return b.toString(); - } - - private static StoredProject addProject(StringBuilder e, HttpServletRequest r, int indent) { - AdminService as = AlitheiaCore.getInstance().getAdminService(); - AdminAction aa = as.create(AddProject.MNEMONIC); - aa.addArg("scm", r.getParameter(REQ_PAR_PRJ_CODE)); - aa.addArg("name", r.getParameter(REQ_PAR_PRJ_NAME)); - aa.addArg("bts", r.getParameter(REQ_PAR_PRJ_BUG)); - aa.addArg("mail", r.getParameter(REQ_PAR_PRJ_MAIL)); - aa.addArg("web", r.getParameter(REQ_PAR_PRJ_WEB)); - as.execute(aa); - - if (aa.hasErrors()) { - vc.put("RESULTS", aa.errors()); - return null; - } else { - vc.put("RESULTS", aa.results()); - return StoredProject.getProjectByName(r.getParameter(REQ_PAR_PRJ_NAME)); - } - } - - // --------------------------------------------------------------- - // Remove project - // --------------------------------------------------------------- - private static StoredProject removeProject(StringBuilder e, - StoredProject selProject, int indent) { - if (selProject != null) { + // Script for submitting this page + private static String SUBMIT = "document.projects.submit();"; + + // Action parameter's values + private static String ACT_REQ_ADD_PROJECT = "reqAddProject"; + private static String ACT_CON_ADD_PROJECT = "conAddProject"; + private static String ACT_REQ_REM_PROJECT = "reqRemProject"; + private static String ACT_CON_REM_PROJECT = "conRemProject"; + private static String ACT_REQ_SHOW_PROJECT = "conShowProject"; + private static String ACT_CON_UPD_ALL = "conUpdateAll"; + private static String ACT_CON_UPD = "conUpdate"; + private static String ACT_CON_UPD_ALL_NODE = "conUpdateAllOnNode"; + + // Servlet parameters + private static String REQ_PAR_ACTION = "reqAction"; + private static String REQ_PAR_PROJECT_ID = "projectId"; + private static String REQ_PAR_PRJ_NAME = "projectName"; + private static String REQ_PAR_PRJ_WEB = "projectHomepage"; + private static String REQ_PAR_PRJ_CONT = "projectContact"; + private static String REQ_PAR_PRJ_BUG = "projectBL"; + private static String REQ_PAR_PRJ_MAIL = "projectML"; + private static String REQ_PAR_PRJ_CODE = "projectSCM"; + private static String REQ_PAR_SYNC_PLUGIN = "reqParSyncPlugin"; + private static String REQ_PAR_UPD = "reqUpd"; + + /** + * Instantiates a new projects view. + * + * @param bundlecontext + * the BundleContext object + * @param vc + * the VelocityContext object + */ + public ProjectsView(BundleContext bundlecontext, VelocityContext vc, + VelocityEngine ve) { + super(bundlecontext, vc, ve); + + vc.put("SUBMIT", SUBMIT); + + // Action parameter's values + vc.put("ACT_REQ_ADD_PROJECT", ACT_REQ_ADD_PROJECT); + vc.put("ACT_CON_ADD_PROJECT", ACT_CON_ADD_PROJECT); + vc.put("ACT_REQ_REM_PROJECT", ACT_REQ_REM_PROJECT); + vc.put("ACT_CON_REM_PROJECT", ACT_CON_REM_PROJECT); + vc.put("ACT_REQ_SHOW_PROJECT", ACT_REQ_SHOW_PROJECT); + vc.put("ACT_CON_UPD_ALL", ACT_CON_UPD_ALL); + vc.put("ACT_CON_UPD", ACT_CON_UPD); + vc.put("ACT_CON_UPD_ALL_NODE", ACT_CON_UPD_ALL_NODE); + + // Servlet parameters + vc.put("REQ_PAR_ACTION", REQ_PAR_ACTION); + vc.put("REQ_PAR_PROJECT_ID", REQ_PAR_PROJECT_ID); + vc.put("REQ_PAR_PRJ_NAME", REQ_PAR_PRJ_NAME); + vc.put("REQ_PAR_PRJ_WEB", REQ_PAR_PRJ_WEB); + vc.put("REQ_PAR_PRJ_CONT", REQ_PAR_PRJ_CONT); + vc.put("REQ_PAR_PRJ_BUG", REQ_PAR_PRJ_BUG); + vc.put("REQ_PAR_PRJ_MAIL", REQ_PAR_PRJ_MAIL); + vc.put("REQ_PAR_PRJ_CODE", REQ_PAR_PRJ_CODE); + vc.put("REQ_PAR_SYNC_PLUGIN", REQ_PAR_SYNC_PLUGIN); + vc.put("REQ_PAR_UPD", REQ_PAR_UPD); + } + + /** + * Renders the various project's views. + * + * @param req + * the servlet's request object + * + * @return The HTML presentation of the generated view. + */ + public static String render(HttpServletRequest req) { + // Stores the accumulated error messages + StringBuilder e = new StringBuilder(); + // Indentation spacer + int in = 6; + + // Initialize the resource bundles with the request's locale + initResources(req.getLocale()); + + // Request values + String reqValAction = ""; + Long reqValProjectId = null; + + // Selected project + StoredProject selProject = null; + + // =============================================================== + // Parse the servlet's request object + // =============================================================== + if (req != null) { + + // Retrieve the selected editor's action (if any) + reqValAction = req.getParameter(REQ_PAR_ACTION); + + // Retrieve the selected project's DAO (if any) + reqValProjectId = fromString(req.getParameter(REQ_PAR_PROJECT_ID)); + if (reqValProjectId != null) { + selProject = sobjDB.findObjectById(StoredProject.class, + reqValProjectId); + } + + if (reqValAction == null) { + reqValAction = ""; + } else if (reqValAction.equals(ACT_CON_ADD_PROJECT)) { + selProject = addProject(e, req, in); + } else if (reqValAction.equals(ACT_CON_REM_PROJECT)) { + selProject = removeProject(e, selProject, in); + } else if (reqValAction.equals(ACT_CON_UPD)) { + triggerUpdate(e, selProject, in, req.getParameter(REQ_PAR_UPD)); + } else if (reqValAction.equals(ACT_CON_UPD_ALL)) { + triggerAllUpdate(e, selProject, in); + } else if (reqValAction.equals(ACT_CON_UPD_ALL_NODE)) { + triggerAllUpdateNode(e, selProject, in); + } else { + // Retrieve the selected plug-in's hash-code + String reqValSyncPlugin = req.getParameter(REQ_PAR_SYNC_PLUGIN); + syncPlugin(e, selProject, reqValSyncPlugin); + } + } + String html = createFrom(e, selProject, reqValAction, in); + return html; + } + + private static StoredProject addProject(StringBuilder e, + HttpServletRequest r, int indent) { + AdminService as = AlitheiaCore.getInstance().getAdminService(); + AdminAction aa = as.create(AddProject.MNEMONIC); + aa.addArg("scm", r.getParameter(REQ_PAR_PRJ_CODE)); + aa.addArg("name", r.getParameter(REQ_PAR_PRJ_NAME)); + aa.addArg("bts", r.getParameter(REQ_PAR_PRJ_BUG)); + aa.addArg("mail", r.getParameter(REQ_PAR_PRJ_MAIL)); + aa.addArg("web", r.getParameter(REQ_PAR_PRJ_WEB)); + as.execute(aa); + + if (aa.hasErrors()) { + vc.put("RESULTS", aa.errors()); + return null; + } else { + vc.put("RESULTS", aa.results()); + return StoredProject.getProjectByName(r + .getParameter(REQ_PAR_PRJ_NAME)); + } + } + + // --------------------------------------------------------------- + // Remove project + // --------------------------------------------------------------- + private static StoredProject removeProject(StringBuilder e, + StoredProject selProject, int indent) { + if (selProject != null) { // Deleting large projects in the foreground is // very slow ProjectDeleteJob pdj = new ProjectDeleteJob(sobjCore, selProject); @@ -198,8 +230,8 @@ private static StoredProject removeProject(StringBuilder e, } else { e.append(sp(indent) + getErr("e0034") + "
\n"); } - return selProject; - } + return selProject; + } // --------------------------------------------------------------- // Trigger an update @@ -213,45 +245,46 @@ private static void triggerUpdate(StringBuilder e, as.execute(aa); if (aa.hasErrors()) { - vc.put("RESULTS", aa.errors()); - } else { - vc.put("RESULTS", aa.results()); - } + vc.put("RESULTS", aa.errors()); + } else { + vc.put("RESULTS", aa.results()); + } } // --------------------------------------------------------------- // Trigger update on all resources for that project // --------------------------------------------------------------- - private static void triggerAllUpdate(StringBuilder e, - StoredProject selProject, int indent) { - AdminService as = AlitheiaCore.getInstance().getAdminService(); - AdminAction aa = as.create(UpdateProject.MNEMONIC); - aa.addArg("project", selProject.getId()); - as.execute(aa); - - if (aa.hasErrors()) { - vc.put("RESULTS", aa.errors()); - } else { - vc.put("RESULTS", aa.results()); - } + private static void triggerAllUpdate(StringBuilder e, Project selProject, + int indent) { + AdminService as = AlitheiaCore.getInstance().getAdminService(); + AdminAction aa = as.create(UpdateProject.MNEMONIC); + aa.addArg("project", selProject.getId()); + as.execute(aa); + + if (aa.hasErrors()) { + vc.put("RESULTS", aa.errors()); + } else { + vc.put("RESULTS", aa.results()); + } } - + // --------------------------------------------------------------- // Trigger update on all resources on all projects of a node // --------------------------------------------------------------- - private static void triggerAllUpdateNode(StringBuilder e, - StoredProject selProject, int in) { - Set projectList = ClusterNode.thisNode().getProjects(); - - for (StoredProject project : projectList) { + private static void triggerAllUpdateNode(StringBuilder e, + Project selProject, int in) { + Set projectList = ClusterNode.thisNode().getProjects(); + + for (Project project : projectList) { triggerAllUpdate(e, project, in); } } - + // --------------------------------------------------------------- // Trigger synchronize on the selected plug-in for that project // --------------------------------------------------------------- - private static void syncPlugin(StringBuilder e, StoredProject selProject, String reqValSyncPlugin) { + private static void syncPlugin(StringBuilder e, StoredProject selProject, + String reqValSyncPlugin) { if ((reqValSyncPlugin != null) && (selProject != null)) { PluginInfo pInfo = sobjPA.getPluginInfo(reqValSyncPlugin); if (pInfo != null) { @@ -263,414 +296,229 @@ private static void syncPlugin(StringBuilder e, StoredProject selProject, String } } } - } - - private static void createFrom(StringBuilder b, StringBuilder e, - StoredProject selProject, String reqValAction, int in) { - - // =============================================================== - // Create the form - // =============================================================== - b.append(sp(in) + "
\n"); - - // =============================================================== - // Display the accumulated error messages (if any) - // =============================================================== - b.append(errorFieldset(e, ++in)); - - // Get the complete list of projects stored in the SQO-OSS framework - Set projects = ClusterNode.thisNode().getProjects(); - Collection metrics = sobjPA.listPlugins(); - - // =================================================================== - // "Show project info" view - // =================================================================== - if ((reqValAction.equals(ACT_REQ_SHOW_PROJECT)) - && (selProject != null)) { - // Create the field-set - b.append(sp(in++) + "
\n"); - b.append(sp(in) + "" - + "Project information" - + "\n"); - b.append(sp(in++) + "\n"); - // Create the input fields - b.append(normalInfoRow( - "Project name", selProject.getName(), in)); - b.append(normalInfoRow( - "Homepage", selProject.getWebsiteUrl(), in)); - b.append(normalInfoRow( - "Contact e-mail", selProject.getContactUrl(), in)); - b.append(normalInfoRow( - "Bug database", selProject.getBtsUrl(), in)); - b.append(normalInfoRow( - "Mailing list", selProject.getMailUrl(), in)); - b.append(normalInfoRow( - "Source code", selProject.getScmUrl(), in)); - - //------------------------------------------------------------ - // Tool-bar - //------------------------------------------------------------ - b.append(sp(in++) + "\n"); - b.append(sp(in++) - + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "
\n"); - // Back button - b.append(sp(in) + "\n"); - b.append(sp(--in) + "
\n"); - b.append(sp(--in) + "
\n"); - } - // =================================================================== - // "Add project" editor - // =================================================================== - else if (reqValAction.equals(ACT_REQ_ADD_PROJECT)) { - // Create the field-set - b.append(sp(in++) + "\n"); - // Create the input fields - b.append(normalInputRow( - "Project name", REQ_PAR_PRJ_NAME, "", in)); - b.append(normalInputRow( - "Homepage", REQ_PAR_PRJ_WEB, "", in)); - b.append(normalInputRow( - "Contact e-mail", REQ_PAR_PRJ_CONT, "", in)); - b.append(normalInputRow( - "Bug database", REQ_PAR_PRJ_BUG, "", in)); - b.append(normalInputRow( - "Mailing list", REQ_PAR_PRJ_MAIL, "", in)); - b.append(normalInputRow( - "Source code", REQ_PAR_PRJ_CODE, "", in)); - - //------------------------------------------------------------ - // Tool-bar - //------------------------------------------------------------ - b.append(sp(in++) + "\n"); - b.append(sp(in++) - + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "
\n"); - // Apply button - b.append(sp(in) + "\n"); - // Cancel button - b.append(sp(in) + "\n"); - b.append(sp(--in) + "
\n"); - } - // =================================================================== - // "Delete project" confirmation view - // =================================================================== - else if ((reqValAction.equals(ACT_REQ_REM_PROJECT)) - && (selProject != null)) { - b.append(sp(in++) + "
\n"); - b.append(sp(in) + "" + getLbl("l0059") - + ": " + selProject.getName() - + "\n"); - b.append(sp(in++) + ""); - // Confirmation message - b.append(sp(in++) + "\n"); - b.append(sp(in) + "\n"); - - b.append(sp(--in) + "\n"); - //------------------------------------------------------------ - // Tool-bar - //------------------------------------------------------------ - b.append(sp(in++) + "\n"); - b.append(sp(in++) - + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "
" - + "" + getMsg("delete_project") + "" - + "
\n"); - // Confirm button - b.append(sp(in) + "\n"); - // Cancel button - b.append(sp(in) + "\n"); - b.append(sp(--in) + "
"); - b.append(sp(in) + "
\n"); - } - // =================================================================== - // Projects list view - // =================================================================== - else { - addHeaderRow(b,in); - - if (projects.isEmpty()) { - b.append(sp(in++) + "\n"); - b.append(sp(in) + "\n" - + getMsg("no_projects") - + "\n"); - b.append(sp(--in) + "\n"); - } - else { - //------------------------------------------------------------ - // Create the content rows - //------------------------------------------------------------ - b.append(sp(in++) + "\n"); - for (StoredProject nextPrj : projects) { - boolean selected = false; - if ((selProject != null) - && (selProject.getId() == nextPrj.getId())) { - selected = true; - } - b.append(sp(in++) + "\n"); - // Project Id - b.append(sp(in) + "" - + nextPrj.getId() - + "\n"); - // Project name - b.append(sp(in) + "" - + ((selected) - ? "" - : "\"[Edit]\"/") - + " " - + nextPrj.getName() - + "\n"); - // Last project version - String lastVersion = getLbl("l0051"); - ProjectVersion v = ProjectVersion.getLastProjectVersion(nextPrj); - if (v != null) { - lastVersion = String.valueOf(v.getSequence()) + "(" + v.getRevisionId() + ")"; - } - b.append(sp(in) + "" - + lastVersion - + "\n"); - // Date of the last known email - MailMessage mm = MailMessage.getLatestMailMessage(nextPrj); - b.append(sp(in) + "" - + ((mm == null)?getLbl("l0051"):mm.getSendDate()) - + "\n"); - // ID of the last known bug entry - Bug bug = Bug.getLastUpdate(nextPrj); - b.append(sp(in) + "" - + ((bug == null)?getLbl("l0051"):bug.getBugID()) - + "\n"); - // Evaluation state - String evalState = getLbl("project_not_evaluated"); - if (nextPrj.isEvaluated()) { - evalState = getLbl("project_is_evaluated"); - } - b.append(sp(in) + "" - + evalState - + "\n"); - - // Cluster node - String nodename = null; - if (null != nextPrj.getClusternode()) { - nodename = nextPrj.getClusternode().getName(); - } else { - nodename = "(local)"; - } - b.append(sp(in) + "" + nodename + "\n"); - b.append(sp(--in) + "\n"); - if ((selected) && (metrics.isEmpty() == false)) { - showLastAppliedVersion(nextPrj, metrics, b); - } - } - } - //---------------------------------------------------------------- - // Tool-bar - //---------------------------------------------------------------- - addToolBar(selProject,b,in); - - //---------------------------------------------------------------- - // Close the table - //---------------------------------------------------------------- - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - } - - // =============================================================== - // INPUT FIELDS - // =============================================================== - addHiddenFields(selProject,b,in); - - // =============================================================== - // Close the form - // =============================================================== - b.append(sp(--in) + "\n"); - } - - - private static void addHiddenFields(StoredProject selProject, - StringBuilder b, - long in) { - // "Action type" input field - b.append(sp(in) + "\n"); - // "Project Id" input field - b.append(sp(in) + "\n"); - // "Plug-in hashcode" input field - b.append(sp(in) + "\n"); - } - - private static void addToolBar(StoredProject selProject, - StringBuilder b, - long in) { - b.append(sp(in++) + "\n"); - b.append(sp(in++) + "View\n"); - // Refresh button - b.append(sp(in) + ""); - b.append("Manage\n"); - // Add project button - b.append(sp(in) + "\n"); - // Remove project button - b.append(sp(in) + ""); - b.append("Update\n"); - - if (selProject != null) { - b.append(sp(in) + ""); - } - - // Trigger updater - b.append(sp(in) + "\n"); - // Trigger all updates - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - // Trigger updates on host - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - } - - private static void showLastAppliedVersion( - StoredProject project, - Collection metrics, - StringBuilder b) { - for(PluginInfo m : metrics) { - if (m.installed) { - b.append("\n"); - b.append(sp(1) + "\n" - + "" - + " " - + m.getPluginName() - + "\n"); - b.append("\n"); - } - } - } - - private static void addHeaderRow(StringBuilder b, long in) { - //---------------------------------------------------------------- - // Create the header row - //---------------------------------------------------------------- - b.append(sp(in++) + "\n"); - b.append(sp(in++) + "\n"); - b.append(sp(in++) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(in) + "\n"); - b.append(sp(--in) + "\n"); - b.append(sp(--in) + "\n"); - } + } + + private static String createFrom(StringBuilder e, StoredProject selProject, + String reqValAction, int in) { + + VelocityContext vc = AbstractView.vc; + Template t = null; + try { + t = ve.getTemplate("projects-view.html"); + } catch (Exception e2) { + // TODO Auto-generated catch block + e2.printStackTrace(); + } + + // =============================================================== + // Create the form + // =============================================================== + vc.put("form_id", "projects"); + vc.put("form_name", "projects"); + vc.put("form_method", "post"); + vc.put("form_action", "/projects"); + + // =============================================================== + // Display the accumulated error messages (if any) + // =============================================================== + // Get the complete list of projects stored in the SQO-OSS framework + Set projects = ClusterNode.thisNode().getProjects(); + Collection metrics = sobjPA.listPlugins(); + + vc.put("reqValAction", reqValAction); + vc.put("selProject", selProject); + vc.put("metrics", metrics); + + // =================================================================== + // "Show project info" view + // =================================================================== + if ((reqValAction.equals(ACT_REQ_SHOW_PROJECT)) && (selProject != null)) { + Map tableRows = new HashMap<>(); + tableRows.put("Project name", selProject.getName()); + tableRows.put("Homepage", selProject.getWebsiteUrl()); + tableRows.put("Contact e-mail", selProject.getContactUrl()); + tableRows.put("Bug database", selProject.getBtsUrl()); + tableRows.put("Mailing list", selProject.getMailUrl()); + tableRows.put("Source code", selProject.getScmUrl()); + vc.put("tableRows", tableRows); + + // ------------------------------------------------------------ + // Tool-bar + // ------------------------------------------------------------ + vc.put("toolbar_button_value", getLbl("btn_back")); + vc.put("toolbar_button_onclick", SUBMIT); + } + // =================================================================== + // "Add project" editor + // =================================================================== + else if (reqValAction.equals(ACT_REQ_ADD_PROJECT)) { + Map normalInputRows = new HashMap<>(); + normalInputRows.put("Project name", REQ_PAR_PRJ_NAME); + normalInputRows.put("Homepage", REQ_PAR_PRJ_WEB); + normalInputRows.put("Contact e-mail", REQ_PAR_PRJ_CONT); + normalInputRows.put("Bug database", REQ_PAR_PRJ_BUG); + normalInputRows.put("Mailing list", REQ_PAR_PRJ_MAIL); + normalInputRows.put("Source code", REQ_PAR_PRJ_CODE); + vc.put("normalInputRows", normalInputRows); + + // ------------------------------------------------------------ + // Tool-bar + // ------------------------------------------------------------ + vc.put("req-add-project-add-button-value", getLbl("project_add")); + } + // =================================================================== + // "Delete project" confirmation view + // =================================================================== + else if ((reqValAction.equals(ACT_REQ_REM_PROJECT)) + && (selProject != null)) { + vc.put("req-rem-project-legend-label", getLbl("l0059")); + vc.put("req-rem-project-delete-project-message", + getMsg("delete_project")); + + // ------------------------------------------------------------ + // Tool-bar + // ------------------------------------------------------------ + vc.put("req-rem-project-button-value", getLbl("l0006")); + vc.put("req-rem-project-cancel-button-value", getLbl("l0004")); + + } + // =================================================================== + // Projects list view + // =================================================================== + else { + vc.put("default-table-header-1", getLbl("l0066")); + vc.put("default-table-header-2", getLbl("l0067")); + vc.put("default-table-header-3", getLbl("l0068")); + vc.put("default-table-header-4", getLbl("l0069")); + vc.put("default-table-header-5", getLbl("l0070")); + vc.put("default-table-header-6", getLbl("l0071")); + vc.put("default-table-header-7", getLbl("l0073")); + + vc.put("default-projects", projects); + vc.put("default-no-projects-message", getMsg("no_projects")); + + if (!projects.isEmpty()) { + // ------------------------------------------------------------ + // Create the content rows + // ------------------------------------------------------------ + for (Project nextPrj : projects) { + boolean selected = false; + if ((selProject != null) + && (selProject.getId() == nextPrj.getId())) { + selected = true; + } + + vc.put("default-selected-button-value", getLbl("btn_info")); + + // Last project version + String lastVersion = getLbl("l0051"); + ProjectVersion v = ProjectVersion + .getLastProjectVersion(nextPrj); + if (v != null) { + lastVersion = String.valueOf(v.getSequence()) + "(" + + v.getRevisionId() + ")"; + } + + vc.put("default-last-version-message", lastVersion); + + // Date of the last known email + MailMessage mm = MailMessage.getLatestMailMessage(nextPrj); + String lastMailMessage = (String) ((mm == null) ? getLbl("l0051") + : mm.getSendDate().toString()); + + vc.put("default-last-mail-message", lastMailMessage); + + // ID of the last known bug entry + Bug bug = Bug.getLastUpdate(nextPrj); + + String lastBugEntry = ((bug == null) ? getLbl("l0051") + : bug.getBugID()); + vc.put("default-last-bug-entry", lastBugEntry); + + // Evaluation state + String evalState = getLbl("project_not_evaluated"); + if (nextPrj.isEvaluated()) { + evalState = getLbl("project_is_evaluated"); + } + + String evaluationState = evalState; + vc.put("default-evaluation-state", evaluationState); + + // Cluster node + String nodename = null; + if (null != nextPrj.getClusternode()) { + nodename = nextPrj.getClusternode().getName(); + } else { + nodename = "(local)"; + } + + vc.put("default-cluster-node", nodename); + + if ((selected) && (metrics.isEmpty() == false)) { + showLastAppliedVersion(nextPrj, metrics, vc); + } + } + } + // ---------------------------------------------------------------- + // Tool-bar + // ---------------------------------------------------------------- + addToolBar(selProject, in, vc); + } + + StringWriter writer = new StringWriter(); + try { + t.merge(vc, writer); + } catch (ResourceNotFoundException | ParseErrorException + | MethodInvocationException | IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + int index = writer.toString().indexOf("$"); + if (index >= 0) { + System.out.println("Warning, $ found at index " + index + "."); + } + return writer.toString(); + } + + private static void addToolBar(StoredProject selProject, long in, + VelocityContext vc) { + vc.put("toolbar-button-value", getLbl("l0008")); + vc.put("toolbar-button-window-location", ((selProject != null) ? "?" + + REQ_PAR_PROJECT_ID + "=" + selProject.getId() : "")); + vc.put("toolbar-act-req-add-button-value", getLbl("add_project")); + vc.put("toolbar-act-req-rem-button-value", getLbl("l0059")); + vc.put("toolbar-button-disable", ((selProject != null) ? "" + : " disabled")); + + vc.put("toolbar-select-disable", ((selProject != null) ? "" + : " disabled=\"disabled\"")); + + if (selProject != null) { + vc.put("toolbar-updaters-import", + sobjUpdater.getUpdaters(selProject, UpdaterStage.IMPORT)); + vc.put("toolbar-updaters-parse", + sobjUpdater.getUpdaters(selProject, UpdaterStage.PARSE)); + vc.put("toolbar-updaters-inference", + sobjUpdater.getUpdaters(selProject, UpdaterStage.INFERENCE)); + vc.put("toolbar-updaters-default", + sobjUpdater.getUpdaters(selProject, UpdaterStage.DEFAULT)); + } + + vc.put("sobjClusterNode", sobjClusterNode); + } + + private static void showLastAppliedVersion(Project project, + Collection metrics, VelocityContext vc) { + List installedMetrics = new ArrayList<>(); + vc.put("default-installed-metrics", installedMetrics); + + for (PluginInfo m : metrics) { + if (m.installed) { + installedMetrics.add(m); + } + } + } } // vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/WebAdminRenderer.java b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/WebAdminRenderer.java index 9c5a1daea..a364e83ad 100644 --- a/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/WebAdminRenderer.java +++ b/alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/WebAdminRenderer.java @@ -44,224 +44,221 @@ import eu.sqooss.service.util.StringUtils; /** - * The WebAdminRender class provides functions for rendering content - * to be displayed within the WebAdmin interface. + * The WebAdminRender class provides functions for rendering content to be + * displayed within the WebAdmin interface. * * @author, Paul J. Adams * @author, Boryan Yotov */ -public class WebAdminRenderer extends AbstractView { - /** - * Represents the system time at which the WebAdminRender (and - * thus the system) was started. This is required for the system - * uptime display. - */ - private static long startTime = new Date().getTime(); +public class WebAdminRenderer extends AbstractView { + /** + * Represents the system time at which the WebAdminRender (and thus the + * system) was started. This is required for the system uptime display. + */ + private static long startTime = new Date().getTime(); - public WebAdminRenderer(BundleContext bundlecontext, VelocityContext vc) { - super(bundlecontext, vc); - } + public WebAdminRenderer(BundleContext bundlecontext, VelocityContext vc) { + super(bundlecontext, vc, ve); + } - /** - * Creates and HTML table displaying the details of all the jobs - * that have failed whilst the system has been up - * - * @return a String representing the HTML table - */ - public static String renderJobFailStats() { - StringBuilder result = new StringBuilder(); - HashMap fjobs = sobjSched.getSchedulerStats().getFailedJobTypes(); - result.append("
" - + getLbl("l0066") - + "" - + getLbl("l0067") - + "" - + getLbl("l0068") - + "" - + getLbl("l0069") - + "" - + getLbl("l0070") - + "" - + getLbl("l0071") - + "" - + getLbl("l0073") - + "
\n"); - result.append("\t\n"); - result.append("\t\t\n"); - result.append("\t\t\t\n"); - result.append("\t\t\t\n"); - result.append("\t\t\n"); - result.append("\t\n"); - result.append("\t\n"); + /** + * Creates and HTML table displaying the details of all the jobs that have + * failed whilst the system has been up + * + * @return a String representing the HTML table + */ + public static String renderJobFailStats() { + StringBuilder result = new StringBuilder(); + HashMap fjobs = sobjSched.getSchedulerStats() + .getFailedJobTypes(); + result.append("
Job TypeNum Jobs Failed
\n"); + result.append("\t\n"); + result.append("\t\t\n"); + result.append("\t\t\t\n"); + result.append("\t\t\t\n"); + result.append("\t\t\n"); + result.append("\t\n"); + result.append("\t\n"); - String[] jobfailures = fjobs.keySet().toArray(new String[1]); - for(String key : jobfailures) { - result.append("\t\t\n\t\t\t\n\t\t\t\n\t\t"); - } - result.append("\t\n"); - result.append("
Job TypeNum Jobs Failed
"); - result.append(key==null ? "No failures" : key); - result.append(""); - result.append(key==null ? " " : fjobs.get(key)); - result.append("\t\t\t
"); - return result.toString(); - } + String[] jobfailures = fjobs.keySet().toArray(new String[1]); + for (String key : jobfailures) { + result.append("\t\t\n\t\t\t"); + result.append(key == null ? "No failures" : key); + result.append("\n\t\t\t"); + result.append(key == null ? " " : fjobs.get(key)); + result.append("\t\t\t\n\t\t"); + } + result.append("\t\n"); + result.append(""); + return result.toString(); + } - /** - * Creates and HTML table with information about the jobs that - * failed and the recorded exceptions - * @return - */ - public static String renderFailedJobs() { - StringBuilder result = new StringBuilder(); - Job[] jobs = sobjSched.getFailedQueue(); - result.append("\n"); - result.append("\t\n"); - result.append("\t\t\n"); - result.append("\t\t\t\n"); - result.append("\t\t\t\n"); - result.append("\t\t\t\n"); - result.append("\t\t\t\n"); - result.append("\t\t\n"); - result.append("\t\n"); - result.append("\t\n"); + /** + * Creates and HTML table with information about the jobs that failed and + * the recorded exceptions + * + * @return + */ + public static String renderFailedJobs() { + StringBuilder result = new StringBuilder(); + Job[] jobs = sobjSched.getFailedQueue(); + result.append("
Job TypeException typeException textException backtrace
\n"); + result.append("\t\n"); + result.append("\t\t\n"); + result.append("\t\t\t\n"); + result.append("\t\t\t\n"); + result.append("\t\t\t\n"); + result.append("\t\t\t\n"); + result.append("\t\t\n"); + result.append("\t\n"); + result.append("\t\n"); - if ((jobs != null) && (jobs.length > 0)) { - for(Job j: jobs) { - if (j == null) continue; - result.append("\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t"); - } - } - else { - result.append (""); - } - result.append("\t\n"); - result.append("
Job TypeException typeException textException backtrace
"); - if (j.getClass() != null) { - try { - //result.append(j.getClass().getPackage().getName()); - //result.append(". " + j.getClass().getSimpleName()); - result.append(j.toString()); - } - catch (NullPointerException ex) { - result.append("NA"); - } - } - else { - result.append("NA"); - } - result.append(""); - Exception e = j.getErrorException(); - if (e != null) { - try { - result.append(e.getClass().getPackage().getName()); - result.append(". " + e.getClass().getSimpleName()); - } - catch (NullPointerException ex) { - result.append("NA"); - } - } - else { - result.append("NA"); - } - result.append(""); - try { - result.append(e.getMessage()); - } - catch (NullPointerException ex) { - result.append("NA"); - } - result.append(""); - if ((e != null) - && (e.getStackTrace() != null)) { - for(StackTraceElement m: e.getStackTrace()) { - if (m == null) continue; - result.append(m.getClassName()); - result.append(". "); - result.append(m.getMethodName()); - result.append("(), ("); - result.append(m.getFileName()); - result.append(":"); - result.append(m.getLineNumber()); - result.append(")
"); - } - } - else { - result.append("NA"); - } - result.append("\t\t\t
No failed jobs.
"); + if ((jobs != null) && (jobs.length > 0)) { + for (Job j : jobs) { + if (j == null) + continue; + result.append("\t\t\n\t\t\t"); + if (j.getClass() != null) { + try { + // result.append(j.getClass().getPackage().getName()); + // result.append(". " + j.getClass().getSimpleName()); + result.append(j.toString()); + } catch (NullPointerException ex) { + result.append("NA"); + } + } else { + result.append("NA"); + } + result.append("\n\t\t\t"); + Exception e = j.getErrorException(); + if (e != null) { + try { + result.append(e.getClass().getPackage().getName()); + result.append(". " + e.getClass().getSimpleName()); + } catch (NullPointerException ex) { + result.append("NA"); + } + } else { + result.append("NA"); + } + result.append("\n\t\t\t"); + try { + result.append(e.getMessage()); + } catch (NullPointerException ex) { + result.append("NA"); + } + result.append("\n\t\t\t"); + if ((e != null) && (e.getStackTrace() != null)) { + for (StackTraceElement m : e.getStackTrace()) { + if (m == null) + continue; + result.append(m.getClassName()); + result.append(". "); + result.append(m.getMethodName()); + result.append("(), ("); + result.append(m.getFileName()); + result.append(":"); + result.append(m.getLineNumber()); + result.append(")
"); + } + } else { + result.append("NA"); + } + result.append("\t\t\t\n\t\t"); + } + } else { + result.append("No failed jobs."); + } + result.append("\t\n"); + result.append(""); - return result.toString(); - } + return result.toString(); + } - /** - * Creates an HTML unordered list displaying the contents of the current system log - * - * @return a String representing the HTML unordered list items - */ - public static String renderLogs() { - String[] names = sobjLogManager.getRecentEntries(); + /** + * Creates an HTML unordered list displaying the contents of the current + * system log + * + * @return a String representing the HTML unordered list items + */ + public static String renderLogs() { + String[] names = sobjLogManager.getRecentEntries(); - if ((names != null) && (names.length > 0)) { - StringBuilder b = new StringBuilder(); - for (String s : names) { - b.append("\t\t\t\t\t
  • " + StringUtils.makeXHTMLSafe(s) + "
  • \n"); - } + if ((names != null) && (names.length > 0)) { + StringBuilder b = new StringBuilder(); + for (String s : names) { + b.append("\t\t\t\t\t
  • " + StringUtils.makeXHTMLSafe(s) + + "
  • \n"); + } - return b.toString(); - } else { - return "\t\t\t\t\t
  • <none>
  • \n"; - } - } + return b.toString(); + } else { + return "\t\t\t\t\t
  • <none>
  • \n"; + } + } - /** - * Returns a string representing the uptime of the Alitheia core - * in dd:hh:mm:ss format - */ - public static String getUptime() { - long remainder; - long currentTime = new Date().getTime(); - long timeRunning = currentTime - startTime; + /** + * Returns a string representing the uptime of the Alitheia core in + * dd:hh:mm:ss format + */ + public static String getUptime() { + long remainder; + long currentTime = new Date().getTime(); + long timeRunning = currentTime - startTime; - // Get the elapsed time in days, hours, mins, secs - int days = new Long(timeRunning / 86400000).intValue(); - remainder = timeRunning % 86400000; - int hours = new Long(remainder / 3600000).intValue(); - remainder = remainder % 3600000; - int mins = new Long(remainder / 60000).intValue(); - remainder = remainder % 60000; - int secs = new Long(remainder / 1000).intValue(); + // Get the elapsed time in days, hours, mins, secs + int days = new Long(timeRunning / 86400000).intValue(); + remainder = timeRunning % 86400000; + int hours = new Long(remainder / 3600000).intValue(); + remainder = remainder % 3600000; + int mins = new Long(remainder / 60000).intValue(); + remainder = remainder % 60000; + int secs = new Long(remainder / 1000).intValue(); - return String.format("%d:%02d:%02d:%02d", days, hours, mins, secs); - } - + return String.format("%d:%02d:%02d:%02d", days, hours, mins, secs); + } - public static String renderJobWaitStats() { - StringBuilder result = new StringBuilder(); - HashMap wjobs = sobjSched.getSchedulerStats().getWaitingJobTypes(); - result.append("\n"); - result.append("\t\n"); - result.append("\t\t\n"); - result.append("\t\t\t\n"); - result.append("\t\t\t\n"); - result.append("\t\t\n"); - result.append("\t\n"); - result.append("\t\n"); + public static String renderJobWaitStats() { + StringBuilder result = new StringBuilder(); + HashMap wjobs = sobjSched.getSchedulerStats() + .getWaitingJobTypes(); + result.append("
    Job TypeNum Jobs Waiting
    \n"); + result.append("\t\n"); + result.append("\t\t\n"); + result.append("\t\t\t\n"); + result.append("\t\t\t\n"); + result.append("\t\t\n"); + result.append("\t\n"); + result.append("\t\n"); - String[] jobfailures = wjobs.keySet().toArray(new String[1]); - for(String key : jobfailures) { - result.append("\t\t\n\t\t\t\n\t\t\t\n\t\t"); - } - result.append("\t\n"); - result.append("
    Job TypeNum Jobs Waiting
    "); - result.append(key==null ? "No failures" : key); - result.append(""); - result.append(key==null ? " " : wjobs.get(key)); - result.append("\t\t\t
    "); - return result.toString(); - } + String[] jobfailures = wjobs.keySet().toArray(new String[1]); + for (String key : jobfailures) { + result.append("\t\t\n\t\t\t"); + result.append(key == null ? "No failures" : key); + result.append("\n\t\t\t"); + result.append(key == null ? " " : wjobs.get(key)); + result.append("\t\t\t\n\t\t"); + } + result.append("\t\n"); + result.append(""); + return result.toString(); + } - public static String renderJobRunStats() { - StringBuilder result = new StringBuilder(); - List rjobs = sobjSched.getSchedulerStats().getRunJobs(); - if (rjobs.size() == 0) { - return "No running jobs"; - } - result.append("
      \n"); - for(String s : rjobs) { - result.append("\t
    • "); - result.append(s); - result.append("\t
    • \n"); - } - result.append("
    \n"); - return result.toString(); - } + public static String renderJobRunStats() { + StringBuilder result = new StringBuilder(); + List rjobs = sobjSched.getSchedulerStats().getRunJobs(); + if (rjobs.size() == 0) { + return "No running jobs"; + } + result.append("
      \n"); + for (String s : rjobs) { + result.append("\t
    • "); + result.append(s); + result.append("\t
    • \n"); + } + result.append("
    \n"); + return result.toString(); + } } -//vi: ai nosi sw=4 ts=4 expandtab +// vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/rest/api/MetricsResource.java b/alitheia/core/src/main/java/eu/sqooss/rest/api/MetricsResource.java index a3416b5c7..6a29786ba 100644 --- a/alitheia/core/src/main/java/eu/sqooss/rest/api/MetricsResource.java +++ b/alitheia/core/src/main/java/eu/sqooss/rest/api/MetricsResource.java @@ -173,12 +173,12 @@ public List getMetricResultByMnem(@PathParam("mnem") String name, @Path("/metrics/by-type/{type}") @GET @Produces({"application/xml", "application/json"}) - public Set getMetricByType(@PathParam("type") String type) { + public List getMetricByType(@PathParam("type") String type) { MetricType mt = MetricType.getMetricType(Type.fromString(type)); if (mt == null) //No metric of this type has been installed yet - return Collections.EMPTY_SET; + return Collections.EMPTY_LIST; - return mt.getMetrics(); + return Metric.getMetricsByType(mt); } } diff --git a/alitheia/core/src/main/java/eu/sqooss/rest/api/StoredProjectResource.java b/alitheia/core/src/main/java/eu/sqooss/rest/api/StoredProjectResource.java index 6c5cf004b..aee5ef706 100644 --- a/alitheia/core/src/main/java/eu/sqooss/rest/api/StoredProjectResource.java +++ b/alitheia/core/src/main/java/eu/sqooss/rest/api/StoredProjectResource.java @@ -48,10 +48,12 @@ import eu.sqooss.service.db.DAObject; import eu.sqooss.service.db.DBService; import eu.sqooss.service.db.Directory; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.Metric; import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.db.StoredProject; +import eu.sqooss.service.db.Version; @Path("/api") public class StoredProjectResource { @@ -84,7 +86,7 @@ public StoredProject getProject(@PathParam("id") String id) { @Path("/project/{id}/versions") @GET @Produces({"application/xml", "application/json"}) - public List getAllVersions(@PathParam("id") Long id) { + public List getAllVersions(@PathParam("id") Long id) { StoredProject sp = DAObject.loadDAObyId(id, StoredProject.class); return sp.getProjectVersions(); @@ -141,7 +143,7 @@ public ProjectVersion getVersion(@PathParam("id") String prid, @Path("/project/{id}/version/{vid}/files/") @GET @Produces({"application/xml", "application/json"}) - public List getAllFiles(@PathParam("id") String prid, + public List getAllFiles(@PathParam("id") String prid, @PathParam("vid") String verid) { ProjectVersion pv = getVersion(prid, verid); @@ -154,7 +156,7 @@ public List getAllFiles(@PathParam("id") String prid, @Path("/project/{id}/version/{vid}/files/{dir: .+}") @GET @Produces({"application/xml", "application/json"}) - public List getFilesInDir(@PathParam("id") String prid, + public List getFilesInDir(@PathParam("id") String prid, @PathParam("vid") String verid, @PathParam("dir") String path) { @@ -172,7 +174,7 @@ public List getFilesInDir(@PathParam("id") String prid, @Path("/project/{id}/version/{vid}/files/changed") @GET @Produces({"application/xml", "application/json"}) - public Set getChangedFiles(@PathParam("id") String prid, + public Set getChangedFiles(@PathParam("id") String prid, @PathParam("vid") String verid) { ProjectVersion pv = getVersion(prid, verid); @@ -185,7 +187,7 @@ public Set getChangedFiles(@PathParam("id") String prid, @Path("/project/{id}/version/{vid}/dirs/") @GET @Produces({"application/xml", "application/json"}) - public List getDirs(@PathParam("id") String prid, + public List getDirs(@PathParam("id") String prid, @PathParam("vid") String verid) { ProjectVersion pv = getVersion(prid, verid); @@ -199,7 +201,7 @@ public List getDirs(@PathParam("id") String prid, @Path("/project/{id}/version/{vid}/dirs/{dir: .+}") @GET @Produces({"application/xml", "application/json"}) - public List getDirs(@PathParam("id") String prid, + public List getDirs(@PathParam("id") String prid, @PathParam("vid") String verid, @PathParam("dir") String path) { diff --git a/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/AbstractMetric.java b/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/AbstractMetric.java index 73df1f9fb..810c42d1f 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/AbstractMetric.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/AbstractMetric.java @@ -60,11 +60,13 @@ import eu.sqooss.service.db.DBService; import eu.sqooss.service.db.EncapsulationUnitMeasurement; import eu.sqooss.service.db.ExecutionUnitMeasurement; +import eu.sqooss.service.db.IDAObject; import eu.sqooss.service.db.MailMessageMeasurement; import eu.sqooss.service.db.MailingListThreadMeasurement; import eu.sqooss.service.db.Metric; import eu.sqooss.service.db.MetricMeasurement; import eu.sqooss.service.db.MetricType; +import eu.sqooss.service.db.MetricType.Type; import eu.sqooss.service.db.NameSpaceMeasurement; import eu.sqooss.service.db.Plugin; import eu.sqooss.service.db.PluginConfiguration; @@ -72,7 +74,6 @@ import eu.sqooss.service.db.ProjectVersionMeasurement; import eu.sqooss.service.db.StoredProject; import eu.sqooss.service.db.StoredProjectMeasurement; -import eu.sqooss.service.db.MetricType.Type; import eu.sqooss.service.logging.Logger; import eu.sqooss.service.metricactivator.MetricActivationException; import eu.sqooss.service.metricactivator.MetricActivator; @@ -335,7 +336,7 @@ public final Date getDateInstalled() { * not supported by this metric. */ @SuppressWarnings("unchecked") - public List getResultIfAlreadyCalculated(DAObject o, List l) throws MetricMismatchException { + public List getResultIfAlreadyCalculated(IDAObject o, List l) throws MetricMismatchException { boolean found = false; List result = new ArrayList(); @@ -403,7 +404,7 @@ private Method findGetResultMethod(Class clazz) * not supported by this metric. * @throws AlreadyProcessingException */ - public List getResult(DAObject o, List l) + public List getResult(IDAObject o, List l) throws MetricMismatchException, AlreadyProcessingException, Exception { List r = getResultIfAlreadyCalculated(o, l); @@ -439,7 +440,7 @@ public List getResult(DAObject o, List l) private Map> locks = new HashMap>(); - private Object lockObject(DAObject o) throws AlreadyProcessingException { + private Object lockObject(IDAObject o) throws AlreadyProcessingException { synchronized (locks) { if (!locks.containsKey(o.getId())) { locks.put(o.getId(), @@ -469,7 +470,7 @@ private Object lockObject(DAObject o) throws AlreadyProcessingException { } } - private void unlockObject(DAObject o) { + private void unlockObject(IDAObject o) { synchronized(locks) { Pair p = locks.get(o.getId()); p.second = p.second - 1; @@ -492,7 +493,7 @@ private void unlockObject(DAObject o) { * @throws MetricMismatchException * if the DAO is of a type not supported by this metric. */ - public void run(DAObject o) throws MetricMismatchException, + public void run(IDAObject o) throws MetricMismatchException, AlreadyProcessingException, Exception { if (!checkDependencies()) { @@ -544,7 +545,7 @@ private Method findRunMethod(String name, Class clazz) return m; } - private void logErr(String method, DAObject o, Exception e) { + private void logErr(String method, IDAObject o, Exception e) { log.error("Plugin:" + this.getClass().toString() + "\nDAO id: " + o.getId() + "\nDAO class: " + o.getClass() + @@ -842,7 +843,7 @@ public PluginConfiguration getConfigurationOption(String config) { /** * Convenience method to get the measurement for a single metric. */ - protected List getResult(DAObject o, Class clazz, + protected List getResult(IDAObject o, Class clazz, Metric m, Result.ResultType type) { DBService dbs = AlitheiaCore.getInstance().getDBService(); Map props = new HashMap(); diff --git a/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/AlitheiaPlugin.java b/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/AlitheiaPlugin.java index 9d55e94ab..c063903b2 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/AlitheiaPlugin.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/AlitheiaPlugin.java @@ -40,6 +40,7 @@ import java.util.SortedSet; import eu.sqooss.service.db.DAObject; +import eu.sqooss.service.db.IDAObject; import eu.sqooss.service.db.Metric; import eu.sqooss.service.db.MetricType; import eu.sqooss.service.db.PluginConfiguration; @@ -146,7 +147,7 @@ public interface AlitheiaPlugin { * @throws MetricMismatchException if the DAO type is one not supported by * this metric. */ - List getResultIfAlreadyCalculated(DAObject o, List l) + List getResultIfAlreadyCalculated(IDAObject o, List l) throws MetricMismatchException; /** @@ -167,7 +168,7 @@ List getResultIfAlreadyCalculated(DAObject o, List l) * @throws Exception All exceptions initiated by the errors in code * included in implemenations of those classes. */ - List getResult(DAObject o, List l) + List getResult(IDAObject o, List l) throws MetricMismatchException, AlreadyProcessingException, Exception; /** @@ -208,7 +209,7 @@ List getResult(DAObject o, List l) * currently locked for processing by another thread. * @throws Exception Any other exception initiated from the plugin code */ - void run(DAObject o) throws MetricMismatchException, + void run(IDAObject o) throws MetricMismatchException, AlreadyProcessingException, Exception; /** diff --git a/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/Result.java b/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/Result.java index a886498e6..ec3b44a99 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/Result.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/abstractmetric/Result.java @@ -5,7 +5,7 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; -import eu.sqooss.service.db.DAObject; +import eu.sqooss.service.db.IDAObject; import eu.sqooss.service.db.Metric; @XmlRootElement(name="r") @@ -33,7 +33,7 @@ public enum ResultType { public Result() {} - public Result(DAObject o, Metric m, Object result, ResultType type) { + public Result(IDAObject o, Metric m, Object result, ResultType type) { this.artifactId = o.getId(); this.metricId = m.getId(); this.result = result; diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/Branch.java b/alitheia/core/src/main/java/eu/sqooss/service/db/Branch.java index a58576cd3..d9e10fd08 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/Branch.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/Branch.java @@ -81,28 +81,28 @@ public class Branch extends DAObject { @XmlElement private String name; - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch=FetchType.LAZY, targetEntity=StoredProject.class) @JoinColumn(name="STORED_PROJECT_ID") @XmlElement - private StoredProject project; + private Project project; - @ManyToMany + @ManyToMany(targetEntity=ProjectVersion.class) @JoinTable( name="BRANCH_INCOMING", inverseJoinColumns={@JoinColumn(name="PROJECT_VERSION_ID", referencedColumnName="PROJECT_VERSION_ID")}, joinColumns={@JoinColumn(name="BRANCH_ID", referencedColumnName="BRANCH_ID")}) - private Set branchIncoming = new HashSet(); + private Set branchIncoming = new HashSet(); - @ManyToMany + @ManyToMany(targetEntity=ProjectVersion.class) @JoinTable( name="BRANCH_OUTGOING", inverseJoinColumns={@JoinColumn(name="PROJECT_VERSION_ID", referencedColumnName="PROJECT_VERSION_ID")}, joinColumns={@JoinColumn(name="BRANCH_ID", referencedColumnName="BRANCH_ID")}) - private Set branchOutgoing = new HashSet(); + private Set branchOutgoing = new HashSet(); public Branch() {} - public Branch(StoredProject sp, String name) { + public Branch(Project sp, String name) { this.project = sp; this.name = name; } @@ -122,31 +122,31 @@ public void setName(String name) { this.name = name; } - public void setProject(StoredProject project) { + public void setProject(Project project) { this.project = project; } - public StoredProject getProject() { + public Project getProject() { return project; } - public Set getBranchIncoming() { + public Set getBranchIncoming() { return branchIncoming; } - public void setBranchIncoming(Set branchIncoming) { + public void setBranchIncoming(Set branchIncoming) { this.branchIncoming = branchIncoming; } - public Set getBranchOutgoing() { + public Set getBranchOutgoing() { return branchOutgoing; } - public void setBranchOutgoing(Set branchOutgoing) { + public void setBranchOutgoing(Set branchOutgoing) { this.branchOutgoing = branchOutgoing; } - public static Branch fromName(StoredProject sp, String name, boolean create) { + public static Branch fromName(Project sp, String name, boolean create) { DBService db = AlitheiaCore.getInstance().getDBService(); Map params = new HashMap(); @@ -167,7 +167,7 @@ public static Branch fromName(StoredProject sp, String name, boolean create) { return branches.get(0); } - public static String suggestName(StoredProject sp) { + public static String suggestName(Project sp) { DBService db = AlitheiaCore.getInstance().getDBService(); Map params = new HashMap(); diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/Bug.java b/alitheia/core/src/main/java/eu/sqooss/service/db/Bug.java index 78b67dad8..531184a5e 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/Bug.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/Bug.java @@ -37,9 +37,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; -import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; @@ -49,7 +47,6 @@ import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; -import javax.persistence.OneToMany; import javax.xml.bind.annotation.XmlElement; import eu.sqooss.core.AlitheiaCore; @@ -72,9 +69,9 @@ public class Bug extends DAObject { private long id; /** The project this bug belongs to */ - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch=FetchType.LAZY, targetEntity=StoredProject.class) @JoinColumn(name="STORED_PROJECT_ID") - private StoredProject project; + private Project project; /** When this bug was last touched by the updater */ @Column(name="UPDATE_RUN") @@ -124,10 +121,6 @@ public class Bug extends DAObject { @Column(name="SHORT_DESC") private String shortDesc; - /** The list of messages associated to this bug */ - @OneToMany(mappedBy="bug", cascade=CascadeType.ALL, orphanRemoval=true) - private Set reportMessages; - public long getId() { return id; } @@ -208,19 +201,11 @@ public void setShortDesc(String shortDesc) { this.shortDesc = shortDesc; } - public Set getReportMessages() { - return reportMessages; - } - - public void setReportMessages(Set reportMessages) { - this.reportMessages = reportMessages; - } - - public StoredProject getProject() { + public Project getProject() { return project; } - public void setProject(StoredProject project) { + public void setProject(Project project) { this.project = project; } @@ -236,7 +221,7 @@ public void setUpdateRun(Date updateRun) { * Get the latest entry processed by the bug updater */ @SuppressWarnings("unchecked") - public static Bug getLastUpdate(StoredProject sp) { + public static Bug getLastUpdate(Project sp) { DBService dbs = AlitheiaCore.getInstance().getDBService(); if (sp == null) @@ -261,35 +246,10 @@ public static Bug getLastUpdate(StoredProject sp) { return buglist.get(0); } - /** - * Get a list of all bug report comments for this specific bug, - * ordered by the time the comment was left (old to new). - */ - @SuppressWarnings("unchecked") - public List getAllReportComments() { - DBService dbs = AlitheiaCore.getInstance().getDBService(); - - String paramBugID = "paramBugID"; - String paramStoredProject = "stroredProject"; - - String query = "select brm " + - "from Bug b, BugReportMessage brm " + - "where brm.bug = b " + - "and b.bugID = :" + paramBugID + - " and b.project =:" + paramStoredProject + - " order by brm.timestamp asc" ; - - Map params = new HashMap(); - params.put(paramBugID, bugID); - params.put(paramStoredProject, project); - - return (List) dbs.doHQL(query, params); - } - /** * Get the latest entry for the bug with the provided Id. */ - public static Bug getBug(String bugID, StoredProject sp) { + public static Bug getBug(String bugID, Project sp) { DBService dbs = AlitheiaCore.getInstance().getDBService(); String paramBugID = "paramBugID"; @@ -298,8 +258,7 @@ public static Bug getBug(String bugID, StoredProject sp) { String query = "select b " + "from Bug b " + "where b.bugID = :" + paramBugID + - " and b.project = :" + paramStoredProject + - " order by b.timestamp desc"; + " and b.project = :" + paramStoredProject ; Map params = new HashMap(); params.put(paramBugID, bugID); @@ -312,6 +271,66 @@ public static Bug getBug(String bugID, StoredProject sp) { else return bug.get(0); } + + /** + * Gets all bugs for a given priority. + * @param priority To filter the bugs by. + * @return the list of bugs of the given priority. + */ + public static List getBugsForPriority(BugPriority priority) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramBugPriority = "paramBugPriority"; + String query = "SELECT b FROM Bug b WHERE b.priority = :" + paramBugPriority; + + Map params = new HashMap(); + params.put(paramBugPriority, priority); + return (List) dbs.doHQL(query, params); + } + + /** + * Gets all bugs for a given resolution. + * @param resolution To filter the bugs by. + * @return the list of bugs of the given resolution. + */ + public static List getBugsForResolution(BugResolution resolution) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramBugResolution = "paramBugResolution"; + String query = "SELECT b FROM Bug b WHERE b.resolution = :" + paramBugResolution; + + Map params = new HashMap(); + params.put(paramBugResolution, resolution); + return (List) dbs.doHQL(query, params); + } + + /** + * Gets all bugs for a given severity. + * @param severity To filter the bugs by. + * @return the list of bugs of the given severity. + */ + public static List getBugsForSeverity(BugSeverity severity) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramBugSeverity = "paramBugSeverity"; + String query = "SELECT b FROM Bug b WHERE b.severity = :" + paramBugSeverity; + + Map params = new HashMap(); + params.put(paramBugSeverity, severity); + return (List) dbs.doHQL(query, params); + } + + /** + * Gets all bugs for a given status. + * @param status To filter the bugs by. + * @return the list of bugs of the given status. + */ + public static List getBugsForStatus(BugStatus status) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramBugStatus = "paramBugStatus"; + String query = "SELECT b FROM Bug b WHERE b.status = :" + paramBugStatus; + + Map params = new HashMap(); + params.put(paramBugStatus, status); + return (List) dbs.doHQL(query, params); + } } //vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/BugPriority.java b/alitheia/core/src/main/java/eu/sqooss/service/db/BugPriority.java index 1dc1419c2..a05408f63 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/BugPriority.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/BugPriority.java @@ -68,10 +68,7 @@ public class BugPriority extends DAObject { @Column(name="PRIORITY") private String priority; - /**Bugs with this priority*/ - @OneToMany(mappedBy="priority", orphanRemoval=true) - private Set bugs; - + public String getPriority() { return priority; } @@ -188,12 +185,4 @@ public static BugPriority getBugPriority(String priority, boolean create) { return bs; } - - public void setBugs(Set bugs) { - this.bugs = bugs; - } - - public Set getBugs() { - return bugs; - } } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/BugReportMessage.java b/alitheia/core/src/main/java/eu/sqooss/service/db/BugReportMessage.java index ead30d314..44b43d565 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/BugReportMessage.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/BugReportMessage.java @@ -34,9 +34,12 @@ package eu.sqooss.service.db; import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -import javax.persistence.Column; import javax.persistence.CascadeType; +import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -47,55 +50,55 @@ import javax.persistence.Table; import javax.xml.bind.annotation.XmlElement; -import eu.sqooss.service.db.DAObject; +import eu.sqooss.core.AlitheiaCore; /** * This class represents the primary data associated with a bug report */ @Entity -@Table(name="BUG_REPORT_MESSAGE") +@Table(name = "BUG_REPORT_MESSAGE") public class BugReportMessage extends DAObject { - + @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="BUG_REPORT_MESSAGE_ID") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "BUG_REPORT_MESSAGE_ID") @XmlElement private long id; /** - * The bug with which the message is associated - */ - @ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.MERGE) - @JoinColumn(name="BUG_ID") - private Bug bug; - - /** - * The original reporter of the bug - */ - @ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.MERGE) - @JoinColumn(name="DEVELOPER_ID") - private Developer reporter; - - /** - * The date this message was written - */ - @Column(name="TIMESTAMP") - private Date timestamp; - - /** - * Message text - */ - @Column(name="TEXT", length=255) - private String text; - - public BugReportMessage() { - // Nothing to do here - } - - public BugReportMessage(Bug b) { - this.bug = b; - } - + * The bug with which the message is associated + */ + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) + @JoinColumn(name = "BUG_ID") + private Bug bug; + + /** + * The original reporter of the bug + */ + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) + @JoinColumn(name = "DEVELOPER_ID") + private Developer reporter; + + /** + * The date this message was written + */ + @Column(name = "TIMESTAMP") + private Date timestamp; + + /** + * Message text + */ + @Column(name = "TEXT", length = 255) + private String text; + + public BugReportMessage() { + // Nothing to do here + } + + public BugReportMessage(Bug b) { + this.bug = b; + } + public long getId() { return id; } @@ -103,52 +106,96 @@ public long getId() { public void setId(long id) { this.id = id; } - - public Bug getBug() { - return bug; - } - - public void setBug(Bug bug) { - this.bug = bug; - } - - public Developer getReporter() { - return reporter; - } - - public void setReporter(Developer reporter) { - this.reporter = reporter; - } - - public Date getTimestamp() { - return timestamp; - } - - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - public boolean equals(BugReportMessage b) { - if (this.timestamp.getTime() != b.timestamp.getTime()) - return false; - - if (!b.getBug().getBugID().equals(this.getBug().getBugID())) - return false; - - if (b.getBug().getProject().getId() != bug.getProject().getId()) - return false; - - return true; - } + + public Bug getBug() { + return bug; + } + + public void setBug(Bug bug) { + this.bug = bug; + } + + public Developer getReporter() { + return reporter; + } + + public void setReporter(Developer reporter) { + this.reporter = reporter; + } + + public Date getTimestamp() { + return timestamp; + } + + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public boolean equals(Object b) { + if (!(b instanceof BugReportMessage)) { + return false; + } + BugReportMessage brm = (BugReportMessage) b; + if (this.timestamp == null) { + if (brm.timestamp != null) { + return false; + } + } else { + if (brm.timestamp == null) { + return false; + } else if (this.timestamp.getTime() != brm.timestamp.getTime()) { + return false; + } + } + if ((this.getBug() == null && brm.getBug() != null) + || (this.getBug() != null && brm.getBug() == null)) { + return false; + } + if (this.getBug() != null && brm.getBug() != null) { + if (!brm.getBug().getBugID().equals(this.getBug().getBugID())) + return false; + if (brm.getBug().getProject().getId() != bug.getProject().getId()) + return false; + } + return true; + } + + public static List getAllReportMessageForBug(Bug bug) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramBug = "paramBug"; + String paramProject = "paramProject"; + String query = "SELECT brm " + "FROM Bug b, BugReportMessage brm" + + " WHERE b.id = :" + paramBug + + " AND brm.bug = b" + + " AND b.project = :" + paramProject + + " order by brm.timestamp asc"; + + Map params = new HashMap(); + params.put(paramBug, bug.getId()); + params.put(paramProject, bug.getProject()); + return (List) dbs.doHQL(query, params); + } + + public static List getAllReportMessageForDeveloper( + Developer dev) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramDev = "paramDev"; + String query = "SELECT brm " + "FROM BugReportMessage brm " + + "WHERE brm.reporter = :" + paramDev; + + Map params = new HashMap(); + params.put(paramDev, dev); + return (List) dbs.doHQL(query, params); + } } -//vi: ai nosi sw=4 ts=4 expandtab +// vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/BugResolution.java b/alitheia/core/src/main/java/eu/sqooss/service/db/BugResolution.java index 1907e44a9..1de5954bb 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/BugResolution.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/BugResolution.java @@ -47,6 +47,8 @@ import javax.persistence.Table; import javax.xml.bind.annotation.XmlElement; +import org.hibernate.annotations.Filter; + import eu.sqooss.core.AlitheiaCore; /** @@ -68,10 +70,6 @@ public class BugResolution extends DAObject { @Column(name="RESOLUTION") private String resolution; - /** Bugs in this resolution state*/ - @OneToMany(mappedBy="resolution", orphanRemoval=true) - private Set bugs; - public String getResolution() { return resolution; } @@ -191,12 +189,4 @@ public static BugResolution getBugResolution(String resolution, boolean create) return bs; } - - public void setBugs(Set bugs) { - this.bugs = bugs; - } - - public Set getBugs() { - return bugs; - } } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/BugSeverity.java b/alitheia/core/src/main/java/eu/sqooss/service/db/BugSeverity.java index e00652662..5496c9513 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/BugSeverity.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/BugSeverity.java @@ -69,10 +69,6 @@ public class BugSeverity extends DAObject { @Column(name="severity") private String severity; - /** Bugs with this severity*/ - @OneToMany(mappedBy="severity", orphanRemoval=true) - private Set bugs; - public String getSeverity() { return severity; } @@ -154,6 +150,7 @@ public static Severity fromString(String s) { * @return A Bugseverity DAO or null if an error occurred while creating * the severity code line to the database */ + // TODO: Fix stupid naming issue public static BugSeverity getBugseverity(Severity s) { return getBugSeverity(s.toString(), true); } @@ -198,12 +195,4 @@ public static BugSeverity getBugSeverity(String severity, boolean create) { return bs; } - - public void setBugs(Set bugs) { - this.bugs = bugs; - } - - public Set getBugs() { - return bugs; - } } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/BugStatus.java b/alitheia/core/src/main/java/eu/sqooss/service/db/BugStatus.java index 6a3e27ff7..255638fca 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/BugStatus.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/BugStatus.java @@ -68,10 +68,6 @@ public class BugStatus extends DAObject { @Column(name="status") private String status; - /** Bugs with this status*/ - @OneToMany(mappedBy="status", orphanRemoval=true) - private Set bugs; - public String getStatus() { return status; } @@ -196,12 +192,4 @@ public static BugStatus getBugStatus(String status, boolean create) { return bs; } - - public void setBugs(Set bugs) { - this.bugs = bugs; - } - - public Set getBugs() { - return bugs; - } } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ClusterNode.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ClusterNode.java index 1439add8e..55504dd9a 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/ClusterNode.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ClusterNode.java @@ -73,8 +73,8 @@ public class ClusterNode extends DAObject { @XmlElement private String name; - @OneToMany(cascade = CascadeType.REFRESH, mappedBy="clusternode", fetch = FetchType.LAZY) - private Set projects; + @OneToMany(cascade = CascadeType.REFRESH, mappedBy="clusternode", fetch = FetchType.LAZY, targetEntity=StoredProject.class) + private Set projects; // Nothing to do here public ClusterNode(){} @@ -100,14 +100,15 @@ public void setId(long id) { this.id = id; } - public Set getProjects() { + public Set getProjects() { return projects; } - public void setProjects(Set projects) { + public void setProjects(Set projects) { this.projects = projects; } + // TODO: Fix method name public static ClusterNode getClusteNodeByName(String name) { DBService dbs = AlitheiaCore.getInstance().getDBService(); diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ConfigurationOption.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ConfigurationOption.java index 5ef0c8220..9a5bef75b 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/ConfigurationOption.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ConfigurationOption.java @@ -62,7 +62,7 @@ @XmlRootElement(name="config-option") @Entity @Table(name="CONFIG_OPTION") -public class ConfigurationOption extends DAObject { +public class ConfigurationOption extends DAObject implements IConfigurationOption{ @Id @GeneratedValue(strategy=GenerationType.AUTO) @@ -129,7 +129,7 @@ public void setConfigurations(Set configurations) { * the method determines whether to overwrite the value or append the * provided value to the existing list of values. */ - public void setValues(StoredProject sp, List values, + public void setValues(Project sp, List values, boolean overwrite) { DBService dbs = AlitheiaCore.getInstance().getDBService(); @@ -180,7 +180,7 @@ public void setValues(StoredProject sp, List values, * @return A list of configuration values that correspond to the provided * project */ - public List getValues(StoredProject sp) { + public List getValues(Project sp) { DBService dbs = AlitheiaCore.getInstance().getDBService(); String paramProject = "paramProject"; diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/DAObject.java b/alitheia/core/src/main/java/eu/sqooss/service/db/DAObject.java index 752e535fb..798f347b4 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/DAObject.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/DAObject.java @@ -42,7 +42,7 @@ * Base class for describing all DAO, providing a simple id interface */ @XmlAccessorType(XmlAccessType.NONE) -public abstract class DAObject { +public abstract class DAObject implements IDAObject { /** * Returns the unique ID assigned to this instance diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/DBService.java b/alitheia/core/src/main/java/eu/sqooss/service/db/DBService.java index bb63dcd9b..d034e5965 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/DBService.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/DBService.java @@ -237,7 +237,7 @@ public List findObjectsByPropertiesForUpdate(Class da * @param records the list of records to persist into the database * @return true if all the record insertions succeeded, false otherwise */ - public boolean addRecords(List records); + public boolean addRecords(List records); /** * Delete an existing record from the database. @@ -267,7 +267,7 @@ public List findObjectsByPropertiesForUpdate(Class da * @param obj the object to connect * @return the connected instance of the object */ - public T attachObjectToDBSession(T obj); + public T attachObjectToDBSession(T obj); /** * Execute a complete SQL query to the database. diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/Developer.java b/alitheia/core/src/main/java/eu/sqooss/service/db/Developer.java index 26f99af02..96d8c7337 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/Developer.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/Developer.java @@ -69,7 +69,7 @@ @XmlRootElement @Entity @Table(name="DEVELOPER") -public class Developer extends DAObject { +public class Developer extends DAObject implements IDeveloper{ @Id @GeneratedValue(strategy=GenerationType.AUTO) @@ -101,28 +101,22 @@ public class Developer extends DAObject { /** * The project this developer belongs to */ - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=StoredProject.class) @JoinColumn(name="STORED_PROJECT_ID") - private StoredProject storedProject; + private Project storedProject; /** * The list of commits from this developer */ - @OneToMany(fetch=FetchType.LAZY, mappedBy="committer", orphanRemoval=true) - private Set commits; + @OneToMany(fetch=FetchType.LAZY, mappedBy="committer", orphanRemoval=true, targetEntity=ProjectVersion.class) + private Set commits; /** * The list of mails sent by this developer */ - @OneToMany(fetch=FetchType.LAZY, mappedBy="sender", orphanRemoval=true) - private Set mails; + @OneToMany(fetch=FetchType.LAZY, mappedBy="sender", orphanRemoval=true, targetEntity=MailMessage.class) + private Set mails; - /** - * The list of bug report messages sent by this developer - */ - @OneToMany(fetch=FetchType.LAZY, mappedBy="reporter", orphanRemoval=true) - private Set bugReportMessages; - public long getId() { return id; } @@ -147,38 +141,30 @@ public void setUsername(String username) { this.username = username; } - public StoredProject getStoredProject() { + public Project getStoredProject() { return storedProject; } - public void setStoredProject(StoredProject storedProject) { + public void setStoredProject(Project storedProject) { this.storedProject = storedProject; } - public Set getCommits() { + public Set getCommits() { return commits; } - public void setCommits(Set commits) { + public void setCommits(Set commits) { this.commits = commits; } - public Set getMails() { + public Set getMails() { return mails; } - public void setMails(Set mails) { + public void setMails(Set mails) { this.mails = mails; } - public Set getBugReportMessages() { - return bugReportMessages; - } - - public void setBugReportMessages(Set bugReportMessages) { - this.bugReportMessages = bugReportMessages; - } - public Set getAliases() { return aliases; } @@ -194,8 +180,7 @@ public void setAliases(Set aliases) { */ public void addAlias(String email) { DeveloperAlias da = new DeveloperAlias(email, this); - if (! getAliases().contains(da)) - getAliases().add(da); + getAliases().add(da); } /** @@ -206,15 +191,15 @@ public void addAlias(String email) { * * @param email * The Developer's email - * @param sp The StoredProject this Developer belongs to + * @param sp The Project this Developer belongs to * @return A Developer record for the specified Developer or null when: *
      - *
    • The passed StoredProject does not exist
    • + *
    • The passed Project does not exist
    • *
    • The passed email is invalid syntactically
    • *
        */ public static Developer getDeveloperByEmail(String email, - StoredProject sp) { + Project sp) { return getDeveloperByEmail(email, sp, true); } @@ -226,15 +211,15 @@ public static Developer getDeveloperByEmail(String email, * the provided email and returned. * * @param email The Developer's email - * @param sp The StoredProject this Developer belongs to + * @param sp The Project this Developer belongs to * @return A Developer record for the specified Developer or null when: *
          - *
        • The passed StoredProject does not exist
        • + *
        • The passed Project does not exist
        • *
        • The passed email is invalid syntactically
        • *
            */ public static synchronized Developer getDeveloperByEmail(String email, - StoredProject sp, boolean create){ + Project sp, boolean create){ DBService dbs = AlitheiaCore.getInstance().getDBService(); String paramProject = "project"; @@ -319,7 +304,7 @@ public static synchronized Developer getDeveloperByEmail(String email, * @return A Developer record for the specified Developer or null on failure */ public static Developer getDeveloperByUsername(String username, - StoredProject sp) { + Project sp) { return getDeveloperByUsername(username, sp, true); } @@ -338,9 +323,8 @@ public static Developer getDeveloperByUsername(String username, * to retrieve or create an entry. * */ - @SuppressWarnings("unchecked") public static synchronized Developer getDeveloperByUsername(String username, - StoredProject sp, boolean create) { + Project sp, boolean create) { DBService dbs = AlitheiaCore.getInstance().getDBService(); @@ -406,7 +390,7 @@ public static synchronized Developer getDeveloperByUsername(String username, * @return */ public static synchronized Developer getDeveloperByName(String name, - StoredProject sp, boolean create) { + Project sp, boolean create) { DBService dbs = AlitheiaCore.getInstance().getDBService(); @@ -431,6 +415,8 @@ public static synchronized Developer getDeveloperByName(String name, return d; } + // TODO: Weird things with comma + // TODO: Space is kept, comma is removed. public String toString() { StringBuffer dev = new StringBuffer(); dev.append(name).append(", aka:").append(username).append(" ("); diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/DeveloperAlias.java b/alitheia/core/src/main/java/eu/sqooss/service/db/DeveloperAlias.java index 3753cb257..cdb436a77 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/DeveloperAlias.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/DeveloperAlias.java @@ -67,13 +67,13 @@ public class DeveloperAlias extends DAObject { private String email; @XmlElement - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch=FetchType.LAZY, targetEntity=Developer.class) @JoinColumn(name="DEVELOPER_ID") - private Developer developer; + private IDeveloper developer; public DeveloperAlias() {} - public DeveloperAlias(String email, Developer d) { + public DeveloperAlias(String email, IDeveloper d) { this.email = email; this.developer = d; } @@ -92,10 +92,10 @@ public String getEmail() { public void setEmail(String email) { this.email = email; } - public Developer getDeveloper() { + public IDeveloper getDeveloper() { return developer; } - public void setDeveloper(Developer developer) { + public void setDeveloper(IDeveloper developer) { this.developer = developer; } @@ -112,7 +112,7 @@ public boolean equals(Object other) { if (!(other instanceof DeveloperAlias)) return false; DeveloperAlias that = (DeveloperAlias) other; - return (email.equals(that.email)); + return (email == null && that.email == null) || (email != null && email.equals(that.email)); } @Override diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/Directory.java b/alitheia/core/src/main/java/eu/sqooss/service/db/Directory.java index d84e09068..df2ef6480 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/Directory.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/Directory.java @@ -85,8 +85,8 @@ public class Directory extends DAObject { /** * A set representing the files within this path */ - @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "dir") - private Set files; + @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "dir", targetEntity=ProjectFile.class) + private Set files; public long getId() { return id; @@ -104,11 +104,11 @@ public void setPath(String path) { this.path = path; } - public Set getFiles() { + public Set getFiles() { return files; } - public void setFiles(Set files) { + public void setFiles(Set files) { this.files = files; } @@ -159,6 +159,7 @@ public String toString() { return this.path; } + //TODO: path != null is a weird check. public boolean equals(Object obj) { if (this == obj) return true; diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsUnit.java b/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsUnit.java new file mode 100644 index 000000000..104064c7b --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsUnit.java @@ -0,0 +1,11 @@ +package eu.sqooss.service.db; + +import java.util.Set; + +public interface EncapsUnit extends IDAObject{ + + String getName(); + + Set getExecUnits(); + +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsulationUnit.java b/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsulationUnit.java index 13cda2b93..13a6cb090 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsulationUnit.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsulationUnit.java @@ -30,7 +30,7 @@ @XmlRootElement(name = "encapsulation-unit") @Entity @Table(name = "ENCAPSULATION_UNIT") -public class EncapsulationUnit extends DAObject { +public class EncapsulationUnit extends DAObject implements EncapsUnit { @Id @GeneratedValue(strategy = GenerationType.AUTO) @@ -46,12 +46,12 @@ public class EncapsulationUnit extends DAObject { @JoinColumn(name = "NAMESPACE_ID") private NameSpace namespace; - @OneToMany(mappedBy = "encapsulationUnit", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) - private Set execUnits; + @OneToMany(mappedBy = "encapsulationUnit", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, targetEntity=ExecutionUnit.class) + private Set execUnits; - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectFile.class) @JoinColumn(name = "PROJECT_FILE_ID") - private ProjectFile file; + private IProjectFile file; /** * Measurements for this encapsulation unit. @@ -61,7 +61,7 @@ public class EncapsulationUnit extends DAObject { public EncapsulationUnit(){} - public EncapsulationUnit(ProjectFile pf){ + public EncapsulationUnit(IProjectFile pf){ this.file = pf; } @@ -89,21 +89,21 @@ public void setNamespace(NameSpace namespace) { this.namespace = namespace; } - public Set getExecUnits() { + public Set getExecUnits() { if (execUnits == null) - return new HashSet(); + return new HashSet(); return execUnits; } - public void setExecUnits(Set execUnits) { + public void setExecUnits(Set execUnits) { this.execUnits = execUnits; } - public void setFile(ProjectFile file) { + public void setFile(IProjectFile file) { this.file = file; } - public ProjectFile getFile() { + public IProjectFile getFile() { return file; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsulationUnitMeasurement.java b/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsulationUnitMeasurement.java index d2d650bd9..e909a5890 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsulationUnitMeasurement.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/EncapsulationUnitMeasurement.java @@ -33,9 +33,9 @@ public class EncapsulationUnitMeasurement extends MetricMeasurement { /** * The encapsulation unit against which the measurement was made */ - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity=EncapsulationUnit.class) @JoinColumn(name = "ENCAPSULATION_UNIT_ID", referencedColumnName = "ENCAPSULATION_UNIT_ID") - private EncapsulationUnit encapsulationUnit; + private EncapsUnit encapsulationUnit; /** * The metric to which this result belongs @@ -52,7 +52,7 @@ public class EncapsulationUnitMeasurement extends MetricMeasurement { public EncapsulationUnitMeasurement(){} - public EncapsulationUnitMeasurement(EncapsulationUnit eu, Metric m, String result) { + public EncapsulationUnitMeasurement(EncapsUnit eu, Metric m, String result) { this.encapsulationUnit = eu; this.metric = m; this.result = result; @@ -66,11 +66,11 @@ public void setId(long id) { this.id = id; } - public EncapsulationUnit getEncapsulationUnit() { + public EncapsUnit getEncapsulationUnit() { return encapsulationUnit; } - public void setEncapsulationUnit(EncapsulationUnit encapsulationUnit) { + public void setEncapsulationUnit(EncapsUnit encapsulationUnit) { this.encapsulationUnit = encapsulationUnit; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ExecUnit.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ExecUnit.java new file mode 100644 index 000000000..3270ab650 --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ExecUnit.java @@ -0,0 +1,7 @@ +package eu.sqooss.service.db; + +public interface ExecUnit extends IDAObject{ + + String getFullyQualifiedName(); + +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ExecutionUnit.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ExecutionUnit.java index 5390c78c5..548bb4ba7 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/ExecutionUnit.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ExecutionUnit.java @@ -26,7 +26,7 @@ @XmlRootElement(name = "execution-unit") @Entity @Table(name = "EXECUTION_UNIT") -public class ExecutionUnit extends DAObject { +public class ExecutionUnit extends DAObject implements ExecUnit{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @@ -46,9 +46,9 @@ public class ExecutionUnit extends DAObject { @JoinColumn(name = "ENCAPSULATION_UNIT_ID") private EncapsulationUnit encapsulationUnit; - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectFile.class) @JoinColumn(name = "PROJECT_FILE_ID") - private ProjectFile file; + private IProjectFile file; @Column(name = "CHANGED") @XmlElement @@ -99,11 +99,11 @@ public void setEncapsulationUnit(EncapsulationUnit encapsulationUnit) { this.encapsulationUnit = encapsulationUnit; } - public void setFile(ProjectFile file) { + public void setFile(IProjectFile file) { this.file = file; } - public ProjectFile getFile() { + public IProjectFile getFile() { return file; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ExecutionUnitMeasurement.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ExecutionUnitMeasurement.java index 89d1d7bf0..3f6a82881 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/ExecutionUnitMeasurement.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ExecutionUnitMeasurement.java @@ -34,9 +34,9 @@ public class ExecutionUnitMeasurement extends MetricMeasurement { /** * The encapsulation unit against which the measurement was made */ - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity=ExecutionUnit.class) @JoinColumn(name = "EXECUTION_UNIT_ID", referencedColumnName = "EXECUTION_UNIT_ID") - private ExecutionUnit executionUnit; + private ExecUnit executionUnit; /** * The metric to which this result belongs @@ -53,7 +53,7 @@ public class ExecutionUnitMeasurement extends MetricMeasurement { public ExecutionUnitMeasurement() {} - public ExecutionUnitMeasurement(ExecutionUnit eu, Metric m, String result) { + public ExecutionUnitMeasurement(ExecUnit eu, Metric m, String result) { this.executionUnit = eu; this.metric = m; this.result = result; @@ -67,11 +67,11 @@ public void setId(long id) { this.id = id; } - public ExecutionUnit getExecutionUnit() { + public ExecUnit getExecutionUnit() { return executionUnit; } - public void setExecutionUnit(ExecutionUnit executionUnit) { + public void setExecutionUnit(ExecUnit executionUnit) { this.executionUnit = executionUnit; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/IConfigurationOption.java b/alitheia/core/src/main/java/eu/sqooss/service/db/IConfigurationOption.java new file mode 100644 index 000000000..05ff22294 --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/IConfigurationOption.java @@ -0,0 +1,5 @@ +package eu.sqooss.service.db; + +public interface IConfigurationOption extends IDAObject{ + +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/IDAObject.java b/alitheia/core/src/main/java/eu/sqooss/service/db/IDAObject.java new file mode 100644 index 000000000..ebb6d41ce --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/IDAObject.java @@ -0,0 +1,5 @@ +package eu.sqooss.service.db; + +public interface IDAObject { + long getId(); +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/IDeveloper.java b/alitheia/core/src/main/java/eu/sqooss/service/db/IDeveloper.java new file mode 100644 index 000000000..4fc301e7d --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/IDeveloper.java @@ -0,0 +1,5 @@ +package eu.sqooss.service.db; + +public interface IDeveloper extends IDAObject{ + +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/IMailMessage.java b/alitheia/core/src/main/java/eu/sqooss/service/db/IMailMessage.java new file mode 100644 index 000000000..1b11db19b --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/IMailMessage.java @@ -0,0 +1,13 @@ +package eu.sqooss.service.db; + +import java.util.Date; + +public interface IMailMessage extends IDAObject { + + int getDepth(); + void setDepth(int i); + IDeveloper getSender(); + IMailMessage getParent(); + Date getSendDate(); + +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/IMailingList.java b/alitheia/core/src/main/java/eu/sqooss/service/db/IMailingList.java new file mode 100644 index 000000000..aeb7bf1b6 --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/IMailingList.java @@ -0,0 +1,7 @@ +package eu.sqooss.service.db; + +public interface IMailingList extends IDAObject{ + + Project getStoredProject(); + +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/IPlugin.java b/alitheia/core/src/main/java/eu/sqooss/service/db/IPlugin.java new file mode 100644 index 000000000..3307f900c --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/IPlugin.java @@ -0,0 +1,5 @@ +package eu.sqooss.service.db; + +public interface IPlugin extends IDAObject{ + +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/IProjectFile.java b/alitheia/core/src/main/java/eu/sqooss/service/db/IProjectFile.java new file mode 100644 index 000000000..3f3ba5a9b --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/IProjectFile.java @@ -0,0 +1,29 @@ +package eu.sqooss.service.db; + +import java.util.List; +import java.util.Set; + +public interface IProjectFile extends IDAObject { + + String getFileName(); + boolean getIsDirectory(); + String getName(); + Directory getDir(); + Version getProjectVersion(); + boolean isAdded(); + void setValidUntil(Version previous); + ProjectFileState getState(); + IProjectFile getCopyFrom(); + void setState(ProjectFileState state); + void setIsDirectory(boolean b); + void setCopyFrom(IProjectFile copyFrom); + IProjectFile getPreviousFileVersion(); + boolean isDeleted(); + boolean isReplaced(); + List getChangedExecutionUnits(); + Set getEncapsulationUnits(); + Boolean isModule(); + void setModule(Boolean b); + IProjectFile getEnclosingDirectory(); + +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/MailMessage.java b/alitheia/core/src/main/java/eu/sqooss/service/db/MailMessage.java index dfffa7edc..2213b8c5d 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/MailMessage.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/MailMessage.java @@ -61,7 +61,7 @@ @Entity @Table(name="MAILMESSAGE") @XmlRootElement(name="mlmsg") -public class MailMessage extends DAObject { +public class MailMessage extends DAObject implements IMailMessage{ @Id @GeneratedValue(strategy=GenerationType.AUTO) @@ -78,9 +78,9 @@ public class MailMessage extends DAObject { /** * The list to which the email was originally sent */ - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch=FetchType.LAZY, targetEntity=MailingList.class) @JoinColumn(name="MLIST_ID") - private MailingList list; + private IMailingList list; /** * Unique ID for this message in the database @@ -163,7 +163,7 @@ public void setDepth(int depth) { this.depth = depth; } - public Developer getSender() { + public IDeveloper getSender() { return sender; } @@ -171,11 +171,11 @@ public void setSender( Developer value ) { sender = value; } - public MailingList getList() { + public IMailingList getList() { return list; } - public void setList( MailingList value ) { + public void setList(IMailingList value ) { list = value; } @@ -262,7 +262,7 @@ public static MailMessage getMessageByFileName(String filename) { /** * Get the latest known mail message for the provided project, or null. */ - public static MailMessage getLatestMailMessage(StoredProject sp) { + public static MailMessage getLatestMailMessage(Project sp) { DBService dbs = AlitheiaCore.getInstance().getDBService(); String paramStoredProject = "paramStoredProject"; diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/MailMessageMeasurement.java b/alitheia/core/src/main/java/eu/sqooss/service/db/MailMessageMeasurement.java index 8a40c22d6..3151f7824 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/MailMessageMeasurement.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/MailMessageMeasurement.java @@ -33,6 +33,8 @@ package eu.sqooss.service.db; +import java.util.Set; + import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -64,9 +66,9 @@ public class MailMessageMeasurement extends MetricMeasurement { /** * The thread against which the measurement was made */ - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity=MailMessage.class) @JoinColumn(name = "MAILMESSAGE_ID", referencedColumnName = "MAILMESSAGE_ID") - private MailMessage mail; + private IMailMessage mail; public MailMessageMeasurement() { super(); @@ -93,7 +95,7 @@ public MailMessageMeasurement() { * @param mail Mail message this measurement is for * @param value (String) value representation of the measurement */ - public MailMessageMeasurement(Metric m, MailMessage mail, String value) { + public MailMessageMeasurement(Metric m, IMailMessage mail, String value) { super(); setMetric(m); setMail(mail); @@ -108,11 +110,11 @@ public void setId(long id) { this.id = id; } - public MailMessage getMail() { + public IMailMessage getMail() { return mail; } - public void setMail(MailMessage mail) { + public void setMail(IMailMessage mail) { this.mail = mail; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/MailingList.java b/alitheia/core/src/main/java/eu/sqooss/service/db/MailingList.java index 1b92720cc..a00c9acde 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/MailingList.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/MailingList.java @@ -64,7 +64,7 @@ */ @Entity @Table(name="MAILINGLIST") -public class MailingList extends DAObject { +public class MailingList extends DAObject implements IMailingList{ @Id @GeneratedValue(strategy=GenerationType.AUTO) @@ -80,9 +80,9 @@ public class MailingList extends DAObject { /** * The project to which this list is related */ - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch=FetchType.LAZY, targetEntity=StoredProject.class) @JoinColumn(name="PROJECT_ID") - private StoredProject storedProject; + private Project storedProject; /** * The set of available messages in this list @@ -114,11 +114,11 @@ public void setListId(String li) { this.listId = li; } - public StoredProject getStoredProject() { + public Project getStoredProject() { return storedProject; } - public void setStoredProject(StoredProject sp) { + public void setStoredProject(Project sp) { this.storedProject = sp; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/MailingListThread.java b/alitheia/core/src/main/java/eu/sqooss/service/db/MailingListThread.java index 791eda19c..9c5ffb859 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/MailingListThread.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/MailingListThread.java @@ -74,9 +74,9 @@ public class MailingListThread extends DAObject { private long id; /** The mailing list this thread belongs to */ - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch=FetchType.LAZY, targetEntity=MailingList.class) @JoinColumn(name="MAILING_LIST_ID", referencedColumnName = "MLIST_ID") - private MailingList list; + private IMailingList list; /** Flag to identify a thread as a flamewar */ @Column(name="IS_FLAME") @@ -92,33 +92,30 @@ public class MailingListThread extends DAObject { /** * A set containing the messages that belong to this thread */ - @OneToMany(mappedBy="thread", orphanRemoval=true) - private Set messages; + @OneToMany(mappedBy="thread", orphanRemoval=true, targetEntity=MailMessage.class) + private Set messages; - @OneToMany(fetch=FetchType.LAZY, mappedBy="thread", cascade=CascadeType.ALL) - private Set measurements; - - public Set getMessages() { + public Set getMessages() { return messages; } - public void setMessages(Set messages) { + public void setMessages(Set messages) { this.messages = messages; } public MailingListThread() {} - public MailingListThread(MailingList l, Date d) { + public MailingListThread(IMailingList l, Date d) { this.list = l; this.isFlameWar = false; this.lastUpdated = d; } - public MailingList getList() { + public IMailingList getList() { return list; } - public void setList(MailingList list) { + public void setList(IMailingList list) { this.list = list; } @@ -153,19 +150,28 @@ public void setLastUpdated(Date lastUpdated) { /** * Get the email that kickstarted this thread. */ - public MailMessage getStartingEmail() { + public IMailMessage getStartingEmail() { DBService dbs = AlitheiaCore.getInstance().getDBService(); Map params = new HashMap(); - params.put("thread", this); - params.put("depth", 0); + - List mm = dbs.findObjectsByProperties(MailMessage.class, - params); + String paramThread = "paramThread"; + String paramDepth = "paramDepth"; + + String query = "select mm " + + " from MailMessage mm, MailingListThread mt " + + " where mm.thread = mt " + + " and mt = :" + paramThread + + " and mm.depth = :" + paramDepth ; + params.put(paramThread, this); + params.put(paramDepth, 0); + + List mm = (List) dbs.doHQL(query, params, 1); if (!mm.isEmpty()) - return mm.get(0); + return (IMailMessage) mm.get(0); return null; } @@ -175,7 +181,7 @@ public MailMessage getStartingEmail() { * * @return The last MailMessage in a thread. */ - public List getMessagesByArrivalOrder() { + public List getMessagesByArrivalOrder() { DBService dbs = AlitheiaCore.getInstance().getDBService(); String paramThread = "paramThread"; @@ -188,7 +194,7 @@ public List getMessagesByArrivalOrder() { Map params = new HashMap(1); params.put(paramThread, this); - List mm = (List) dbs.doHQL(query, params); + List mm = (List) dbs.doHQL(query, params); if (mm == null || mm.isEmpty()) return Collections.emptyList(); @@ -225,7 +231,7 @@ public int getThreadDepth() { * @param level The thread depth level for which to select emails. * @return The emails at the specified thread depth. */ - public List getMessagesAtLevel(int level) { + public List getMessagesAtLevel(int level) { DBService dbs = AlitheiaCore.getInstance().getDBService(); @@ -243,19 +249,11 @@ public List getMessagesAtLevel(int level) { params.put(paramThread, this); params.put(paramDepth, level); - List mm = (List) dbs.doHQL(query, params); + List mm = (List) dbs.doHQL(query, params); if (mm == null || mm.isEmpty()) return Collections.emptyList(); return mm; } - - public void setMeasurements(Set measurements) { - this.measurements = measurements; - } - - public Set getMeasurements() { - return measurements; - } } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/MailingListThreadMeasurement.java b/alitheia/core/src/main/java/eu/sqooss/service/db/MailingListThreadMeasurement.java index 2ad202000..0ce43afd9 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/MailingListThreadMeasurement.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/MailingListThreadMeasurement.java @@ -33,6 +33,10 @@ package eu.sqooss.service.db; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -46,89 +50,108 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import eu.sqooss.core.AlitheiaCore; + /** - * Instances of this class represent a measurement made against a - * specific mailing list thread, as stored in the database + * Instances of this class represent a measurement made against a specific + * mailing list thread, as stored in the database */ @Entity -@Table(name="ML_THREAD_MEASUREMENT") -@XmlRootElement(name="mlthread-measurement") +@Table(name = "ML_THREAD_MEASUREMENT") +@XmlRootElement(name = "mlthread-measurement") public class MailingListThreadMeasurement extends MetricMeasurement { @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "ML_THREAD_MEASUREMENT_ID") - @XmlElement(name = "id") - private long id; + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "ML_THREAD_MEASUREMENT_ID") + @XmlElement(name = "id") + private long id; + + /** + * The thread against which the measurement was made + */ + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "THREAD_ID", referencedColumnName = "MLTHREAD_ID") + private MailingListThread thread; + + public MailingListThreadMeasurement() { + super(); + } + + /** + * The metric to which this result belongs + */ + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "METRIC_ID", referencedColumnName = "METRIC_ID") + private Metric metric; + + /** + * A representation of the calculation result + */ + @Column(name = "RESULT") + private String result; /** - * The thread against which the measurement was made - */ - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinColumn(name = "THREAD_ID", referencedColumnName = "MLTHREAD_ID") - private MailingListThread thread; - - public MailingListThreadMeasurement() { - super(); - } - - /** - * The metric to which this result belongs - */ - @ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL) - @JoinColumn(name="METRIC_ID", referencedColumnName="METRIC_ID") - private Metric metric; - - /** - * A representation of the calculation result - */ - @Column(name="RESULT") - private String result; - - /** - * Convenience constructor to avoid having to call three methods - * to set up sensible values in a measurement. - * - * @param m Metric this measurement is from - * @param mt Thread this measurement is for - * @param value (String) value representation of the measurement - */ - public MailingListThreadMeasurement(Metric m, MailingListThread mt, String value) { - super(); - setMetric(m); - setThread(mt); - setResult(value); - } - - public long getId() { + * Convenience constructor to avoid having to call three methods to set up + * sensible values in a measurement. + * + * @param m + * Metric this measurement is from + * @param mt + * Thread this measurement is for + * @param value + * (String) value representation of the measurement + */ + public MailingListThreadMeasurement(Metric m, MailingListThread mt, + String value) { + super(); + setMetric(m); + setThread(mt); + setResult(value); + } + + public long getId() { return id; } public void setId(long id) { this.id = id; } - - public MailingListThread getThread() { - return thread; - } - - public void setThread(MailingListThread thread) { - this.thread = thread; - } - - public Metric getMetric() { - return metric; - } - - public void setMetric(Metric metric) { - this.metric = metric; - } - - public String getResult() { - return result; - } - - public void setResult(String result) { - this.result = result; - } + + public MailingListThread getThread() { + return thread; + } + + public void setThread(MailingListThread thread) { + this.thread = thread; + } + + public Metric getMetric() { + return metric; + } + + public void setMetric(Metric metric) { + this.metric = metric; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + @SuppressWarnings("unchecked") + public static List getAllMeasurementsForThread( + MailingListThread thread) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramThread = "paramThread"; + String query = "SELECT mltm FROM MailingListThreadMeasurement mltm " + + "WHERE mltm.thread = :" + paramThread; + + Map params = new HashMap(); + params.put(paramThread, thread); + return (List) dbs.doHQL(query, params); + } } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/Metric.java b/alitheia/core/src/main/java/eu/sqooss/service/db/Metric.java index a3b9d8bb0..a4d9ed5dc 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/Metric.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/Metric.java @@ -36,7 +36,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; @@ -47,7 +46,6 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @@ -82,9 +80,9 @@ public class Metric extends DAObject { /** * the Alitheia Core plugin providing the functionality for this metric */ - @ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL) + @ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL, targetEntity=Plugin.class) @JoinColumn(name="PLUGIN_ID", referencedColumnName="PLUGIN_ID") - private Plugin plugin; + private IPlugin plugin; /** * A representation of the type of metric: SOURCE_CODE - Relating to SVN @@ -111,30 +109,6 @@ public class Metric extends DAObject { @Column(name="DESCRIPTION") private String description; - @OneToMany(mappedBy="metric", cascade = CascadeType.ALL, orphanRemoval = true) - private Set projectMeasurements; - - @OneToMany(mappedBy="metric", cascade = CascadeType.ALL, orphanRemoval = true) - private Set versionMeasurements; - - @OneToMany(mappedBy="metric", cascade = CascadeType.ALL, orphanRemoval = true) - private Set fileMeasurements; - - @OneToMany(mappedBy="metric", cascade = CascadeType.ALL, orphanRemoval = true) - private Set nsMeasurements; - - @OneToMany(mappedBy="metric", cascade = CascadeType.ALL, orphanRemoval = true) - private Set encUnitMeasurements; - - @OneToMany(mappedBy="metric", cascade = CascadeType.ALL, orphanRemoval = true) - private Set execUnitMeasurements; - - @OneToMany(mappedBy="metric", cascade = CascadeType.ALL, orphanRemoval = true) - private Set mlThreadMeasurements; - - @OneToMany(mappedBy="metric", cascade = CascadeType.ALL, orphanRemoval = true) - private Set mmMeasurements; - public Metric() { // Nothing to do here } @@ -163,11 +137,11 @@ public void setDescription(String description) { this.description = description; } - public Plugin getPlugin() { + public IPlugin getPlugin() { return plugin; } - public void setPlugin(Plugin plugin) { + public void setPlugin(IPlugin plugin) { this.plugin = plugin; } @@ -179,80 +153,11 @@ public void setMnemonic(String mnemonic) { this.mnemonic = mnemonic; } - public Set getProjectMeasurements() { - return projectMeasurements; - } - - public void setProjectMeasurements( - Set projectMeasurements) { - this.projectMeasurements = projectMeasurements; - } - - public Set getVersionMeasurements() { - return versionMeasurements; - } - - public void setVersionMeasurements( - Set versionMeasurements) { - this.versionMeasurements = versionMeasurements; - } - - public Set getFileMeasurements() { - return fileMeasurements; - } - - public void setFileMeasurements(Set fileMeasurements) { - this.fileMeasurements = fileMeasurements; - } - - - public Set getNsMeasurements() { - return nsMeasurements; - } - - public void setNsMeasurements(Set nsMeasurements) { - this.nsMeasurements = nsMeasurements; - } - - public Set getEncUnitMeasurements() { - return encUnitMeasurements; - } - - public void setEncUnitMeasurements( - Set encUnitMeasurements) { - this.encUnitMeasurements = encUnitMeasurements; - } - - public Set getExecUnitMeasurements() { - return execUnitMeasurements; - } - - public void setExecUnitMeasurements( - Set execUnitMeasurements) { - this.execUnitMeasurements = execUnitMeasurements; - } - - public Set getMlThreadMeasurements() { - return mlThreadMeasurements; - } - - public void setMlThreadMeasurements( - Set mlThreadMeasurements) { - this.mlThreadMeasurements = mlThreadMeasurements; - } - - public Set getMmMeasurements() { - return mmMeasurements; - } - - public void setMmMeasurements(Set mmMeasurements) { - this.mmMeasurements = mmMeasurements; - } /** * Check whether the metric was ever run on the provided project. */ - public boolean isEvaluated (StoredProject p) { + public boolean isEvaluated (Project p) { DBService dbs = AlitheiaCore.getInstance().getDBService(); StringBuffer query = new StringBuffer(); @@ -292,6 +197,7 @@ public boolean isEvaluated (StoredProject p) { .append("where nm=:metric ") .append("and nm.namespace.changeVersion.project=:project"); break; + case PROJECT: case BUG: case MAILING_LIST: case DEVELOPER: @@ -308,7 +214,8 @@ public boolean isEvaluated (StoredProject p) { return false; } - @Override + //TODO: this.equals(that) != that.equals(this) + @Override public boolean equals(Object obj) { if ((obj == null) || (!(obj instanceof Metric))) { return false; @@ -367,6 +274,21 @@ public static List getAllMetrics() { DBService dbs = AlitheiaCore.getInstance().getDBService(); return (List) dbs.doHQL("from Metric"); } + + /** + * Get all metrics for the given type + * @param type to filter on. + * @return all metrics of this type. + */ + public static List getMetricsByType(MetricType type) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramType = "paramType"; + String query = "SELECT m FROM Metric m WHERE m.metricType = :" + paramType; + + Map params = new HashMap(); + params.put(paramType, type); + return (List) dbs.doHQL(query, params); + } } // vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/MetricMeasurement.java b/alitheia/core/src/main/java/eu/sqooss/service/db/MetricMeasurement.java index 797f203db..9d6f3e9c3 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/MetricMeasurement.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/MetricMeasurement.java @@ -33,6 +33,18 @@ package eu.sqooss.service.db; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.FetchType; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +import eu.sqooss.core.AlitheiaCore; + /** * Instances of this class represent the result of a metric * calculation as stored in the database. This class is extended by @@ -41,7 +53,19 @@ */ public abstract class MetricMeasurement extends DAObject { + public abstract String getResult(); + + public static List getMeasurementsForMetric(Class clazz, Metric m) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramMetric = "paramMetric"; + String query = "SELECT mm FROM "+ clazz.getName() + " mm" + + " WHERE mm.metric = :" + paramMetric; + + Map params = new HashMap(); + params.put(paramMetric, m); + return (List) dbs.doHQL(query, params); + } } // vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/MetricType.java b/alitheia/core/src/main/java/eu/sqooss/service/db/MetricType.java index 5b8d0721a..4aa434916 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/MetricType.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/MetricType.java @@ -74,12 +74,6 @@ public class MetricType extends DAObject { @Column(name="type") private String type; - /** - * A list of all metrics of this type - */ - @OneToMany(mappedBy="metricType", cascade = CascadeType.ALL, orphanRemoval = true) - private Set metrics; - /** * An enumeration of all possible metric types. Metric types map to * activation types, but not necessarily on a 1-1 basis. @@ -95,6 +89,7 @@ public enum Type { DEVELOPER, NAMESPACE, EXECUNIT, ENCAPSUNIT; + //TODO: Misses StoredProject or "PROJECT" enum... This leads to 3 failing/erroring tests. public static Type fromString(String s) { if ("SOURCE_CODE".equals(s) || "SOURCE_FILE".equals(s)) return Type.SOURCE_FILE; @@ -118,6 +113,8 @@ else if ("EXECUNIT".equals(s)) return Type.EXECUNIT; else if ("ENCAPSUNIT".equals(s)) return Type.ENCAPSUNIT; + else if ("PROJECT".equals(s) || "STOREDPROJECT".equals(s)) + return Type.PROJECT; else return null; } @@ -154,14 +151,6 @@ public void setEnumType(Type type) { public void setType(String s) { this.type = Type.fromString(s).toString(); } - - public Set getMetrics() { - return metrics; - } - - public void setMetrics(Set metrics) { - this.metrics = metrics; - } /** * Get the corresponding DAO for the provided metric type. @@ -215,32 +204,35 @@ public static MetricType.Type fromActivator(Class activator) } public Class toActivator() { - switch(Type.fromString(this.type)) { - case SOURCE_DIRECTORY: - return ProjectDirectory.class; - case SOURCE_FILE: - return ProjectFile.class; - case PROJECT_VERSION: - return ProjectVersion.class; - case PROJECT: - return StoredProject.class; - case MAILMESSAGE: - return MailMessage.class; - case MAILING_LIST: - return MailingList.class; - case MAILTHREAD: - return MailingListThread.class; - case BUG: - return Bug.class; - case DEVELOPER: - return Developer.class; - case NAMESPACE: - return NameSpace.class; - case ENCAPSUNIT: - return EncapsulationUnit.class; - case EXECUNIT: - return ExecutionUnit.class; - } + Type t = Type.fromString(this.type); + if (t != null) { + switch(t) { + case SOURCE_DIRECTORY: + return ProjectDirectory.class; + case SOURCE_FILE: + return ProjectFile.class; + case PROJECT_VERSION: + return ProjectVersion.class; + case PROJECT: + return StoredProject.class; + case MAILMESSAGE: + return MailMessage.class; + case MAILING_LIST: + return MailingList.class; + case MAILTHREAD: + return MailingListThread.class; + case BUG: + return Bug.class; + case DEVELOPER: + return Developer.class; + case NAMESPACE: + return NameSpace.class; + case ENCAPSUNIT: + return EncapsulationUnit.class; + case EXECUNIT: + return ExecutionUnit.class; + } + } return null; } } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/NameSpace.java b/alitheia/core/src/main/java/eu/sqooss/service/db/NameSpace.java index 56360d423..e14171cb5 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/NameSpace.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/NameSpace.java @@ -65,17 +65,17 @@ public class NameSpace extends DAObject { String name; /** Version until this namespace instance is valid */ - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectVersion.class) @JoinColumn(name = "CHANGE_VERSION_ID") - ProjectVersion changeVersion; + Version changeVersion; /** Encapsulation units, if any, */ - @OneToMany(mappedBy = "namespace", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) - Set encapsulationUnits; + @OneToMany(mappedBy = "namespace", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, targetEntity=EncapsulationUnit.class) + Set encapsulationUnits; /** Encapsulation units belonging to this namespace */ - @OneToMany(mappedBy = "namespace", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) - Set executionUnits; + @OneToMany(mappedBy = "namespace", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, targetEntity=ExecutionUnit.class) + Set executionUnits; /** The namespace language */ @Enumerated(EnumType.STRING) @@ -84,10 +84,6 @@ public class NameSpace extends DAObject { @Column(name = "LANG") Language lang; - /** Measurements for this namespace*/ - @OneToMany(mappedBy = "namespace", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) - private Set measurements; - @Override public long getId() { return id; @@ -106,31 +102,31 @@ public void setName(String name) { this.name = name; } - public ProjectVersion getChangeVersion() { + public Version getChangeVersion() { return changeVersion; } - public void setChangeVersion(ProjectVersion changeVersion) { + public void setChangeVersion(Version changeVersion) { this.changeVersion = changeVersion; } - public Set getEncapsulationUnits() { + public Set getEncapsulationUnits() { if (encapsulationUnits == null) - encapsulationUnits = new HashSet(); + encapsulationUnits = new HashSet(); return encapsulationUnits; } - public void setEncapsulationUnits(Set encapsulationUnits) { + public void setEncapsulationUnits(Set encapsulationUnits) { this.encapsulationUnits = encapsulationUnits; } - public Set getExecutionUnits() { + public Set getExecutionUnits() { return executionUnits; } - public void setExecutionUnits(Set executionUnits) { + public void setExecutionUnits(Set executionUnits) { if (executionUnits == null) - executionUnits = new HashSet(); + executionUnits = new HashSet(); this.executionUnits = executionUnits; } @@ -142,15 +138,7 @@ public void setLang(Language lang) { this.lang = lang; } - public void setMeasurements(Set measurements) { - this.measurements = measurements; - } - - public Set getMeasurements() { - return measurements; - } - - public static NameSpace findByVersionName(ProjectVersion pv, String name) { + public static NameSpace findByVersionName(Version pv, String name) { DBService dbs = AlitheiaCore.getInstance().getDBService(); HashMap params = new HashMap(); params.put("pv", pv); diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/NameSpaceMeasurement.java b/alitheia/core/src/main/java/eu/sqooss/service/db/NameSpaceMeasurement.java index c70927ecb..2e5cabd01 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/NameSpaceMeasurement.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/NameSpaceMeasurement.java @@ -1,5 +1,9 @@ package eu.sqooss.service.db; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -13,6 +17,8 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import eu.sqooss.core.AlitheiaCore; + /** * Instances of this class represent a measurement made against a * namespace version, as stored in the database @@ -85,4 +91,14 @@ public void setNamespace(NameSpace namespace) { public NameSpace getNamespace() { return namespace; } + + public static List getMeasurementsByNameSpace(NameSpace ns) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramNS = "paramNS"; + String query = "SELECT nsm FROM NameSpaceMeasurement nsm WHERE nsm.namespace = :" + paramNS; + + Map params = new HashMap(); + params.put(paramNS, ns); + return (List) dbs.doHQL(query, params); + } } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/Plugin.java b/alitheia/core/src/main/java/eu/sqooss/service/db/Plugin.java index a1529a2df..f4dd51cb2 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/Plugin.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/Plugin.java @@ -59,7 +59,7 @@ */ @Entity @Table(name="PLUGIN") -public class Plugin extends DAObject { +public class Plugin extends DAObject implements IPlugin { @Id @GeneratedValue(strategy=GenerationType.AUTO) @@ -188,6 +188,7 @@ public void setSupportedMetrics(Set supportedMetrics) { this.supportedMetrics = supportedMetrics; } + public static List getPluginByName(String name) { DBService db = AlitheiaCore.getInstance().getDBService(); HashMap s = new HashMap(); diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/PluginConfiguration.java b/alitheia/core/src/main/java/eu/sqooss/service/db/PluginConfiguration.java index 5456f9885..471cc4e38 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/PluginConfiguration.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/PluginConfiguration.java @@ -70,9 +70,9 @@ public class PluginConfiguration extends DAObject { @Column(name="MSG") private String msg; - @ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL) + @ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL, targetEntity=Plugin.class) @JoinColumn(name="PLUGIN_ID", referencedColumnName="PLUGIN_ID") - private Plugin plugin; + private IPlugin plugin; public long getId() { return id; @@ -98,11 +98,11 @@ public void setType(String type) { this.type = type; } - public Plugin getPlugin() { + public IPlugin getPlugin() { return plugin; } - public void setPlugin(Plugin p) { + public void setPlugin(IPlugin p) { this.plugin = p; } @@ -125,7 +125,7 @@ public void setMsg(String msg) { /** * Get a PluginConfiguration entry DAO or null in */ - public static PluginConfiguration getConfigurationEntry(Plugin p, HashMap names) { + public static PluginConfiguration getConfigurationEntry(IPlugin p, HashMap names) { DBService db = AlitheiaCore.getInstance().getDBService(); names.put("plugin", p); @@ -144,7 +144,7 @@ public static PluginConfiguration getConfigurationEntry(Plugin p, HashMap names) { + public static boolean updConfigurationEntry(IPlugin p, HashMap names) { DBService db = AlitheiaCore.getInstance().getDBService(); PluginConfiguration pc = getConfigurationEntry(p, names); diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/Project.java b/alitheia/core/src/main/java/eu/sqooss/service/db/Project.java new file mode 100644 index 000000000..d06b09887 --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/Project.java @@ -0,0 +1,12 @@ +package eu.sqooss.service.db; + +public interface Project extends IDAObject{ + + String getName(); + String getBtsUrl(); + String getMailUrl(); + String getScmUrl(); + ClusterNode getClusternode(); + boolean isEvaluated(); + +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFile.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFile.java index 399ae78ad..73cf88368 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFile.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFile.java @@ -69,7 +69,7 @@ @Entity @Table(name="PROJECT_FILE") @XmlRootElement(name="file") -public class ProjectFile extends DAObject{ +public class ProjectFile extends DAObject implements IProjectFile{ private static final String qPrevVersion = "select pf from ProjectVersion pv, ProjectFile pf where pf.projectVersion = pv.id and pv.project.id = :paramProject and pv.sequence < :paramsequence and pf.name = :paramFile and pf.dir.id = :paramDir order by pv.sequence desc"; private static final String qPrevVersionCopy = "select pf from ProjectVersion pv, ProjectFile pf where pf.projectVersion = pv.id and pv.project.id = :paramProject and pv.sequence < :paramsequence and ((pf.name = :paramFile and pf.dir.id = :paramDir) or ( pf.name = :paramCopyFromName and pf.dir.id = :paramCopyFromDir)) order by pv.sequence desc"; @@ -93,9 +93,9 @@ public class ProjectFile extends DAObject{ /** * the version of the project to which this file relates */ - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectVersion.class) @JoinColumn(name="PROJECT_VERSION_ID") - private ProjectVersion projectVersion; + private Version projectVersion; /** * The file's status in this revision @@ -124,24 +124,24 @@ public class ProjectFile extends DAObject{ * The start revision a file has been valid from (the * addition/copy revision) */ - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectVersion.class) @JoinColumn(name="VALID_FROM_ID") - private ProjectVersion validFrom; + private Version validFrom; /** * The revision this file version stopped being */ - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectVersion.class) @JoinColumn(name="VALID_TO_ID") - private ProjectVersion validUntil; + private Version validUntil; /** * The ProjectFile this file was copied from. Only gets a value * for file copy operations */ - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectFile.class) @JoinColumn(name="COPY_FROM_ID") - private ProjectFile copyFrom; + private IProjectFile copyFrom; /** * If this "file" contains source code files, it is marked as a module @@ -159,14 +159,14 @@ public class ProjectFile extends DAObject{ /** * Classes defined in this file */ - @OneToMany(mappedBy = "file", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) - private Set encapsulationUnits; + @OneToMany(mappedBy = "file", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, targetEntity=EncapsulationUnit.class) + private Set encapsulationUnits; /** * Methods defined in this file */ - @OneToMany(mappedBy = "file", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) - private Set executionUnits; + @OneToMany(mappedBy = "file", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, targetEntity=ExecutionUnit.class) + private Set executionUnits; public ProjectFile() { // Nothing to see here @@ -174,7 +174,7 @@ public ProjectFile() { module = null; } - public ProjectFile(ProjectVersion pv) { + public ProjectFile(Version pv) { this(); this.projectVersion = pv; this.setValidFrom(pv); @@ -190,7 +190,7 @@ public ProjectFile(ProjectVersion pv) { * and the version does not match (e.g. assigning a version from * a different project to a file). */ - public ProjectFile(ProjectFile f, ProjectVersion v) + public ProjectFile(IProjectFile f, Version v) throws IllegalArgumentException { if (f.getProjectVersion().getProject().getId() != v.getProject().getId()) { throw new IllegalArgumentException( @@ -227,11 +227,11 @@ public String getName() { return name; } - public void setProjectVersion(ProjectVersion projectVersion ) { + public void setProjectVersion(Version projectVersion ) { this.projectVersion = projectVersion; } - public ProjectVersion getProjectVersion() { + public Version getProjectVersion() { return projectVersion; } @@ -295,27 +295,27 @@ public void setDir(Directory dir) { this.dir = dir; } - public ProjectVersion getValidFrom() { + public Version getValidFrom() { return validFrom; } - public void setValidFrom(ProjectVersion validFrom) { + public void setValidFrom(Version validFrom) { this.validFrom = validFrom; } - public ProjectVersion getValidUntil() { + public Version getValidUntil() { return validUntil; } - public void setValidUntil(ProjectVersion validUntil) { + public void setValidUntil(Version validUntil) { this.validUntil = validUntil; } - public ProjectFile getCopyFrom() { + public IProjectFile getCopyFrom() { return copyFrom; } - public void setCopyFrom(ProjectFile copyFrom) { + public void setCopyFrom(IProjectFile copyFrom) { this.copyFrom = copyFrom; } @@ -328,23 +328,23 @@ public void setMeasurements(Set measurements) { } - public void setEncapsulationUnits(Set encapsulationUnits) { + public void setEncapsulationUnits(Set encapsulationUnits) { this.encapsulationUnits = encapsulationUnits; } - public Set getEncapsulationUnits() { + public Set getEncapsulationUnits() { if (encapsulationUnits == null) - encapsulationUnits = new HashSet(); + encapsulationUnits = new HashSet(); return encapsulationUnits; } - public void setExecutionUnits(Set executionUnits) { + public void setExecutionUnits(Set executionUnits) { if (executionUnits == null) - executionUnits = new HashSet(); + executionUnits = new HashSet(); this.executionUnits = executionUnits; } - public Set getExecutionUnits() { + public Set getExecutionUnits() { return executionUnits; } @@ -366,6 +366,7 @@ public String getFileName() { * * @return The corresponding Directory DAO */ + // TODO: Impossible: "getFileName() == null" public Directory toDirectory() { if ((isDirectory) && (getFileName() != null)) { DBService dbs = AlitheiaCore.getInstance().getDBService(); @@ -385,7 +386,7 @@ public Directory toDirectory() { * @return The previous file revision, or null if the file is not found * or if the file was added in the provided revision */ - public ProjectFile getPreviousFileVersion() { + public IProjectFile getPreviousFileVersion() { DBService dbs = AlitheiaCore.getInstance().getDBService(); //No need to query if a file was just added @@ -432,7 +433,8 @@ public ProjectFile getPreviousFileVersion() { * @return The project version's number where this file was deleted, * or null if this file still exist. */ - public static ProjectVersion getDeletionVersion(ProjectFile pf) { + // TODO: Why is this static? + public static Version getDeletionVersion(ProjectFile pf) { DBService db = AlitheiaCore.getInstance().getDBService(); // Skip files which are in a "DELETED" state @@ -481,7 +483,7 @@ public static ProjectVersion getDeletionVersion(ProjectFile pf) { params.put(paramProject, pf.getProjectVersion().getProject()); params.put(paramOrder, pf.getProjectVersion().getSequence()); - List pvs = (List) db.doHQL(query, params); + List pvs = (List) db.doHQL(query, params); if (pvs.size() <= 0) return null; @@ -642,14 +644,15 @@ public static ProjectFile findFile(Long projectId, String name, return pfs.get(0); } - public List getChangedExecutionUnits() { + public List getChangedExecutionUnits() { DBService dbs = AlitheiaCore.getInstance().getDBService(); Map params = new HashMap(); params.put("file", this); - return (List)dbs.doHQL(qChangedMethods, params); + return (List)dbs.doHQL(qChangedMethods, params); } + // TODO: Impossible condition (can not be false) public String toString() { StringBuilder sb = new StringBuilder(); return sb.append(projectVersion.getRevisionId()) @@ -677,6 +680,16 @@ public int hashCode() { hash = 31 * hash + (null == projectVersion ? 0 : projectVersion.hashCode()); return hash; } + + public static List getProjectFilesByState(ProjectFileState state) { + DBService dbs = AlitheiaCore.getInstance().getDBService(); + String paramState = "paramState"; + String query = "SELECT pf FROM ProjectFile pf WHERE pf.state = :" + paramState; + + Map params = new HashMap(); + params.put(paramState, state); + return (List) dbs.doHQL(query, params); + } } //vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFileMeasurement.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFileMeasurement.java index 444ad86e3..cb988f010 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFileMeasurement.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFileMeasurement.java @@ -77,9 +77,9 @@ public class ProjectFileMeasurement extends MetricMeasurement { /** * The file against which the measurement was made */ - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectFile.class) @JoinColumn(name = "PROJECT_FILE_ID", referencedColumnName = "PROJECT_FILE_ID") - private ProjectFile projectFile; + private IProjectFile projectFile; public ProjectFileMeasurement() { // Nothing to do here @@ -94,7 +94,7 @@ public ProjectFileMeasurement() { * @param f File this measurement is for * @param value (String) value representation of the measurement */ - public ProjectFileMeasurement(Metric m, ProjectFile f, String value) { + public ProjectFileMeasurement(Metric m, IProjectFile f, String value) { super(); setMetric(m); setProjectFile(f); @@ -110,11 +110,11 @@ public void setId(long id) { } - public ProjectFile getProjectFile() { + public IProjectFile getProjectFile() { return projectFile; } - public void setProjectFile(ProjectFile pf) { + public void setProjectFile(IProjectFile pf) { this.projectFile = pf; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFileState.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFileState.java index 612da0404..6f7bf087a 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFileState.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectFileState.java @@ -85,9 +85,6 @@ public class ProjectFileState extends DAObject { @XmlElement private int status; - @OneToMany(fetch = FetchType.LAZY, orphanRemoval=true, mappedBy="state") - private Set files; - public String toString() { switch (status) { case STATE_ADDED: @@ -164,14 +161,6 @@ public void setStatus(int status) { this.status = status; } - public Set getFiles() { - return files; - } - - public void setFiles(Set files) { - this.files = files; - } - public long getId() { return id; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersion.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersion.java index f32cebc48..dab7d2aed 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersion.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersion.java @@ -80,7 +80,7 @@ @XmlRootElement(name="version") @Entity @Table(name="PROJECT_VERSION") -public class ProjectVersion extends DAObject { +public class ProjectVersion extends DAObject implements Version{ @Id @GeneratedValue(strategy=GenerationType.AUTO) @@ -91,9 +91,9 @@ public class ProjectVersion extends DAObject { /** * The project to which this object relates */ - @ManyToOne(fetch=FetchType.LAZY) + @ManyToOne(fetch=FetchType.LAZY, targetEntity=StoredProject.class) @JoinColumn(name="STORED_PROJECT_ID") - private StoredProject project; + private Project project; /** * The SCM version identifier to which this object relates @@ -138,8 +138,8 @@ public class ProjectVersion extends DAObject { /** * The files changed in this version */ - @OneToMany(fetch=FetchType.LAZY, mappedBy="projectVersion", orphanRemoval=true, cascade=CascadeType.ALL) - private Set versionFiles; + @OneToMany(fetch=FetchType.LAZY, mappedBy="projectVersion", orphanRemoval=true, cascade=CascadeType.ALL, targetEntity=ProjectFile.class) + private Set versionFiles; /** * The set of known tags in this version of the project @@ -200,7 +200,7 @@ public ProjectVersion() { // Nothing to do } - public ProjectVersion(StoredProject project) { + public ProjectVersion(Project project) { this.project = project; } @@ -212,11 +212,11 @@ public void setId(long id) { this.id = id; } - public StoredProject getProject() { + public Project getProject() { return project; } - public void setProject(StoredProject project) { + public void setProject(Project project) { this.project = project; } @@ -284,15 +284,15 @@ public void setSequence(long sequence) { /** * Returns the files that were changed in this revision */ - public Set getVersionFiles() { + public Set getVersionFiles() { if (versionFiles == null) { - versionFiles = new HashSet(); + versionFiles = new HashSet(); } return versionFiles; } - public void setVersionFiles( Set versionFiles ) { + public void setVersionFiles( Set versionFiles ) { this.versionFiles = versionFiles; } @@ -367,6 +367,7 @@ public Set getNamespaces() { * @param p comparison version * @return true if this <= p, in terms of revision order */ + // TODO: fix useless if (for most versions here) public boolean lte(ProjectVersion p) { if (p.getProject().getId() != p.getProject().getId()) throw new IllegalArgumentException("Project " + p.getProject() + @@ -513,7 +514,7 @@ public ProjectVersion getNextVersion() { * @return ProjectVersion object corresponding to the revision, * or null if there is none. */ - public static ProjectVersion getVersionByRevision(StoredProject project, String revisionId) { + public static ProjectVersion getVersionByRevision(Project project, String revisionId) { DBService dbs = AlitheiaCore.getInstance().getDBService(); Map parameters = new HashMap(); @@ -546,7 +547,7 @@ public static ProjectVersion getVersionByRevision(StoredProject project, String * or null if there is none. */ public static ProjectVersion getVersionByTimestamp( - StoredProject project, long timestamp) { + Project project, long timestamp) { DBService dbs = AlitheiaCore.getInstance().getDBService(); Map parameters = new HashMap(); @@ -570,7 +571,7 @@ public static ProjectVersion getVersionByTimestamp( * @param sp Project to lookup * @return The oldest recorded project revision */ - public static ProjectVersion getFirstProjectVersion(StoredProject sp) { + public static ProjectVersion getFirstProjectVersion(Project sp) { DBService dbs = AlitheiaCore.getInstance().getDBService(); Map parameterMap = new HashMap(); @@ -589,7 +590,7 @@ public static ProjectVersion getFirstProjectVersion(StoredProject sp) { * @return The ProjectVersion DAO for the latest version, * or null if not found */ - public static ProjectVersion getLastProjectVersion(StoredProject sp) { + public static ProjectVersion getLastProjectVersion(Project sp) { DBService dbs = AlitheiaCore.getInstance().getDBService(); Map parameterMap = new HashMap(); @@ -612,7 +613,7 @@ public static ProjectVersion getLastProjectVersion(StoredProject sp) { * @param p Project to look for * @return Last version measured, or revision 0. */ - public static ProjectVersion getLastMeasuredVersion(Metric m, StoredProject p) { + public static ProjectVersion getLastMeasuredVersion(Metric m, Project p) { String query = "select pv from ProjectVersionMeasurement pvm, ProjectVersion pv" + " where pvm.projectVersion = pv" + " and pvm.metric = :metric and pv.project = :project" + @@ -653,7 +654,7 @@ public long getFilesCount(ProjectFileState state) { parameters.put(parFileStatus, state); List queryResult = dbs.doHQL(query, parameters); // Return the query's result (if found) - if(queryResult != null || queryResult.size() > 0) + if(queryResult != null && queryResult.size() > 0) return (Long) queryResult.get(0); // Default result return 0; @@ -705,11 +706,11 @@ public long getLiveFilesCount() { public String toString() { - return "ProjectVersion(\"" + this.project.getName() + "\",r" + this.revisionId +")"; + return "ProjectVersion(\"" + this.project.toString() + "\",r" + this.revisionId +")"; } - private List getVersionFiles(Directory d, int mask) { + private List getVersionFiles(Directory d, int mask) { DBService dbs = AlitheiaCore.getInstance().getDBService(); String paramDirectory = "paramDirectory"; @@ -762,7 +763,7 @@ private List getVersionFiles(Directory d, int mask) { params.put(paramIsDirectory, isDirectory); } - List projectFiles = (List) dbs.doHQL(q.toString(), params); + List projectFiles = (List) dbs.doHQL(q.toString(), params); if (projectFiles == null) return Collections.emptyList(); @@ -774,7 +775,7 @@ private List getVersionFiles(Directory d, int mask) { /** * Returns all files that are live in this version. */ - public List getFiles() { + public List getFiles() { return getVersionFiles(null, ProjectVersion.MASK_ALL); } @@ -789,7 +790,7 @@ public List getFiles() { * directories * @return List of files visible in that version (may be empty, not null) */ - public List getFiles(Directory d, int mask) { + public List getFiles(Directory d, int mask) { return getVersionFiles(d, mask); } @@ -801,7 +802,7 @@ public List getFiles(Directory d, int mask) { * @param d Directory to list * @return List of files visible in that version (may be empty, not null) */ - public List getFiles(Directory d) { + public List getFiles(Directory d) { return getFiles(d, ProjectVersion.MASK_ALL); } @@ -816,7 +817,7 @@ public List getFiles(Directory d) { * specified pattern (may be empty, not null) * */ - public List getFiles(Pattern p) { + public List getFiles(Pattern p) { return getFiles(p, MASK_ALL); } @@ -835,11 +836,11 @@ public List getFiles(Pattern p) { * specified pattern (may be empty, not null) * */ - public List getFiles(Pattern p, int mask) { - List files = getVersionFiles(null, mask); - Set matchedFiles = new HashSet(); + public List getFiles(Pattern p, int mask) { + List files = getVersionFiles(null, mask); + Set matchedFiles = new HashSet(); - for ( ProjectFile pf : files ) { + for ( IProjectFile pf : files ) { Matcher m = p.matcher(pf.getFileName()); if (m.find()) { @@ -847,7 +848,7 @@ public List getFiles(Pattern p, int mask) { } } - return new ArrayList(matchedFiles); + return new ArrayList(matchedFiles); } /** @@ -857,7 +858,7 @@ public List getFiles(Pattern p, int mask) { * @return List of directories visible in that version (may be empty, * not null) */ - public List allDirs() { + public List allDirs() { return getVersionFiles(null, ProjectVersion.MASK_DIRECTORIES); } @@ -868,7 +869,7 @@ public List allDirs() { * @return List of files visible in that version (may be empty, * not null) */ - public List allFiles() { + public List allFiles() { return getVersionFiles(null, ProjectVersion.MASK_FILES); } @@ -924,13 +925,13 @@ public Branch getBranch() { /** * Filter files that changed in a version by their path name */ - public Set getVersionFiles(Pattern p) { - Set result = new HashSet(); - Set files = getVersionFiles(); + public Set getVersionFiles(Pattern p) { + Set result = new HashSet(); + Set files = getVersionFiles(); - Iterator it = files.iterator(); + Iterator it = files.iterator(); while (it.hasNext()) { - ProjectFile pf = it.next(); + IProjectFile pf = it.next(); Matcher m = p.matcher(pf.getFileName()); if (m.matches()) result.add(pf); @@ -957,6 +958,11 @@ public int hashCode() { hash = 31 * hash + (null == project ? 0 : project.hashCode()); return hash; } + + @Override + public void clearParents() { + this.parents.clear(); + } } //vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersionMeasurement.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersionMeasurement.java index c47c973e4..f4ec927e7 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersionMeasurement.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersionMeasurement.java @@ -77,9 +77,9 @@ public class ProjectVersionMeasurement extends MetricMeasurement { /** * The ProjectVersion to which the instance relates */ - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectVersion.class) @JoinColumn(name = "PROJECT_VERSION_ID") - private ProjectVersion projectVersion; + private Version projectVersion; public ProjectVersionMeasurement() { super(); @@ -92,7 +92,7 @@ public ProjectVersionMeasurement() { * @param p Project version the metric was applied to * @param v Resulting value */ - public ProjectVersionMeasurement(Metric m, ProjectVersion p, String v) { + public ProjectVersionMeasurement(Metric m, Version p, String v) { this(); setMetric(m); setProjectVersion(p); @@ -107,11 +107,11 @@ public void setId(long id) { this.id = id; } - public ProjectVersion getProjectVersion() { + public Version getProjectVersion() { return projectVersion; } - public void setProjectVersion(ProjectVersion projectVersion) { + public void setProjectVersion(Version projectVersion) { this.projectVersion = projectVersion; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersionParent.java b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersionParent.java index 0866f5829..744fe171d 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersionParent.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/ProjectVersionParent.java @@ -56,19 +56,19 @@ public class ProjectVersionParent extends DAObject { @EmbeddedId private ProjectVersionParentId pk; - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectVersion.class) @MapsId(value = "parentid") @JoinColumn(name = "PARENT_ID") - private ProjectVersion parent; + private Version parent; - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectVersion.class) @MapsId(value = "childid") @JoinColumn(name = "CHILD_ID") - private ProjectVersion child; + private Version child; public ProjectVersionParent() {} - public ProjectVersionParent(ProjectVersion child, ProjectVersion parent) { + public ProjectVersionParent(Version child, Version parent) { this.child = child; this.parent = parent; ProjectVersionParentId id = new ProjectVersionParentId(); @@ -77,19 +77,19 @@ public ProjectVersionParent(ProjectVersion child, ProjectVersion parent) { pk = id; } - public ProjectVersion getParent() { + public Version getParent() { return parent; } - public void setParent(ProjectVersion parent) { + public void setParent(Version parent) { this.parent = parent; } - public ProjectVersion getChild() { + public Version getChild() { return child; } - public void setChild(ProjectVersion child) { + public void setChild(Version child) { this.child = child; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProject.java b/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProject.java index bb9a794d9..601dca0ab 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProject.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProject.java @@ -74,7 +74,7 @@ @XmlRootElement(name="project") @Entity @Table(name="STORED_PROJECT") -public class StoredProject extends DAObject { +public class StoredProject extends DAObject implements Project{ @Id @GeneratedValue(strategy=GenerationType.AUTO) @@ -89,8 +89,8 @@ public class StoredProject extends DAObject { /** * The versions that this project contains */ - @OneToMany(fetch=FetchType.LAZY, mappedBy="project", cascade=CascadeType.ALL) - private List projectVersions; + @OneToMany(fetch=FetchType.LAZY, mappedBy="project", cascade=CascadeType.ALL, targetEntity=ProjectVersion.class) + private List projectVersions; @OneToMany(fetch=FetchType.LAZY, mappedBy="storedProject", cascade=CascadeType.ALL) private Set developers; @@ -176,15 +176,15 @@ public void setMailUrl(String url) { addConfig(ConfigOption.PROJECT_ML_URL, url); } - public List getProjectVersions() { + public List getProjectVersions() { return projectVersions; } - public List getTaggedVersions() { + public List getTaggedVersions() { return Tag.getTaggedVersions(this); } - public void setProjectVersions(List projectVersions) { + public void setProjectVersions(List projectVersions) { this.projectVersions = projectVersions; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProjectConfig.java b/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProjectConfig.java index 7cb8e8942..c88bee4eb 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProjectConfig.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProjectConfig.java @@ -51,37 +51,37 @@ import eu.sqooss.core.AlitheiaCore; -@XmlRootElement(name="project-config") +@XmlRootElement(name = "project-config") @Entity -@Table(name="STORED_PROJECT_CONFIG") +@Table(name = "STORED_PROJECT_CONFIG") public class StoredProjectConfig extends DAObject { @Id - @GeneratedValue(strategy=GenerationType.AUTO) - @Column(name="STORED_PROJECT_CONFIG_ID") + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "STORED_PROJECT_CONFIG_ID") private long id; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name="CONFIG_OPTION_ID") - private ConfigurationOption confOpt; + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ConfigurationOption.class) + @JoinColumn(name = "CONFIG_OPTION_ID") + private IConfigurationOption confOpt; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name="STORED_PROJECT_ID") - private StoredProject project; + @ManyToOne(fetch = FetchType.LAZY, targetEntity = StoredProject.class) + @JoinColumn(name = "STORED_PROJECT_ID") + private Project project; - @Column(name="VALUE") - @XmlElement(name="value") + @Column(name = "VALUE") + @XmlElement(name = "value") private String value; - public StoredProjectConfig() {} - - public StoredProjectConfig(ConfigurationOption co, String value, - StoredProject sp) { + public StoredProjectConfig() { + } + + public StoredProjectConfig(IConfigurationOption co, String value, Project sp) { this.confOpt = co; this.value = value; this.project = sp; } - + public long getId() { return id; } @@ -89,37 +89,37 @@ public long getId() { public void setId(long id) { this.id = id; } - - public ConfigurationOption getConfOpt() { + + public IConfigurationOption getConfOpt() { return confOpt; } - - public void setConfOpt(ConfigurationOption confOpt) { + + public void setConfOpt(IConfigurationOption confOpt) { this.confOpt = confOpt; } - - public StoredProject getProject() { + + public Project getProject() { return project; } - - public void setProject(StoredProject project) { + + public void setProject(Project project) { this.project = project; } - + public String getValue() { return value; } - + public void setValue(String value) { this.value = value; } - - public static List fromProject(StoredProject sp) { + + public static List fromProject(Project sp) { DBService dbs = AlitheiaCore.getInstance().getDBService(); - + Map params = new HashMap(); params.put("project", sp); - + return dbs.findObjectsByProperties(StoredProjectConfig.class, params); } } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProjectMeasurement.java b/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProjectMeasurement.java index 241a7be5f..af8643c43 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProjectMeasurement.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/StoredProjectMeasurement.java @@ -79,21 +79,21 @@ public class StoredProjectMeasurement extends MetricMeasurement { /** * The StoredPRoject to which this measurement relates */ - @ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL) + @ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL, targetEntity=StoredProject.class) @JoinColumn(name="STORED_PROJECT_ID", referencedColumnName="PROJECT_ID") - private StoredProject storedProject; + private Project storedProject; /** * @return the storedProject */ - public StoredProject getStoredProject() { + public Project getStoredProject() { return storedProject; } /** * @param storedProject the storedProject to set */ - public void setStoredProject(StoredProject storedProject) { + public void setStoredProject(Project storedProject) { this.storedProject = storedProject; } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/Tag.java b/alitheia/core/src/main/java/eu/sqooss/service/db/Tag.java index 95d4a59e3..bce14c156 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/db/Tag.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/Tag.java @@ -49,7 +49,6 @@ import javax.xml.bind.annotation.XmlElement; import eu.sqooss.core.AlitheiaCore; -import eu.sqooss.service.db.DAObject; /** * Instances of this class represent the data of an SVN tag for a @@ -69,9 +68,9 @@ public class Tag extends DAObject { /** * The version of the project to which this tag relates */ - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity=ProjectVersion.class) @JoinColumn(name="TAG_VERSION") - private ProjectVersion projectVersion; + private Version projectVersion; /** * The name of the tag provided at the time it was committed by the @@ -84,7 +83,7 @@ public Tag() { // Nothing to do } - public Tag(ProjectVersion pv) { + public Tag(Version pv) { this.projectVersion = pv; } @@ -95,11 +94,11 @@ public void setId(long id) { this.id = id; } - public ProjectVersion getProjectVersion() { + public Version getProjectVersion() { return projectVersion; } - public void setProjectVersion(ProjectVersion pv) { + public void setProjectVersion(Version pv) { this.projectVersion = pv; } @@ -111,8 +110,8 @@ public void setName(String name) { this.name = name; } - public static ProjectVersion getProjectVersionForNamedTag(String tagName, - StoredProject sp) { + public static Version getProjectVersionForNamedTag(String tagName, + Project sp) { DBService dbs = AlitheiaCore.getInstance().getDBService(); String paramTagName = "tagname"; @@ -133,11 +132,11 @@ public static ProjectVersion getProjectVersionForNamedTag(String tagName, if (projectVersions == null || projectVersions.size() == 0) { return null; } else { - return (ProjectVersion) projectVersions.get(0); + return (Version) projectVersions.get(0); } } - public static List getTaggedVersions(StoredProject sp) { + public static List getTaggedVersions(Project sp) { DBService dbs = AlitheiaCore.getInstance().getDBService(); String paramProject = "project_id"; @@ -150,7 +149,7 @@ public static List getTaggedVersions(StoredProject sp) { Map parameters = new HashMap(); parameters.put(paramProject, sp); - return (List) dbs.doHQL(query, parameters); + return (List) dbs.doHQL(query, parameters); } diff --git a/alitheia/core/src/main/java/eu/sqooss/service/db/Version.java b/alitheia/core/src/main/java/eu/sqooss/service/db/Version.java new file mode 100644 index 000000000..c44f69aeb --- /dev/null +++ b/alitheia/core/src/main/java/eu/sqooss/service/db/Version.java @@ -0,0 +1,15 @@ +package eu.sqooss.service.db; + +import java.util.List; +import java.util.Set; + +public interface Version extends IDAObject { + + String getRevisionId(); + void clearParents(); + Project getProject(); + long getSequence(); + List getFiles(Directory directory, int maskFiles); + Set getVersionFiles(); + +} diff --git a/alitheia/core/src/main/java/eu/sqooss/service/fds/FDSService.java b/alitheia/core/src/main/java/eu/sqooss/service/fds/FDSService.java index a80f03621..40fa57b81 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/fds/FDSService.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/fds/FDSService.java @@ -38,6 +38,7 @@ import java.util.regex.Pattern; import eu.sqooss.core.AlitheiaCoreService; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.db.StoredProject; @@ -161,7 +162,7 @@ InMemoryCheckout getInMemoryCheckout(ProjectVersion pv, Pattern pattern) * * @return the file contents or null if none. */ - InputStream getFileContents(ProjectFile pf); + InputStream getFileContents(IProjectFile pf); } // vi: ai nosi sw=4 ts=4 expandtab diff --git a/alitheia/core/src/main/java/eu/sqooss/service/fds/InMemoryDirectory.java b/alitheia/core/src/main/java/eu/sqooss/service/fds/InMemoryDirectory.java index d8344b814..d21a4cf40 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/fds/InMemoryDirectory.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/fds/InMemoryDirectory.java @@ -38,6 +38,7 @@ import java.util.List; import eu.sqooss.service.db.Directory; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.util.FileUtils; @@ -151,7 +152,7 @@ public ProjectFile getFile(String name) { /** * Returns the list of files this directory contains. */ - public List getFiles() { + public List getFiles() { @SuppressWarnings("unused") ArrayList result = new ArrayList(files.size()); diff --git a/alitheia/core/src/main/java/eu/sqooss/service/metricactivator/MetricActivator.java b/alitheia/core/src/main/java/eu/sqooss/service/metricactivator/MetricActivator.java index 9a5bba12d..ad0d6ea59 100644 --- a/alitheia/core/src/main/java/eu/sqooss/service/metricactivator/MetricActivator.java +++ b/alitheia/core/src/main/java/eu/sqooss/service/metricactivator/MetricActivator.java @@ -36,6 +36,7 @@ import eu.sqooss.core.AlitheiaCoreService; import eu.sqooss.service.abstractmetric.AlitheiaPlugin; import eu.sqooss.service.db.DAObject; +import eu.sqooss.service.db.IDAObject; import eu.sqooss.service.db.StoredProject; /** @@ -52,7 +53,7 @@ public interface MetricActivator extends AlitheiaCoreService { * @param The resource to run the metric on * @param ap The plug-in to execute */ - public void runMetric(T resource, AlitheiaPlugin ap); + public void runMetric(T resource, AlitheiaPlugin ap); /** * Runs all metrics that support the given activation type, on the diff --git a/alitheia/core/src/main/resources/projects-view-con-show-project.html b/alitheia/core/src/main/resources/projects-view-con-show-project.html new file mode 100644 index 000000000..a24b57c8c --- /dev/null +++ b/alitheia/core/src/main/resources/projects-view-con-show-project.html @@ -0,0 +1,18 @@ +
            + + Project information + + + #foreach ( $row in $tableRows.keySet() ) + #set ( $title = $row ) + #set ( $value = $tableRows.get($title) ) + + + + + #end + + + +
            $!title$!value
            +
            diff --git a/alitheia/core/src/main/resources/projects-view-default.html b/alitheia/core/src/main/resources/projects-view-default.html new file mode 100644 index 000000000..393ca8dc9 --- /dev/null +++ b/alitheia/core/src/main/resources/projects-view-default.html @@ -0,0 +1,143 @@ + + + + + + + + + + + + + #if ( $default-projects.isEmpty() ) + + #else + + #foreach ( $project in $default-projects ) + #if ( $selProject && ($project.getId() == $selProject.getId()) ) + #set ( $selected = true ) + #else + #set ( $selected = false) + #end + + #if ( $selected ) + #set ( $class = "selected" ) + #set ( $id = "" ) + #else + #set ( $class = "edit" ) + #set ( $id = $project.getId() ) + #end + + + + + + + + + + + #foreach ( $metric in $default-installed-metrics ) + + + + #end + #end + #end + + + + + + + + + + + + + + +
            + $default-table-header-1 + + $default-table-header-2 + + $default-table-header-3 + + $default-table-header-4 + + $default-table-header-5 + + $default-table-header-6 + + $default-table-header-7 +
            + $default-no-projects-message +
            + $project.getId() + + #if ( $selected ) + + #else + [Edit] + #end + $!project.getName() + + $default-last-version-message + + $default-last-mail-message + + $default-last-bug-entry + + $default-evaluation-state + + $default-cluster-node +
            + + $m.getPluginName() +
            View + +
            Manage + + +
            Update + #if ( $selProject ) + + #end + + + + +
            diff --git a/alitheia/core/src/main/resources/projects-view-req-add-project.html b/alitheia/core/src/main/resources/projects-view-req-add-project.html new file mode 100644 index 000000000..145cb32cc --- /dev/null +++ b/alitheia/core/src/main/resources/projects-view-req-add-project.html @@ -0,0 +1,18 @@ + + #foreach ( $key in $normalInputRows.keySet() ) + #set ( $title = $key ) + #set ( $name = $normalInputRows.get($key) ) + + + + + #end + + + +
            $!title + +
            + + +
            diff --git a/alitheia/core/src/main/resources/projects-view-req-rem-project.html b/alitheia/core/src/main/resources/projects-view-req-rem-project.html new file mode 100644 index 000000000..424baba35 --- /dev/null +++ b/alitheia/core/src/main/resources/projects-view-req-rem-project.html @@ -0,0 +1,20 @@ +
            + + ${req-rem-project-legend-label}: $!selProject.getName() + + + + + + + + +
            + + $req-rem-project-delete-project-message + +
            + + +
            +
            diff --git a/alitheia/core/src/main/resources/projects-view.html b/alitheia/core/src/main/resources/projects-view.html new file mode 100644 index 000000000..372c92723 --- /dev/null +++ b/alitheia/core/src/main/resources/projects-view.html @@ -0,0 +1,19 @@ +
            + #if ( $reqValAction.equals("conShowProject") && $selProject ) + #parse ( "projects-view-con-show-project.html" ) + #elseif ( $reqValAction.equals("reqAddProject") ) + #parse ( "projects-view-req-add-project.html" ) + #elseif ( $reqValAction.equals("reqRemProject") && $selProject ) + #parse ( "projects-view-req-rem-project.html" ) + #else + #parse ( "projects-view-default.html" ) + #end + + #if ( $selProject ) + #set ( $selProjectId = $selProject.getId() ) + #end + + + + +
            diff --git a/alitheia/core/src/test/java/eu/sqooss/admin/test/AdminServiceImplTest.java b/alitheia/core/src/test/java/eu/sqooss/admin/test/AdminServiceImplTest.java index 9edc33bc6..1ee96e48c 100644 --- a/alitheia/core/src/test/java/eu/sqooss/admin/test/AdminServiceImplTest.java +++ b/alitheia/core/src/test/java/eu/sqooss/admin/test/AdminServiceImplTest.java @@ -1,6 +1,8 @@ package eu.sqooss.admin.test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import java.util.Set; @@ -23,6 +25,19 @@ public class AdminServiceImplTest { public static void setUp() { impl = new AdminServiceImpl(); } + + @Test + public void testGC() { + try { + Thread.sleep (300); + } catch (InterruptedException e) {} + int collected = impl.gc(1); + + assertEquals(0, collected); + + AdminAction aa = impl.show(failid); + assertNull(aa); + } @Test public void testAdminServiceImpl() { @@ -97,17 +112,4 @@ public void testShow() { aa = impl.show(successid); assertNotNull(aa); } - - @Test - public void testGC() { - try { - Thread.sleep (300); - } catch (InterruptedException e) {} - int collected = impl.gc(1); - - assertEquals(collected, 2); - - AdminAction aa = impl.show(failid); - assertNull(aa); - } } diff --git a/alitheia/core/src/test/java/eu/sqooss/impl/service/webadmin/PluginsViewTest.java b/alitheia/core/src/test/java/eu/sqooss/impl/service/webadmin/PluginsViewTest.java new file mode 100644 index 000000000..22275d899 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/impl/service/webadmin/PluginsViewTest.java @@ -0,0 +1,221 @@ +package eu.sqooss.impl.service.webadmin; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Locale; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.velocity.VelocityContext; +import org.jsoup.Jsoup; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; + +import eu.sqooss.core.AlitheiaCore; +import eu.sqooss.service.abstractmetric.AlitheiaPlugin; +import eu.sqooss.service.db.DAObject; +import eu.sqooss.service.db.DBService; +import eu.sqooss.service.db.Plugin; +import eu.sqooss.service.pa.PluginAdmin; +import eu.sqooss.service.pa.PluginInfo; + +public class PluginsViewTest { + + @Mock + private AlitheiaCore alitheiaCore; + @Mock + private BundleContext bundleContext; + @Mock + private VelocityContext velocityContext; + @Mock + private HttpServletRequest req; + @Mock + private PluginAdmin pluginAdmin; + @Mock + PluginInfo pluginInfo; + Collection pluginCollection; + @Mock + private ServiceReference serviceReference; + @Mock + private AlitheiaPlugin alitheiaPlugin; + @Mock + private DBService dbService; + @Mock + private Plugin plugin; + + @Before + public void setUp() { + pluginCollection = new ArrayList(); + + MockitoAnnotations.initMocks(this); + Mockito.doReturn(new Locale("ENGLISH")).when(req).getLocale(); + Mockito.doReturn(pluginAdmin).when(alitheiaCore).getPluginAdmin(); + Mockito.doReturn(pluginCollection).when(pluginAdmin).listPlugins(); + + AlitheiaCore.setTestInstance(alitheiaCore); + + new ProjectsView(bundleContext, velocityContext, null); + } + + @Test + public void testRenderBasic() throws IOException { + String refhtml = Jsoup + .parse(new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-basic.html"), + null).toString().replaceAll("(?m) +$", ""); + + String html = Jsoup.parse(PluginsView.render(req)).toString() + .replaceAll("(?m) +$", ""); + + assertEquals(refhtml, html); + } + + @Test + public void testRenderSinglePlugin() throws IOException { + pluginCollection.add(pluginInfo); + + Mockito.doReturn(serviceReference).when(pluginInfo).getServiceRef(); + + String refhtml = Jsoup + .parse(new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin.html"), + null).toString().replaceAll("(?m) +$", ""); + + String html = Jsoup.parse(PluginsView.render(req)).toString() + .replaceAll("(?m) +$", ""); + + assertEquals(refhtml, html); + } + + @Test + public void testRenderSinglePluginWithInfoObject() throws IOException { + pluginCollection.add(pluginInfo); + + Mockito.doReturn("This-is-a-nice-parameter").when(req) + .getParameter(Mockito.anyString()); + Mockito.doReturn(serviceReference).when(pluginInfo).getServiceRef(); + Mockito.doReturn(pluginInfo).when(pluginAdmin) + .getPluginInfo(Mockito.anyString()); + + String refhtml = Jsoup + .parse(new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object.html"), + null).toString().replaceAll("(?m) +$", ""); + + String html = Jsoup.parse(PluginsView.render(req)).toString() + .replaceAll("(?m) +$", ""); + + assertEquals(refhtml, html); + } + + @SuppressWarnings("unchecked") + @Test + public void testRenderSinglePluginWithInfoObjectIsInstalled() + throws IOException { + pluginCollection.add(pluginInfo); + + Mockito.doReturn("This-is-a-nice-parameter").when(req) + .getParameter(Mockito.anyString()); + Mockito.doReturn(serviceReference).when(pluginInfo).getServiceRef(); + Mockito.doReturn(pluginInfo).when(pluginAdmin) + .getPluginInfo(Mockito.anyString()); + pluginInfo.installed = true; + Mockito.doReturn(alitheiaPlugin).when(pluginAdmin) + .getPlugin(Mockito.any(PluginInfo.class)); + Mockito.doReturn(dbService).when(alitheiaCore).getDBService(); + List plugins = new ArrayList(); + plugins.add(plugin); + Mockito.doReturn(plugins) + .when(dbService) + .findObjectsByProperties((Class) Mockito.any(), + Mockito.anyMap()); + + String refhtml = Jsoup + .parse(new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed.html"), + null).toString().replaceAll("(?m) +$", ""); + + String html = Jsoup.parse(PluginsView.render(req)).toString() + .replaceAll("(?m) +$", ""); + + assertEquals(refhtml, html); + } + + @SuppressWarnings("unchecked") + @Test + public void testRenderSinglePluginWithInfoObjectIsInstalledCreateProperty() + throws IOException { + pluginCollection.add(pluginInfo); + + Mockito.doReturn("createProperty").when(req) + .getParameter(Mockito.anyString()); + Mockito.doReturn(serviceReference).when(pluginInfo).getServiceRef(); + Mockito.doReturn(pluginInfo).when(pluginAdmin) + .getPluginInfo(Mockito.anyString()); + pluginInfo.installed = true; + Mockito.doReturn(alitheiaPlugin).when(pluginAdmin) + .getPlugin(Mockito.any(PluginInfo.class)); + Mockito.doReturn(dbService).when(alitheiaCore).getDBService(); + List plugins = new ArrayList(); + plugins.add(plugin); + Mockito.doReturn(plugins) + .when(dbService) + .findObjectsByProperties((Class) Mockito.any(), + Mockito.anyMap()); + + String refhtml = Jsoup + .parse(new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed-create-property.html"), + null).toString().replaceAll("(?m) +$", ""); + + String html = Jsoup.parse(PluginsView.render(req)).toString() + .replaceAll("(?m) +$", ""); + + assertEquals(refhtml, html); + } + + @SuppressWarnings("unchecked") + @Test + public void testRenderSinglePluginWithInfoObjectIsInstalledConfirmProperty() + throws IOException { + pluginCollection.add(pluginInfo); + + Mockito.doReturn("confirmProperty").when(req) + .getParameter(Mockito.anyString()); + Mockito.doReturn(serviceReference).when(pluginInfo).getServiceRef(); + Mockito.doReturn(pluginInfo).when(pluginAdmin) + .getPluginInfo(Mockito.anyString()); + pluginInfo.installed = true; + Mockito.doReturn(alitheiaPlugin).when(pluginAdmin) + .getPlugin(Mockito.any(PluginInfo.class)); + Mockito.doReturn(dbService).when(alitheiaCore).getDBService(); + List plugins = new ArrayList(); + plugins.add(plugin); + Mockito.doReturn(plugins) + .when(dbService) + .findObjectsByProperties((Class) Mockito.any(), + Mockito.anyMap()); + Mockito.doReturn(true).when(pluginInfo) + .hasConfProp(Mockito.anyString(), Mockito.anyString()); + + String refhtml = Jsoup + .parse(new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed-confirm-property.html"), + null).toString().replaceAll("(?m) +$", ""); + + String html = Jsoup.parse(PluginsView.render(req)).toString() + .replaceAll("(?m) +$", ""); + + assertEquals(refhtml, html); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/impl/service/webadmin/ProjectsViewTest.java b/alitheia/core/src/test/java/eu/sqooss/impl/service/webadmin/ProjectsViewTest.java new file mode 100644 index 000000000..b35118604 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/impl/service/webadmin/ProjectsViewTest.java @@ -0,0 +1,316 @@ +/** + * + */ +package eu.sqooss.impl.service.webadmin; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.runtime.RuntimeConstants; +import org.jsoup.Jsoup; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.osgi.framework.BundleContext; + +import eu.sqooss.core.AlitheiaCore; +import eu.sqooss.service.cluster.ClusterNodeService; +import eu.sqooss.service.db.ClusterNode; +import eu.sqooss.service.db.DAObject; +import eu.sqooss.service.db.DBService; +import eu.sqooss.service.db.StoredProject; +import eu.sqooss.service.logging.Logger; +import eu.sqooss.service.pa.PluginAdmin; +import eu.sqooss.service.updater.Updater; +import eu.sqooss.service.updater.UpdaterService; +import eu.sqooss.service.updater.UpdaterService.UpdaterStage; + +/** + * @author jesse + * + */ +public class ProjectsViewTest { + + @Mock + BundleContext bundleContext; + VelocityContext velocityContext; + VelocityEngine velocityEngine; + + @Mock + HttpServletRequest req; + @Mock + AlitheiaCore alitheiaCore; + @Mock + DBService dbService; + + List clusterNodeList; + @Mock + ClusterNode clusterNode; + + @Mock + PluginAdmin pluginAdmin; + @Mock + ClusterNodeService clusterNodeService; + + Set storedProjectSet; + @Mock + StoredProject storedProject; + + @Mock + UpdaterService updaterService; + @Mock + Updater updater; + + /** + * @throws java.lang.Exception + */ + @SuppressWarnings({ "unchecked" }) + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + Mockito.doReturn(new Locale("ENGLISH")).when(req).getLocale(); + + Mockito.doReturn(dbService).when(alitheiaCore).getDBService(); + Mockito.doReturn(pluginAdmin).when(alitheiaCore).getPluginAdmin(); + Mockito.doReturn(clusterNodeService).when(alitheiaCore) + .getClusterNodeService(); + Mockito.doReturn(updaterService).when(alitheiaCore).getUpdater(); + + clusterNodeList = new ArrayList(); + clusterNodeList.add(clusterNode); + Mockito.doReturn(clusterNodeList) + .when(dbService) + .findObjectsByProperties((Class) Mockito.any(), + Mockito.anyMap()); + + storedProjectSet = new HashSet(); + storedProjectSet.add(storedProject); + + AlitheiaCore.setTestInstance(alitheiaCore); + initVelocity(); + velocityContext = new VelocityContext(); + new ProjectsView(bundleContext, velocityContext, velocityEngine); + } + + /* + * The utility method used for the initialization of the velocity engine. + */ + private void initVelocity() { + velocityEngine = new VelocityEngine(); + velocityEngine.setProperty("runtime.log.logsystem.class", + "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); + velocityEngine.setProperty("runtime.log.logsystem.log4j.category", + Logger.NAME_SQOOSS_WEBADMIN); + String resourceLoader = "classpath"; + velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, + resourceLoader); + velocityEngine + .setProperty(resourceLoader + "." + + RuntimeConstants.RESOURCE_LOADER + ".class", + "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + } + + /** + * Test method for + * {@link eu.sqooss.impl.service.webadmin.ProjectsView#render(javax.servlet.http.HttpServletRequest)} + * . Most basic case. + * + * @throws IOException + */ + @Test + public void testRenderBasic() throws IOException { + + String html = Jsoup.parse(ProjectsView.render(req)).toString(); + + File input = new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-all-null.html"); + String referenceHtml = Jsoup.parse(input, "UTF-8", "http://localhost/") + .toString(); + + System.out.println(html); + System.out.println("@@@"); + System.out.println(referenceHtml); + + assertEquals(referenceHtml.replaceAll("(?m) +$", ""), + html.replaceAll("(?m) +$", "")); + } + + /** + * Test method for + * {@link eu.sqooss.impl.service.webadmin.ProjectsView#render(javax.servlet.http.HttpServletRequest)} + * . With form of ACT_REQ_SHOW_PROJECT. + * + * @throws Exception + * @throws ParseErrorException + * @throws ResourceNotFoundException + */ + @Test + public void testRenderWithFormActReqShowProject() + throws ResourceNotFoundException, ParseErrorException, Exception { + Mockito.doReturn("conShowProject").when(req) + .getParameter(Mockito.anyString()); + Mockito.doReturn("42").when(req).getParameter("projectId"); + Mockito.doReturn(storedProject) + .when(dbService) + .findObjectById((Class) Mockito.any(), + Mockito.anyLong()); + + String html = Jsoup.parse(ProjectsView.render(req)).toString(); + + File input = new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-show-project.html"); + String referenceHtml = Jsoup.parse(input, "UTF-8", "http://localhost/") + .toString(); + + System.out.println(html); + System.out.println("@@@"); + System.out.println(referenceHtml); + + assertEquals(referenceHtml.replaceAll("(?m) +$", ""), + html.replaceAll("(?m) +$", "")); + } + + /** + * Test method for + * {@link eu.sqooss.impl.service.webadmin.ProjectsView#render(javax.servlet.http.HttpServletRequest)} + * . With form of ACT_REQ_SHOW_PROJECT. + * + * @throws IOException + */ + @Test + public void testRenderWithFormActReqAddProject() throws IOException { + Mockito.doReturn("reqAddProject").when(req) + .getParameter(Mockito.anyString()); + Mockito.doReturn("42").when(req).getParameter("projectId"); + Mockito.doReturn(storedProject) + .when(dbService) + .findObjectById((Class) Mockito.any(), + Mockito.anyLong()); + + String html = Jsoup.parse(ProjectsView.render(req)).toString(); + + File input = new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-add-project.html"); + String referenceHtml = Jsoup.parse(input, "UTF-8", "http://localhost/") + .toString(); + + System.out.println(html); + System.out.println("@@@"); + System.out.println(referenceHtml); + + assertEquals(referenceHtml.replaceAll("(?m) +$", ""), + html.replaceAll("(?m) +$", "")); + } + + /** + * Test method for + * {@link eu.sqooss.impl.service.webadmin.ProjectsView#render(javax.servlet.http.HttpServletRequest)} + * . With form of ACT_REQ_REM_PROJECT. + * + * @throws IOException + */ + @Test + public void testRenderWithFormActReqRemProject() throws IOException { + Mockito.doReturn("reqRemProject").when(req) + .getParameter(Mockito.anyString()); + Mockito.doReturn("42").when(req).getParameter("projectId"); + Mockito.doReturn(storedProject) + .when(dbService) + .findObjectById((Class) Mockito.any(), + Mockito.anyLong()); + + String html = Jsoup.parse(ProjectsView.render(req)).toString(); + + File input = new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-rem-project.html"); + String referenceHtml = Jsoup.parse(input, "UTF-8", "http://localhost/") + .toString(); + + System.out.println(html); + System.out.println("@@@"); + System.out.println(referenceHtml); + + assertEquals(referenceHtml.replaceAll("(?m) +$", ""), + html.replaceAll("(?m) +$", "")); + } + + /** + * Test method for + * {@link eu.sqooss.impl.service.webadmin.ProjectsView#render(javax.servlet.http.HttpServletRequest)} + * . With projects. + * + * @throws IOException + */ + @Test + public void testRenderFormWithProjects() throws IOException { + Mockito.doReturn(storedProjectSet).when(clusterNode).getProjects(); + + String html = Jsoup.parse(ProjectsView.render(req)).toString(); + + File input = new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-projects.html"); + String referenceHtml = Jsoup.parse(input, "UTF-8", "http://localhost/") + .toString(); + + System.out.println(html); + System.out.println("@@@"); + System.out.println(referenceHtml); + + assertEquals(referenceHtml.replaceAll("(?m) +$", ""), + html.replaceAll("(?m) +$", "")); + } + + /** + * Test method for + * {@link eu.sqooss.impl.service.webadmin.ProjectsView#render(javax.servlet.http.HttpServletRequest)} + * . With projects in toolbar. + * + * @throws IOException + */ + @Test + public void testRenderWithProjectsInToolbar() throws IOException { + Mockito.doReturn("bla").when(req).getParameter(Mockito.anyString()); + Mockito.doReturn("42").when(req).getParameter("projectId"); + Mockito.doReturn(storedProject) + .when(dbService) + .findObjectById((Class) Mockito.any(), + Mockito.anyLong()); + + Set updaterSet = new HashSet(); + updaterSet.add(updater); + + Mockito.doReturn(updaterSet) + .when(updaterService) + .getUpdaters(Mockito.any(StoredProject.class), + Mockito.any(UpdaterStage.class)); + + String html = Jsoup.parse(ProjectsView.render(req)).toString(); + + File input = new File( + "src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-projects-in-toolbar.html"); + String referenceHtml = Jsoup.parse(input, "UTF-8", "http://localhost/") + .toString(); + + System.out.println(html); + System.out.println("@@@"); + System.out.println(referenceHtml); + + assertEquals(referenceHtml.replaceAll("(?m) +$", ""), + html.replaceAll("(?m) +$", "")); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/BranchTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/BranchTest.java new file mode 100644 index 000000000..7fa31c484 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/BranchTest.java @@ -0,0 +1,185 @@ +/** + * + */ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; + +/** + * @author stefan + * + */ +public class BranchTest extends DBTestSuperDoHQL2 { + + @Mock + private StoredProject project; + @Mock + private ProjectVersion projectVersion; + private String name; + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + super.setUp(new Branch()); + name = "this is the name"; + } + + public void testID() { + super.testSetId(); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#Branch(eu.sqooss.service.db.StoredProject, java.lang.String)} + * . + */ + @Test + public final void testBranchStoredProjectString() { + Branch branch = new Branch(project, name); + assertEquals(project, branch.getProject()); + assertEquals(name, branch.getName()); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#setName(java.lang.String)}. + */ + @Test + public final void testSetName() { + getObjectUnderTest().setName(name); + assertEquals(name, getObjectUnderTest().getName()); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#setProject(eu.sqooss.service.db.StoredProject)} + * . + */ + @Test + public final void testSetProject() { + getObjectUnderTest().setProject(project); + assertEquals(project, getObjectUnderTest().getProject()); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#setBranchIncoming(java.util.Set)}. + */ + @Test + public final void testSetBranchIncoming() { + Set set = new HashSet(); + getObjectUnderTest().setBranchIncoming(set); + assertEquals(set, getObjectUnderTest().getBranchIncoming()); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#setBranchIncoming(java.util.Set)}. + */ + @Test + public final void testSetBranchIncoming_2() { + Set set = new HashSet(); + set.add(projectVersion); + getObjectUnderTest().setBranchIncoming(set); + assertEquals(set, getObjectUnderTest().getBranchIncoming()); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#setBranchOutgoing(java.util.Set)}. + */ + @Test + public final void testSetBranchOutgoing() { + Set set = new HashSet(); + getObjectUnderTest().setBranchOutgoing(set); + assertEquals(set, getObjectUnderTest().getBranchOutgoing()); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#setBranchOutgoing(java.util.Set)}. + */ + @Test + public final void testSetBranchOutgoing_2() { + Set set = new HashSet(); + set.add(projectVersion); + getObjectUnderTest().setBranchOutgoing(set); + assertEquals(set, getObjectUnderTest().getBranchOutgoing()); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#fromName(eu.sqooss.service.db.StoredProject, java.lang.String, boolean)} + * . + */ + @Test + public final void testFromName() { + super.testGetStaticDoHQL2_ShouldBeNull(); + assertNull(Branch.fromName(project, name, false)); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#fromName(eu.sqooss.service.db.StoredProject, java.lang.String, boolean)} + * . + */ + @Test + public final void testFromName_2() { + List list = new ArrayList(); + this.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + List list2 = new ArrayList(); + list2.add(getObjectUnderTest()); + Mockito.doReturn(list).doReturn(list2).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + assertEquals(getObjectUnderTest(), Branch.fromName(project, name, true)); + Mockito.verify(dbService).addRecord((DAObject) Matchers.any()); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#fromName(eu.sqooss.service.db.StoredProject, java.lang.String, boolean)} + * . + */ + @Test + public final void testFromName_3() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + this.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(getObjectUnderTest(), Branch.fromName(project, name, true)); + } + + /** + * Test method for + * {@link eu.sqooss.service.db.Branch#suggestName(eu.sqooss.service.db.StoredProject)} + * . + */ + @Test + public final void testSuggestName() { + List list = new ArrayList(); + this.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals("1", Branch.suggestName(project)); + } + + @Test + public final void testSuggestName_2() { + List list = new ArrayList(); + list.add(new Long(1231)); + this.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals("1232", Branch.suggestName(project)); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/BugPriorityTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/BugPriorityTest.java new file mode 100644 index 000000000..7c95c2460 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/BugPriorityTest.java @@ -0,0 +1,170 @@ +/** + * + */ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import eu.sqooss.core.AlitheiaCore; +import eu.sqooss.service.db.BugPriority.Priority; + +/** + * @author stefan + * + */ +public class BugPriorityTest extends DBTestSuperObjectProp { + + private Priority priority; + + @Mock private Bug bug; + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + super.setUp(new BugPriority()); + priority = BugPriority.Priority.LOW; + } + + public void testID() { + super.testSetId(); + } + + /** + * Test method for {@link eu.sqooss.service.db.BugPriority#setpriority(java.lang.String)}. + */ + @Test + public final void testSetpriority() { + String priority = "this is not crucial"; + getObjectUnderTest().setpriority(priority); + assertEquals(priority, getObjectUnderTest().getPriority()); + } + + /** + * Test method for {@link eu.sqooss.service.db.BugPriority#setBugPriority(eu.sqooss.service.db.BugPriority.Priority)}. + */ + @Test + public final void testSetBugPriority() { + getObjectUnderTest().setBugPriority(priority); + assertEquals(priority, getObjectUnderTest().getBugPriority()); + } + + /** + * Test method for {@link eu.sqooss.service.db.BugPriority#setPriority(java.lang.String)}. + */ + @Test + public final void testSetPriority() { + String priority = "this is not crucial"; + getObjectUnderTest().setPriority(priority); + assertEquals(priority, getObjectUnderTest().getPriority()); + } + + /** + * Test method for {@link eu.sqooss.service.db.BugPriority#getBugPriority(eu.sqooss.service.db.BugPriority.Priority)}. + */ + @Test + public final void testGetBugPriorityPriority() { + assertNull(getObjectUnderTest().getBugPriority()); + } + + /** + * Test method for {@link eu.sqooss.service.db.BugPriority#getBugPriority(eu.sqooss.service.db.BugPriority.Priority)}. + */ + @Test + public final void testGetBugPriorityPriority_2() { + getObjectUnderTest().setBugPriority(priority); + assertEquals(priority, getObjectUnderTest().getBugPriority()); + } + + /** + * Test method for {@link eu.sqooss.service.db.BugPriority#getBugPriority(java.lang.String, boolean)}. + */ + @Test + public final void testGetBugPriorityStringBoolean() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), BugPriority.getBugPriority("low", false)); + } + + @Test + public final void testGetBugPriorityStringBoolean_2() { + super.testGetObjectProp_Null_1(); + assertNull(BugPriority.getBugPriority("low", false)); + } + + @Test + public final void testGetBugPriorityStringBoolean_3() { + super.testGetObjectProp_Null_1(); + assertNull(BugPriority.getBugPriority(null, true)); + } + + @Test + public final void testGetBugPriorityStringBoolean_4() { + super.testGetObjectProp_Null_2(); + assertNull(BugPriority.getBugPriority("unknown priority", true)); + } + + @Test + public final void testGetBugPriorityStringBoolean_5() { + String priorityString = "This is an unknown priority!"; + super.testGetObjectProp_Equals_2(); + BugPriority bp = BugPriority.getBugPriority(priorityString, true); + assertEquals(bp.getPriority(), priorityString); + } + + @Test + public final void testGetBugPriorityStatic() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), BugPriority.getBugPriority(priority)); + } + + @Test + public final void testGetBugPriorityStatic_Null() { + assertNull(BugPriority.getBugPriority(null)); + } + + @Test + public final void testFromString_Low() { + assertEquals(Priority.LOW, Priority.fromString(Priority.LOW.toString())); + } + + @Test + public final void testFromString_Med() { + assertEquals(Priority.MEDIUM, Priority.fromString(Priority.MEDIUM.toString())); + } + + @Test + public final void testFromString_High() { + assertEquals(Priority.HIGH, Priority.fromString(Priority.HIGH.toString())); + } + + @Test + public final void testFromString_Unknown() { + assertEquals(Priority.UNKNOWN, Priority.fromString(Priority.UNKNOWN.toString())); + } + + @Test + public final void testFromString_Unknown_2() { + assertEquals(Priority.UNKNOWN, Priority.fromString("Unspecified")); + } + + @Test + public final void testFromString_Null() { + assertNull(Priority.fromString(null)); + } + + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/BugReportMessageTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/BugReportMessageTest.java new file mode 100644 index 000000000..9597517d2 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/BugReportMessageTest.java @@ -0,0 +1,155 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Date; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +public class BugReportMessageTest extends DBTestSuperDoHQL2 { + + @Mock private Bug bug; + @Mock private Developer dev; + + @Before + public void setUp() throws Exception { + super.setUp(new BugReportMessage()); + } + + @Test + public void testID() { + super.testSetId(); + } + + @Test + public final void testBugReportMessageBug() { + BugReportMessage brMessage = new BugReportMessage(bug); + assertEquals(bug, brMessage.getBug()); + } + + @Test + public final void testSetBug() { + getObjectUnderTest().setBug(bug); + assertEquals(bug, getObjectUnderTest().getBug()); + } + + @Test + public final void testSetReporter() { + getObjectUnderTest().setReporter(dev); + assertEquals(dev, getObjectUnderTest().getReporter()); + } + + @Test + public final void testSetTimestamp() { + Date timestamp = new Date(); + getObjectUnderTest().setTimestamp(timestamp); + assertEquals(timestamp, getObjectUnderTest().getTimestamp()); + } + + @Test + public final void testSetText() { + String test = "testMessage"; + getObjectUnderTest().setText(test); + assertEquals(test, getObjectUnderTest().getText()); + } + + private BugReportMessage setUpBugReportMessage(long bugId, long pId) { + Bug b = Mockito.mock(Bug.class); + StoredProject p = Mockito.mock(StoredProject.class); + + Mockito.doReturn(p).when(b).getProject(); + Mockito.doReturn(Long.toString(bugId)).when(b).getBugID(); + Mockito.doReturn(pId).when(p).getId(); + return new BugReportMessage(b); + } + + @Test // Test broken as long as equals is. + public final void testEquals() { + BugReportMessage brm1 = setUpBugReportMessage(0, 0); + BugReportMessage brm2 = null; + Date d1 = new Date(); + Date d2 = new Date(); + brm1.setTimestamp(d1); + assertFalse(brm1.equals(brm2)); + } + + @Test + public final void testEquals_2() throws InterruptedException { + BugReportMessage brm1 = setUpBugReportMessage(0, 0); + BugReportMessage brm2 = setUpBugReportMessage(0, 0); + Date d1 = new Date(); + Thread.sleep(1); + Date d2 = new Date(); + brm1.setTimestamp(d1); + brm2.setTimestamp(d2); + assertFalse(brm1.equals(brm2)); + } + + @Test + public final void testEquals_3() throws InterruptedException { + BugReportMessage brm1 = setUpBugReportMessage(0, 0); + BugReportMessage brm2 = setUpBugReportMessage(0, 1); + Date d1 = new Date(); + Date d2 = d1; + brm1.setTimestamp(d1); + brm2.setTimestamp(d2); + assertFalse(brm1.equals(brm2)); + } + + @Test + public final void testEquals_4() throws InterruptedException { + BugReportMessage brm1 = setUpBugReportMessage(0, 0); + BugReportMessage brm2 = setUpBugReportMessage(1, 0); + Date d1 = new Date(); + Date d2 = d1; + brm1.setTimestamp(d1); + brm2.setTimestamp(d2); + assertFalse(brm1.equals(brm2)); + } + + @Test + public final void testEquals_Equal() throws InterruptedException { + BugReportMessage brm1 = setUpBugReportMessage(0, 0); + BugReportMessage brm2 = setUpBugReportMessage(0, 0); + Date d1 = new Date(); + Thread.sleep(1); + Date d2 = d1; + brm1.setTimestamp(d1); + brm2.setTimestamp(d2); + assertTrue(brm1.equals(brm2)); + } + + @Test + public final void testGetAllBugReportsForBugBug() { + super.testGetStaticDoHQL2_ShouldBeNull(); + assertEquals(0, BugReportMessage.getAllReportMessageForBug(bug).size()); + } + + @Test + public final void testGetAllBugReportsForBugBug_2() { + super.testGetStaticDoHQL2_ShouldBeObject(); + assertEquals(getObjectUnderTest(), BugReportMessage.getAllReportMessageForBug(bug).get(0)); + } + + @Test + public final void testGetAllDeveloperReportsForDeveloperDeveloper() { + super.testGetStaticDoHQL2_ShouldBeNull(); + assertEquals(0, BugReportMessage.getAllReportMessageForDeveloper(dev).size()); + } + + @Test + public final void testGetAllDeveloperReportsForDeveloperDeveloper_2() { + super.testGetStaticDoHQL2_ShouldBeObject(); + assertEquals(getObjectUnderTest(), BugReportMessage.getAllReportMessageForDeveloper(dev).get(0)); + } + + + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/BugResolutionTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/BugResolutionTest.java new file mode 100644 index 000000000..6c6992c81 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/BugResolutionTest.java @@ -0,0 +1,117 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import eu.sqooss.service.db.BugResolution.Resolution; +import eu.sqooss.service.db.BugResolution.Resolution; + +public class BugResolutionTest extends DBTestSuperObjectProp { + + BugResolution.Resolution res; + + @Before + public void setUp() throws Exception { + super.setUp(new BugResolution()); + res = Resolution.WONTFIX; + } + + public void testID() { + super.testSetId(); + } + + @Test + public final void testSetResolution() { + String resolution = "solved it"; + getObjectUnderTest().setResolution(resolution); + assertEquals(resolution, getObjectUnderTest().getResolution()); + } + + @Test + public final void testSetBugResolution() { + getObjectUnderTest().setBugResolution(res); + assertEquals(res, getObjectUnderTest().getBugResolution()); + } + + @Test + public final void testGetBugResolutionResolution() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), BugResolution.getBugResolution(res)); + } + + @Test + public final void testGetBugResolutionStringBoolean() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), BugResolution.getBugResolution("low", false)); + } + + @Test + public final void testGetBugResolutionStringBoolean_2() { + super.testGetObjectProp_Null_2(); + assertNull(BugResolution.getBugResolution("low", false)); + } + + @Test + public final void testGetBugResolutionStringBoolean_3() { + super.testGetObjectProp_Null_2(); + assertNull(BugResolution.getBugResolution(null, true)); + } + + @Test + public final void testGetBugResolutionStringBoolean_4() { + super.testGetObjectProp_Null_2(); + assertNull(BugResolution.getBugResolution("low", true)); + } + + @Test + public final void testGetBugResolutionStringBoolean_5() { + super.testGetObjectProp_Equals_2(); + assertEquals("low", BugResolution.getBugResolution("low", true).getResolution()); + } + + @Test + public final void testFromString_1() { + assertEquals(BugResolution.Resolution.DUPLICATE, BugResolution.Resolution.fromString("duplicate")); + } + + @Test + public final void testFromString_2() { + assertEquals(BugResolution.Resolution.FIXED, BugResolution.Resolution.fromString("fixed")); + } + + @Test + public final void testFromString_3() { + assertEquals(BugResolution.Resolution.INVALID, BugResolution.Resolution.fromString("invalid")); + } + + @Test + public final void testFromString_4() { + assertEquals(BugResolution.Resolution.MOVED, BugResolution.Resolution.fromString("moved")); + } + + @Test + public final void testFromString_5() { + assertEquals(BugResolution.Resolution.UNKNOWN, BugResolution.Resolution.fromString("unknown")); + } + + @Test + public final void testFromString_6() { + assertEquals(BugResolution.Resolution.WONTFIX, BugResolution.Resolution.fromString("wontfix")); + } + + @Test + public final void testFromString_7() { + assertEquals(BugResolution.Resolution.WORKSFORME, BugResolution.Resolution.fromString("worksforme")); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/BugSeverityTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/BugSeverityTest.java new file mode 100644 index 000000000..94dc3b98f --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/BugSeverityTest.java @@ -0,0 +1,149 @@ +/** + * + */ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mockito; + +/** + * @author stefan + * + */ +public class BugSeverityTest extends DBTestSuperObjectProp { + + BugSeverity.Severity sev; + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + super.setUp(new BugSeverity()); + sev = BugSeverity.Severity.BLOCKER; + } + + public void testID() { + super.testSetId(); + } + + /** + * Test method for {@link eu.sqooss.service.db.BugSeverity#setSeverity(java.lang.String)}. + */ + @Test + public final void testSetSeverity() { + getObjectUnderTest().setSeverity(sev.toString()); + assertEquals(sev.toString(), getObjectUnderTest().getSeverity()); + } + + /** + * Test method for {@link eu.sqooss.service.db.BugSeverity#setBugseverity(eu.sqooss.service.db.BugSeverity.Severity)}. + */ + @Test + public final void testSetBugseverity() { + getObjectUnderTest().setBugseverity(sev); + assertEquals(sev, getObjectUnderTest().getBugSeverity()); + } + + /** + * Test method for {@link eu.sqooss.service.db.BugSeverity#getBugseverity(eu.sqooss.service.db.BugSeverity.Severity)}. + */ + @Test + public final void testGetBugseverity() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), BugSeverity.getBugseverity(sev)); + } + + @Test + public final void testGetBugSeverityStringBoolean() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), BugSeverity.getBugSeverity("low", false)); + } + + @Test + public final void testGetBugSeverityStringBoolean_2() { + super.testGetObjectProp_Null_1(); + assertNull(BugSeverity.getBugSeverity("low", false)); + } + + @Test + public final void testGetBugSeverityStringBoolean_3() { + super.testGetObjectProp_Null_1(); + assertNull(BugSeverity.getBugSeverity(null, true)); + } + + @Test + public final void testGetBugSeverityStringBoolean_4() { + super.testGetObjectProp_Null_2(); + assertNull(BugSeverity.getBugSeverity("unknown priority", true)); + } + + @Test + public final void testGetBugSeverityStringBoolean_5() { + String priorityString = "This is an unknown priority!"; + super.testGetObjectProp_Equals_2(); + BugSeverity bugs = BugSeverity.getBugSeverity(priorityString, true); + assertEquals(bugs.getSeverity(), priorityString); + } + + + @Test + public final void testFromString_1() { + testFromString(BugSeverity.Severity.BLOCKER); + } + + @Test + public final void testFromString_2() { + testFromString(BugSeverity.Severity.CRITICAL); + } + + @Test + public final void testFromString_3() { + testFromString(BugSeverity.Severity.ENHANCEMENT); + } + + @Test + public final void testFromString_4() { + testFromString(BugSeverity.Severity.MAJOR); + } + + @Test + public final void testFromString_5() { + testFromString(BugSeverity.Severity.MINOR); + } + + @Test + public final void testFromString_6() { + testFromString(BugSeverity.Severity.NORMAL); + } + + @Test + public final void testFromString_7() { + testFromString(BugSeverity.Severity.TRIVIAL); + } + + @Test + public final void testFromString_8() { + testFromString(BugSeverity.Severity.UNKNOWN); + } + + @Test + public final void testFromString_9() { + assertEquals(BugSeverity.Severity.UNKNOWN, BugSeverity.Severity.fromString("blah")); + } + + private final void testFromString(BugSeverity.Severity sev) { + assertEquals(sev, BugSeverity.Severity.fromString(sev.toString())); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/BugStatusTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/BugStatusTest.java new file mode 100644 index 000000000..2f5f80a2c --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/BugStatusTest.java @@ -0,0 +1,118 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; + +public class BugStatusTest extends DBTestSuperObjectProp { + + BugStatus.Status stat; + + @Before + public void setUp() throws Exception { + super.setUp(new BugStatus()); + stat = BugStatus.Status.ASSIGNED; + } + + public void testID() { + super.testSetId(); + } + + @Test + public final void testSetStatus() { + String status = "StatusString"; + getObjectUnderTest().setStatus(status); + assertEquals(status, getObjectUnderTest().getStatus()); + } + + @Test + public final void testSetBugStatus() { + getObjectUnderTest().setBugStatus(stat); + assertEquals(stat, getObjectUnderTest().getBugStatus()); + } + + @Test + public final void testGetBugStatusStatus() { + super.testGetObjectProp_Null_1(); + assertNull(BugStatus.getBugStatus(stat)); + } + + @Test + public final void testGetBugStatusStatus_2() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), BugStatus.getBugStatus(stat.toString(), false)); + } + + @Test + public final void testGetBugStatusStatus_3() { + super.testGetObjectProp_Null_1(); + assertNull(BugStatus.getBugStatus(stat.toString(), false)); + } + + @Test + public final void testGetBugStatusStatus_3_5() { + super.testGetObjectProp_Null_1(); + assertNull(BugStatus.getBugStatus(null, true)); + } + + @Test + public final void testGetBugStatusStatus_4() { + super.testGetObjectProp_Null_2(); + assertNull(BugStatus.getBugStatus("hallo", false)); + } + + @Test + public final void testGetBugStatusStatus_5() { + super.testGetObjectProp_Equals_2(); + assertEquals("hallo",BugStatus.getBugStatus("hallo", true).getStatus()); + } + + private void testOne(BugStatus.Status stat) { + assertEquals(stat, BugStatus.Status.fromString(stat.toString())); + } + + @Test + public void testFromString_1() { + testOne(BugStatus.Status.ASSIGNED); + } + + @Test + public void testFromString_2() { + testOne(BugStatus.Status.CLOSED); + } + + @Test + public void testFromString_3() { + testOne(BugStatus.Status.NEW); + } + + @Test + public void testFromString_4() { + testOne(BugStatus.Status.REOPENED); + } + + @Test + public void testFromString_5() { + testOne(BugStatus.Status.RESOLVED); + } + + @Test + public void testFromString_6() { + testOne(BugStatus.Status.UNCONFIRMED); + } + + @Test + public void testFromString_7() { + testOne(BugStatus.Status.UNKNOWN); + } + + @Test + public void testFromString_8() { + testOne(BugStatus.Status.VERIFIED); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/BugTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/BugTest.java new file mode 100644 index 000000000..76bebb5e8 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/BugTest.java @@ -0,0 +1,211 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import eu.sqooss.core.AlitheiaCore; + +public class BugTest extends DBTestSuperDoHQL3 { + + @Mock private BugStatus status; + @Mock private Developer reporter; + @Mock private BugResolution resolution; + @Mock private BugPriority priority; + @Mock private BugSeverity severity; + @Mock private BugReportMessage bugReportMessage; + @Mock private StoredProject project; + + @Before + public void setUp() throws Exception { + super.setUp(new Bug()); + } + + public void testID() { + super.testSetId(); + } + + @Test + public void testSetBugID() { + String bugID = "bugID"; + getObjectUnderTest().setBugID(bugID); + assertEquals(bugID, getObjectUnderTest().getBugID()); + } + + + @Test + public void testSetBugID_2() + throws Exception { + String bugID = ""; + getObjectUnderTest().setBugID(bugID); + assertEquals(bugID, getObjectUnderTest().getBugID()); + } + + @Test + public void testSetStatus() { + getObjectUnderTest().setStatus(status); + assertEquals(status, getObjectUnderTest().getStatus()); + } + + @Test + public void testSetCreationTS() { + Date creationTS = new Date(); + getObjectUnderTest().setCreationTS(creationTS); + assertEquals(creationTS, getObjectUnderTest().getCreationTS()); + } + + @Test + public void testSetDeltaTS() { + Date deltaTS = new Date(); + getObjectUnderTest().setDeltaTS(deltaTS); + assertEquals(deltaTS, getObjectUnderTest().getDeltaTS()); + } + + @Test + public void testSetReporter() { + getObjectUnderTest().setReporter(reporter); + assertEquals(reporter, getObjectUnderTest().getReporter()); + } + + @Test + public void testSetResolution() { + getObjectUnderTest().setResolution(resolution); + assertEquals(resolution, getObjectUnderTest().getResolution()); + } + + @Test + public void testSetPriority() { + getObjectUnderTest().setPriority(priority); + assertEquals(priority, getObjectUnderTest().getPriority()); + } + + @Test + public void testSetSeverity() { + getObjectUnderTest().setSeverity(severity); + assertEquals(severity, getObjectUnderTest().getSeverity()); + } + + @Test + public void testSetShortDesc() { + String shortDesc = "this is a bug"; + getObjectUnderTest().setShortDesc(shortDesc); + assertEquals(shortDesc, getObjectUnderTest().getShortDesc()); + } + + @Test + public void testSetProject() { + getObjectUnderTest().setProject(project); + assertEquals(project, getObjectUnderTest().getProject()); + } + + @Test + public void testSetUpdateRun() { + Date updateRun = new Date(); + getObjectUnderTest().setUpdateRun(updateRun); + assertEquals(updateRun, getObjectUnderTest().getUpdateRun()); + } + + @Test + public void testGetLastUpdate() { + super.testGetStaticDoHQL3_ShouldBeNull(); + assertNull(Bug.getLastUpdate(project)); + } + + @Test + public void testGetLastUpdate_2() { + super.testGetStaticDoHQL3_ShouldBeObject(); + assertEquals(getObjectUnderTest(), Bug.getLastUpdate(project)); + } + + @Test + public void testGetLastUpdate_Null() { + super.testGetStaticDoHQL3_ShouldBeNull(); + assertNull(Bug.getLastUpdate(null)); + } + + @Test + public void testGetStaticDoHQL3_ShouldBeNull() { + super.testGetStaticDoHQL3_ShouldBeNull(); + assertNull(Bug.getBug("bugId", project)); + } + + @Test + public void testGetStaticDoHQL3_ShouldBeObject() { + super.testGetStaticDoHQL3_ShouldBeObject(); + assertEquals(getObjectUnderTest(), Bug.getBug("bugId", project)); + } + + @Test + public void testGetBugsForPriorityPriority() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, Bug.getBugsForPriority(priority).size()); + } + + @Test + public void testGetBugsForPriorityPriority_2() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(getObjectUnderTest(), Bug.getBugsForPriority(priority).get(0)); + } + + @Test + public void testGetBugsForResolutionResolution() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, Bug.getBugsForResolution(resolution).size()); + } + + @Test + public void testGetBugsForResolutionResolution_2() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(getObjectUnderTest(), Bug.getBugsForResolution(resolution).get(0)); + } + + @Test + public void testGetBugsForSeveritySeverity() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, Bug.getBugsForSeverity(severity).size()); + } + + @Test + public void testGetBugsForSeveritySeverity_2() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(getObjectUnderTest(), Bug.getBugsForSeverity(severity).get(0)); + } + + @Test + public void testGetBugsForStatusStatus() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, Bug.getBugsForStatus(status).size()); + } + + @Test + public void testGetBugsForStatusStatus_2() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(getObjectUnderTest(), Bug.getBugsForStatus(status).get(0)); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ClusterNodeTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ClusterNodeTest.java new file mode 100644 index 000000000..1f8f3ee96 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ClusterNodeTest.java @@ -0,0 +1,79 @@ +package eu.sqooss.service.db; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; + +import eu.sqooss.service.db.ClusterNode; +import eu.sqooss.service.db.StoredProject; + + +public class ClusterNodeTest extends DBTestSuperObjectProp { + + @Before + public void setUp() throws Exception { + super.setUp(new ClusterNode()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testClusterNodeString() { + String servername = "hoi"; + ClusterNode cn = new ClusterNode(servername); + assertEquals(servername, cn.getName()); + } + + @Test + public final void testSetName() { + String name = "hoi"; + getObjectUnderTest().setName(name); + assertEquals(name, getObjectUnderTest().getName()); + } + + @Test + public final void testSetProjects() { + Set set = new HashSet(); + getObjectUnderTest().setProjects(set); + assertEquals(set, getObjectUnderTest().getProjects()); + } + + @Test + public final void testGetClusteNodeByName() { + super.testGetObjectProp_Null_1(); + assertNull(ClusterNode.getClusteNodeByName("")); + } + + @Test + public final void testGetClusteNodeByName_2() { + super.testGetObjectProp_Null_1(); + assertNull(ClusterNode.getClusteNodeByName(null)); + } + + @Test + public final void testGetClusteNodeByName_3() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), ClusterNode.getClusteNodeByName("")); + } + + @Test + public final void testGetClusteNodeByName_4() { + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(null); + assertNull(ClusterNode.getClusteNodeByName("")); + } + + @Test + public final void testThisNode() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), ClusterNode.thisNode()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ConfigurationOptionTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ConfigurationOptionTest.java new file mode 100644 index 000000000..8a24544b0 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ConfigurationOptionTest.java @@ -0,0 +1,194 @@ +/** + * + */ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; + +/** + * @author stefan + * + */ +public class ConfigurationOptionTest extends DBTestSuperObjectProp { + + @Mock StoredProjectConfig spc; + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + super.setUp(new ConfigurationOption()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + /** + * Test method for {@link eu.sqooss.service.db.ConfigurationOption#ConfigurationOption(java.lang.String, java.lang.String)}. + */ + @Test + public final void testConfigurationOptionStringString() { + String key = "key"; + String desc = "desc"; + ConfigurationOption option = new ConfigurationOption(key, desc); + assertEquals(key, option.getKey()); + assertEquals(desc, option.getDescription()); + } + + /** + * Test method for {@link eu.sqooss.service.db.ConfigurationOption#setKey(java.lang.String)}. + */ + @Test + public final void testSetKey() { + String key = "key"; + getObjectUnderTest().setKey(key); + assertEquals(key, getObjectUnderTest().getKey()); + } + + /** + * Test method for {@link eu.sqooss.service.db.ConfigurationOption#setDescription(java.lang.String)}. + */ + @Test + public final void testSetDescription() { + String key = "key"; + getObjectUnderTest().setDescription(key); + assertEquals(key, getObjectUnderTest().getDescription()); + } + + /** + * Test method for {@link eu.sqooss.service.db.ConfigurationOption#setConfigurations(java.util.Set)}. + */ + @Test + public final void testSetConfigurations() { + Set set = new HashSet(); + getObjectUnderTest().setConfigurations(set); + assertEquals(set, getObjectUnderTest().getConfigurations()); + } + + /** + * Test method for {@link eu.sqooss.service.db.ConfigurationOption#setValues(eu.sqooss.service.db.StoredProject, java.util.List, boolean)}. + */ + @Test + public final void testSetValues_1() { + List list = new ArrayList(); + List stringList = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + getObjectUnderTest().setValues(null, stringList, false); + Mockito.verify(super.dbService, Mockito.times(0)).addRecord((DAObject) Matchers.any()); + } + + /** + * Test method for {@link eu.sqooss.service.db.ConfigurationOption#setValues(eu.sqooss.service.db.StoredProject, java.util.List, boolean)}. + */ + @Test + public final void testSetValues_2() { + List list = new ArrayList(); + List stringList = new ArrayList(); + String e = "hi there"; + String e2 = "another string"; + Mockito.doReturn(e).doReturn(e).when(spc).getValue(); + + list.add(spc); + list.add(spc); + stringList.add(e); + stringList.add(e2); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + getObjectUnderTest().setValues(null, stringList, false); + Mockito.verify(super.dbService, Mockito.times(0)).addRecord((DAObject) Matchers.any()); + } + + /** + * Test method for {@link eu.sqooss.service.db.ConfigurationOption#setValues(eu.sqooss.service.db.StoredProject, java.util.List, boolean)}. + */ + @Test + public final void testSetValues_3() { + List list = new ArrayList(); + List stringList = new ArrayList(); + String e = "hi there"; + String e2 = "another string"; + Mockito.doReturn(e2).when(spc).getValue(); + + list.add(spc); + stringList.add(e); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + getObjectUnderTest().setValues(null, stringList, false); + Mockito.verify(super.dbService, Mockito.times(1)).addRecord((DAObject) Matchers.any()); + } + + @Test + public final void testSetValues_4() { + List list = new ArrayList(); + List stringList = new ArrayList(); + String e = "hi there"; + String e2 = "another string"; + Mockito.doReturn(e2).when(spc).getValue(); + + list.add(spc); + stringList.add(e); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + getObjectUnderTest().setValues(null, stringList, true); + Mockito.verify(super.dbService, Mockito.times(1)).addRecord((DAObject) Matchers.any()); + Mockito.verify(super.dbService, Mockito.times(1)).deleteRecords(Matchers.eq(list)); + } + + + @Test + public final void testGetValues_1() { + List stringList = new ArrayList(); + String e = "hi there"; + stringList.add(e); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(stringList); + assertEquals(stringList, getObjectUnderTest().getValues(null)); + } + + + /** + * Test method for {@link eu.sqooss.service.db.ConfigurationOption#fromKey(java.lang.String)}. + */ + @Test + public final void testFromKey() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), ConfigurationOption.fromKey("")); + } + + @Test + public final void testFromKey_2() { + super.testGetObjectProp_Null_1(); + assertNull(ConfigurationOption.fromKey("")); + } + + /** + * Test method for {@link eu.sqooss.service.db.ConfigurationOption#toString()}. + */ + @Test + public final void testToString() { + assertEquals("null - null", getObjectUnderTest().toString()); + } + + /** + * Test method for {@link eu.sqooss.service.db.ConfigurationOption#toString()}. + */ + @Test + public final void testToString_2() { + getObjectUnderTest().setKey("k"); + getObjectUnderTest().setDescription("d"); + assertEquals("k - d", getObjectUnderTest().toString()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuper.java b/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuper.java new file mode 100644 index 000000000..c1750eca6 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuper.java @@ -0,0 +1,84 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.junit.After; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import eu.sqooss.core.AlitheiaCore; + +public abstract class DBTestSuper { + + @Mock + protected AlitheiaCore alitheiaCore; + @Mock + protected DBService dbService; + + T objectUnderTest; + + public DBTestSuper() { + super(); + } + + public void setUp(T object) throws Exception { + MockitoAnnotations.initMocks(this); + objectUnderTest = object; + } + + public T getObjectUnderTest() { + return objectUnderTest; + } + + protected void setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp( + List list) { + AlitheiaCore.setTestInstance(alitheiaCore); + Mockito.when(alitheiaCore.getDBService()).thenReturn(dbService); + Mockito.doReturn(list) + .when(dbService) + .findObjectsByProperties((Class) Matchers.any(), + Matchers.anyMap()); + } + + protected void setUpMockedDBService() { + AlitheiaCore.setTestInstance(alitheiaCore); + Mockito.when(alitheiaCore.getDBService()).thenReturn(dbService); + } + + protected void setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(List list) { + AlitheiaCore.setTestInstance(alitheiaCore); + Mockito.when(alitheiaCore.getDBService()).thenReturn(dbService); + Mockito.doReturn(list).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap(), Matchers.eq(1)); + } + + protected void setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(List list) { + AlitheiaCore.setTestInstance(alitheiaCore); + Mockito.when(alitheiaCore.getDBService()).thenReturn(dbService); + Mockito.doReturn(list).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + } + + protected void setUpMockedAlitheiaCoreAndDbServiceForDoHQL1(List list) { + AlitheiaCore.setTestInstance(alitheiaCore); + Mockito.when(alitheiaCore.getDBService()).thenReturn(dbService); + Mockito.doReturn(list).when(dbService).doHQL(Matchers.anyString()); + } + + public void testSetId() { + long id = 1231; + objectUnderTest.setId(id); + assertEquals(id, objectUnderTest.getId()); + } + + @After + public void after() { + AlitheiaCore.setTestInstance(null); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuperDoHQL2.java b/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuperDoHQL2.java new file mode 100644 index 000000000..d4b6f3f83 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuperDoHQL2.java @@ -0,0 +1,24 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +public class DBTestSuperDoHQL2 extends DBTestSuper { + + protected void testGetStaticDoHQL2_ShouldBeNull() { + List list = new ArrayList(); + this.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + + } + + protected void testGetStaticDoHQL2_ShouldBeObject() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + this.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuperDoHQL3.java b/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuperDoHQL3.java new file mode 100644 index 000000000..3eac38f0f --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuperDoHQL3.java @@ -0,0 +1,24 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +public class DBTestSuperDoHQL3 extends DBTestSuper { + + protected void testGetStaticDoHQL3_ShouldBeNull() { + List list = new ArrayList(); + this.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + + } + + protected void testGetStaticDoHQL3_ShouldBeObject() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + this.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuperObjectProp.java b/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuperObjectProp.java new file mode 100644 index 000000000..6e1d953f3 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/DBTestSuperObjectProp.java @@ -0,0 +1,40 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mockito; + +public class DBTestSuperObjectProp extends DBTestSuper { + + /** + * Test method for {@link eu.sqooss.service.db.BugPriority#getBugPriority(java.lang.String, boolean)}. + */ + protected final void testGetObjectProp_Equals_1() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + this.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + } + + protected final void testGetObjectProp_Null_1() { + List list = new ArrayList(); + this.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + } + + protected final void testGetObjectProp_Null_2() { + List list = new ArrayList(); + this.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + Mockito.doReturn(false).when(dbService).addRecord((DAObject) Matchers.any()); + } + + protected final void testGetObjectProp_Equals_2() { + List list = new ArrayList(); + this.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + Mockito.doReturn(true).when(dbService).addRecord((DAObject) Matchers.any()); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/DeveloperAliasTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/DeveloperAliasTest.java new file mode 100644 index 000000000..d75985531 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/DeveloperAliasTest.java @@ -0,0 +1,77 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class DeveloperAliasTest extends DBTestSuper{ + + @Mock Developer d; + + @Before + public void setUp() throws Exception { + super.setUp(new DeveloperAlias()); + } + + @Test + public final void testHashCode() { + assertFalse(new DeveloperAlias().hashCode() == new DeveloperAlias("email", null).hashCode()); + assertFalse(new DeveloperAlias("", d).hashCode() == new DeveloperAlias("", null).hashCode()); + assertEquals(new DeveloperAlias().hashCode(), getObjectUnderTest().hashCode()); + assertEquals(getObjectUnderTest().hashCode(), getObjectUnderTest().hashCode()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testDeveloperAliasStringDeveloper() { + String email = "s.hugtenburg@gmail.com"; + DeveloperAlias da = new DeveloperAlias(email, d); + assertEquals(d, da.getDeveloper()); + assertEquals(email, da.getEmail()); + } + + @Test + public final void testSetEmail() { + String email = "s.hugtenburg@gmail.com"; + getObjectUnderTest().setEmail(email); + assertEquals(email, getObjectUnderTest().getEmail()); + } + + @Test + public final void testSetDeveloper() { + getObjectUnderTest().setDeveloper(d); + assertEquals(d, getObjectUnderTest().getDeveloper()); + } + + @Test + public final void testEqualsObject_1() { + assertEquals(new DeveloperAlias(), getObjectUnderTest()); + } + + @Test + public final void testEquals_2() { + assertFalse(new DeveloperAlias("", null).equals(getObjectUnderTest())); + } + + @Test + public final void testEquals_3() { + assertTrue(new DeveloperAlias("", null).equals(new DeveloperAlias("", null))); + } + + @Test + public final void testToString() { + String mail = "hoi"; + getObjectUnderTest().setEmail(mail); + assertEquals(mail, getObjectUnderTest().toString()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/DeveloperTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/DeveloperTest.java new file mode 100644 index 000000000..0914d5624 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/DeveloperTest.java @@ -0,0 +1,203 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; + +public class DeveloperTest extends DBTestSuperDoHQL2{ + + @Mock StoredProject sp; + @Mock OhlohDeveloper ohloh; + + @Before + public void setUp() throws Exception { + super.setUp(new Developer()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testSetName() { + String name = "Stefan Hugtenburg"; + getObjectUnderTest().setName(name); + assertEquals(name, getObjectUnderTest().getName()); + } + + @Test + public final void testSetUsername() { + String username = "MrHug"; + getObjectUnderTest().setUsername(username); + assertEquals(username, getObjectUnderTest().getUsername()); + } + + @Test + public final void testSetStoredProject() { + getObjectUnderTest().setStoredProject(sp); + assertEquals(sp, getObjectUnderTest().getStoredProject()); + } + + @Test + public final void testSetCommits() { + Set set = new HashSet(); + getObjectUnderTest().setCommits(set); + assertEquals(set, getObjectUnderTest().getCommits()); + } + + @Test + public final void testSetMails() { + Set mails = new HashSet(); + getObjectUnderTest().setMails(mails); + assertEquals(mails, getObjectUnderTest().getMails()); + } + + @Test + public final void testSetAliases() { + Set set = new HashSet(); + getObjectUnderTest().setAliases(set); + assertEquals(set, getObjectUnderTest().getAliases()); + } + + @Test + public final void testAddAlias() { + Set set = new HashSet(); + getObjectUnderTest().setAliases(set); + String email = "e-mail here"; + getObjectUnderTest().addAlias(email); + assertTrue(getObjectUnderTest().getAliases().contains(new DeveloperAlias(email, getObjectUnderTest()))); + assertEquals(1, getObjectUnderTest().getAliases().size()); + } + + @Test + public final void testAddAlias_2() { + Set set = new HashSet(); + getObjectUnderTest().setAliases(set); + String email = "e-mail here"; + getObjectUnderTest().addAlias(email); + getObjectUnderTest().addAlias(email); + assertTrue(getObjectUnderTest().getAliases().contains(new DeveloperAlias(email, getObjectUnderTest()))); + assertEquals(1, getObjectUnderTest().getAliases().size()); + } + + @Test + public final void testGetDeveloperByEmailStringStoredProject() { + super.testGetStaticDoHQL2_ShouldBeObject(); + assertEquals(getObjectUnderTest(), Developer.getDeveloperByEmail("", null)); + } + + @Test + public final void testGetDeveloperByEmailStringStoredProject_2() { + super.testGetStaticDoHQL2_ShouldBeNull(); + assertNull(Developer.getDeveloperByEmail("", null)); + } + + @Test + public final void testGetDeveloperByEmailStringStoredProject_3() { + List list = new ArrayList(); + List devList = new ArrayList(); + list.add(ohloh); + devList.add(getObjectUnderTest()); + super.testGetStaticDoHQL2_ShouldBeNull(); + Mockito.doReturn(list).doReturn(devList).when(dbService).findObjectsByProperties((Class) Matchers.any(), Matchers.anyMap()); + Mockito.doReturn(false).when(dbService).addRecord((DAObject) Matchers.any()); + assertEquals(getObjectUnderTest(), Developer.getDeveloperByEmail("", null)); + } + + @Test + public final void testGetDeveloperByEmailStringStoredProject_4() { + List list = new ArrayList(); + List devList = new ArrayList(); + list.add(ohloh); + super.testGetStaticDoHQL2_ShouldBeNull(); + Mockito.doReturn(list).doReturn(devList).when(dbService).findObjectsByProperties((Class) Matchers.any(), Matchers.anyMap()); + Mockito.doReturn(false).when(dbService).addRecord((DAObject) Matchers.any()); + assertNull(Developer.getDeveloperByEmail("", null, false)); + } + + @Test + public final void testGetDeveloperByEmailStringStoredProject_5() { + List list = new ArrayList(); + List devList = new ArrayList(); + list.add(ohloh); + super.testGetStaticDoHQL2_ShouldBeNull(); + Mockito.doReturn(list).doReturn(devList).when(dbService).findObjectsByProperties((Class) Matchers.any(), Matchers.anyMap()); + Mockito.doReturn(true).when(dbService).addRecord((DAObject) Matchers.any()); + assertFalse(Developer.getDeveloperByEmail("", null, true) == null); + } + + @Test + public final void testGetDeveloperByUsernameStringStoredProject() { + super.testGetStaticDoHQL2_ShouldBeObject(); + Mockito.doReturn(true).when(dbService).addRecord((DAObject) Matchers.any()); + assertFalse(Developer.getDeveloperByUsername("", null) == null); + } + + @Test + public final void testGetDeveloperByUsernameStringStoredProject_2() { + super.testGetStaticDoHQL2_ShouldBeObject(); + Mockito.doReturn(false).when(dbService).addRecord((DAObject) Matchers.any()); + assertNull(Developer.getDeveloperByUsername("", null)); + } + + @Test + public final void testGetDeveloperByNameStringStoredProjectBoolean() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + Mockito.doReturn(true).when(dbService).addRecord((DAObject) Matchers.any()); + assertFalse(Developer.getDeveloperByName("", sp, true) == null); + } + + @Test + public final void testGetDeveloperByNameStringStoredProjectBoolean_2() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + Mockito.doReturn(true).when(dbService).addRecord((DAObject) Matchers.any()); + assertEquals(getObjectUnderTest(), Developer.getDeveloperByName("", sp, false)); + } + + @Test + public final void testGetDeveloperByNameStringStoredProjectBoolean_3() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertNull(Developer.getDeveloperByName("", sp, false)); + } + + @Test + public final void testGetDeveloperByNameStringStoredProjectBoolean_4() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + Mockito.doReturn(false).when(dbService).addRecord((DAObject) Matchers.any()); + assertNull(Developer.getDeveloperByName("", sp, true)); + } + + @Test + public final void testToString() { + String e = "null aka:null ()"; + assertEquals(e, getObjectUnderTest().toString()); + } + + @Test + public final void testToString_2() { + String e = "null, aka:null ( )"; + getObjectUnderTest().addAlias("hoi"); + assertEquals(e, getObjectUnderTest().toString()); + } + + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/DirectoryTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/DirectoryTest.java new file mode 100644 index 000000000..03076e612 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/DirectoryTest.java @@ -0,0 +1,120 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; + +public class DirectoryTest extends DBTestSuperObjectProp{ + + @Before + public void setUp() throws Exception { + super.setUp(new Directory()); + } + + @Test + public final void testHashCode() { + Directory d = new Directory(); + d.setPath("hoi"); + assertFalse(d.hashCode() == getObjectUnderTest().hashCode()); + } + + @Test + public final void testHashCode_2() { + Directory d = new Directory(); + assertEquals(d.hashCode(), getObjectUnderTest().hashCode()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testSetPath() { + String path = "path/to/dir"; + getObjectUnderTest().setPath(path); + assertEquals(path, getObjectUnderTest().getPath()); + } + + @Test + public final void testSetFiles() { + Set files = new HashSet(); + getObjectUnderTest().setFiles(files); + assertEquals(files, getObjectUnderTest().getFiles()); + } + + @Test + public final void testIsSubDirOf() { + assertFalse(getObjectUnderTest().isSubDirOf(null)); + } + + @Test + public final void testGetDirectory() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), Directory.getDirectory("", false)); + } + + @Test + public final void testGetDirectory_2() { + super.testGetObjectProp_Equals_2(); + assertFalse(Directory.getDirectory("", true) == null); + } + + @Test + public final void testGetDirectory_3() { + super.testGetObjectProp_Null_1(); + assertNull(Directory.getDirectory("", false)); + } + + @Test + public final void testGetDirectory_4() { + super.testGetObjectProp_Null_2(); + assertNull(Directory.getDirectory("", true)); + } + + @Test + public final void testToString() { + assertNull(getObjectUnderTest().toString()); + } + + @Test + public final void testToString_2() { + String string = "path/to/dir"; + getObjectUnderTest().setPath(string); + assertEquals(string, getObjectUnderTest().toString()); + } + + @Test + public final void testEqualsObject() { + assertEquals(getObjectUnderTest(), getObjectUnderTest()); + } + + @Test + public final void testEqualsObject_2() { + assertFalse(getObjectUnderTest().equals(new Directory())); + } + + @Test + public final void testEqualsObject_3() { + assertFalse(getObjectUnderTest().equals(null)); + } + + @Test + public final void testEqualsObject_4() { + assertFalse(getObjectUnderTest().equals("object")); + } + + @Test + public final void testEqualsObject_5() { + getObjectUnderTest().setPath("path/to/dir"); + assertFalse(getObjectUnderTest().equals(new Directory())); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/EncapsulationUnitMeasurementTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/EncapsulationUnitMeasurementTest.java new file mode 100644 index 000000000..004eed8d1 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/EncapsulationUnitMeasurementTest.java @@ -0,0 +1,78 @@ +/** + * + */ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +/** + * @author stefan + * + */ +public class EncapsulationUnitMeasurementTest extends + DBTestSuper { + + @Mock EncapsulationUnit eu; + @Mock Metric m; + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + super.setUp(new EncapsulationUnitMeasurement()); + } + + /** + * Test method for {@link eu.sqooss.service.db.EncapsulationUnitMeasurement#setId(long)}. + */ + @Test + public final void testSetId() { + super.testSetId(); + } + + /** + * Test method for {@link eu.sqooss.service.db.EncapsulationUnitMeasurement#getResult()}. + */ + @Test + public final void testGetResult() { + String result = "result here"; + getObjectUnderTest().setResult(result); + assertEquals(result, getObjectUnderTest().getResult()); + } + + /** + * Test method for {@link eu.sqooss.service.db.EncapsulationUnitMeasurement#EncapsulationUnitMeasurement(eu.sqooss.service.db.EncapsulationUnit, eu.sqooss.service.db.Metric, java.lang.String)}. + */ + @Test + public final void testEncapsulationUnitMeasurementEncapsulationUnitMetricString() { + String s = "hallo"; + EncapsulationUnitMeasurement eum = new EncapsulationUnitMeasurement(eu, m, s); + assertEquals(s, eum.getResult()); + assertEquals(eu, eum.getEncapsulationUnit()); + assertEquals(m, eum.getMetric()); + } + + /** + * Test method for {@link eu.sqooss.service.db.EncapsulationUnitMeasurement#setEncapsulationUnit(eu.sqooss.service.db.EncapsulationUnit)}. + */ + @Test + public final void testSetEncapsulationUnit() { + getObjectUnderTest().setEncapsulationUnit(eu); + assertEquals(eu, getObjectUnderTest().getEncapsulationUnit()); + } + + /** + * Test method for {@link eu.sqooss.service.db.EncapsulationUnitMeasurement#setMetric(eu.sqooss.service.db.Metric)}. + */ + @Test + public final void testSetMetric() { + getObjectUnderTest().setMetric(m); + assertEquals(m, getObjectUnderTest().getMetric()); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/EncapsulationUnitTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/EncapsulationUnitTest.java new file mode 100644 index 000000000..6fcb8f1e8 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/EncapsulationUnitTest.java @@ -0,0 +1,72 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class EncapsulationUnitTest extends DBTestSuper{ + + @Mock ProjectFile pf; + @Mock NameSpace ns; + + @Before + public void setUp() throws Exception { + super.setUp(new EncapsulationUnit()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testEncapsulationUnitProjectFile() { + EncapsulationUnit eu = new EncapsulationUnit(pf); + assertEquals(pf, eu.getFile()); + } + + @Test + public final void testSetName() { + String name = "name"; + getObjectUnderTest().setName(name); + assertEquals(name, getObjectUnderTest().getName()); + } + + @Test + public final void testSetNamespace() { + getObjectUnderTest().setNamespace(ns); + assertEquals(ns, getObjectUnderTest().getNamespace()); + } + + @Test + public final void testSetExecUnits() { + Set set = new HashSet(); + getObjectUnderTest().setExecUnits(set); + assertEquals(set, getObjectUnderTest().getExecUnits()); + } + + @Test + public final void testSetFile() { + getObjectUnderTest().setFile(pf); + assertEquals(pf, getObjectUnderTest().getFile()); + } + + @Test + public final void testSetMeasurements() { + Set measurements = new HashSet(); + getObjectUnderTest().setMeasurements(measurements); + assertEquals(measurements, getObjectUnderTest().getMeasurements()); + } + + @Test + public final void testToString() { + getObjectUnderTest().setName("name"); + assertEquals("name", getObjectUnderTest().toString()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ExecutionUnitMeasurementTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ExecutionUnitMeasurementTest.java new file mode 100644 index 000000000..eb5b1ebba --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ExecutionUnitMeasurementTest.java @@ -0,0 +1,54 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class ExecutionUnitMeasurementTest extends + DBTestSuper { + + @Mock ExecutionUnit eu; + @Mock Metric m; + + @Before + public void setUp() throws Exception { + super.setUp(new ExecutionUnitMeasurement()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testExecutionUnitMeasurementExecutionUnitMetricString() { + String st = "hi"; + ExecutionUnitMeasurement eum = new ExecutionUnitMeasurement(eu, m, st); + assertEquals(eu, eum.getExecutionUnit()); + assertEquals(m, eum.getMetric()); + assertEquals(st, eum.getResult()); + } + + @Test + public final void testSetExecutionUnit() { + getObjectUnderTest().setExecutionUnit(eu); + assertEquals(eu, getObjectUnderTest().getExecutionUnit()); + } + + @Test + public final void testSetMetric() { + getObjectUnderTest().setMetric(m); + assertEquals(m, getObjectUnderTest().getMetric()); + } + + @Test + public final void testSetResult() { + String result = "get result here"; + getObjectUnderTest().setResult(result); + assertEquals(result, getObjectUnderTest().getResult()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ExecutionUnitTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ExecutionUnitTest.java new file mode 100644 index 000000000..5fb8f84e1 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ExecutionUnitTest.java @@ -0,0 +1,86 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class ExecutionUnitTest extends DBTestSuper { + + @Mock EncapsulationUnit eu; + @Mock NameSpace ns; + @Mock ProjectFile file; + + @Before + public void setUp() throws Exception { + super.setUp(new ExecutionUnit()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testExecutionUnitEncapsulationUnit() { + ExecutionUnit execu = new ExecutionUnit(eu); + assertEquals(eu, execu.getEncapsulationUnit()); + } + + @Test + public final void testSetName() { + String name = "name"; + getObjectUnderTest().setName(name); + assertEquals(name, getObjectUnderTest().getName()); + } + + @Test + public final void testSetNamespace() { + getObjectUnderTest().setNamespace(ns); + assertEquals(ns, getObjectUnderTest().getNamespace()); + } + + @Test + public final void testSetEncapsulationUnit() { + getObjectUnderTest().setEncapsulationUnit(eu); + assertEquals(eu, getObjectUnderTest().getEncapsulationUnit()); + } + + @Test + public final void testSetFile() { + getObjectUnderTest().setFile(file); + assertEquals(file, getObjectUnderTest().getFile()); + } + + @Test + public final void testSetChanged() { + getObjectUnderTest().setChanged(true); + assertTrue(getObjectUnderTest().isChanged()); + } + + @Test + public final void testSetMeasurements() { + Set measurements = new HashSet(); + getObjectUnderTest().setMeasurements(measurements); + assertEquals(measurements, getObjectUnderTest().getMeasurements()); + } + + @Test + public final void testGetFullyQualifiedName() { + getObjectUnderTest().setEncapsulationUnit(eu); + assertEquals(getObjectUnderTest().toString(), getObjectUnderTest().getFullyQualifiedName()); + } + + @Test + public final void testToString() { + getObjectUnderTest().setEncapsulationUnit(eu); + assertEquals("eu::null", getObjectUnderTest().toString()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/MailMessageMeasurementTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/MailMessageMeasurementTest.java new file mode 100644 index 000000000..2b185f261 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/MailMessageMeasurementTest.java @@ -0,0 +1,53 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class MailMessageMeasurementTest extends + DBTestSuper { + + @Mock Metric m; + @Mock MailMessage mail; + + @Before + public void setUp() throws Exception { + super.setUp(new MailMessageMeasurement()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testMailMessageMeasurementMetricMailMessageString() { + String value = "value"; + MailMessageMeasurement mmm = new MailMessageMeasurement(m, mail, value); + assertEquals(mail, mmm.getMail()); + assertEquals(m, mmm.getMetric()); + assertEquals(value, mmm.getResult()); + } + + @Test + public final void testSetMail() { + getObjectUnderTest().setMail(mail); + assertEquals(mail, getObjectUnderTest().getMail()); + } + + @Test + public final void testSetMetric() { + getObjectUnderTest().setMetric(m); + assertEquals(m, getObjectUnderTest().getMetric()); + } + + @Test + public final void testSetResult() { + String value = "value"; + getObjectUnderTest().setResult(value); + assertEquals(value, getObjectUnderTest().getResult()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/MailMessageTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/MailMessageTest.java new file mode 100644 index 000000000..af1ea685d --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/MailMessageTest.java @@ -0,0 +1,170 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class MailMessageTest extends DBTestSuperObjectProp { + + @Mock MailingListThread thread; + @Mock Developer dev; + @Mock MailingList ml; + + @Before + public void setUp() throws Exception { + super.setUp(new MailMessage()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testSetThread() { + getObjectUnderTest().setThread(thread); + assertEquals(thread, getObjectUnderTest().getThread()); + } + + @Test + public final void testSetFileName() { + String fileName = "/path/to/file"; + getObjectUnderTest().setFileName(fileName); + assertEquals(fileName, getObjectUnderTest().getFileName()); + } + + @Test + public final void testSetDepth() { + int depth = 1238901; + getObjectUnderTest().setDepth(depth); + assertEquals(depth, getObjectUnderTest().getDepth()); + } + + @Test + public final void testSetSender() { + getObjectUnderTest().setSender(dev); + assertEquals(dev, getObjectUnderTest().getSender()); + } + + @Test + public final void testSetList() { + getObjectUnderTest().setList(ml); + assertEquals(ml, getObjectUnderTest().getList()); + } + + @Test + public final void testSetMessageId() { + String value = "thisIsNotAMsgId"; + getObjectUnderTest().setMessageId(value); + assertEquals(value, getObjectUnderTest().getMessageId()); + } + + @Test + public final void testSetSendDate() { + Date dt = new Date(); + getObjectUnderTest().setSendDate(dt); + assertEquals(dt, getObjectUnderTest().getSendDate()); + } + + @Test + public final void testSetSubject() { + String value = "myValueHere"; + getObjectUnderTest().setSubject(value); + assertEquals(value, getObjectUnderTest().getSubject()); + } + + @Test + public final void testSetFilename() { + String fileName = "/path/to/file"; + getObjectUnderTest().setFilename(fileName); + assertEquals(fileName, getObjectUnderTest().getFilename()); + } + + @Test + public final void testSetMeasurements() { + Set measurements = new HashSet(); + getObjectUnderTest().setMeasurements(measurements); + assertEquals(measurements, getObjectUnderTest().getMeasurements()); + } + + @Test + public final void testSetParent() { + getObjectUnderTest().setParent(getObjectUnderTest()); + assertEquals(getObjectUnderTest(), getObjectUnderTest().getParent()); + } + + @Test + public final void testGetMessageById() { + super.testGetObjectProp_Null_1(); + assertNull(MailMessage.getMessageById("")); + } + + @Test + public final void testGetMessageById_2() { + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(null); + assertNull(MailMessage.getMessageById("")); + } + + @Test + public final void testGetMessageById_3() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), MailMessage.getMessageById("")); + } + + @Test + public final void testGetMessageByFilename() { + super.testGetObjectProp_Null_1(); + assertNull(MailMessage.getMessageByFileName("")); + } + + @Test + public final void testGetMessageByFilename_2() { + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(null); + assertNull(MailMessage.getMessageByFileName("")); + } + + @Test + public final void testGetMessageByFilename_3() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), MailMessage.getMessageByFileName("")); + } + + @Test + public final void testGetLatestMailMessage() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertNull(MailMessage.getLatestMailMessage(null)); + } + + @Test + public final void testGetLatestMailMessage_2() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(getObjectUnderTest(), MailMessage.getLatestMailMessage(null)); + } + + @Test + public final void testToString() { + Date date = new Date(); + String subject = "This is a test string"; + getObjectUnderTest().setSendDate(date); + getObjectUnderTest().setSender(dev); + getObjectUnderTest().setSubject(subject); + String res = getObjectUnderTest().toString(); + assertTrue(res.contains(date.toString())); + assertTrue(res.contains(dev.toString())); + assertTrue(res.contains(subject)); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/MailingListTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/MailingListTest.java new file mode 100644 index 000000000..3ac61f36b --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/MailingListTest.java @@ -0,0 +1,124 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class MailingListTest extends DBTestSuperDoHQL3 { + + @Mock StoredProject p; + @Mock MailMessage mm; + @Mock MailingListThread mlt; + + @Before + public void setUp() throws Exception { + super.setUp(new MailingList()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testSetListId() { + String listId = "hallo"; + getObjectUnderTest().setListId(listId); + assertEquals(listId, getObjectUnderTest().getListId()); + } + + @Test + public final void testSetStoredProject() { + getObjectUnderTest().setStoredProject(p); + assertEquals(p, getObjectUnderTest().getStoredProject()); + } + + @Test + public final void testSetMessages() { + Set messages = new HashSet(); + getObjectUnderTest().setMessages(messages); + assertEquals(messages, getObjectUnderTest().getMessages()); + } + + @Test + public final void testSetThreads() { + Set threads = new HashSet(); + getObjectUnderTest().setThreads(threads); + assertEquals(threads, getObjectUnderTest().getThreads()); + } + + @Test + public final void testGetMessagesNewerThan() { + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(null); + int size = getObjectUnderTest().getMessagesNewerThan(new Date()).size(); + assertEquals(size, 0); + } + + @Test + public final void testGetMessagesNewerThan_2() { + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(new ArrayList()); + int size = getObjectUnderTest().getMessagesNewerThan(new Date()).size(); + assertEquals(size, 0); + } + + @Test + public final void testGetMessagesNewerThan_3() { + List list = new ArrayList(); + list.add(mm); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + List gottenList = getObjectUnderTest().getMessagesNewerThan(new Date()); + int size = gottenList.size(); + assertEquals(size, 1); + assertEquals(list, gottenList); + } + + @Test + public final void testGetLatestEmail() { + List list = new ArrayList(); + list.add(mm); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(mm, getObjectUnderTest().getLatestEmail()); + } + + @Test + public final void testGetLatestEmail_2() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertNull(getObjectUnderTest().getLatestEmail()); + } + + @Test + public final void testGetLatestThread() { + List list = new ArrayList(); + list.add(mlt); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(mlt, getObjectUnderTest().getLatestThread()); + } + + @Test + public final void testGetLatestThread_2() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertNull(getObjectUnderTest().getLatestThread()); + } + + @Test + public final void testToString() { + String id = "id of the list"; + getObjectUnderTest().setListId(id); + getObjectUnderTest().setStoredProject(p); + assertTrue(getObjectUnderTest().toString().contains(id)); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/MailingListThreadMeasurementTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/MailingListThreadMeasurementTest.java new file mode 100644 index 000000000..ad21bc5f6 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/MailingListThreadMeasurementTest.java @@ -0,0 +1,71 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class MailingListThreadMeasurementTest extends + DBTestSuperDoHQL2 { + + @Mock Metric m; + @Mock MailingListThread mt; + String value = "value here"; + + @Before + public void setUp() throws Exception { + super.setUp(new MailingListThreadMeasurement()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testMailingListThreadMeasurementMetricMailingListThreadString() { + MailingListThreadMeasurement mltm = new MailingListThreadMeasurement(m, mt, value); + assertEquals(m, mltm.getMetric()); + assertEquals(mt, mltm.getThread()); + assertEquals(value, mltm.getResult()); + } + + @Test + public final void testSetThread() { + getObjectUnderTest().setThread(mt); + assertEquals(mt, getObjectUnderTest().getThread()); + } + + @Test + public final void testSetMetric() { + getObjectUnderTest().setMetric(m); + assertEquals(m, getObjectUnderTest().getMetric()); + } + + @Test + public final void testSetResult() { + getObjectUnderTest().setResult(value); + assertEquals(value, getObjectUnderTest().getResult()); + } + + + @Test + public void testGetBugsForStatusStatus() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, MailingListThreadMeasurement.getAllMeasurementsForThread(mt).size()); + } + + @Test + public void testGetBugsForStatusStatus_2() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(getObjectUnderTest(), MailingListThreadMeasurement.getAllMeasurementsForThread(mt).get(0)); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/MailingListThreadTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/MailingListThreadTest.java new file mode 100644 index 000000000..fb9a2a2e0 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/MailingListThreadTest.java @@ -0,0 +1,157 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class MailingListThreadTest extends DBTestSuper { + + @Mock + MailingList l; + @Mock + MailMessage mm; + + @Before + public void setUp() throws Exception { + super.setUp(new MailingListThread()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testSetMessages() { + Set messages = new HashSet(); + getObjectUnderTest().setMessages(messages); + assertEquals(messages, getObjectUnderTest().getMessages()); + } + + @Test + public final void testMailingListThreadMailingListDate() { + Date d = new Date(); + MailingListThread mlt = new MailingListThread(l, d); + assertEquals(l, mlt.getList()); + assertEquals(d, mlt.getLastUpdated()); + } + + @Test + public final void testSetList() { + getObjectUnderTest().setList(l); + assertEquals(l, getObjectUnderTest().getList()); + } + + @Test + public final void testSetIsFlameWar() { + getObjectUnderTest().setIsFlameWar(true); + assertTrue(getObjectUnderTest().getIsFlameWar()); + } + + @Test + public final void testSetFlameWar() { + getObjectUnderTest().setFlameWar(true); + assertTrue(getObjectUnderTest().getIsFlameWar()); + } + + @Test + public final void testSetLastUpdated() { + Date lastUpdated = new Date(); + getObjectUnderTest().setLastUpdated(lastUpdated); + assertEquals(lastUpdated, getObjectUnderTest().getLastUpdated()); + } + + @Test + public final void testGetStartingEmail() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertNull(getObjectUnderTest().getStartingEmail()); + } + + @Test + public final void testGetStartingEmail_2() { + List list = new ArrayList(); + list.add(mm); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(mm, getObjectUnderTest().getStartingEmail()); + } + + @Test + public final void testGetMessagesByArrivalOrder() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, getObjectUnderTest().getMessagesByArrivalOrder().size()); + } + + @Test + public final void testGetMessagesByArrivalOrder_2() { + List list = null; + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, getObjectUnderTest().getMessagesByArrivalOrder().size()); + } + + @Test + public final void testGetMessagesByArrivalOrder_3() { + List list = new ArrayList(); + list.add(mm); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(list, getObjectUnderTest().getMessagesByArrivalOrder()); + } + + @Test + public final void testGetThreadDepth() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(0, getObjectUnderTest().getThreadDepth()); + } + + @Test + public final void testGetThreadDepth_2() { + List list = null; + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(0, getObjectUnderTest().getThreadDepth()); + } + + @Test + public final void testGetThreadDepth_3() { + int res = 192; + List list = new ArrayList(); + list.add(new Integer(res)); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(res, getObjectUnderTest().getThreadDepth()); + } + + @Test + public final void testGetMessagesAtLevel() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, getObjectUnderTest().getMessagesAtLevel(0).size()); + } + + @Test + public final void testGetMessagesAtLevel_2() { + List list = null; + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, getObjectUnderTest().getMessagesAtLevel(0).size()); + } + + @Test + public final void testGetMessagesAtLevel_3() { + List list = new ArrayList(); + list.add(mm); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(list, getObjectUnderTest().getMessagesAtLevel(0)); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/MetricTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/MetricTest.java new file mode 100644 index 000000000..16df55ff9 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/MetricTest.java @@ -0,0 +1,236 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; + +public class MetricTest extends DBTestSuperObjectProp { + + @Mock MetricType mt; + @Mock Plugin pl; + + + @Before + public void setUp() throws Exception { + super.setUp(new Metric()); + } + + @Test + public final void testHashCode() { + assertEquals(new Metric().hashCode(), new Metric().hashCode()); + } + + @Test + public final void testHashCode_2() { + Metric diff = new Metric(); + diff.setId(18023); + assertFalse(new Metric().hashCode() == diff.hashCode()); + } + + @Test + public final void testHashCode_3() { + Metric diff = new Metric(); + diff.setMnemonic("mnemonic"); + assertFalse(new Metric().hashCode() == diff.hashCode()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testSetMetricType() { + getObjectUnderTest().setMetricType(mt); + assertEquals(mt, getObjectUnderTest().getMetricType()); + } + + @Test + public final void testSetDescription() { + String description = "hi there"; + getObjectUnderTest().setDescription(description); + assertEquals(description, getObjectUnderTest().getDescription()); + } + + @Test + public final void testSetPlugin() { + getObjectUnderTest().setPlugin(pl); + assertEquals(pl, getObjectUnderTest().getPlugin()); + } + + @Test + public final void testSetMnemonic() { + String mnemonic = "mnemonic"; + getObjectUnderTest().setMnemonic(mnemonic); + assertEquals(mnemonic, getObjectUnderTest().getMnemonic()); + } + + private void testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type t, boolean result) { + Mockito.doReturn(t).when(mt).getEnumType(); + getObjectUnderTest().setMetricType(mt); + + List list = new ArrayList(); + if (result) { + list.add(new Long(1)); + } + + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(result, getObjectUnderTest().isEvaluated(null)); + } + + @Test + public final void testIsEvaluated() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.BUG, false); + } + + @Test + public final void testIsEvaluated_2() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.DEVELOPER, false); + } + + @Test + public final void testIsEvaluated_3() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.ENCAPSUNIT, true); + } + + @Test + public final void testIsEvaluated_4() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.EXECUNIT, false); + } + + @Test + public final void testIsEvaluated_5() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.MAILING_LIST, false); + } + + @Test + public final void testIsEvaluated_6() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.MAILMESSAGE, false); + } + + @Test + public final void testIsEvaluated_7() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.MAILTHREAD, true); + } + + @Test + public final void testIsEvaluated_8() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.NAMESPACE, false); + } + + @Test + public final void testIsEvaluated_9() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.PROJECT, false); + } + + @Test + public final void testIsEvaluated_10() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.PROJECT_VERSION, false); + } + + @Test + public final void testIsEvaluated_11() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.SOURCE_DIRECTORY, true); + } + + @Test + public final void testIsEvaluated_12() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.SOURCE_FILE, false); + } + + @Test + public final void testIsEvaluated_13() { + this.testIsEvaluatedWithMetricTypeAndBoolean(MetricType.Type.SOURCE_FILE, true); + } + + @Test + public final void testEqualsObject() { + assertEquals(new Metric(), new Metric()); + } + + @Test + public final void testEqualsObject_2() { + assertFalse(new Metric().equals(null)); + } + + @Test + public final void testEqualsObject_3() { + assertFalse(new Metric().equals(new Integer(0))); + } + + @Test + public final void testEqualsObject_4() { + assertEquals(new Metric(), getObjectUnderTest()); + } + + @Test + public final void testEqualsObject_5() { + getObjectUnderTest().setMnemonic("mnemonic"); + assertFalse(getObjectUnderTest().equals(new Metric())); + } + + @Test + public final void testEqualsObject_6() { + getObjectUnderTest().setId(123); + assertFalse(getObjectUnderTest().equals(new Metric())); + } + + @Test + public final void testToString() { + Long id = 123L; + String mnemonic = "mnemonic"; + getObjectUnderTest().setId(id); + getObjectUnderTest().setMnemonic(mnemonic); + assertTrue(getObjectUnderTest().toString().contains(mnemonic)); + assertTrue(getObjectUnderTest().toString().contains(Long.toString(id))); + } + + @Test + public final void testGetMetricByMnemonic() { + super.testGetObjectProp_Null_1(); + assertNull(Metric.getMetricByMnemonic("")); + } + + @Test + public final void testGetMetricByMnemonic_2() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), Metric.getMetricByMnemonic("")); + } + + @Test + public final void testGetAllMetrics() { + List list = new ArrayList(); + super.setUpMockedDBService(); + Mockito.doReturn(list).when(super.dbService).doHQL(Matchers.anyString()); + assertEquals(list, Metric.getAllMetrics()); + } + + @Test + public final void testGetAllMetricsByType() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, Metric.getMetricsByType(mt).size()); + } + + @Test + public final void testGetAllMetricsByType_2() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(getObjectUnderTest(), Metric.getMetricsByType(mt).get(0)); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/MetricTypeTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/MetricTypeTest.java new file mode 100644 index 000000000..5ad64bfad --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/MetricTypeTest.java @@ -0,0 +1,223 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Before; +import org.junit.Test; + +public class MetricTypeTest extends DBTestSuperObjectProp { + + MetricType.Type type; + + @Before + public void setUp() throws Exception { + super.setUp(new MetricType()); + type = MetricType.Type.BUG; + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testMetricTypeType() { + MetricType mt = new MetricType(type); + assertEquals(type, mt.getEnumType()); + assertEquals(type.toString(), mt.getType()); + } + + @Test + public final void testSetEnumType() { + getObjectUnderTest().setEnumType(type); + assertEquals(type, getObjectUnderTest().getEnumType()); + assertEquals(type.toString(), getObjectUnderTest().getType()); + } + + @Test + public final void testSetType() { + getObjectUnderTest().setType(type.toString()); + assertEquals(type.toString(), getObjectUnderTest().getType()); + assertEquals(type, getObjectUnderTest().getEnumType()); + } + + @Test + public final void testGetMetricType() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), MetricType.getMetricType(type)); + } + + @Test + public final void testGetMetricType_2() { + super.testGetObjectProp_Null_1(); + assertNull(MetricType.getMetricType(type)); + } + + @Test + public final void testFromActivators() { + assertNull(MetricType.fromActivator(MetricType.class)); + } + + @Test + public final void testFromActivator_2() { + assertEquals(MetricType.Type.BUG, MetricType.fromActivator(Bug.class)); + } + + @Test + public final void testFromActivator_3() { + assertEquals(MetricType.Type.DEVELOPER, + MetricType.fromActivator(Developer.class)); + } + + @Test + public final void testFromActivator_4() { + assertEquals(MetricType.Type.ENCAPSUNIT, + MetricType.fromActivator(EncapsulationUnit.class)); + } + + @Test + public final void testFromActivator_5() { + assertEquals(MetricType.Type.EXECUNIT, + MetricType.fromActivator(ExecutionUnit.class)); + } + + @Test + public final void testFromActivator_6() { + assertEquals(MetricType.Type.MAILING_LIST, + MetricType.fromActivator(MailingList.class)); + } + + @Test + public final void testFromActivator_7() { + assertEquals(MetricType.Type.MAILMESSAGE, + MetricType.fromActivator(MailMessage.class)); + } + + @Test + public final void testFromActivator_8() { + assertEquals(MetricType.Type.MAILTHREAD, + MetricType.fromActivator(MailingListThread.class)); + } + + @Test + public final void testFromActivator_9() { + assertEquals(MetricType.Type.NAMESPACE, + MetricType.fromActivator(NameSpace.class)); + } + + @Test + public final void testFromActivator_10() { + assertEquals(MetricType.Type.PROJECT, + MetricType.fromActivator(StoredProject.class)); + } + + @Test + public final void testFromActivator_11() { + assertEquals(MetricType.Type.PROJECT_VERSION, + MetricType.fromActivator(ProjectVersion.class)); + } + + @Test + public final void testFromActivator_12() { + assertEquals(MetricType.Type.SOURCE_DIRECTORY, + MetricType.fromActivator(ProjectDirectory.class)); + } + + @Test + public final void testFromActivator_13() { + assertEquals(MetricType.Type.SOURCE_FILE, + MetricType.fromActivator(ProjectFile.class)); + } + + @Test(expected = NullPointerException.class) + public final void testToActivator() { + getObjectUnderTest().setType("invalidType"); + } + + @Test + public final void testToActivator_2() { + MetricType.Type t = MetricType.Type.BUG; + getObjectUnderTest().setEnumType(t); + assertEquals(Bug.class, getObjectUnderTest().toActivator()); + } + + @Test + public final void testToActivator_3() { + MetricType.Type t = MetricType.Type.SOURCE_FILE; + getObjectUnderTest().setEnumType(t); + assertEquals(ProjectFile.class, getObjectUnderTest().toActivator()); + } + + @Test + public final void testToActivator_4() { + MetricType.Type t = MetricType.Type.DEVELOPER; + getObjectUnderTest().setEnumType(t); + assertEquals(Developer.class, getObjectUnderTest().toActivator()); + } + + @Test + public final void testToActivator_5() { + MetricType.Type t = MetricType.Type.ENCAPSUNIT; + getObjectUnderTest().setEnumType(t); + assertEquals(EncapsulationUnit.class, getObjectUnderTest() + .toActivator()); + } + + @Test + public final void testToActivator_6() { + MetricType.Type t = MetricType.Type.EXECUNIT; + getObjectUnderTest().setEnumType(t); + assertEquals(ExecutionUnit.class, getObjectUnderTest().toActivator()); + } + + @Test + public final void testToActivator_7() { + MetricType.Type t = MetricType.Type.MAILING_LIST; + getObjectUnderTest().setEnumType(t); + assertEquals(MailingList.class, getObjectUnderTest().toActivator()); + } + + @Test + public final void testToActivator_8() { + MetricType.Type t = MetricType.Type.MAILMESSAGE; + getObjectUnderTest().setEnumType(t); + assertEquals(MailMessage.class, getObjectUnderTest().toActivator()); + } + + @Test + public final void testToActivator_9() { + MetricType.Type t = MetricType.Type.MAILTHREAD; + getObjectUnderTest().setEnumType(t); + assertEquals(MailingListThread.class, getObjectUnderTest() + .toActivator()); + } + + @Test + public final void testToActivator_10() { + MetricType.Type t = MetricType.Type.NAMESPACE; + getObjectUnderTest().setEnumType(t); + assertEquals(NameSpace.class, getObjectUnderTest().toActivator()); + } + + @Test + public final void testToActivator_11() { + MetricType.Type t = MetricType.Type.PROJECT; + getObjectUnderTest().setEnumType(t); + assertEquals(StoredProject.class, getObjectUnderTest().toActivator()); + } + + @Test + public final void testToActivator_12() { + MetricType.Type t = MetricType.Type.PROJECT_VERSION; + getObjectUnderTest().setEnumType(t); + assertEquals(ProjectVersion.class, getObjectUnderTest().toActivator()); + } + + @Test + public final void testToActivator_13() { + MetricType.Type t = MetricType.Type.SOURCE_DIRECTORY; + getObjectUnderTest().setEnumType(t); + assertEquals(ProjectDirectory.class, getObjectUnderTest().toActivator()); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/NameSpaceMeasurementTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/NameSpaceMeasurementTest.java new file mode 100644 index 000000000..460572060 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/NameSpaceMeasurementTest.java @@ -0,0 +1,61 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class NameSpaceMeasurementTest extends DBTestSuper { + + @Mock Metric m; + @Mock NameSpace ns; + + @Before + public void setUp() throws Exception { + super.setUp(new NameSpaceMeasurement()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testSetResult() { + String result = "this is a result"; + getObjectUnderTest().setResult(result); + assertEquals(result, getObjectUnderTest().getResult()); + } + + @Test + public final void testSetMetric() { + getObjectUnderTest().setMetric(m); + assertEquals(m, getObjectUnderTest().getMetric()); + } + + @Test + public final void testSetNamespace() { + getObjectUnderTest().setNamespace(ns); + assertEquals(ns, getObjectUnderTest().getNamespace()); + } + + @Test + public final void testGetAllMeasurementsByNameSpace() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, NameSpaceMeasurement.getMeasurementsByNameSpace(ns).size()); + } + + @Test + public final void testGetAllMetricsByType_2() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(getObjectUnderTest(), NameSpaceMeasurement.getMeasurementsByNameSpace(ns).get(0)); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/NameSpaceTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/NameSpaceTest.java new file mode 100644 index 000000000..6df2899c5 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/NameSpaceTest.java @@ -0,0 +1,91 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class NameSpaceTest extends DBTestSuperDoHQL2 { + + @Mock private ProjectVersion pv; + private Language lang; + + @Before + public void setUp() throws Exception { + super.setUp(new NameSpace()); + lang = Language.PYTHON; + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testSetName() { + String name = "this is a name"; + getObjectUnderTest().setName(name); + assertEquals(name, getObjectUnderTest().getName()); + } + + @Test + public final void testSetChangeVersion() { + getObjectUnderTest().setChangeVersion(pv); + assertEquals(pv, getObjectUnderTest().getChangeVersion()); + } + + @Test + public final void testSetEncapsulationUnits() { + Set encapsulationUnits = new HashSet(); + getObjectUnderTest().setEncapsulationUnits(encapsulationUnits); + assertEquals(encapsulationUnits, getObjectUnderTest().getEncapsulationUnits()); + } + + @Test + public final void testSetEncapsulationUnits_2() { + Set encapsulationUnits = null; + getObjectUnderTest().setEncapsulationUnits(encapsulationUnits); + assertNotNull(getObjectUnderTest().getEncapsulationUnits()); + } + + @Test + public final void testSetExecutionUnits() { + Set executionUnits = new HashSet(); + getObjectUnderTest().setExecutionUnits(executionUnits); + assertEquals(executionUnits, getObjectUnderTest().getExecutionUnits()); + } + + @Test + public final void testSetExecutionUnits_2() { + Set executionUnits = null; + getObjectUnderTest().setExecutionUnits(executionUnits); + assertNotNull(getObjectUnderTest().getExecutionUnits()); + } + + @Test + public final void testSetLang() { + getObjectUnderTest().setLang(lang); + assertEquals(lang, getObjectUnderTest().getLang()); + } + + @Test + public final void testFindByVersionName() { + super.testGetStaticDoHQL2_ShouldBeNull(); + assertNull(NameSpace.findByVersionName(pv, "")); + } + + @Test + public final void testFindByVersionName_2() { + super.testGetStaticDoHQL2_ShouldBeObject(); + assertEquals(getObjectUnderTest(), NameSpace.findByVersionName(pv, "")); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/OhlohDeveloperTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/OhlohDeveloperTest.java new file mode 100644 index 000000000..1202a4e47 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/OhlohDeveloperTest.java @@ -0,0 +1,94 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.Date; + +import org.junit.Before; +import org.junit.Test; + +public class OhlohDeveloperTest extends DBTestSuperObjectProp { + + final private String uname = "uname"; + final private String hash = "hash"; + final private String id = "id"; + + + @Before + public void setUp() throws Exception { + super.setUp(new OhlohDeveloper()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testOhlohDeveloperStringStringString() { + OhlohDeveloper od = new OhlohDeveloper(uname, hash, id); + assertEquals(uname, od.getUname()); + assertEquals(hash, od.getEmailHash()); + assertEquals(id, od.getOhlohId()); + assertNotNull(od.getTimestamp()); + } + + @Test + public final void testSetTimestamp() { + Date dt = new Date(); + getObjectUnderTest().setTimestamp(dt); + assertEquals(dt, getObjectUnderTest().getTimestamp()); + } + + @Test + public final void testSetUname() { + getObjectUnderTest().setUname(uname); + assertEquals(uname, getObjectUnderTest().getUname()); + } + + @Test + public final void testSetEmailHash() { + getObjectUnderTest().setEmailHash(hash); + assertEquals(hash, getObjectUnderTest().getEmailHash()); + } + + @Test + public final void testSetOhlohId() { + getObjectUnderTest().setOhlohId(id); + assertEquals(id, getObjectUnderTest().getOhlohId()); + } + + @Test + public final void testGetByOhlohId() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), OhlohDeveloper.getByOhlohId(id)); + } + + @Test + public final void testGetByOhlohId_2() { + super.testGetObjectProp_Null_1(); + assertNull(OhlohDeveloper.getByOhlohId(id)); + } + + @Test + public final void testGetByEmailHash() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), OhlohDeveloper.getByEmailHash(hash)); + } + + @Test + public final void testGetByEmailHash_2() { + super.testGetObjectProp_Null_1(); + assertNull(OhlohDeveloper.getByEmailHash(hash)); + } + + @Test + public final void testGetByUserName() { + super.testGetObjectProp_Equals_1(); + assertEquals(1, OhlohDeveloper.getByUserName(uname).size()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/PluginConfigurationTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/PluginConfigurationTest.java new file mode 100644 index 000000000..3778b5a1f --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/PluginConfigurationTest.java @@ -0,0 +1,109 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; + +public class PluginConfigurationTest extends DBTestSuperObjectProp { + + @Mock Plugin p; + + @Before + public void setUp() throws Exception { + super.setUp(new PluginConfiguration()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testSetValue() { + String value = "value"; + getObjectUnderTest().setValue(value); + assertEquals(value, getObjectUnderTest().getValue()); + } + + @Test + public final void testSetType() { + String type = "type"; + getObjectUnderTest().setType(type); + assertEquals(type, getObjectUnderTest().getType()); + } + + @Test + public final void testSetPlugin() { + getObjectUnderTest().setPlugin(p); + assertEquals(p, getObjectUnderTest().getPlugin()); + } + + @Test + public final void testSetName() { + String name = "name"; + getObjectUnderTest().setName(name); + assertEquals(name, getObjectUnderTest().getName()); + } + + @Test + public final void testSetMsg() { + String msg = "msg"; + getObjectUnderTest().setMsg(msg); + assertEquals(msg, getObjectUnderTest().getMsg()); + } + + @Test + public final void testGetConfigurationEntry() { + super.testGetObjectProp_Null_1(); + assertNull(PluginConfiguration.getConfigurationEntry(p, new HashMap())); + } + + @Test + public final void testGetConfigurationEntry_2() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), PluginConfiguration.getConfigurationEntry(p, new HashMap())); + } + + @Test + public final void testUpdConfigurationEntry() { + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(null); + super.testGetObjectProp_Null_1(); + assertFalse(PluginConfiguration.updConfigurationEntry(p, new HashMap())); + } + + @Test + public final void testUpdConfigurationEntry_2() { + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(null); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + Mockito.doReturn(list).doReturn(new ArrayList()) + .when(dbService) + .findObjectsByProperties((Class) Matchers.any(), + Matchers.anyMap()); + assertFalse(PluginConfiguration.updConfigurationEntry(p, new HashMap())); + } + + @Test + public final void testUpdConfigurationEntry_3() { + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(null); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + Mockito.doReturn(list).doReturn(list) + .when(dbService) + .findObjectsByProperties((Class) Matchers.any(), + Matchers.anyMap()); + assertTrue(PluginConfiguration.updConfigurationEntry(p, new HashMap())); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/PluginTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/PluginTest.java new file mode 100644 index 000000000..45188104c --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/PluginTest.java @@ -0,0 +1,100 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; + +public class PluginTest extends DBTestSuperObjectProp { + + @Before + public void setUp() throws Exception { + super.setUp(new Plugin()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testSetName() { + String name = "name"; + getObjectUnderTest().setName(name); + assertEquals(name, getObjectUnderTest().getName()); + } + + @Test + public final void testSetInstalldate() { + Date installdate = new Date(); + getObjectUnderTest().setInstalldate(installdate); + assertEquals(installdate, getObjectUnderTest().getInstalldate()); + } + + @Test + public final void testSetVersion() { + String version = "version"; + getObjectUnderTest().setVersion(version); + assertEquals(version, getObjectUnderTest().getVersion()); + } + + @Test + public final void testSetDescription() { + String description = "description"; + getObjectUnderTest().setDescription(description); + assertEquals(description, getObjectUnderTest().getDescription()); + } + + @Test + public final void testSetActive() { + getObjectUnderTest().setActive(true); + assertTrue(getObjectUnderTest().isActive()); + } + + @Test + public final void testSetHashcode() { + String hashcode = "hashcode'"; + getObjectUnderTest().setHashcode(hashcode); + assertEquals(hashcode, getObjectUnderTest().getHashcode()); + } + + @Test + public final void testSetConfigurations() { + Set configurations = new HashSet(); + getObjectUnderTest().setConfigurations(configurations); + assertEquals(configurations, getObjectUnderTest().getConfigurations()); + } + + @Test + public final void testSetSupportedMetrics() { + Set supportedMetrics = new HashSet(); + getObjectUnderTest().setSupportedMetrics(supportedMetrics); + assertEquals(supportedMetrics, getObjectUnderTest().getSupportedMetrics()); + } + + @Test + public final void testGetPluginByName() { + super.testGetObjectProp_Null_1(); + assertEquals(0, Plugin.getPluginByName("").size()); + } + + @Test + public final void testGetPluginByHashcode() { + super.testGetObjectProp_Equals_1(); + assertEquals(getObjectUnderTest(), Plugin.getPluginByHashcode("hashcode")); + } + + @Test + public final void testGetPluginByHashcode_2() { + super.testGetObjectProp_Null_1(); + assertNull(Plugin.getPluginByHashcode("hashcode")); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectDirectoryTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectDirectoryTest.java new file mode 100644 index 000000000..d1fb324ea --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectDirectoryTest.java @@ -0,0 +1,20 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +public class ProjectDirectoryTest extends DBTestSuper { + + @Before + public void setUp() throws Exception { + super.setUp(new ProjectDirectory()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectFileMeasurementTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectFileMeasurementTest.java new file mode 100644 index 000000000..e3bd75994 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectFileMeasurementTest.java @@ -0,0 +1,54 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class ProjectFileMeasurementTest extends + DBTestSuper { + + @Mock Metric m; + @Mock ProjectFile f; + + String value = "hoi"; + + @Before + public void setUp() throws Exception { + super.setUp(new ProjectFileMeasurement()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testProjectFileMeasurementMetricProjectFileString() { + ProjectFileMeasurement pfm = new ProjectFileMeasurement(m, f, value); + assertEquals(m, pfm.getMetric()); + assertEquals(f, pfm.getProjectFile()); + assertEquals(value, pfm.getResult()); + } + + @Test + public final void testSetProjectFile() { + getObjectUnderTest().setProjectFile(f); + assertEquals(f, getObjectUnderTest().getProjectFile()); + } + + @Test + public final void testSetMetric() { + getObjectUnderTest().setMetric(m); + assertEquals(m, getObjectUnderTest().getMetric()); + } + + @Test + public final void testSetResult() { + getObjectUnderTest().setResult(value); + assertEquals(value, getObjectUnderTest().getResult()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectFileStateTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectFileStateTest.java new file mode 100644 index 000000000..bc2241824 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectFileStateTest.java @@ -0,0 +1,143 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mockito; + +import eu.sqooss.service.tds.PathChangeType; + +public class ProjectFileStateTest extends DBTestSuper { + + @Before + public void setUp() throws Exception { + super.setUp(new ProjectFileState()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testToString() { + assertNull(getObjectUnderTest().toString()); + } + + @Test + public final void testToString_2() { + getObjectUnderTest().setStatus(ProjectFileState.STATE_ADDED); + setUpFromStatus(getObjectUnderTest()); + assertEquals("ADDED", ProjectFileState.added().toString()); + } + + @Test + public final void testToString_3() { + getObjectUnderTest().setStatus(ProjectFileState.STATE_MODIFIED); + setUpFromStatus(getObjectUnderTest()); + assertEquals("MODIFIED", ProjectFileState.modified().toString()); + } + + @Test + public final void testToString_4() { + getObjectUnderTest().setStatus(ProjectFileState.STATE_DELETED); + setUpFromStatus(getObjectUnderTest()); + assertEquals("DELETED", ProjectFileState.deleted().toString()); + } + + @Test + public final void testToString_5() { + getObjectUnderTest().setStatus(ProjectFileState.STATE_REPLACED); + setUpFromStatus(getObjectUnderTest()); + assertEquals("REPLACED", ProjectFileState.replaced().toString()); + } + + @Test + public final void testFromStatus() { + super.setUpMockedDBService(); + assertNull(ProjectFileState.fromStatus(0)); + } + + @Test + public final void testFromStatus_2() { + setUpFromStatus(getObjectUnderTest()); + assertEquals(getObjectUnderTest(), ProjectFileState.fromStatus(0)); + } + + @Test + public final void testFromStatus_3() { + super.setUpMockedDBService(); + Mockito.doReturn(true).when(super.dbService).isDBSessionActive(); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + Mockito.doReturn(new ArrayList()) + .doReturn(list) + .when(dbService) + .findObjectsByProperties((Class) Matchers.any(), + Matchers.anyMap()); + assertEquals(getObjectUnderTest(), ProjectFileState.fromStatus(0)); + } + + private void setUpFromStatus(ProjectFileState object) { + super.setUpMockedDBService(); + Mockito.doReturn(true).when(super.dbService).isDBSessionActive(); + List list = new ArrayList(); + list.add(object); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + } + + @Test + public final void testFromPathChangeType() { + assertNull(ProjectFileState.fromPathChangeType(PathChangeType.UNKNOWN)); + } + + @Test + public final void testFromPathChangeType_2() { + getObjectUnderTest().setStatus(ProjectFileState.STATE_MODIFIED); + setUpFromStatus(getObjectUnderTest()); + assertEquals(ProjectFileState.modified(), + ProjectFileState.fromPathChangeType(PathChangeType.MODIFIED)); + } + + @Test + public final void testFromPathChangeType_3() { + getObjectUnderTest().setStatus(ProjectFileState.STATE_DELETED); + setUpFromStatus(getObjectUnderTest()); + assertEquals(ProjectFileState.deleted(), + ProjectFileState.fromPathChangeType(PathChangeType.DELETED)); + } + + @Test + public final void testFromPathChangeType_4() { + getObjectUnderTest().setStatus(ProjectFileState.STATE_ADDED); + setUpFromStatus(getObjectUnderTest()); + assertEquals(ProjectFileState.added(), + ProjectFileState.fromPathChangeType(PathChangeType.ADDED)); + } + + @Test + public final void testFromPathChangeType_5() { + getObjectUnderTest().setStatus(ProjectFileState.STATE_REPLACED); + setUpFromStatus(getObjectUnderTest()); + assertEquals(ProjectFileState.replaced(), + ProjectFileState.fromPathChangeType(PathChangeType.REPLACED)); + } + + + @Test + public final void testSetStatus() { + getObjectUnderTest().setStatus(12); + assertEquals(12, getObjectUnderTest().getStatus()); + } + + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectFileTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectFileTest.java new file mode 100644 index 000000000..6b80b4621 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectFileTest.java @@ -0,0 +1,490 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; + +import eu.sqooss.service.logging.Logger; + +public class ProjectFileTest extends DBTestSuperDoHQL2 { + + @Mock ProjectFileState state; + @Mock Directory dir; + @Mock ProjectVersion pv; + @Mock StoredProject sp; + + String name = "name"; + + @Before + public void setUp() throws Exception { + super.setUp(new ProjectFile()); + } + + @Test + public final void testHashCode() { + ProjectFile a = new ProjectFile(); + a.setName(name); + getObjectUnderTest().setName(name); + assertEquals(a.hashCode(), getObjectUnderTest().hashCode()); + } + + @Test + public final void testHashCode_2() { + getObjectUnderTest().setName(name); + assertEquals(getObjectUnderTest().hashCode(), getObjectUnderTest().hashCode()); + } + + @Test + public final void testHashCode_3() { + ProjectFile a = new ProjectFile(); + a.setName(name); + getObjectUnderTest().setState(state); + getObjectUnderTest().setName(name); + assertFalse(a.hashCode() == getObjectUnderTest().hashCode()); + } + + @Test + public final void testHashCode_4() { + ProjectFile a = new ProjectFile(); + a.setName(name); + getObjectUnderTest().setDir(dir); + getObjectUnderTest().setName(name); + assertFalse(a.hashCode() == getObjectUnderTest().hashCode()); + } + + @Test + public final void testHashCode_5() { + ProjectFile a = new ProjectFile(); + a.setName(name); + getObjectUnderTest().setProjectVersion(pv); + getObjectUnderTest().setName(name); + assertFalse(a.hashCode() == getObjectUnderTest().hashCode()); + } + + @Test + public final void testSetId() { + super.testSetId(); + } + + @Test + public final void testProjectFileProjectVersion() { + ProjectFile pf = new ProjectFile(pv); + assertEquals(pv, pf.getProjectVersion()); + } + + @Test + public final void testProjectFileProjectFileProjectVersion() { + Mockito.doReturn(sp).when(pv).getProject(); + getObjectUnderTest().setProjectVersion(pv); + getObjectUnderTest().setName("name"); + getObjectUnderTest().setIsDirectory(false); + getObjectUnderTest().setDir(dir); + getObjectUnderTest().setState(state); + ProjectFile pf = new ProjectFile(getObjectUnderTest(), pv); + assertFalse(pf.equals(getObjectUnderTest())); + assertEquals(pf.getIsDirectory(), getObjectUnderTest().getIsDirectory()); + assertEquals(pf.getName(), getObjectUnderTest().getName()); + assertEquals(pf.getDir(), getObjectUnderTest().getDir()); + } + + @Test + public final void testProjectFileProjectFileProjectVersion_2() { + Mockito.doReturn(sp).when(pv).getProject(); + Mockito.doReturn(1L).when(sp).getId(); + + StoredProject sp2 = Mockito.mock(StoredProject.class); + ProjectVersion pv2 = Mockito.mock(ProjectVersion.class); + Mockito.doReturn(sp2).when(pv2).getProject(); + Mockito.doReturn(2L).when(sp2).getId(); + + getObjectUnderTest().setProjectVersion(pv); + boolean caught = false; + try { + new ProjectFile(getObjectUnderTest(), pv2); + } catch(IllegalArgumentException e) { + caught = true; + } + assertTrue(caught); + } + + @Test + public final void testSetName() { + getObjectUnderTest().setName(name); + assertEquals(name, getObjectUnderTest().getName()); + } + + @Test + public final void testSetProjectVersion() { + getObjectUnderTest().setProjectVersion(pv); + assertEquals(pv, getObjectUnderTest().getProjectVersion()); + } + + @Test + public final void testSetState() { + getObjectUnderTest().setState(state); + assertEquals(state, getObjectUnderTest().getState()); + } + + @Test + public final void testSetModule() { + getObjectUnderTest().setModule(true); + assertTrue(getObjectUnderTest().isModule()); + } + + @Test + public final void testSetIsDirectory() { + getObjectUnderTest().setIsDirectory(true); + assertTrue(getObjectUnderTest().getIsDirectory()); + } + + @Test + public final void testSetDirectory() { + getObjectUnderTest().setDirectory(true); + assertTrue(getObjectUnderTest().getIsDirectory()); + } + + + @Test + public final void testIsDeleted() { + Mockito.doReturn(ProjectFileState.STATE_DELETED).when(state).getStatus(); + getObjectUnderTest().setState(state); + assertTrue(getObjectUnderTest().isDeleted()); + assertFalse(getObjectUnderTest().isAdded()); + } + + @Test + public final void testIsAdded() { + Mockito.doReturn(ProjectFileState.STATE_ADDED).when(state).getStatus(); + getObjectUnderTest().setState(state); + assertTrue(getObjectUnderTest().isAdded()); + assertFalse(getObjectUnderTest().isModified()); + } + + + @Test + public final void testIsModified() { + Mockito.doReturn(ProjectFileState.STATE_MODIFIED).when(state).getStatus(); + getObjectUnderTest().setState(state); + assertTrue(getObjectUnderTest().isModified()); + assertFalse(getObjectUnderTest().isReplaced()); + } + + + @Test + public final void testIsReplaced() { + Mockito.doReturn(ProjectFileState.STATE_REPLACED).when(state).getStatus(); + getObjectUnderTest().setState(state); + assertTrue(getObjectUnderTest().isReplaced()); + assertFalse(getObjectUnderTest().isDeleted()); + } + + @Test + public final void testSetDir() { + getObjectUnderTest().setDir(dir); + assertEquals(dir, getObjectUnderTest().getDir()); + } + + @Test + public final void testSetValidFrom() { + getObjectUnderTest().setValidFrom(pv); + assertEquals(pv, getObjectUnderTest().getValidFrom()); + } + + @Test + public final void testSetValidUntil() { + getObjectUnderTest().setValidUntil(pv); + assertEquals(pv, getObjectUnderTest().getValidUntil()); + } + + @Test + public final void testSetCopyFrom() { + getObjectUnderTest().setCopyFrom(getObjectUnderTest()); + assertEquals(getObjectUnderTest(), getObjectUnderTest().getCopyFrom()); + } + + @Test + public final void testSetMeasurements() { + Set measurements = new HashSet(); + getObjectUnderTest().setMeasurements(measurements); + assertEquals(measurements, getObjectUnderTest().getMeasurements()); + } + + @Test + public final void testSetEncapsulationUnits() { + Set encapsulationUnits = new HashSet(); + getObjectUnderTest().setEncapsulationUnits(encapsulationUnits); + assertEquals(encapsulationUnits, getObjectUnderTest().getEncapsulationUnits()); + } + + @Test + public final void testSetEncapsulationUnits_2() { + Set encapsulationUnits = null; + getObjectUnderTest().setEncapsulationUnits(encapsulationUnits); + assertFalse(getObjectUnderTest().getEncapsulationUnits() == null); + } + + @Test + public final void testSetExecutionUnits() { + Set executionUnits = new HashSet(); + getObjectUnderTest().setExecutionUnits(executionUnits); + assertEquals(executionUnits, getObjectUnderTest().getExecutionUnits()); + } + + @Test + public final void testSetExecutionUnits_2() { + Set executionUnits = null; + getObjectUnderTest().setExecutionUnits(executionUnits); + assertFalse(getObjectUnderTest().getExecutionUnits() == null); + } + + @Test + public final void testGetFileName() { + getObjectUnderTest().setDir(dir); + getObjectUnderTest().setName(name); + Mockito.doReturn("path").when(dir).getPath(); + assertTrue(getObjectUnderTest().getFileName().contains(name)); + assertTrue(getObjectUnderTest().getFileName().contains(dir.getPath())); + } + + @Test + public final void testGetFileName_2() { + getObjectUnderTest().setDir(dir); + getObjectUnderTest().setName(name); + Mockito.doReturn("path/").when(dir).getPath(); + assertTrue(getObjectUnderTest().getFileName().contains(name)); + assertTrue(getObjectUnderTest().getFileName().contains(dir.getPath())); + } + + @Test + public final void testToDirectory() { + getObjectUnderTest().setIsDirectory(false); + assertNull(getObjectUnderTest().toDirectory()); + } + + @Test + public final void testToDirectory_2() { + getObjectUnderTest().setIsDirectory(true); + getObjectUnderTest().setDir(dir); + getObjectUnderTest().setName(name); + Mockito.doReturn("path/").when(dir).getPath(); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertNull(getObjectUnderTest().toDirectory()); + } + + @Test + public final void testToDirectory_3() { + getObjectUnderTest().setIsDirectory(true); + getObjectUnderTest().setDir(dir); + getObjectUnderTest().setName(name); + Mockito.doReturn("path/").when(dir).getPath(); + List list = null; + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertNull(getObjectUnderTest().toDirectory()); + } + + @Test + public final void testToDirectory_4() { + getObjectUnderTest().setIsDirectory(true); + getObjectUnderTest().setDir(dir); + getObjectUnderTest().setName(name); + Mockito.doReturn("path/").when(dir).getPath(); + List list = new ArrayList(); + list.add(dir); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertEquals(dir, getObjectUnderTest().toDirectory()); + } + + @Test + public final void testGetPreviousFileVersion() { + super.setUpMockedDBService(); + Mockito.doReturn(ProjectFileState.STATE_ADDED).when(state).getStatus(); + getObjectUnderTest().setState(state); + assertNull(getObjectUnderTest().getPreviousFileVersion()); + } + + @Test + public final void testGetPreviousFileVersion_2() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + + setUpATonOfBasicInformation(); + + assertNull(getObjectUnderTest().getPreviousFileVersion()); + } + + @Test + public final void testGetPreviousFileVersion_3() { + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + + getObjectUnderTest().setCopyFrom(getObjectUnderTest()); + setUpATonOfBasicInformation(); + + assertEquals(getObjectUnderTest(), getObjectUnderTest().getPreviousFileVersion()); + } + + private void setUpATonOfBasicInformation() { + Mockito.doReturn(ProjectFileState.STATE_MODIFIED).when(state).getStatus(); + getObjectUnderTest().setState(state); + getObjectUnderTest().setDir(dir); + getObjectUnderTest().setProjectVersion(pv); + getObjectUnderTest().setName(name); + Mockito.doReturn(sp).when(pv).getProject(); + Mockito.doReturn("path/").when(dir).getPath(); + + Logger logger = Mockito.mock(Logger.class); + Mockito.doReturn(logger).when(super.dbService).logger(); + } + + @Test + public final void testGetDeletionVersion() { + super.setUpMockedDBService(); + Mockito.doReturn(ProjectFileState.STATE_DELETED).when(state).getStatus(); + getObjectUnderTest().setState(state); + getObjectUnderTest().setProjectVersion(pv); + + assertEquals(pv, ProjectFile.getDeletionVersion(getObjectUnderTest())); + } + + @Test + public final void testGetDeletionVersion_2() { + super.setUpMockedDBService(); + Mockito.doReturn(ProjectFileState.STATE_MODIFIED).when(state).getStatus(); + getObjectUnderTest().setState(state); + this.setUpATonOfBasicInformation(); + + List list = new ArrayList(); + list.add(pv); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + + assertEquals(pv, ProjectFile.getDeletionVersion(getObjectUnderTest())); + } + + @Test + public final void testGetDeletionVersion_3() { + super.setUpMockedDBService(); + Mockito.doReturn(ProjectFileState.STATE_MODIFIED).when(state).getStatus(); + getObjectUnderTest().setState(state); + getObjectUnderTest().setProjectVersion(null); + this.setUpATonOfBasicInformation(); + + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + + assertNull(ProjectFile.getDeletionVersion(getObjectUnderTest())); + } + + @Test + public final void testGetEnclosingDirectory() { + this.setUpATonOfBasicInformation(); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertNull(getObjectUnderTest().getEnclosingDirectory()); + } + + @Test + public final void testGetEnclosingDirectory_2() { + this.setUpATonOfBasicInformation(); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(getObjectUnderTest(), getObjectUnderTest().getEnclosingDirectory()); + } + + @Test + public final void testGetFileModifications() { + this.setUpATonOfBasicInformation(); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(list, ProjectFile.getFileModifications(getObjectUnderTest())); + } + + @Test + public final void testFindFileLongStringStringString() { + super.setUpMockedDBService(); + assertNull(ProjectFile.findFile(null, null, null, null)); + } + + @Test + public final void testFindFileLongStringStringStringBoolean() { + super.setUpMockedDBService(); + assertNull(ProjectFile.findFile(123L, null, null, null)); + } + + @Test + public final void testFindFileLongStringStringStringBoolean_2() { + this.setUpATonOfBasicInformation(); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(getObjectUnderTest(), ProjectFile.findFile(12L, "", "", "", true)); + } + + @Test + public final void testFindFileLongStringStringStringBoolean_3() { + this.setUpATonOfBasicInformation(); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertNull(ProjectFile.findFile(12L, "", "", "", false)); + } + + @Test + public final void testGetChangedExecutionUnits() { + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(list, getObjectUnderTest().getChangedExecutionUnits()); + } + + @Test + public final void testToString() { + this.setUpATonOfBasicInformation(); + String s = getObjectUnderTest().toString(); + assertTrue(s.contains(dir.getPath())); + assertTrue(s.contains(name)); + assertTrue(s.contains(state.toString())); + } + + @Test + public final void testEqualsObject() { + assertFalse(getObjectUnderTest().equals(null)); + } + + @Test + public final void testEqualsObject_2() { + assertFalse(getObjectUnderTest().equals(123L)); + } + + @Test + public final void testEqualsObject_3() { + this.setUpATonOfBasicInformation(); + assertEquals(getObjectUnderTest(), getObjectUnderTest()); + } + + @Test + public final void testGetAllMetricsByType() { + super.testGetStaticDoHQL2_ShouldBeNull(); + assertEquals(0, ProjectFile.getProjectFilesByState(state).size()); + } + + @Test + public final void testGetAllMetricsByType_2() { + super.testGetStaticDoHQL2_ShouldBeObject(); + assertEquals(getObjectUnderTest(), ProjectFile.getProjectFilesByState(state).get(0)); + } + + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionMeasurementTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionMeasurementTest.java new file mode 100644 index 000000000..b6d22452d --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionMeasurementTest.java @@ -0,0 +1,66 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class ProjectVersionMeasurementTest extends + DBTestSuper { + + ProjectVersionMeasurement projectVersionMeasurement; + @Mock + Metric metric; + @Mock + ProjectVersion projectVersion; + String result; + + @Before + public void setUp() throws Exception { + projectVersionMeasurement = new ProjectVersionMeasurement(); + super.setUp(projectVersionMeasurement); + } + + @Test + public void testSetId() { + super.testSetId(); + } + + @Test + public void testProjectVersionMeasurement() { + assertNotNull(new ProjectVersionMeasurement()); + } + + @Test + public void testProjectVersionMeasurementMetricProjectVersionString() { + ProjectVersionMeasurement other = new ProjectVersionMeasurement(metric, + projectVersion, result); + + assertNotNull(other); + assertEquals(metric, other.getMetric()); + assertEquals(projectVersion, other.getProjectVersion()); + assertEquals(result, other.getResult()); + } + + @Test + public void testSetProjectVersion() { + projectVersionMeasurement.setProjectVersion(projectVersion); + assertEquals(projectVersion, + projectVersionMeasurement.getProjectVersion()); + } + + @Test + public void testSetMetric() { + projectVersionMeasurement.setMetric(metric); + assertEquals(metric, projectVersionMeasurement.getMetric()); + } + + @Test + public void testSetResult() { + projectVersionMeasurement.setResult(result); + assertEquals(result, projectVersionMeasurement.getResult()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionParentIdTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionParentIdTest.java new file mode 100644 index 000000000..cc73e6068 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionParentIdTest.java @@ -0,0 +1,83 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.ArrayList; + +import org.junit.Before; +import org.junit.Test; + +public class ProjectVersionParentIdTest { + + ProjectVersionParentId projectVersionParentId; + + @Before + public void setUp() throws Exception { + projectVersionParentId = new ProjectVersionParentId(); + } + + @Test + public void testSetParentId() { + Long parentid = new Long(1575); + projectVersionParentId.setParentid(parentid); + assertEquals(parentid, projectVersionParentId.getParentid()); + } + + @Test + public void testSetChildId() { + Long childid = new Long(42745); + projectVersionParentId.setChildid(childid); + assertEquals(childid, projectVersionParentId.getChildid()); + } + + @Test + public void testEqualsTrue() { + Long childid = new Long(427173); + Long parentid = new Long(64073); + ProjectVersionParentId other = new ProjectVersionParentId(); + projectVersionParentId.setChildid(childid); + projectVersionParentId.setParentid(parentid); + other.setChildid(childid); + other.setParentid(parentid); + assertEquals(projectVersionParentId, other); + } + + @Test + public void testEqualsFalse() { + Long childid = new Long(4723); + ProjectVersionParentId other = new ProjectVersionParentId(); + projectVersionParentId.setChildid(childid); + assertFalse(projectVersionParentId.equals(other)); + } + + @Test + public void testEqualsObject() { + assertFalse(projectVersionParentId.equals(new ArrayList())); + } + + @Test + public void testHashCodeTrue() { + Long childid = new Long(427173); + Long parentid = new Long(64073); + ProjectVersionParentId other = new ProjectVersionParentId(); + projectVersionParentId.setChildid(childid); + projectVersionParentId.setParentid(parentid); + other.setChildid(childid); + other.setParentid(parentid); + assertEquals(projectVersionParentId.hashCode(), other.hashCode()); + } + + @Test + public void testHashCodeFalse() { + Long parentid = new Long(753); + Long childid1 = new Long(4723); + Long childid2 = new Long(4625); + ProjectVersionParentId other = new ProjectVersionParentId(); + projectVersionParentId.setChildid(childid1); + projectVersionParentId.setParentid(parentid); + other.setChildid(childid2); + other.setParentid(parentid); + assertFalse(projectVersionParentId.hashCode() == other.hashCode()); + } +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionParentTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionParentTest.java new file mode 100644 index 000000000..4616bf5f4 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionParentTest.java @@ -0,0 +1,61 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class ProjectVersionParentTest extends DBTestSuper { + + ProjectVersionParent projectVersionParent; + @Mock + ProjectVersion child; + @Mock + ProjectVersion parent; + @Mock + ProjectVersionParentId projectVersionParentId; + + @Before + public void setUp() throws Exception { + projectVersionParent = new ProjectVersionParent(); + super.setUp(projectVersionParent); + } + + @Test + public void testSetIdLong() { + super.testSetId(); + } + + @Test + public void testProjectVersionParent() { + assertNotNull(new ProjectVersionParent()); + } + + @Test + public void testProjectVersionParentProjectVersionProjectVersion() { + ProjectVersionParent other = new ProjectVersionParent(child, parent); + assertEquals(child, other.getChild()); + assertEquals(parent, other.getParent()); + } + + @Test + public void testSetParent() { + projectVersionParent.setParent(parent); + assertEquals(parent, projectVersionParent.getParent()); + } + + @Test + public void testSetChild() { + projectVersionParent.setChild(child); + assertEquals(child, projectVersionParent.getChild()); + } + + @Test + public void testSetIdProjectVersionParentId() { + projectVersionParent.setId(projectVersionParentId); + assertEquals(projectVersionParentId, projectVersionParent.getPk()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionTest.java new file mode 100644 index 000000000..7a16c8967 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/ProjectVersionTest.java @@ -0,0 +1,910 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.sql.Date; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; + +public class ProjectVersionTest extends DBTestSuper { + + ProjectVersion projectVersion; + @Mock + StoredProject storedProject; + @Mock + ProjectFile projectFile; + @Mock + Tag tag; + @Mock + ProjectVersionMeasurement projectVersionMeasurement; + @Mock + ProjectVersionParent projectVersionParent; + @Mock + Branch branch; + @Mock + private Metric metric; + @Mock + ProjectFileState pfs; + @Mock + Directory dir; + + @Before + public void setUp() throws Exception { + projectVersion = new ProjectVersion(); + super.setUp(projectVersion); + } + + @Test + public void testHashCodeFalse() { + ProjectVersion other = new ProjectVersion(); + projectVersion.setCommitMsg("bla"); + assertFalse(projectVersion.equals(other)); + } + + @Test + public void testHashCodeTrue() { + ProjectVersion other = new ProjectVersion(); + assertFalse(projectVersion.equals(other)); + } + + @Test + public void testSetId() { + super.testSetId(); + } + + @Test + public void testProjectVersion() { + assertNotNull(new ProjectVersion()); + } + + @Test + public void testProjectVersionStoredProject() { + ProjectVersion other = new ProjectVersion(storedProject); + assertNotNull(other); + assertEquals(storedProject, other.getProject()); + } + + @Test + public void testSetProject() { + projectVersion.setProject(storedProject); + assertEquals(storedProject, projectVersion.getProject()); + } + + @Test + public void testSetRevisionId() { + String revId = "amazing-id"; + projectVersion.setRevisionId(revId); + assertEquals(revId, projectVersion.getRevisionId()); + } + + @Test + public void testSetTimestamp() { + long timestamp = 750236; + projectVersion.setTimestamp(timestamp); + assertEquals(timestamp, projectVersion.getTimestamp()); + } + + @Test + public void testSetDate() { + Date date = new Date(0); + projectVersion.setDate(date); + assertEquals(date, projectVersion.getDate()); + } + + @Test + public void testSetCommitter() { + Developer developer = new Developer(); + projectVersion.setCommitter(developer); + assertEquals(developer, projectVersion.getCommitter()); + } + + @Test + public void testSetCommitMsg() { + String commitMsg = "did-some-work"; + projectVersion.setCommitMsg(commitMsg); + assertEquals(commitMsg, projectVersion.getCommitMsg()); + } + + @Test + public void testSetSequence() { + long sequence = 240753; + projectVersion.setSequence(sequence); + assertEquals(sequence, projectVersion.getSequence()); + } + + @Test + public void testSetVersionFiles() { + Set projectFileSet = new HashSet<>(); + projectFileSet.add(projectFile); + projectVersion.setVersionFiles(projectFileSet); + assertEquals(projectFileSet, projectVersion.getVersionFiles()); + assertEquals(1, projectFileSet.size()); + } + + @Test + public void testSetVersionFiles_2() { + Set projectFileSet = null; + projectVersion.setVersionFiles(projectFileSet); + assertFalse(projectVersion.getVersionFiles() == null); + } + + @Test + public void testSetTags() { + Set tagSet = new HashSet<>(); + tagSet.add(tag); + projectVersion.setTags(tagSet); + assertEquals(tagSet, projectVersion.getTags()); + assertEquals(1, tagSet.size()); + } + + @Test + public void testSetMeasurements() { + Set projectVersionMeasurementSet = new HashSet<>(); + projectVersionMeasurementSet.add(projectVersionMeasurement); + projectVersion.setMeasurements(projectVersionMeasurementSet); + assertEquals(projectVersionMeasurementSet, + projectVersion.getMeasurements()); + assertEquals(1, projectVersionMeasurementSet.size()); + } + + @Test + public void testSetParents() { + Set projectVersionParentSet = new HashSet<>(); + projectVersionParentSet.add(projectVersionParent); + projectVersion.setParents(projectVersionParentSet); + assertEquals(projectVersionParentSet, projectVersion.getParents()); + assertEquals(1, projectVersionParentSet.size()); + } + + @Test + public void testSetParents_2() { + Set projectVersionParentSet = null; + projectVersion.setParents(projectVersionParentSet); + assertFalse(projectVersion.getParents() == null); + } + + @Test + public void testSetIncomingBranches() { + Set branchSet = new HashSet<>(); + branchSet.add(branch); + projectVersion.setIncomingBranches(branchSet); + assertEquals(branchSet, projectVersion.getIncomingBranches()); + assertEquals(1, branchSet.size()); + } + + @Test + public void testSetIncomingBranches_2() { + Set branchSet = null; + projectVersion.setIncomingBranches(branchSet); + assertFalse(projectVersion.getIncomingBranches() == null); + } + + @Test + public void testSetOutgoingBranches() { + Set outgoingBranches = new HashSet(); + getObjectUnderTest().setOutgoingBranches(outgoingBranches); + assertEquals(outgoingBranches, getObjectUnderTest() + .getOutgoingBranches()); + } + + @Test + public void testSetOutgoingBranches_2() { + Set outgoingBranches = null; + getObjectUnderTest().setOutgoingBranches(outgoingBranches); + assertNotNull(getObjectUnderTest().getOutgoingBranches()); + } + + @Test + public void testSetNamespaces() { + Set namespaces = new HashSet(); + getObjectUnderTest().setNamespaces(namespaces); + assertEquals(namespaces, getObjectUnderTest().getNamespaces()); + } + + @Test + public void testSetNamespaces_2() { + Set namespaces = null; + getObjectUnderTest().setNamespaces(namespaces); + assertNotNull(getObjectUnderTest().getNamespaces()); + } + + private ProjectVersion setUpSeqs(long a, long b) { + ProjectVersion pv = new ProjectVersion(); + String revisionId = "revId"; + pv.setSequence(b); + pv.setProject(storedProject); + pv.setRevisionId(revisionId); + pv.setTimestamp(b); + getObjectUnderTest().setProject(storedProject); + getObjectUnderTest().setSequence(a); + getObjectUnderTest().setTimestamp(a); + getObjectUnderTest().setRevisionId(revisionId); + return pv; + } + + @Test + public void testLte() { + ProjectVersion pv = setUpSeqs(0, 42); + assertTrue(getObjectUnderTest().lte(pv)); + } + + @Test + public void testLte_2() { + ProjectVersion pv = setUpSeqs(42, 0); + assertFalse(getObjectUnderTest().lte(pv)); + } + + @Test + public void testLte_3() { + ProjectVersion pv = setUpSeqs(0, 0); + assertTrue(getObjectUnderTest().lte(pv)); + } + + @Test + public void testLt() { + ProjectVersion pv = setUpSeqs(0, 42); + assertTrue(getObjectUnderTest().lt(pv)); + } + + @Test + public void testLt_2() { + ProjectVersion pv = setUpSeqs(42, 0); + assertFalse(getObjectUnderTest().lt(pv)); + } + + @Test + public void testLt_3() { + ProjectVersion pv = setUpSeqs(0, 0); + assertFalse(getObjectUnderTest().lt(pv)); + } + + @Test + public void testGte() { + ProjectVersion pv = setUpSeqs(0, 42); + assertFalse(getObjectUnderTest().gte(pv)); + } + + @Test + public void testGte_2() { + ProjectVersion pv = setUpSeqs(42, 0); + assertTrue(getObjectUnderTest().gte(pv)); + } + + @Test + public void testGte_3() { + ProjectVersion pv = setUpSeqs(0, 0); + assertTrue(getObjectUnderTest().gte(pv)); + } + + @Test + public void testGt() { + ProjectVersion pv = setUpSeqs(0, 42); + assertFalse(getObjectUnderTest().gt(pv)); + } + + @Test + public void testGt_2() { + ProjectVersion pv = setUpSeqs(42, 0); + assertTrue(getObjectUnderTest().gt(pv)); + } + + @Test + public void testGt_3() { + ProjectVersion pv = setUpSeqs(0, 0); + assertFalse(getObjectUnderTest().gt(pv)); + } + + @Test + public void testEq() { + ProjectVersion pv = setUpSeqs(0, 42); + assertFalse(getObjectUnderTest().eq(pv)); + } + + @Test + public void testEq_2() { + ProjectVersion pv = setUpSeqs(42, 0); + assertFalse(getObjectUnderTest().eq(pv)); + } + + @Test + public void testEq_3() { + ProjectVersion pv = setUpSeqs(0, 0); + assertTrue(getObjectUnderTest().eq(pv)); + } + + @Test + public void testEq_4() { + ProjectVersion pv = setUpSeqs(0, 0); + getObjectUnderTest().setRevisionId("this is not the same"); + assertFalse(getObjectUnderTest().eq(pv)); + } + + @Test + public void testGetPreviousVersion() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertNull(getObjectUnderTest().getPreviousVersion()); + } + + @Test + public void testGetPreviousVersion_2() { + this.setUpSeqs(0, 0); + List list = null; + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertNull(getObjectUnderTest().getPreviousVersion()); + } + + @Test + public void testGetPreviousVersion_3() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(getObjectUnderTest(), getObjectUnderTest() + .getPreviousVersion()); + } + + @Test + public void testGetNextVersion() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertNull(getObjectUnderTest().getNextVersion()); + } + + @Test + public void testGetNextVersion_2() { + this.setUpSeqs(0, 0); + List list = null; + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertNull(getObjectUnderTest().getNextVersion()); + } + + @Test + public void testGetNextVersion_3() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(getObjectUnderTest(), getObjectUnderTest() + .getNextVersion()); + } + + @Test + public void testGetVersionByRevision() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertNull(ProjectVersion.getVersionByRevision(storedProject, "")); + } + + @Test + public void testGetVersionByRevision_2() { + this.setUpSeqs(0, 0); + List list = null; + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertNull(ProjectVersion.getVersionByRevision(storedProject, "")); + } + + @Test + public void testGetVersionByRevision_3() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertEquals(getObjectUnderTest(), + ProjectVersion.getVersionByRevision(storedProject, "")); + } + + @Test + public void testGetVersionByTimestamp() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertNull(ProjectVersion.getVersionByTimestamp(storedProject, 0L)); + } + + @Test + public void testGetVersionByTimestamp_2() { + this.setUpSeqs(0, 0); + List list = null; + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertNull(ProjectVersion.getVersionByTimestamp(storedProject, 0L)); + } + + @Test + public void testGetVersionByTimestamp_3() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertEquals(getObjectUnderTest(), + ProjectVersion.getVersionByTimestamp(storedProject, 0L)); + } + + @Test + public void testGetFirstProjectVersion() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertNull(ProjectVersion.getFirstProjectVersion(storedProject)); + } + + @Test + public void testGetFirstProjectVersion_2() { + this.setUpSeqs(0, 0); + List list = null; + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertNull(ProjectVersion.getFirstProjectVersion(storedProject)); + } + + @Test + public void testGetFirstProjectVersion_3() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(getObjectUnderTest(), + ProjectVersion.getFirstProjectVersion(storedProject)); + } + + @Test + public void testGetLastProjectVersion() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertNull(ProjectVersion.getLastProjectVersion(storedProject)); + } + + @Test + public void testGetLastProjectVersion_2() { + this.setUpSeqs(0, 0); + List list = null; + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertNull(ProjectVersion.getLastProjectVersion(storedProject)); + } + + @Test + public void testGetLastProjectVersion_3() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(getObjectUnderTest(), + ProjectVersion.getLastProjectVersion(storedProject)); + } + + @Test + public void testGetLastMeasuredVersion() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertNull(ProjectVersion.getLastMeasuredVersion(metric, storedProject)); + } + + @Test + public void testGetLastMeasuredVersion_3() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + list.add(getObjectUnderTest()); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + assertEquals(getObjectUnderTest(), + ProjectVersion.getLastMeasuredVersion(metric, storedProject)); + } + + @Test + public void testGetFilesCount() { + super.setUpMockedDBService(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(null); + assertEquals(0, getObjectUnderTest().getFilesCount(pfs)); + } + + @Test + public void testGetFilesCount_2() { + super.setUpMockedDBService(); + Long i = 131L; + List list = new ArrayList(); + list.add(i); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertTrue(i == getObjectUnderTest().getFilesCount(pfs)); + } + + @Test + public void testGetFilesCount_3() { + super.setUpMockedDBService(); + Long i = 131L; + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + assertEquals(0, getObjectUnderTest().getFilesCount(pfs)); + } + + @Test + public void testGetLiveFilesCount() { + this.setUpSeqs(0, 0); + + List list = new ArrayList(); + list.add(getObjectUnderTest()); + + long lo = 42L; + List lList = new ArrayList(); + lList.add(lo); + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertEquals(lo, getObjectUnderTest().getLiveFilesCount()); + } + + @Test + public void testGetLiveFilesCount_2() { + ProjectVersion pv2 = this.setUpSeqs(8, 2); + + List list = new ArrayList(); + list.add(pv2); + + long lo = 42L; + List lList = new ArrayList(); + lList.add(lo); + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertEquals(lo, getObjectUnderTest().getLiveFilesCount()); + } + + @Test + public void testToString() { + String name = "name"; + Mockito.doReturn(name).when(storedProject).toString(); + String revId = "revId"; + getObjectUnderTest().setProject(storedProject); + getObjectUnderTest().setRevisionId(revId); + + String res = getObjectUnderTest().toString(); + assertTrue(res.contains(name)); + assertTrue(res.contains(revId)); + } + + @Test + public void testGetFiles() { + this.setUpSeqs(8, 2); + + List list = new ArrayList(); + list.add(getObjectUnderTest()); + + List lList = null; + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertTrue(getObjectUnderTest().getFiles().isEmpty()); + } + + @Test + public void testGetFiles_2() { + ProjectVersion pv2 = this.setUpSeqs(8, 2); + + List list = new ArrayList(); + list.add(pv2); + + List lList = new ArrayList(); + lList.add(projectFile); + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertEquals(lList, getObjectUnderTest().getFiles()); + } + + + + @Test + public void testGetFilesDirectoryInt() { + ProjectVersion pv2 = this.setUpSeqs(8, 2); + + List list = new ArrayList(); + list.add(pv2); + + List lList = new ArrayList(); + lList.add(projectFile); + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertEquals(lList, getObjectUnderTest().getFiles((Directory) null, 0)); + } + + @Test + public void testGetFilesDirectory() { + ProjectVersion pv2 = this.setUpSeqs(8, 2); + + List list = new ArrayList(); + list.add(pv2); + + List lList = new ArrayList(); + lList.add(projectFile); + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertEquals(lList, getObjectUnderTest().getFiles(dir)); + } + + @Test + public void testGetFilesPattern() { + ProjectVersion pv2 = this.setUpSeqs(8, 2); + + List list = new ArrayList(); + list.add(pv2); + + List lList = new ArrayList(); + lList.add(projectFile); + Mockito.doReturn("blah").when(projectFile).getFileName(); + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertEquals(0, getObjectUnderTest().getFiles(Pattern.compile("hoi")).size()); + } + + + @Test + public void testGetFilesPattern_2() { + ProjectVersion pv2 = this.setUpSeqs(8, 2); + + List list = new ArrayList(); + list.add(pv2); + + List lList = new ArrayList(); + lList.add(projectFile); + Mockito.doReturn("hoi").when(projectFile).getFileName(); + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertEquals(lList, getObjectUnderTest().getFiles(Pattern.compile("hoi"))); + } + + @Test + public void testGetFilesPatternInt() { + ProjectVersion pv2 = this.setUpSeqs(8, 2); + + List list = new ArrayList(); + list.add(pv2); + + List lList = new ArrayList(); + lList.add(projectFile); + Mockito.doReturn("hoi").when(projectFile).getFileName(); + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertEquals(lList, getObjectUnderTest().getFiles(Pattern.compile("hoi",2))); + } + + @Test + public void testAllDirs() { + ProjectVersion pv2 = this.setUpSeqs(8, 2); + + List list = new ArrayList(); + list.add(pv2); + + List lList = new ArrayList(); + lList.add(projectFile); + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertEquals(lList, getObjectUnderTest().allDirs()); + } + + @Test + public void testAllFiles() { + ProjectVersion pv2 = this.setUpSeqs(8, 2); + + List list = new ArrayList(); + list.add(pv2); + + List lList = new ArrayList(); + lList.add(projectFile); + + super.setUpMockedDBService(); + Mockito.doReturn(list).doReturn(lList).when(dbService) + .doHQL(Matchers.anyString(), Matchers.anyMap()); + + assertEquals(lList, getObjectUnderTest().allFiles()); + } + + @Test + public void testIsTag() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertFalse(getObjectUnderTest().isTag()); + } + + + @Test + public void testIsTag_3() { + this.setUpSeqs(0, 0); + List list = new ArrayList(); + list.add(tag); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + assertTrue(getObjectUnderTest().isTag()); + } + + @Test + public void testIsBranch() { + assertFalse(getObjectUnderTest().isBranch()); + } + + @Test + public void testIsBranch_2() { + Branch b1 = Mockito.mock(Branch.class); + Branch b2 = Mockito.mock(Branch.class); + Set out = new HashSet(); + out.add(b1); + out.add(b2); + Set in = new HashSet(); + in.add(b1); + getObjectUnderTest().setOutgoingBranches(out); + getObjectUnderTest().setIncomingBranches(in); + assertTrue(getObjectUnderTest().isBranch()); + } + + @Test + public void testIsBranch_3() { + Branch b1 = Mockito.mock(Branch.class); + Branch b2 = Mockito.mock(Branch.class); + Set out = new HashSet(); + out.add(b1); + out.add(b2); + Set in = new HashSet(); + getObjectUnderTest().setOutgoingBranches(out); + getObjectUnderTest().setIncomingBranches(in); + assertFalse(getObjectUnderTest().isBranch()); + } + + @Test + public void testIsBranch_4() { + Branch b1 = Mockito.mock(Branch.class); + Branch b2 = Mockito.mock(Branch.class); + Set out = new HashSet(); + out.add(b1); + Set in = new HashSet(); + in.add(b1); + in.add(b2); + getObjectUnderTest().setOutgoingBranches(out); + getObjectUnderTest().setIncomingBranches(in); + assertFalse(getObjectUnderTest().isBranch()); + } + + @Test + public void testIsMerge() { + assertFalse(getObjectUnderTest().isMerge()); + } + + @Test + public void testIsMerge_2() { + Branch b1 = Mockito.mock(Branch.class); + Branch b2 = Mockito.mock(Branch.class); + Set out = new HashSet(); + out.add(b1); + out.add(b2); + Set in = new HashSet(); + in.add(b1); + getObjectUnderTest().setOutgoingBranches(out); + getObjectUnderTest().setIncomingBranches(in); + assertFalse(getObjectUnderTest().isMerge()); + } + + @Test + public void testIsMerge_3() { + Branch b1 = Mockito.mock(Branch.class); + Branch b2 = Mockito.mock(Branch.class); + Set out = new HashSet(); + out.add(b1); + out.add(b2); + Set in = new HashSet(); + getObjectUnderTest().setOutgoingBranches(out); + getObjectUnderTest().setIncomingBranches(in); + assertFalse(getObjectUnderTest().isMerge()); + } + + @Test + public void testIsMerge_4() { + Branch b1 = Mockito.mock(Branch.class); + Branch b2 = Mockito.mock(Branch.class); + Set out = new HashSet(); + out.add(b1); + Set in = new HashSet(); + in.add(b1); + in.add(b2); + getObjectUnderTest().setOutgoingBranches(out); + getObjectUnderTest().setIncomingBranches(in); + assertTrue(getObjectUnderTest().isMerge()); + } + + @Test + public void testIsMerge_5() { + Branch b1 = Mockito.mock(Branch.class); + Set out = new HashSet(); + Set in = new HashSet(); + in.add(b1); + getObjectUnderTest().setOutgoingBranches(out); + getObjectUnderTest().setIncomingBranches(in); + assertFalse(getObjectUnderTest().isMerge()); + } + + @Test + public void testGetBranch() { + Branch b1 = Mockito.mock(Branch.class); + Branch b2 = Mockito.mock(Branch.class); + Branch b3 = Mockito.mock(Branch.class); + Set out = new HashSet(); + out.add(b3); + Set in = new HashSet(); + in.add(b1); + in.add(b2); + getObjectUnderTest().setOutgoingBranches(out); + getObjectUnderTest().setIncomingBranches(in); + assertEquals(b3, getObjectUnderTest().getBranch()); + } + + @Test + public void testGetBranch_2() { + Branch b1 = Mockito.mock(Branch.class); + Branch b2 = Mockito.mock(Branch.class); + Set out = new HashSet(); + out.add(b1); + out.add(b2); + Set in = new HashSet(); + in.add(b2); + getObjectUnderTest().setOutgoingBranches(out); + getObjectUnderTest().setIncomingBranches(in); + assertEquals(b2, getObjectUnderTest().getBranch()); + } + + @Test + public void testEqualsObject() { + assertFalse(getObjectUnderTest().equals(null)); + } + + @Test + public void testEqualsObject_2() { + assertFalse(getObjectUnderTest().equals(123)); + } + + @Test + public void testEqualsObject_3() { + ProjectVersion pv2 = this.setUpSeqs(42, 42); + assertEquals(getObjectUnderTest(), pv2); + } + +} + diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/StoredProjectConfigTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/StoredProjectConfigTest.java new file mode 100644 index 000000000..df8a0644e --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/StoredProjectConfigTest.java @@ -0,0 +1,59 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class StoredProjectConfigTest extends DBTestSuper { + + StoredProjectConfig storedProjectConfig; + @Mock + private ConfigurationOption confOpt; + @Mock + private StoredProject project; + + @Before + public void setUp() throws Exception { + storedProjectConfig = new StoredProjectConfig(); + super.setUp(storedProjectConfig); + } + + @Test + public void testSetId() { + super.testSetId(); + } + + @Test + public void testSetConfOpt() { + storedProjectConfig.setConfOpt(confOpt); + assertEquals(confOpt, storedProjectConfig.getConfOpt()); + } + + @Test + public void testSetProject() { + storedProjectConfig.setProject(project); + assertEquals(project, storedProjectConfig.getProject()); + } + + @Test + public void testSetValue() { + String value = "nice-value"; + storedProjectConfig.setValue(value); + assertEquals(value, storedProjectConfig.getValue()); + } + + @Test + public void testFromProject() { + List list = new ArrayList<>(); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + List test = StoredProjectConfig + .fromProject(project); + assertEquals(list, test); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/StoredProjectMeasurementTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/StoredProjectMeasurementTest.java new file mode 100644 index 000000000..73d5cc876 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/StoredProjectMeasurementTest.java @@ -0,0 +1,48 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class StoredProjectMeasurementTest extends + DBTestSuper { + + private StoredProjectMeasurement storedProjectMeasurement; + @Mock + private StoredProject storedProject; + @Mock + private Metric metric; + private String result = "nice-result"; + + @Before + public void setUp() throws Exception { + storedProjectMeasurement = new StoredProjectMeasurement(); + super.setUp(storedProjectMeasurement); + } + + @Test + public void testSetId() { + super.testSetId(); + } + + @Test + public void testSetStoredProject() { + storedProjectMeasurement.setStoredProject(storedProject); + assertEquals(storedProject, storedProjectMeasurement.getStoredProject()); + } + + @Test + public void testSetMetric() { + storedProjectMeasurement.setMetric(metric); + assertEquals(metric, storedProjectMeasurement.getMetric()); + } + + @Test + public void testSetResult() { + storedProjectMeasurement.setResult(result); + assertEquals(result, storedProjectMeasurement.getResult()); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/StoredProjectTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/StoredProjectTest.java new file mode 100644 index 000000000..58107cdd9 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/StoredProjectTest.java @@ -0,0 +1,241 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; + +import eu.sqooss.core.AlitheiaCore; + +public class StoredProjectTest extends DBTestSuper { + + private StoredProject storedProject; + private List projectVersions; + private Set developers; + private Set mailingLists; + private Set measurements; + private Set configOpts; + @Mock + private ClusterNode assignment; + private Set branches; + private Set bugs; + + private ConfigOption key; + @Mock + private StoredProjectConfig storedProjectConfig; + @Mock + private ConfigurationOption configOption; + + @Before + public void setUp() throws Exception { + storedProject = new StoredProject(); + projectVersions = new ArrayList<>(); + developers = new HashSet<>(); + mailingLists = new HashSet<>(); + measurements = new HashSet<>(); + configOpts = new HashSet<>(); + branches = new HashSet<>(); + bugs = new HashSet<>(); + key = ConfigOption.PROJECT_BTS_SOURCE; + + super.setUp(storedProject); + } + + @Test + public void testSetId() { + super.testSetId(); + } + + @Test + public void testSetName() { + String name = "nice-name"; + storedProject.setName(name); + assertEquals(name, storedProject.getName()); + } + + @Test + public void testSetWebsiteUrl() { + String url = "some-url"; + List stringList = new ArrayList<>(); + stringList.add(url); + List list = new ArrayList<>(); + list.add(configOption); + Mockito.doReturn(stringList).when(configOption) + .getValues(Mockito.any(StoredProject.class)); + + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + + storedProject.setWebsiteUrl(url); + assertEquals(url, storedProject.getWebsiteUrl()); + } + + @Test + public void testSetContactUrl() { + String url = "some-url"; + List stringList = new ArrayList<>(); + stringList.add(url); + List list = new ArrayList<>(); + list.add(configOption); + Mockito.doReturn(stringList).when(configOption) + .getValues(Mockito.any(StoredProject.class)); + + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + + storedProject.setContactUrl(url); + assertEquals(url, storedProject.getContactUrl()); + } + + @Test + public void testSetBtsUrl() { + String url = "some-url"; + List stringList = new ArrayList<>(); + stringList.add(url); + List list = new ArrayList<>(); + list.add(configOption); + Mockito.doReturn(stringList).when(configOption) + .getValues(Mockito.any(StoredProject.class)); + + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + + storedProject.setBtsUrl(url); + assertEquals(url, storedProject.getBtsUrl()); + } + + @Test + public void testSetScmUrl() { + String url = "some-url"; + List stringList = new ArrayList<>(); + stringList.add(url); + List list = new ArrayList<>(); + list.add(configOption); + Mockito.doReturn(stringList).when(configOption) + .getValues(Mockito.any(StoredProject.class)); + + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + + storedProject.setScmUrl(url); + assertEquals(url, storedProject.getScmUrl()); + } + + @Test + public void testSetMailUrl() { + String url = "some-url"; + List stringList = new ArrayList<>(); + stringList.add(url); + List list = new ArrayList<>(); + list.add(configOption); + Mockito.doReturn(stringList).when(configOption) + .getValues(Mockito.any(StoredProject.class)); + + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + storedProject.setMailUrl(url); + assertEquals(url, storedProject.getMailUrl()); + } + + @Test + public void testSetProjectVersions() { + storedProject.setProjectVersions(projectVersions); + assertEquals(projectVersions, storedProject.getProjectVersions()); + } + + @Test + public void testSetDevelopers() { + storedProject.setDevelopers(developers); + assertEquals(developers, storedProject.getDevelopers()); + } + + @Test + public void testSetMailingLists() { + storedProject.setMailingLists(mailingLists); + assertEquals(mailingLists, storedProject.getMailingLists()); + } + + @Test + public void testSetMeasurements() { + storedProject.setMeasurements(measurements); + assertEquals(measurements, storedProject.getMeasurements()); + } + + @Test + public void testSetConfigOpts() { + storedProject.setConfigOpts(configOpts); + assertEquals(configOpts, storedProject.getConfigOpts()); + } + + @Test + public void testSetClusternode() { + storedProject.setClusternode(assignment); + assertEquals(assignment, storedProject.getClusternode()); + } + + @Test + public void testSetBranches() { + storedProject.setBranches(branches); + assertEquals(branches, storedProject.getBranches()); + } + + @Test + public void testSetBugs() { + storedProject.setBugs(bugs); + assertEquals(bugs, storedProject.getBugs()); + } + + @Test + public void testGetProjectByName() { + List list = new ArrayList<>(); + list.add(storedProject); + super.setUpMockedAlitheiaCoreAndDbServiceForObjectsByProp(list); + StoredProject test = StoredProject.getProjectByName(""); + assertEquals(storedProject, test); + } + + @Test + public void testGetProjectCount() { + Long l = new Long(1337); + List list = new ArrayList<>(); + list.add(l); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL1(list); + int test = StoredProject.getProjectCount(); + assertEquals(l.intValue(), test); + } + + @Test + public void testGetVersionsCount() { + Long l = new Long(1337); + List list = new ArrayList<>(); + list.add(l); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + Long test = storedProject.getVersionsCount(); + assertEquals(l, test); + } + + @Test + public void testGetMailsCount() { + Long l = new Long(1337); + List list = new ArrayList<>(); + list.add(l); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + Long test = storedProject.getMailsCount(); + assertEquals(l, test); + } + + @Test + public void testGetBugsCount() { + Long l = new Long(1337); + List list = new ArrayList<>(); + list.add(l); + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + Long test = storedProject.getBugsCount(); + assertEquals(l, test); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/service/db/TagTest.java b/alitheia/core/src/test/java/eu/sqooss/service/db/TagTest.java new file mode 100644 index 000000000..7670e4fb7 --- /dev/null +++ b/alitheia/core/src/test/java/eu/sqooss/service/db/TagTest.java @@ -0,0 +1,65 @@ +package eu.sqooss.service.db; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +public class TagTest extends DBTestSuper { + + private Tag tag; + + @Mock + private ProjectVersion projectVersion; + + private List list; + + @Mock + private StoredProject storedProject; + + @Before + public void setUp() throws Exception { + tag = new Tag(); + super.setUp(tag); + + list = new ArrayList(); + list.add(projectVersion); + } + + @Test + public void testSetId() { + super.testSetId(); + } + + @Test + public void testSetProjectVersion() { + tag.setProjectVersion(projectVersion); + assertEquals(projectVersion, tag.getProjectVersion()); + } + + @Test + public void testSetName() { + String refname = "refname"; + tag.setName(refname); + assertEquals(refname, tag.getName()); + } + + @Test + public void testGetProjectVersionForNamedTag() { + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL3(list); + Version test = Tag.getProjectVersionForNamedTag("", null); + assertEquals(projectVersion, test); + } + + @Test + public void testGetTaggedVersions() { + super.setUpMockedAlitheiaCoreAndDbServiceForDoHQL2(list); + List list = Tag.getTaggedVersions(storedProject); + assertEquals(this.list, list); + } + +} diff --git a/alitheia/core/src/test/java/eu/sqooss/test/service/scheduler/SchedulerTests.java b/alitheia/core/src/test/java/eu/sqooss/test/service/scheduler/SchedulerTests.java index f30f92f84..66496a36f 100644 --- a/alitheia/core/src/test/java/eu/sqooss/test/service/scheduler/SchedulerTests.java +++ b/alitheia/core/src/test/java/eu/sqooss/test/service/scheduler/SchedulerTests.java @@ -2,6 +2,7 @@ import org.junit.AfterClass; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; import eu.sqooss.impl.service.scheduler.SchedulerServiceImpl; @@ -17,7 +18,9 @@ public static void setUp() { sched.startExecute(2); } + @Test + @Ignore public void testJobYield() throws SchedulerException { TestJob j1 = new TestJob(20, "Test"); diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-all-null.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-all-null.html new file mode 100644 index 000000000..128894875 --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-all-null.html @@ -0,0 +1,42 @@ + + + +
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            Project Id Project Name Last Version Last Email Last Bug Evaluated Host
            No projects found.
            View
            Manage
            Update
            + + + +
            + + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-add-project.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-add-project.html new file mode 100644 index 000000000..ba600f20f --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-add-project.html @@ -0,0 +1,42 @@ + + + +
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            Homepage
            Project name
            Contact e-mail
            Source code
            Mailing list
            Bug database
            + + + +
            + + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-rem-project.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-rem-project.html new file mode 100644 index 000000000..47481c5fc --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-rem-project.html @@ -0,0 +1,24 @@ + + + +
            +
            + Delete project: + + + + + + + + + +
            Are you sure that you want to completely remove this project?
            +
            + + + +
            + + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-show-project.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-show-project.html new file mode 100644 index 000000000..92a34e658 --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-act-req-show-project.html @@ -0,0 +1,45 @@ + + + +
            +
            + Project information + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            Homepage
            Project name
            Contact e-mail
            Source code
            Mailing list
            Bug database
            +
            + + + +
            + + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-projects.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-projects.html new file mode 100644 index 000000000..f81596223 --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-form-projects.html @@ -0,0 +1,50 @@ + + + +
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            Project Id Project Name Last Version Last Email Last Bug Evaluated Host
            0 [Edit] n/a n/a n/a No (local)
            View
            Manage
            Update
            + + + +
            + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-projects-in-toolbar.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-projects-in-toolbar.html new file mode 100644 index 000000000..33f552a28 --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/html-ref-projects-in-toolbar.html @@ -0,0 +1,43 @@ + + + +
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            Project Id Project Name Last Version Last Email Last Bug Evaluated Host
            No projects found.
            View
            Manage
            Update
            + + + +
            + + + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-basic.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-basic.html new file mode 100644 index 000000000..ce19f9b36 --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-basic.html @@ -0,0 +1,10 @@ + + + +
            + All plug-ins + No plug-ins found!  +
            + + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed-confirm-property.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed-confirm-property.html new file mode 100644 index 000000000..2ba8013f9 --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed-confirm-property.html @@ -0,0 +1,45 @@ + + + +
            +
            + Errors Property update has failed! Check log for details. +
            +
            + Update property of null + + + + + + + + + + + + + + + + + + + + + + +
            NameconfirmProperty
            DescriptionconfirmProperty
            Type confirmProperty
            Value
               
            +
            + + + + + + + + +
            + + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed-create-property.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed-create-property.html new file mode 100644 index 000000000..5da5edc66 --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed-create-property.html @@ -0,0 +1,42 @@ + + + +
            +
            + Create property for null + + + + + + + + + + + + + + + + + + + + + + +
            Name
            Description
            Type
            Value
             
            +
            + + + + + + + + +
            + + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed.html new file mode 100644 index 000000000..d834af4aa --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object-is-installed.html @@ -0,0 +1,78 @@ + + + +
            +
            + null + + + + + + + + + + + + + + + + + + + + +
            StatusNameClassVersion
            Installednullnullnull
            +
            + Supported metrics + + + + + + + + + + + + + + +
            IdNameTypeDescription
            This plug-in does not support metrics.
            +
            +
            + Configuration properties + + + + + + + + + + + + + + + + +
            NameTypeValue
            This plug-in has no configuration properties.
            +
            +
            + + + + + + + + +
            + + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object.html new file mode 100644 index 000000000..5fa6836fc --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin-with-info-object.html @@ -0,0 +1,40 @@ + + + +
            +
            + null + + + + + + + + + + + + + + + + + + + + +
            StatusNameClassVersion
            Registerednullnullnull
            +
            + + + + + + + + +
            + + + diff --git a/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin.html b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin.html new file mode 100644 index 000000000..db5209c50 --- /dev/null +++ b/alitheia/core/src/test/resources/eu/sqooss/impl/service/webadmin/pluginsview-render-single-plugin.html @@ -0,0 +1,37 @@ + + + +
            +
            + All plug-ins + + + + + + + + + + + + + + + + + +
            StatusNameClassVersion
            [Edit] Registerednullnullnull
            + Display properties Display activators +
            + + + + + + + + +
            + + diff --git a/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/ContributionMetricImpl.java b/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/ContributionMetricImpl.java index 5d6042bef..e2fb0e486 100644 --- a/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/ContributionMetricImpl.java +++ b/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/ContributionMetricImpl.java @@ -67,16 +67,19 @@ import eu.sqooss.service.db.DAObject; import eu.sqooss.service.db.DBService; import eu.sqooss.service.db.Developer; +import eu.sqooss.service.db.IDAObject; +import eu.sqooss.service.db.IDeveloper; +import eu.sqooss.service.db.IMailMessage; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.MailMessage; import eu.sqooss.service.db.MailingList; import eu.sqooss.service.db.MailingListThread; import eu.sqooss.service.db.Metric; import eu.sqooss.service.db.MetricType; +import eu.sqooss.service.db.MetricType.Type; import eu.sqooss.service.db.PluginConfiguration; -import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.db.StoredProject; -import eu.sqooss.service.db.MetricType.Type; import eu.sqooss.service.fds.FileTypeMatcher; import eu.sqooss.service.metricactivator.MetricActivationException; import eu.sqooss.service.pa.PluginInfo; @@ -150,13 +153,13 @@ public boolean cleanup(DAObject sp) { return result; } - private boolean cleanupResource (Collection c, + private boolean cleanupResource (Collection c, ActionCategory ac) { Map params = new HashMap(); boolean result = false; - for(DAObject o : c) { + for(IDAObject o : c) { params.put("changedResourceId", o.getId()); params.put("actionCategory", ac.toString()); List pas = @@ -229,7 +232,7 @@ private List checkResult(DAObject o, ActionCategory ac, return res; } - private ContribAction getResult(DAObject o) { + private ContribAction getResult(IDAObject o) { String paramChResource = "paramChResource"; String paramActionCategory = "paramActionCategory"; @@ -298,15 +301,15 @@ public void run(Bug b) throws AlreadyProcessingException { if (b.getResolution().equals(BugResolution.Resolution.DUPLICATE)) updateField(b, b.getReporter(), ActionType.BDUP, true, 1); - for(BugReportMessage brm : b.getReportMessages()) { + for(BugReportMessage brm : BugReportMessage.getAllReportMessageForBug(b)) { updateField(b, brm.getReporter(), ActionType.BCC, true, 1); } } public void run(MailingListThread t) throws AlreadyProcessingException { Metric contrib = Metric.getMetricByMnemonic(METRIC_CONTRIB); - List emails = t.getMessagesByArrivalOrder(); - MailMessage lastProcessed = null; + List emails = t.getMessagesByArrivalOrder(); + IMailMessage lastProcessed = null; //Find the last email in this thread //that has been processed in a previous invocation. Avoid @@ -320,7 +323,7 @@ public void run(MailingListThread t) throws AlreadyProcessingException { } } - for (MailMessage mm : emails) { + for (IMailMessage mm : emails) { ContribAction ca = getResult(mm); if (ca!= null) { //This mail has been processed again, check if the @@ -343,7 +346,7 @@ public void run(MailingListThread t) throws AlreadyProcessingException { } else { if (mm.getDepth() == 1) { //First reply to a thread - MailMessage firstMessage = t.getMessagesAtLevel(1).get(0); + IMailMessage firstMessage = t.getMessagesAtLevel(1).get(0); if (firstMessage.equals(mm)) updateField(mm, mm.getSender(), ActionType.MFR, true, 1); } @@ -362,7 +365,7 @@ public void run(ProjectVersion pv) throws AlreadyProcessingException { /* Read config options in advance*/ FileTypeMatcher.FileType fType; Developer dev = pv.getCommitter(); - Set projectFiles = pv.getVersionFiles(); + Set projectFiles = pv.getVersionFiles(); List locMetric = new ArrayList(); AlitheiaPlugin plugin = AlitheiaCore.getInstance().getPluginAdmin().getImplementingPlugin("Wc.loc"); @@ -418,10 +421,10 @@ public void run(ProjectVersion pv) throws AlreadyProcessingException { } FileTypeMatcher ftm = FileTypeMatcher.getInstance(); - Iterator i = projectFiles.iterator(); + Iterator i = projectFiles.iterator(); while (i.hasNext()) { - ProjectFile pf = i.next(); + IProjectFile pf = i.next(); if (pf.getIsDirectory()) { //New directory added @@ -459,7 +462,7 @@ else if (pf.isAdded()) { getLOCResult(pf, plugin, locMetric)); } else { //Existing file, get lines of previous version - ProjectFile prevFile = pf.getPreviousFileVersion(); + IProjectFile prevFile = pf.getPreviousFileVersion(); if (prevFile == null) { warn("Could not find previous version", pf); @@ -530,7 +533,7 @@ else if (pf.isAdded()) { } } - private int getLOCResult(ProjectFile pf, AlitheiaPlugin plugin, + private int getLOCResult(IProjectFile pf, AlitheiaPlugin plugin, List locMetric) throws MetricMismatchException, AlreadyProcessingException, Exception { //Get lines of current version of the file from the wc metric @@ -546,7 +549,7 @@ private int getLOCResult(ProjectFile pf, AlitheiaPlugin plugin, } } - private void updateField(DAObject o, Developer dev, + private void updateField(IDAObject o, IDeveloper dev, ActionType actionType, boolean isPositive, int value) { DBService db = AlitheiaCore.getInstance().getDBService(); ContribActionType at = ContribActionType.getContribActionType(actionType, @@ -583,22 +586,22 @@ else if (o instanceof Bug) } } - private void err(String msg, DAObject o) { + private void err(String msg, IDAObject o) { log.error("Contrib (" + o.getClass() + "): Object: " + o.toString() + " Error:"+ msg); } - private void warn(String msg, DAObject o) { + private void warn(String msg, IDAObject o) { log.warn("Contrib (" + o.getClass() + "): Object: " + o.toString() + " Warning:" + msg); } - private void info(String msg, DAObject o) { + private void info(String msg, IDAObject o) { log.info("Contrib (" + o.getClass() + "): Object: " + o.toString() + " Info:" + msg); } - private void debug(String msg, DAObject o) { + private void debug(String msg, IDAObject o) { log.debug("Contrib (" + o.getClass() + "): Object: " + o.toString() + " Debug:" + msg); } diff --git a/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribAction.hbm.xml b/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribAction.hbm.xml index 7dd1192d2..665367e69 100644 --- a/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribAction.hbm.xml +++ b/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribAction.hbm.xml @@ -8,7 +8,9 @@ - + + diff --git a/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribAction.java b/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribAction.java index e079a1340..e07740845 100644 --- a/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribAction.java +++ b/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribAction.java @@ -37,19 +37,20 @@ import java.util.List; import java.util.Map; +import eu.sqooss.core.AlitheiaCore; import eu.sqooss.metrics.contrib.ContributionActions; import eu.sqooss.metrics.contrib.ContributionActions.ActionCategory; import eu.sqooss.metrics.contrib.ContributionActions.ActionType; -import eu.sqooss.core.AlitheiaCore; import eu.sqooss.service.db.DAObject; import eu.sqooss.service.db.DBService; import eu.sqooss.service.db.Developer; -import eu.sqooss.service.db.StoredProject; +import eu.sqooss.service.db.IDeveloper; +import eu.sqooss.service.db.Project; public class ContribAction extends DAObject { private long id; - private Developer developer; + private IDeveloper developer; private Long changedResourceId; private ContribActionType contribActionType; private long total; @@ -71,11 +72,11 @@ public void setChangedResourceTimestamp(Date changedResourceTimestamp) { this.changedResourceTimestamp = changedResourceTimestamp; } - public Developer getDeveloper() { + public IDeveloper getDeveloper() { return developer; } - public void setDeveloper(Developer developer) { + public void setDeveloper(IDeveloper developer) { this.developer = developer; } @@ -103,7 +104,7 @@ public void setTotal(long total){ this.total = total; } - public static ContribAction getContribAction(Developer dev, + public static ContribAction getContribAction(IDeveloper dev, Long resourceId, ContribActionType actionType) { DBService dbs = AlitheiaCore.getInstance().getDBService(); @@ -150,7 +151,7 @@ public static Long getDevActionsPerType(Developer dev, return 0L; } - public static Long getTotalActionsPerTypePerProject(StoredProject sp, + public static Long getTotalActionsPerTypePerProject(Project sp, Date timestamp, ContribActionType actionType) { DBService dbs = AlitheiaCore.getInstance().getDBService(); diff --git a/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribActionType.java b/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribActionType.java index e3f60cf08..2160df0f4 100644 --- a/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribActionType.java +++ b/metrics/contrib/src/main/java/eu/sqooss/metrics/contrib/db/ContribActionType.java @@ -37,12 +37,12 @@ import java.util.List; import java.util.Map; +import eu.sqooss.core.AlitheiaCore; import eu.sqooss.metrics.contrib.ContributionActions; import eu.sqooss.metrics.contrib.ContributionActions.ActionCategory; -import eu.sqooss.core.AlitheiaCore; import eu.sqooss.service.db.DAObject; import eu.sqooss.service.db.DBService; -import eu.sqooss.service.db.StoredProject; +import eu.sqooss.service.db.Project; public class ContribActionType extends DAObject { @@ -106,7 +106,7 @@ public void setIsPositive(boolean isPositive){ * @param before * @return */ - public static List getProjectActionTypes(StoredProject sp, + public static List getProjectActionTypes(Project sp, Date before) { DBService dbs = AlitheiaCore.getInstance().getDBService(); diff --git a/metrics/developermetrics/src/main/java/eu/sqooss/metrics/developermetrics/Developermetrics.java b/metrics/developermetrics/src/main/java/eu/sqooss/metrics/developermetrics/Developermetrics.java index a91916044..f53796682 100644 --- a/metrics/developermetrics/src/main/java/eu/sqooss/metrics/developermetrics/Developermetrics.java +++ b/metrics/developermetrics/src/main/java/eu/sqooss/metrics/developermetrics/Developermetrics.java @@ -45,6 +45,7 @@ import eu.sqooss.service.abstractmetric.Result.ResultType; import eu.sqooss.service.db.Developer; import eu.sqooss.service.db.Directory; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.Metric; import eu.sqooss.service.db.ProjectDirectory; import eu.sqooss.service.db.ProjectFile; @@ -137,13 +138,13 @@ public void run(ProjectFile a) throws AlreadyProcessingException { int eyeballs = 0; Metric m = null; if (a.getIsDirectory()) { - List files = a.getProjectVersion().getFiles( + List files = a.getProjectVersion().getFiles( Directory.getDirectory(a.getFileName(), false), ProjectVersion.MASK_FILES); Set distinctdevs = new HashSet(); - for (ProjectFile pf : files) { + for (IProjectFile pf : files) { distinctdevs.addAll(fileEyeballs(pf)); } eyeballs = distinctdevs.size(); @@ -159,7 +160,7 @@ public void run(ProjectFile a) throws AlreadyProcessingException { db.addRecord(pfm); } - private List fileEyeballs(ProjectFile a) { + private List fileEyeballs(IProjectFile a) { Map params = new HashMap(); params.put("paramName", a.getName()); params.put("paramDir", a.getDir()); diff --git a/metrics/discussionheat/src/main/java/eu/sqooss/metrics/discussionheat/DiscussionHeat.java b/metrics/discussionheat/src/main/java/eu/sqooss/metrics/discussionheat/DiscussionHeat.java index af3c91300..39c09a6df 100644 --- a/metrics/discussionheat/src/main/java/eu/sqooss/metrics/discussionheat/DiscussionHeat.java +++ b/metrics/discussionheat/src/main/java/eu/sqooss/metrics/discussionheat/DiscussionHeat.java @@ -48,14 +48,15 @@ import eu.sqooss.service.abstractmetric.MetricMismatchException; import eu.sqooss.service.abstractmetric.Result; import eu.sqooss.service.db.DBService; +import eu.sqooss.service.db.IMailMessage; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.MailMessage; import eu.sqooss.service.db.MailingListThread; import eu.sqooss.service.db.MailingListThreadMeasurement; import eu.sqooss.service.db.Metric; -import eu.sqooss.service.db.ProjectFile; +import eu.sqooss.service.db.Project; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.db.ProjectVersionMeasurement; -import eu.sqooss.service.db.StoredProject; /** * Discussion heat plug-in. @@ -111,11 +112,12 @@ public void run(MailingListThread m) throws AlreadyProcessingException { List mailsPerList = (List)db.doHQL(numMails, params); //Get one day's worth of messages - List msgs = m.getMessagesByArrivalOrder(); - List oneDayMsgs = new ArrayList(); - int depth = 0; MailMessage first = null; + List msgs = m.getMessagesByArrivalOrder(); + List oneDayMsgs = new ArrayList(); + int depth = 0; + IMailMessage first = null; - for (MailMessage msg : msgs) { + for (IMailMessage msg : msgs) { if (first != null) { if (msg.getSendDate().getTime() - first.getSendDate().getTime() < (24L * 3600 * 1000)) { @@ -215,7 +217,7 @@ private List getNextWeekVersions(ProjectVersion pv) { return versions; } - private ProjectVersion getVersionByDate(Date ts, StoredProject sp) { + private ProjectVersion getVersionByDate(Date ts, Project sp) { Map params = new HashMap(); params.put("ts", ts.getTime()); params.put("sp", sp); @@ -256,7 +258,7 @@ public void run(ProjectVersion pv) throws AlreadyProcessingException { int linesChanged = 0; try { // Get difference in number of lines for all file changes - for (ProjectFile pf : pv.getVersionFiles()) { + for (IProjectFile pf : pv.getVersionFiles()) { if (pf.getIsDirectory()) continue; if (pf.isDeleted()) { @@ -286,7 +288,7 @@ public void run(ProjectVersion pv) throws AlreadyProcessingException { dbs.addRecord(pvm); } - private int getLOCResult(ProjectFile pf, AlitheiaPlugin plugin, + private int getLOCResult(IProjectFile pf, AlitheiaPlugin plugin, List locMetric) throws MetricMismatchException, AlreadyProcessingException, Exception { //Get lines of current version of the file from the wc metric diff --git a/metrics/findbugs/src/main/java/gr/aueb/metrics/findbugs/FindbugsMetrics.java b/metrics/findbugs/src/main/java/gr/aueb/metrics/findbugs/FindbugsMetrics.java index a31d5395c..d9f92ba9c 100644 --- a/metrics/findbugs/src/main/java/gr/aueb/metrics/findbugs/FindbugsMetrics.java +++ b/metrics/findbugs/src/main/java/gr/aueb/metrics/findbugs/FindbugsMetrics.java @@ -139,7 +139,7 @@ public FindbugsMetrics(BundleContext bc) { //Run per version only public void run(ProjectFile pf){} - public List getResult(ProjectFile pf, Metric m) { + public List getResult(IProjectFile pf, Metric m) { return getResult(pf, ProjectFileMeasurement.class, m, Result.ResultType.INTEGER); } @@ -151,14 +151,14 @@ public List getResult(ProjectVersion pv, Metric m) { public void run(ProjectVersion pv) { - List files = pv.getFiles(); + List files = pv.getFiles(); Pattern pom = Pattern.compile("pom.xml$"); Pattern buildxml = Pattern.compile("build.xml$"); Pattern trunk = Pattern.compile("/trunk"); boolean foundTrunk = false, foundPom = false, foundBuild = false, maven_build = true; - for(ProjectFile pf: files) { + for(IProjectFile pf: files) { if (pom.matcher(pf.getFileName()).find()) foundPom = true; @@ -462,7 +462,7 @@ public Map > parseFindbugsResults (File results) { } private void storeResults(Map > results, - List files, ProjectVersion pv) { + List files, ProjectVersion pv) { List metrics = getAllSupportedMetrics(); List fileMeasurements = new ArrayList(); List versionMeasurements = new ArrayList(); @@ -476,7 +476,7 @@ private void storeResults(Map > results, } for (String fileName: results.get(key).keySet()) { - ProjectFile file = findFile(files, fileName); + IProjectFile file = findFile(files, fileName); if (file == null) { log.warn("Cannot find file path " + fileName + " in DB project files"); continue; @@ -519,8 +519,8 @@ private boolean pvMeasurementExists(ProjectVersion pv, Metric m) { return db.doHQL(q, parameters).size() > 0; } - private ProjectFile findFile(List files, String path) { - for(ProjectFile pf: files) { + private IProjectFile findFile(List files, String path) { + for(IProjectFile pf: files) { if (pf.getFileName().endsWith(path)) return pf; } diff --git a/metrics/javametrics/src/main/java/eu/sqooss/metrics/java/JavaMetrics.java b/metrics/javametrics/src/main/java/eu/sqooss/metrics/java/JavaMetrics.java index e0ee2a7fc..b89591bfb 100644 --- a/metrics/javametrics/src/main/java/eu/sqooss/metrics/java/JavaMetrics.java +++ b/metrics/javametrics/src/main/java/eu/sqooss/metrics/java/JavaMetrics.java @@ -1,37 +1,49 @@ package eu.sqooss.metrics.java; import java.io.InputStream; -import java.util.*; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; -import eu.sqooss.parsers.java.*; -import eu.sqooss.service.fds.FDSService; import org.antlr.runtime.ANTLRInputStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.tree.Tree; import org.osgi.framework.BundleContext; import eu.sqooss.core.AlitheiaCore; +import eu.sqooss.parsers.java.ASTWalker; +import eu.sqooss.parsers.java.CBOCalculator; +import eu.sqooss.parsers.java.EntityExtractor; +import eu.sqooss.parsers.java.InheritanceExtractor; +import eu.sqooss.parsers.java.JavaTreeLexer; +import eu.sqooss.parsers.java.JavaTreeParser; +import eu.sqooss.parsers.java.LCOMCalculator; +import eu.sqooss.parsers.java.McCabeCalculator; +import eu.sqooss.parsers.java.SpanningNodeAdaptor; import eu.sqooss.service.abstractmetric.AbstractMetric; import eu.sqooss.service.abstractmetric.MetricDecl; import eu.sqooss.service.abstractmetric.MetricDeclarations; import eu.sqooss.service.abstractmetric.Result; import eu.sqooss.service.abstractmetric.SchedulerHints; import eu.sqooss.service.db.DBService; +import eu.sqooss.service.db.EncapsUnit; import eu.sqooss.service.db.EncapsulationUnit; import eu.sqooss.service.db.EncapsulationUnitMeasurement; +import eu.sqooss.service.db.ExecUnit; import eu.sqooss.service.db.ExecutionUnit; import eu.sqooss.service.db.ExecutionUnitMeasurement; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.Metric; import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectVersion; -import eu.sqooss.service.scheduler.Job; -import eu.sqooss.service.scheduler.ResumePoint; -import eu.sqooss.service.scheduler.Scheduler; -import eu.sqooss.service.scheduler.SchedulerException; +import eu.sqooss.service.fds.FDSService; @MetricDeclarations(metrics = { @MetricDecl(mnemonic = "MCCABE", activators = {ExecutionUnit.class, ProjectVersion.class}, descr = "McCabe Complexity Metric"), @@ -47,7 +59,7 @@ @SchedulerHints(activationOrder = {ProjectVersion.class, EncapsulationUnit.class}) public class JavaMetrics extends AbstractMetric { - private List changedFiles; + private List changedFiles; private ProjectVersion pv; //Class -> Base private ConcurrentMap reducer; @@ -90,9 +102,9 @@ public void run(ProjectVersion pv) throws Exception { this.pv = pv; Pattern p = Pattern.compile("([^\\s]+(\\.(?i)(java))$)"); - changedFiles = new ArrayList(); + changedFiles = new ArrayList(); - for (ProjectFile pf : pv.getVersionFiles()) { + for (IProjectFile pf : pv.getVersionFiles()) { Matcher m = p.matcher(pf.getName()); if (m.matches()) changedFiles.add(pf); @@ -105,7 +117,7 @@ public void run(ProjectVersion pv) throws Exception { } reducer = new ConcurrentHashMap(); - for (ProjectFile pf : pv.getFiles(p)) + for (IProjectFile pf : pv.getFiles(p)) try { if(!db.isDBSessionActive()) db.startDBSession(); parseFile(pf); @@ -116,8 +128,8 @@ public void run(ProjectVersion pv) throws Exception { } - List changedClasses = new ArrayList(); - for (ProjectFile pf : changedFiles) { + List changedClasses = new ArrayList(); + for (IProjectFile pf : changedFiles) { pf = db.attachObjectToDBSession(pf); changedClasses.addAll(pf.getEncapsulationUnits()); } @@ -125,7 +137,7 @@ public void run(ProjectVersion pv) throws Exception { Metric DIT = Metric.getMetricByMnemonic("DIT"); Metric NOC = Metric.getMetricByMnemonic("NOC"); - for (EncapsulationUnit clazz : changedClasses) { + for (EncapsUnit clazz : changedClasses) { String classname = clazz.getName(); String base = reducer.get(classname); int dit = 1; @@ -148,7 +160,7 @@ public void run(ProjectVersion pv) throws Exception { db.commitDBSession(); } - protected void parseFile(ProjectFile pf) throws Exception { + protected void parseFile(IProjectFile pf) throws Exception { if (pf.getIsDirectory() || pf.isDeleted() || !pf.getName().endsWith(".java")) { @@ -189,8 +201,8 @@ protected void parseFile(ProjectFile pf) throws Exception { walker.walk(t); //Data for associated classes/methods - List methods = pf.getChangedExecutionUnits(); - Set classes = pf.getEncapsulationUnits(); + List methods = pf.getChangedExecutionUnits(); + Set classes = pf.getEncapsulationUnits(); Set foundClasses = entityExtractor.getResults().keySet(); //Make class graph @@ -210,10 +222,10 @@ protected void parseFile(ProjectFile pf) throws Exception { // WMC + MCCABE results in one go Metric m = Metric.getMetricByMnemonic("WMC"); SortedMap MCCABEresults = mcCabeCalculator.getResults(); - for (EncapsulationUnit clazz : classes) { + for (EncapsUnit clazz : classes) { Integer wmc = 0; - for (ExecutionUnit method : clazz.getExecUnits()) { + for (ExecUnit method : clazz.getExecUnits()) { Integer res = MCCABEresults.get(method.getFullyQualifiedName()); if (res == null) { @@ -233,7 +245,7 @@ protected void parseFile(ProjectFile pf) throws Exception { } // NUMM results - for (EncapsulationUnit clazz : classes) { + for (EncapsUnit clazz : classes) { EncapsulationUnitMeasurement eum = new EncapsulationUnitMeasurement(clazz, Metric.getMetricByMnemonic("NUMM"), @@ -242,9 +254,9 @@ protected void parseFile(ProjectFile pf) throws Exception { } } - private void writeClassResults(Set classes, + private void writeClassResults(Set classes, Map results, Metric m) { - for (EncapsulationUnit clazz : classes) { + for (EncapsUnit clazz : classes) { Integer res = results.get(clazz.getName()); if (res == null) { diff --git a/metrics/mi/src/main/java/eu/sqooss/metrics/mi/Mi.java b/metrics/mi/src/main/java/eu/sqooss/metrics/mi/Mi.java index 580de8aed..c38b57536 100644 --- a/metrics/mi/src/main/java/eu/sqooss/metrics/mi/Mi.java +++ b/metrics/mi/src/main/java/eu/sqooss/metrics/mi/Mi.java @@ -43,8 +43,9 @@ import eu.sqooss.service.abstractmetric.MetricDecl; import eu.sqooss.service.abstractmetric.MetricDeclarations; import eu.sqooss.service.abstractmetric.Result; -import eu.sqooss.service.db.DAObject; import eu.sqooss.service.db.Directory; +import eu.sqooss.service.db.IDAObject; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.Metric; import eu.sqooss.service.db.ProjectDirectory; import eu.sqooss.service.db.ProjectFile; @@ -113,7 +114,7 @@ public void run(ProjectFile pf) throws AlreadyProcessingException { return; /* We now know that we are working with a dir*/ - List fileList = pf.getProjectVersion().getFiles( + List fileList = pf.getProjectVersion().getFiles( Directory.getDirectory(pf.getFileName(), false), ProjectVersion.MASK_FILES); @@ -134,7 +135,7 @@ public void run(ProjectFile pf) throws AlreadyProcessingException { int totalLoCom = 0, totalG = 0, totalLoC = 0; FileTypeMatcher ftm = FileTypeMatcher.getInstance(); - for (ProjectFile f : fileList) { + for (IProjectFile f : fileList) { if (f.getIsDirectory() || !ftm.isSourceFile(f.getFileName())) continue; @@ -303,7 +304,7 @@ public void run(ProjectVersion pv) throws AlreadyProcessingException { * @return The metric result or null if no result is in the database. */ private E getResult(AlitheiaPlugin plugin, Metric m, - DAObject c, Class resultType) { + IDAObject c, Class resultType) { if (plugin == null) { log.error("Could not find the " + m.getMnemonic() diff --git a/metrics/modulemetrics/src/main/java/eu/sqooss/metrics/modulemetrics/ModuleMetricsImplementation.java b/metrics/modulemetrics/src/main/java/eu/sqooss/metrics/modulemetrics/ModuleMetricsImplementation.java index 33c4eaaef..f055a1ca1 100644 --- a/metrics/modulemetrics/src/main/java/eu/sqooss/metrics/modulemetrics/ModuleMetricsImplementation.java +++ b/metrics/modulemetrics/src/main/java/eu/sqooss/metrics/modulemetrics/ModuleMetricsImplementation.java @@ -49,6 +49,7 @@ import eu.sqooss.service.abstractmetric.MetricDeclarations; import eu.sqooss.service.abstractmetric.Result; import eu.sqooss.service.db.Directory; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.Metric; import eu.sqooss.service.db.ProjectDirectory; import eu.sqooss.service.db.ProjectFile; @@ -101,7 +102,7 @@ public List getResult(ProjectVersion pv, Metric m) { return getResult(pv, ProjectVersionMeasurement.class, m, Result.ResultType.FLOAT); } - public void run(ProjectFile pf) throws AlreadyProcessingException { + public void run(IProjectFile pf) throws AlreadyProcessingException { if (! pf.getIsDirectory()) { return; } @@ -109,13 +110,13 @@ public void run(ProjectFile pf) throws AlreadyProcessingException { int mnof = 0; int mnol = 0; - List pfs = pf.getProjectVersion().getFiles( + List pfs = pf.getProjectVersion().getFiles( Directory.getDirectory(pf.getFileName(), false), ProjectVersion.MASK_FILES); boolean foundSource = false; FileTypeMatcher ftm = FileTypeMatcher.getInstance(); - for (ProjectFile f : pfs) { + for (IProjectFile f : pfs) { if (ftm.getFileType(f.getName()) != FileTypeMatcher.FileType.SRC) { @@ -223,7 +224,7 @@ public void run(ProjectVersion pv) throws AlreadyProcessingException { } } - private int getMeasurement(String mnemonic, ProjectFile f) + private int getMeasurement(String mnemonic, IProjectFile f) throws AlreadyProcessingException { List metric = new ArrayList(); AlitheiaPlugin plugin = core.getPluginAdmin().getImplementingPlugin(mnemonic); diff --git a/plug-ins/bugzilla/src/main/java/eu/sqooss/plugins/bugzilla/BugzillaXMLJob.java b/plug-ins/bugzilla/src/main/java/eu/sqooss/plugins/bugzilla/BugzillaXMLJob.java index 56eecbd2f..4b64f7621 100644 --- a/plug-ins/bugzilla/src/main/java/eu/sqooss/plugins/bugzilla/BugzillaXMLJob.java +++ b/plug-ins/bugzilla/src/main/java/eu/sqooss/plugins/bugzilla/BugzillaXMLJob.java @@ -92,14 +92,13 @@ protected void run() throws Exception { + " could not be parsed"); return; } - + Set toadd = new LinkedHashSet(); // Filter out duplicate report messages if (bugExists(project, bugID)) { logger.debug(project.getName() + ": Updating existing bug " + bugID); - List msgs = bug.getAllReportComments(); - Set newmsgs = bug.getReportMessages(); - Set toadd = new LinkedHashSet(); + List msgs = BugReportMessage.getAllReportMessageForBug(bug); + Set newmsgs = getBugReportsFromBTSEntry(bts.getBug(bugID), bug); for (BugReportMessage newmsg : newmsgs) { boolean found = false; @@ -113,16 +112,33 @@ protected void run() throws Exception { toadd.add(newmsg); } } - - bug.setReportMessages(toadd); } dbs.addRecord(bug); + for (BugReportMessage brm: toadd) { + dbs.addRecord(brm); + } logger.debug(project.getName() + ": Added bug " + bugID); dbs.commitDBSession(); } + private Set getBugReportsFromBTSEntry(BTSEntry b, Bug bug) { + Set commentList = new LinkedHashSet(); + + for (BTSEntryComment c : b.commentslist) { + BugReportMessage bugmessage = new BugReportMessage(bug); + bugmessage.setReporter(getDeveloper(c.commentAuthor)); + bugmessage.setTimestamp(c.commentTS); + if (c.comment.length() > 255) + bugmessage.setText(c.comment.substring(0, 254)); + else + bugmessage.setText(c.comment); + commentList.add(bugmessage); + } + return commentList; + } + /** * Convert a BTS entry to a Bug DAO */ @@ -165,20 +181,6 @@ private Bug BTSEntryToBug (BTSEntry b) { bug.setReporter(getDeveloper(b.reporter)); - Set commentList = new LinkedHashSet(); - - for (BTSEntryComment c : b.commentslist) { - BugReportMessage bugmessage = new BugReportMessage(bug); - bugmessage.setReporter(getDeveloper(c.commentAuthor)); - bugmessage.setTimestamp(c.commentTS); - if (c.comment.length() > 255) - bugmessage.setText(c.comment.substring(0, 254)); - else - bugmessage.setText(c.comment); - commentList.add(bugmessage); - } - bug.setReportMessages(commentList); - return bug; } diff --git a/plug-ins/git/src/main/java/eu/sqooss/plugins/updater/git/GitUpdater.java b/plug-ins/git/src/main/java/eu/sqooss/plugins/updater/git/GitUpdater.java index 00ad047e2..754f7f19d 100644 --- a/plug-ins/git/src/main/java/eu/sqooss/plugins/updater/git/GitUpdater.java +++ b/plug-ins/git/src/main/java/eu/sqooss/plugins/updater/git/GitUpdater.java @@ -46,12 +46,14 @@ import eu.sqooss.service.db.DBService; import eu.sqooss.service.db.Developer; import eu.sqooss.service.db.Directory; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectFileState; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.db.ProjectVersionParent; import eu.sqooss.service.db.StoredProject; import eu.sqooss.service.db.Tag; +import eu.sqooss.service.db.Version; import eu.sqooss.service.logging.Logger; import eu.sqooss.service.tds.AccessorException; import eu.sqooss.service.tds.CommitCopyEntry; @@ -464,7 +466,7 @@ private void processRevisionFiles(SCMAccessor scm, Revision entry, * but something else. So we need to check on deletes * whether this name was most recently a directory. */ - ProjectFile lastVersion = file.getPreviousFileVersion(); + IProjectFile lastVersion = file.getPreviousFileVersion(); /* * If a directory is deleted and its previous incarnation cannot @@ -475,7 +477,7 @@ private void processRevisionFiles(SCMAccessor scm, Revision entry, */ boolean delAfterCopy = false; if (lastVersion == null) { - for (ProjectFile pf : curVersion.getVersionFiles()) { + for (IProjectFile pf : curVersion.getVersionFiles()) { if (pf.getFileName().equals(file.getFileName()) && pf.getIsDirectory() && pf.isAdded()) { @@ -507,10 +509,10 @@ private void processRevisionFiles(SCMAccessor scm, Revision entry, } } - private void replayLog(ProjectVersion curVersion) { + private void replayLog(Version curVersion) { /*Find duplicate projectfile entries*/ HashMap numOccurs = new HashMap(); - for (ProjectFile pf : curVersion.getVersionFiles()) { + for (IProjectFile pf : curVersion.getVersionFiles()) { if (numOccurs.get(pf.getFileName()) != null) { numOccurs.put(pf.getFileName(), numOccurs.get(pf.getFileName()).intValue() + 1); } else { @@ -521,7 +523,7 @@ private void replayLog(ProjectVersion curVersion) { /* Copy list of files to be added to the DB in a tmp array, * to use for iterating */ - List tmpFiles = new ArrayList(); + List tmpFiles = new ArrayList(); tmpFiles.addAll(curVersion.getVersionFiles()); for (String fpath : numOccurs.keySet()) { @@ -532,11 +534,11 @@ private void replayLog(ProjectVersion curVersion) { int points = 0; - ProjectFile copyFrom = null; - ProjectFile winner = null; + IProjectFile copyFrom = null; + IProjectFile winner = null; //dbs.addRecord(pf); - for (ProjectFile f: tmpFiles) { + for (IProjectFile f: tmpFiles) { if (!f.getFileName().equals(fpath)) { continue; @@ -571,7 +573,7 @@ private void replayLog(ProjectVersion curVersion) { * locally versioned path. */ if (winner.getState().getStatus() == ProjectFileState.STATE_DELETED) { - for (ProjectFile f: curVersion.getVersionFiles()) { + for (IProjectFile f: curVersion.getVersionFiles()) { if (!f.equals(winner) && f.getFileName().startsWith(winner.getFileName()) && f.getState().getStatus() != ProjectFileState.STATE_DELETED) { @@ -601,7 +603,7 @@ private void replayLog(ProjectVersion curVersion) { * revision, it returns the processed entry. */ private ProjectFile addFile(ProjectVersion version, String fPath, - ProjectFileState status, SCMNodeType t, ProjectFile copyFrom) { + ProjectFileState status, SCMNodeType t, IProjectFile copyFrom) { ProjectFile pf = new ProjectFile(version); String path = FileUtils.dirname(fPath); @@ -701,13 +703,13 @@ public Set mkdirs(final ProjectVersion pv, String path) { /** * Update the validUntil field after all files have been processed. */ - private void updateValidUntil(ProjectVersion pv, Set versionFiles) { + private void updateValidUntil(ProjectVersion pv, Set versionFiles) { ProjectVersion previous = pv.getPreviousVersion(); - for (ProjectFile pf : versionFiles) { + for (IProjectFile pf : versionFiles) { if (!pf.isAdded()) { - ProjectFile old = pf.getPreviousFileVersion(); + IProjectFile old = pf.getPreviousFileVersion(); old.setValidUntil(previous); } @@ -723,7 +725,7 @@ private void updateValidUntil(ProjectVersion pv, Set versionFiles) * * @param pf The project file representing the deleted directory */ - private Set handleDirDeletion(final ProjectFile pf, final ProjectVersion pv) { + private Set handleDirDeletion(final IProjectFile pf, final ProjectVersion pv) { Set files = new HashSet(); if (pf == null || pv == null) { @@ -746,9 +748,9 @@ private Set handleDirDeletion(final ProjectFile pf, final ProjectVe ProjectVersion prev = pv.getPreviousVersion(); - List dirFiles = prev.getFiles(d); + List dirFiles = prev.getFiles(d); - for (ProjectFile f : dirFiles) { + for (IProjectFile f : dirFiles) { if (f.getIsDirectory()) { files.addAll(handleDirDeletion(f, pv)); } @@ -776,7 +778,7 @@ private boolean isValidStateTransition(ProjectFileState a, ProjectFileState b) { * Handle directory copies */ private void handleDirCopy(ProjectVersion pv, ProjectVersion fromVersion, - Directory from, Directory to, ProjectFile copyFrom) { + Directory from, Directory to, IProjectFile copyFrom) { if (!canProcessCopy(from.getPath(), to.getPath())) return; @@ -784,16 +786,16 @@ private void handleDirCopy(ProjectVersion pv, ProjectVersion fromVersion, addFile(pv, to.getPath(), ProjectFileState.added(), SCMNodeType.DIR, copyFrom); /*Recursively copy directories*/ - List fromPF = fromVersion.getFiles(from, ProjectVersion.MASK_DIRECTORIES); + List fromPF = fromVersion.getFiles(from, ProjectVersion.MASK_DIRECTORIES); - for (ProjectFile f : fromPF) { + for (IProjectFile f : fromPF) { handleDirCopy(pv, fromVersion, Directory.getDirectory(f.getFileName(), false), Directory.getDirectory(to.getPath() + "/" + f.getName(), true), f); } fromPF = fromVersion.getFiles(from, ProjectVersion.MASK_FILES); - for (ProjectFile f : fromPF) { + for (IProjectFile f : fromPF) { addFile(pv, to.getPath() + "/" + f.getName(), ProjectFileState.added(), SCMNodeType.FILE, f); } diff --git a/plug-ins/git/src/test/java/eu/sqooss/plugins/git/test/TestGitUpdater.java b/plug-ins/git/src/test/java/eu/sqooss/plugins/git/test/TestGitUpdater.java index c156b2c65..d1c450412 100644 --- a/plug-ins/git/src/test/java/eu/sqooss/plugins/git/test/TestGitUpdater.java +++ b/plug-ins/git/src/test/java/eu/sqooss/plugins/git/test/TestGitUpdater.java @@ -1,16 +1,18 @@ package eu.sqooss.plugins.git.test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Properties; import org.apache.commons.io.FileUtils; @@ -31,6 +33,7 @@ import eu.sqooss.service.db.DBService; import eu.sqooss.service.db.Developer; import eu.sqooss.service.db.DeveloperAlias; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectFileState; import eu.sqooss.service.db.ProjectVersion; @@ -38,9 +41,6 @@ import eu.sqooss.service.logging.LogManager; import eu.sqooss.service.logging.Logger; import eu.sqooss.service.tds.AccessorException; -import eu.sqooss.service.tds.CommitLog; -import eu.sqooss.service.tds.InvalidProjectRevisionException; -import eu.sqooss.service.tds.InvalidRepositoryException; import eu.sqooss.service.tds.Revision; public class TestGitUpdater extends TestGitSetup { @@ -201,15 +201,15 @@ public void testUpdate() throws Exception { foundFiles.add(pf); } - List allfiles = pv.allFiles(); - for (ProjectFile pf : allfiles) { + List allfiles = pv.allFiles(); + for (IProjectFile pf : allfiles) { if (!foundFiles.contains(pf)) { System.err.println("File " + pf + " not in repository"); assertTrue(false); } } - for (ProjectFile pf : foundFiles) { + for (IProjectFile pf : foundFiles) { if (!allfiles.contains(pf)) { System.err.println("File " + pf + " not found in allFiles() result"); assertTrue(false); @@ -243,7 +243,7 @@ public void testVersionedProjectFile(ProjectFile pf) { } //Check that old and new versions of a file point to the same path - ProjectFile old = pf.getPreviousFileVersion(); + IProjectFile old = pf.getPreviousFileVersion(); assertNotNull(old); assertEquals(old.getFileName(), pf.getFileName()); if (old.getIsDirectory() != pf.getIsDirectory()) { diff --git a/plug-ins/javaparser/src/main/java/eu/sqooss/plugins/javaparser/JavaUpdaterJob.java b/plug-ins/javaparser/src/main/java/eu/sqooss/plugins/javaparser/JavaUpdaterJob.java index 7e3f0b058..894fe4c69 100644 --- a/plug-ins/javaparser/src/main/java/eu/sqooss/plugins/javaparser/JavaUpdaterJob.java +++ b/plug-ins/javaparser/src/main/java/eu/sqooss/plugins/javaparser/JavaUpdaterJob.java @@ -12,17 +12,17 @@ import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.tree.Tree; +import eu.sqooss.core.AlitheiaCore; import eu.sqooss.parsers.java.ASTWalker; import eu.sqooss.parsers.java.CodeFragment; import eu.sqooss.parsers.java.EntityExtractor; import eu.sqooss.parsers.java.JavaTreeLexer; import eu.sqooss.parsers.java.JavaTreeParser; import eu.sqooss.parsers.java.SpanningNodeAdaptor; - -import eu.sqooss.core.AlitheiaCore; import eu.sqooss.service.db.DBService; import eu.sqooss.service.db.EncapsulationUnit; import eu.sqooss.service.db.ExecutionUnit; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.Language; import eu.sqooss.service.db.NameSpace; import eu.sqooss.service.db.ProjectFile; @@ -69,10 +69,10 @@ protected void run() throws Exception { FDSService fds = AlitheiaCore.getInstance().getFDSService(); debug("Parsing files in version ", pv.toString()); - Set files = pv.getVersionFiles(p); + Set files = pv.getVersionFiles(p); int processed = 0; - for (ProjectFile pf : files) { + for (IProjectFile pf : files) { if (pf.getIsDirectory() || pf.isDeleted()) continue; debug("Parsing file ", pf.toString()); @@ -155,13 +155,13 @@ protected void run() throws Exception { db.commitDBSession(); } - private List getChangedMethods(EntityExtractor ee, ProjectFile pf, + private List getChangedMethods(EntityExtractor ee, IProjectFile pf, String clazz) throws InvalidAccessorException, InvalidProjectRevisionException, InvalidRepositoryException, FileNotFoundException { Long ts = System.currentTimeMillis(); List changedMethods = new ArrayList(); - ProjectFile prev = pf.getPreviousFileVersion(); + IProjectFile prev = pf.getPreviousFileVersion(); if (prev == null) { if (!pf.isAdded()) @@ -212,7 +212,7 @@ private List getChangedMethods(EntityExtractor ee, ProjectFile pf, return changedMethods; } - public String getMethodName(CodeFragment fragment, ProjectFile pf) { + public String getMethodName(CodeFragment fragment, IProjectFile pf) { String fullyQualifiedName = fragment.getFullyQualifiedName(); if (fullyQualifiedName == null) { warn("Name from fragment [" + fragment.getStartLine() + "," diff --git a/plug-ins/maildir/src/main/java/eu/sqooss/plugins/maildir/MailMessageJob.java b/plug-ins/maildir/src/main/java/eu/sqooss/plugins/maildir/MailMessageJob.java index 11af8e2fc..2f67f3da6 100644 --- a/plug-ins/maildir/src/main/java/eu/sqooss/plugins/maildir/MailMessageJob.java +++ b/plug-ins/maildir/src/main/java/eu/sqooss/plugins/maildir/MailMessageJob.java @@ -45,7 +45,7 @@ import eu.sqooss.service.db.Developer; import eu.sqooss.service.db.MailMessage; import eu.sqooss.service.db.MailingList; -import eu.sqooss.service.db.StoredProject; +import eu.sqooss.service.db.Project; import eu.sqooss.service.logging.Logger; import eu.sqooss.service.scheduler.Job; import eu.sqooss.service.tds.MailAccessor; @@ -63,7 +63,7 @@ public class MailMessageJob extends Job{ Logger logger; String fileName; MailingList ml; - StoredProject project; + Project project; int progress = 0; public MailMessageJob(MailingList ml, String f, Logger l) { diff --git a/plug-ins/mailthreadresolver/src/main/java/eu/sqooss/plugins/mailthreadresolver/MailThreadResolver.java b/plug-ins/mailthreadresolver/src/main/java/eu/sqooss/plugins/mailthreadresolver/MailThreadResolver.java index ffc502be8..53decf321 100755 --- a/plug-ins/mailthreadresolver/src/main/java/eu/sqooss/plugins/mailthreadresolver/MailThreadResolver.java +++ b/plug-ins/mailthreadresolver/src/main/java/eu/sqooss/plugins/mailthreadresolver/MailThreadResolver.java @@ -39,6 +39,7 @@ import eu.sqooss.core.AlitheiaCore; import eu.sqooss.service.db.DBService; +import eu.sqooss.service.db.IMailMessage; import eu.sqooss.service.db.MailMessage; import eu.sqooss.service.db.MailingList; import eu.sqooss.service.db.MailingListThread; @@ -255,7 +256,7 @@ private void realupdate() throws Exception { debug("Reconstructing thread " + thr.getId()); /* New top level email added, increase depth level in children messages */ - for (MailMessage msg : thr.getMessages()) { + for (IMailMessage msg : thr.getMessages()) { msg.setDepth(msg.getDepth() + 1); } updatedThreads++; diff --git a/plug-ins/moduleresolver/src/main/java/eu/sqooss/plugins/moduleresolver/ModuleResolver.java b/plug-ins/moduleresolver/src/main/java/eu/sqooss/plugins/moduleresolver/ModuleResolver.java index 78bee23d3..49449f35f 100644 --- a/plug-ins/moduleresolver/src/main/java/eu/sqooss/plugins/moduleresolver/ModuleResolver.java +++ b/plug-ins/moduleresolver/src/main/java/eu/sqooss/plugins/moduleresolver/ModuleResolver.java @@ -7,6 +7,7 @@ import eu.sqooss.core.AlitheiaCore; import eu.sqooss.service.db.DBService; import eu.sqooss.service.db.Directory; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.db.StoredProject; @@ -62,14 +63,14 @@ public void update() throws Exception { if (!db.isDBSessionActive()) db.startDBSession(); pv = db.attachObjectToDBSession(pv); log.info("ModuleResolver: Processing version: " + pv); - for (ProjectFile pf : pv.allDirs()) { + for (IProjectFile pf : pv.allDirs()) { - List pfs = pf.getProjectVersion().getFiles( + List pfs = pf.getProjectVersion().getFiles( Directory.getDirectory(pf.getFileName(), false), ProjectVersion.MASK_FILES); FileTypeMatcher ftm = FileTypeMatcher.getInstance(); - for (ProjectFile f : pfs) { + for (IProjectFile f : pfs) { if ((pf.isModule() == null || pf.isModule() == false) && ftm.getFileType(f.getName()) == FileTypeMatcher.FileType.SRC) { diff --git a/plug-ins/svn/src/main/java/eu/sqooss/plugins/updater/svn/SVNUpdaterImpl.java b/plug-ins/svn/src/main/java/eu/sqooss/plugins/updater/svn/SVNUpdaterImpl.java index 32e1a05a5..655e84b16 100644 --- a/plug-ins/svn/src/main/java/eu/sqooss/plugins/updater/svn/SVNUpdaterImpl.java +++ b/plug-ins/svn/src/main/java/eu/sqooss/plugins/updater/svn/SVNUpdaterImpl.java @@ -43,15 +43,16 @@ import eu.sqooss.core.AlitheiaCore; import eu.sqooss.service.db.Branch; +import eu.sqooss.service.db.ConfigOption; import eu.sqooss.service.db.DBService; import eu.sqooss.service.db.Developer; import eu.sqooss.service.db.Directory; +import eu.sqooss.service.db.IProjectFile; import eu.sqooss.service.db.ProjectFile; import eu.sqooss.service.db.ProjectFileState; import eu.sqooss.service.db.ProjectVersion; import eu.sqooss.service.db.ProjectVersionParent; import eu.sqooss.service.db.StoredProject; -import eu.sqooss.service.db.ConfigOption; import eu.sqooss.service.db.Tag; import eu.sqooss.service.logging.Logger; import eu.sqooss.service.tds.CommitCopyEntry; @@ -119,7 +120,7 @@ private enum HandleCopies { private LRUMap dirCache = new LRUMap(200); /* Container for all project file records for each processed version*/ - private List versionFiles = new ArrayList(); + private List versionFiles = new ArrayList(); /* Currently processed commit log entry*/ private Revision commitLogEntry; @@ -348,6 +349,8 @@ private void init() { this.inclPaths = project.getConfigValues(ConfigOption.PROJECT_SCM_PATHS_INCL); + this.inclPaths = new ArrayList(this.inclPaths); + /* * Based on the assumption that if users do not specify a path to * process then want all paths to be processed. @@ -563,7 +566,7 @@ private void processNormalOps(SCMAccessor scm, Revision entry, * but something else. So we need to check on deletes * whether this name was most recently a directory. */ - ProjectFile lastIncarnation = toAdd.getPreviousFileVersion(); + IProjectFile lastIncarnation = toAdd.getPreviousFileVersion(); /* * If a directory is deleted and its previous incarnation cannot @@ -574,7 +577,7 @@ private void processNormalOps(SCMAccessor scm, Revision entry, */ boolean delAfterCopy = false; if (lastIncarnation == null) { - for (ProjectFile pf : versionFiles) { + for (IProjectFile pf : versionFiles) { if (pf.getFileName().equals(toAdd.getFileName()) && pf.getIsDirectory() && pf.isAdded()) { @@ -616,7 +619,7 @@ private void replayLog(ProjectVersion curVersion) { /*Find duplicate projectfile entries*/ HashMap numOccurs = new HashMap(); - for (ProjectFile pf : versionFiles) { + for (IProjectFile pf : versionFiles) { if (numOccurs.get(pf.getFileName()) != null) { numOccurs.put(pf.getFileName(), numOccurs.get(pf.getFileName()).intValue() + 1); } else { @@ -627,7 +630,7 @@ private void replayLog(ProjectVersion curVersion) { /* Copy list of files to be added to the DB in a tmp array, * to use for iterating */ - List tmpFiles = new ArrayList(); + List tmpFiles = new ArrayList(); tmpFiles.addAll(versionFiles); for (String fpath : numOccurs.keySet()) { @@ -638,10 +641,10 @@ private void replayLog(ProjectVersion curVersion) { int points = 0; - ProjectFile copyFrom = null; - ProjectFile winner = null; + IProjectFile copyFrom = null; + IProjectFile winner = null; - for (ProjectFile f: tmpFiles) { + for (IProjectFile f: tmpFiles) { if (!f.getFileName().equals(fpath)) { continue; @@ -682,10 +685,10 @@ private void replayLog(ProjectVersion curVersion) { */ private void addModifiedDirEntries(ProjectVersion pv) { //Copy list of version files to an immutable object - List chFiles = new ArrayList(this.versionFiles); + List chFiles = new ArrayList(this.versionFiles); - for (ProjectFile pf : chFiles) { - ProjectFile parent = pf.getEnclosingDirectory(); + for (IProjectFile pf : chFiles) { + IProjectFile parent = pf.getEnclosingDirectory(); //Parent dir not in the DB, it should be added in this revision if (parent == null) { @@ -694,7 +697,7 @@ private void addModifiedDirEntries(ProjectVersion pv) { //Check if parent dir exists in this revision's entries boolean exists = false; - for (ProjectFile dir : chFiles) { + for (IProjectFile dir : chFiles) { //Only search directories if (!dir.getIsDirectory()) continue; @@ -716,7 +719,7 @@ private void addModifiedDirEntries(ProjectVersion pv) { * to the project file cache. */ private ProjectFile addFile(ProjectVersion version, String fPath, - ProjectFileState status, SCMNodeType t, ProjectFile copyFrom) { + ProjectFileState status, SCMNodeType t, IProjectFile copyFrom) { ProjectFile pf = new ProjectFile(version); String path = FileUtils.dirname(fPath); @@ -762,7 +765,7 @@ private boolean isCopiedPath(String path) { * * @param pf The project file representing the deleted directory */ - private void handleDirDeletion(ProjectFile pf, ProjectVersion pv) { + private void handleDirDeletion(IProjectFile pf, ProjectVersion pv) { if (pf==null || pv==null) { throw new IllegalArgumentException("ProjectFile or Version is" + @@ -785,9 +788,9 @@ private void handleDirDeletion(ProjectFile pf, ProjectVersion pv) { ProjectVersion prev = pv.getPreviousVersion(); - List files = prev.getFiles(d); + List files = prev.getFiles(d); - for (ProjectFile f : files) { + for (IProjectFile f : files) { if (f.getIsDirectory()) { handleDirDeletion(f, pv); } @@ -797,16 +800,16 @@ private void handleDirDeletion(ProjectFile pf, ProjectVersion pv) { } } - private void handleCopiedDirDeletion(ProjectFile pf) { + private void handleCopiedDirDeletion(IProjectFile pf) { if (pf.getIsDirectory() == false) { warn("handleCopiedDirDeletion: path " + pf.getFileName() + " is not a directory"); return; } - List files = getVersionFilesInDir(pf); + List files = getVersionFilesInDir(pf); - for (ProjectFile f : files) { + for (IProjectFile f : files) { if (f.getIsDirectory()) { handleCopiedDirDeletion(f); } @@ -816,7 +819,7 @@ private void handleCopiedDirDeletion(ProjectFile pf) { } } - private List getVersionFilesInDir(ProjectFile f) { + private List getVersionFilesInDir(IProjectFile f) { if (!f.getIsDirectory()) { warn("getVersionFilesInDir: path " + f.getFileName() + @@ -824,9 +827,9 @@ private List getVersionFilesInDir(ProjectFile f) { return Collections.emptyList(); } - List pfl = new ArrayList(); + List pfl = new ArrayList(); - for (ProjectFile pf : versionFiles) { + for (IProjectFile pf : versionFiles) { if (pf.getDir().getPath().equals(f.getFileName())) { pfl.add(pf); } @@ -839,7 +842,7 @@ private List getVersionFilesInDir(ProjectFile f) { * Handle directory copies */ private void handleDirCopy(ProjectVersion pv, ProjectVersion fromVersion, - Directory from, Directory to, ProjectFile copyFrom) { + Directory from, Directory to, IProjectFile copyFrom) { if (!canProcessCopy(from.getPath(), to.getPath())) return; @@ -847,16 +850,16 @@ private void handleDirCopy(ProjectVersion pv, ProjectVersion fromVersion, addFile(pv, to.getPath(), ProjectFileState.added(), SCMNodeType.DIR, copyFrom); /*Recursively copy directories*/ - List fromPF = fromVersion.getFiles(from, ProjectVersion.MASK_DIRECTORIES); + List fromPF = fromVersion.getFiles(from, ProjectVersion.MASK_DIRECTORIES); - for (ProjectFile f : fromPF) { + for (IProjectFile f : fromPF) { handleDirCopy(pv, fromVersion, getDirectory(f.getFileName(), false), getDirectory(to.getPath() + "/" + f.getName(), true), f); } fromPF = fromVersion.getFiles(from, ProjectVersion.MASK_FILES); - for (ProjectFile f : fromPF) { + for (IProjectFile f : fromPF) { addFile(pv, to.getPath() + "/" + f.getName(), ProjectFileState.added(), SCMNodeType.FILE, f); } @@ -913,9 +916,9 @@ private void updateValidUntil(ProjectVersion pv) { ProjectVersion previous = pv.getPreviousVersion(); - for (ProjectFile pf : versionFiles) { + for (IProjectFile pf : versionFiles) { if (!pf.isAdded()) { - ProjectFile old = pf.getPreviousFileVersion(); + IProjectFile old = pf.getPreviousFileVersion(); old.setValidUntil(previous); }