aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--site-manager/pom.xml25
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java469
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/data/service/DatabaseAccessService.java55
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/data/service/DatabaseAccessServiceImpl.java120
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/IllegalCommandLineArgumentException.java30
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/MissingPropertyException.java31
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/NoMatchingEntryFoundException.java31
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/PropertyFileProcessingException.java35
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/CommandLineHelper.java116
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/Constants.java54
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/ErrorMessages.java76
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/ExtraCommandLineArgument.java138
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/JmxOpProcessor.java71
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/PersistenceUnitPropertiesProvider.java94
-rw-r--r--site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/Printable.java28
-rw-r--r--site-manager/src/test/java/org/onap/policy/common/sitemanager/MainTest.java495
-rw-r--r--site-manager/src/test/java/org/onap/policy/common/sitemanager/MainTestRunner.java73
-rw-r--r--site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/IllegalCommandLineArgumentExceptionTest.java35
-rw-r--r--site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/MissingPropertyExceptionTest.java35
-rw-r--r--site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/NoMatchingEntryFoundExceptionTest.java35
-rw-r--r--site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/PropertyFileProcessingExceptionTest.java35
-rw-r--r--site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/CommandLineHelperTest.java194
-rw-r--r--site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/ExtraCommandLineArgumentTest.java84
-rw-r--r--site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/PersistenceUnitPropertiesProviderTest.java97
-rw-r--r--site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/PrintableImpl.java39
25 files changed, 2151 insertions, 344 deletions
diff --git a/site-manager/pom.xml b/site-manager/pom.xml
index a30be04d..84c38b47 100644
--- a/site-manager/pom.xml
+++ b/site-manager/pom.xml
@@ -19,10 +19,9 @@
============LICENSE_END=========================================================
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
<modelVersion>4.0.0</modelVersion>
<artifactId>site-manager</artifactId>
@@ -76,7 +75,7 @@
<exclude>org.eclipse.persistence:javax.persistence</exclude>
</excludes>
</artifactSet>
- </configuration>
+ </configuration>
</execution>
</executions>
</plugin>
@@ -124,5 +123,21 @@
<artifactId>commons-cli</artifactId>
<version>1.3</version>
</dependency>
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.eclipse.persistence</groupId>
+ <artifactId>eclipselink</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.onap.policy.common</groupId>
+ <artifactId>utils-test</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java
index dcaa26c8..780e14f0 100644
--- a/site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java
@@ -20,50 +20,38 @@
package org.onap.policy.common.sitemanager;
-import java.io.BufferedReader;
-
/*
* Site Manager argument list:
*
- * none - dump help information
- * show - dump information about all nodes
- * ([site, nodetype, resourceName],
- * adminState, opState, availStatus, standbyStatus)
- * The first 3 determine the sort order.
- * setAdminState [ -s <site> | -r <resourceName> ] <new-state>
- * lock [ -s <site> | -r <resourceName> ]
- * unlock [ -s <site> | -r <resourceName> ]
+ * none - dump help information show - dump information about all nodes ([site, nodetype,
+ * resourceName], adminState, opState, availStatus, standbyStatus) The first 3 determine the sort
+ * order. setAdminState [ -s <site> | -r <resourceName> ] <new-state> lock [ -s <site> | -r
+ * <resourceName> ] unlock [ -s <site> | -r <resourceName> ]
*/
-import java.io.File;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Comparator;
+import static org.onap.policy.common.sitemanager.utils.Constants.OPERATIONAL_PERSISTENCE_UNIT;
+import static org.onap.policy.common.sitemanager.utils.Constants.SITE_MANAGER_PROPERTIES_PROPERTY_NAME;
+import static org.onap.policy.common.sitemanager.utils.ErrorMessages.HELP_STRING;
+import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.LOCK;
+import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.SET_ADMIN_STATE;
+import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.UNLOCK;
+import static org.onap.policy.common.sitemanager.utils.JmxOpProcessor.jmxOp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeSet;
-
-import javax.management.JMX;
-import javax.management.ObjectName;
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityTransaction;
-import javax.persistence.Persistence;
-import javax.persistence.TypedQuery;
-
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.DefaultParser;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.onap.policy.common.im.jmx.ComponentAdminMBean;
import org.onap.policy.common.im.jpa.ResourceRegistrationEntity;
import org.onap.policy.common.im.jpa.StateManagementEntity;
+import org.onap.policy.common.sitemanager.data.service.DatabaseAccessService;
+import org.onap.policy.common.sitemanager.data.service.DatabaseAccessServiceImpl;
+import org.onap.policy.common.sitemanager.exception.IllegalCommandLineArgumentException;
+import org.onap.policy.common.sitemanager.exception.MissingPropertyException;
+import org.onap.policy.common.sitemanager.exception.NoMatchingEntryFoundException;
+import org.onap.policy.common.sitemanager.exception.PropertyFileProcessingException;
+import org.onap.policy.common.sitemanager.utils.CommandLineHelper;
+import org.onap.policy.common.sitemanager.utils.PersistenceUnitPropertiesProvider;
+import org.onap.policy.common.sitemanager.utils.Printable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -71,19 +59,6 @@ import org.slf4j.LoggerFactory;
* This class contains the main entry point for Site Manager.
*/
public class Main {
- private static final String SITE_NAME = "site";
-
- private static final String WHERE_R_SITE_SITE = " WHERE r.site = :" + SITE_NAME;
-
- private static final String WHERE_R_RESOURCE_NAME = " WHERE r.resourceName = :";
-
- private static final String RESOURCE_NAME = "resourceName";
-
- private static final String WHERE_S_RESOURCE_NAME = " WHERE s.resourceName = :";
-
- private static final String RESOURCE_REGISTRATION_QUERY = "SELECT r FROM ResourceRegistrationEntity r";
-
- private static final String STATE_MANAGEMENT_QUERY = "SELECT s FROM StateManagementEntity s";
private static final Logger logger = LoggerFactory.getLogger(Main.class.getName());
@@ -96,189 +71,92 @@ public class Main {
/**
* Print out help information regarding command arguments.
*/
- private static void help() {
- System.out.print("Usage:\n" + " siteManager show [ -s <site> | -r <resourceName> ] :\n"
- + " display node information\n"
- + " siteManager setAdminState { -s <site> | -r <resourceName> }" + " <new-state> :\n"
- + " update admin state on selected nodes\n"
- + " siteManager lock { -s <site> | -r <resourceName> } :\n" + " lock selected nodes\n"
- + " siteManager unlock { -s <site> | -r <resourceName> } :\n" + " unlock selected nodes\n");
+ private static String getHelpString() {
+ return HELP_STRING;
}
/**
- * Print out help information regarding the properties file.
+ * This is the main entry point
*
- * @param propertiesFileName the path to the properties file
+ * @param args these are command-line arguments to 'siteManager'
*/
- private static void helpProperties(final String propertiesFileName) {
- if (propertiesFileName == null) {
- // file name not specified (missing system property)
- System.out.print("'siteManager' needs to be passed the system property\n"
- + "'siteManager.properties', which is the file name of a\n"
- + "properties file containing database access information\n\n");
- } else {
- final File file = new File(propertiesFileName);
- if (!file.exists()) {
- // file name specified, but does not exist
- System.out.print("Properties file '" + file.getAbsolutePath() + "' does not exist.\n\n");
- } else {
- // file name specified and does exist -- presumably, the
- // problem is with one or more properties
- System.out.print("One or more missing properties in\n'" + file.getAbsolutePath() + "'.\n\n");
+ public static void main(final String[] args) {
+ final Printable printable = new PrintableImpl();
+ new Main().process(args, printable);
+ }
+
+ public void process(final String[] args, final Printable printable) {
+ try {
+ final CommandLineHelper commandLineHelper = new CommandLineHelper(args, printable);
+
+ if (commandLineHelper.isHelpArgumentSet()) {
+ printable.println(getHelpString());
+ System.exit(0);
}
- }
- System.out.print("The following properties need to be specified:\n\n" + " javax.persistence.jdbc.driver -"
- + " typically 'org.mariadb.jdbc.Driver'\n"
- + " javax.persistence.jdbc.url - URL referring to the database,\n"
- + " which typically has the form:" + " 'jdbc:mariadb://<host>:<port>/<db>'\n"
- + " ('<db>' is probably 'xacml' in this case)\n"
- + " javax.persistence.jdbc.user - the user id for accessing the" + " database\n"
- + " javax.persistence.jdbc.password - password for accessing the" + " database\n");
+ if (!commandLineHelper.isValid()) {
+ printable.println(getHelpString());
+ System.exit(2);
+ }
+ process(commandLineHelper, printable);
+ } catch (final IllegalCommandLineArgumentException illegalCommandLineArgumentException) {
+ printable.println(illegalCommandLineArgumentException.getMessage());
+ printable.println(getHelpString());
+ System.exit(1);
+ } catch (final PropertyFileProcessingException | MissingPropertyException exception) {
+ System.exit(3);
+ } catch (final NoMatchingEntryFoundException exception) {
+ System.exit(4);
+ }
}
- /**
- * This is the main entry point.
- *
- * @param args these are command-line arguments to 'siteManager'
- */
- public static void main(final String[] args) {
- CommandLine cmd = getCommandLine(args);
-
+ private void process(final CommandLineHelper cmd, final Printable printable) {
// fetch options, and remaining arguments
- final String sOption = cmd.getOptionValue('s');
- final String rOption = cmd.getOptionValue('r');
+ final String sOption = cmd.getSite();
+ final String rOption = cmd.getResourceName();
final List<String> argList = cmd.getArgList();
- // a number of commands require either the '-r' option or '-s' option
- final boolean optionLetterSpecified = (rOption != null || sOption != null);
+ final String arg0 = argList.get(0);
- // used to accumulate any error messages that are generated
- final StringBuilder error = new StringBuilder();
+ // read in properties used to access the database
+ final String propertiesFileName = System.getProperty(SITE_MANAGER_PROPERTIES_PROPERTY_NAME);
+ final Properties properties = PersistenceUnitPropertiesProvider.getProperties(propertiesFileName, printable);
- // first non-option argument
- String arg0 = null;
+ try (final DatabaseAccessService accessService =
+ getDatabaseAccessService(OPERATIONAL_PERSISTENCE_UNIT, properties)) {
- if (argList.isEmpty()) {
- error.append("No command specified\n");
- } else {
- arg0 = argList.get(0);
- if ("show".equalsIgnoreCase(arg0)) {
- // show [ -s <site> | -r <resourceName> ]
- if (argList.size() != 1) {
- error.append("show: Extra arguments\n");
- }
- } else if ("setAdminState".equalsIgnoreCase(arg0)) {
- // setAdminState { -s <site> | -r <resourceName> } <new-state>
- switch (argList.size()) {
- case 1:
- error.append("setAdminState: Missing <new-state> value\n");
- break;
- case 2:
- // this is expected
- break;
- default:
- error.append("setAdminState: Extra arguments\n");
- break;
- }
- if (!optionLetterSpecified) {
- error.append("setAdminState: Either '-s' or '-r' option is needed\n");
- }
- } else if ("lock".equalsIgnoreCase(arg0)) {
- // lock { -s <site> | -r <resourceName> }
- if (argList.size() != 1) {
- error.append("lock: Extra arguments\n");
- }
- if (!optionLetterSpecified) {
- error.append("lock: Either '-s' or '-r' option is needed\n");
- }
- } else if ("unlock".equalsIgnoreCase(arg0)) {
- // unlock { -s <site> | -r <resourceName> }
- if (argList.size() != 1) {
- error.append("unlock: Extra arguments\n");
- }
- if (!optionLetterSpecified) {
- error.append("unlock: Either '-s' or '-r' option is needed\n");
- }
- } else {
- error.append(arg0).append(": Unknown command\n");
- }
- }
- if (sOption != null && rOption != null) {
- error.append(arg0).append(": 'r' and 's' options are mutually exclusive\n");
- }
- if (error.length() != 0) {
- // if any errors have occurred, dump out the error string,
- // help information, and exit
- System.out.println(error.toString());
- help();
- System.exit(2);
- }
+ final List<StateManagementEntity> stateManagementResultList =
+ accessService.getStateManagementEntities(rOption, sOption);
+ final List<ResourceRegistrationEntity> resourceRegistrationResultList =
+ accessService.getResourceRegistrationEntities(rOption, sOption);
- // read in properties used to access the database
- final String propertiesFileName = System.getProperty("siteManager.properties");
- final Properties properties = getProperties(propertiesFileName);
-
- // access database through 'EntityManager'
- final EntityManagerFactory emf = Persistence.createEntityManagerFactory("operationalPU", properties);
- final EntityManager em = emf.createEntityManager();
-
- TypedQuery<StateManagementEntity> stateManagementEntityTableQuery;
- TypedQuery<ResourceRegistrationEntity> resourceRegistryEntityTableQuery;
-
- if (rOption != null) {
- // 'resourceName' specified -- both queries are limited to this
- // resource
- stateManagementEntityTableQuery =
- em.createQuery(STATE_MANAGEMENT_QUERY + WHERE_S_RESOURCE_NAME + RESOURCE_NAME,
- StateManagementEntity.class).setParameter(RESOURCE_NAME, rOption);
- resourceRegistryEntityTableQuery =
- em.createQuery(RESOURCE_REGISTRATION_QUERY + WHERE_R_RESOURCE_NAME + RESOURCE_NAME,
- ResourceRegistrationEntity.class).setParameter(RESOURCE_NAME, rOption);
- } else if (sOption != null) {
- // 'site' is specified -- 'ResourceRegistrationEntity' has a 'site'
- // field, but 'StateManagementEntity' does not
- stateManagementEntityTableQuery = em.createQuery(STATE_MANAGEMENT_QUERY, StateManagementEntity.class);
- resourceRegistryEntityTableQuery =
- em.createQuery(RESOURCE_REGISTRATION_QUERY + WHERE_R_SITE_SITE, ResourceRegistrationEntity.class)
- .setParameter(SITE_NAME, sOption);
- } else {
- // query all entries
- stateManagementEntityTableQuery = em.createQuery(STATE_MANAGEMENT_QUERY, StateManagementEntity.class);
- resourceRegistryEntityTableQuery =
- em.createQuery(RESOURCE_REGISTRATION_QUERY, ResourceRegistrationEntity.class);
- }
-
- // perform 'StateManagementEntity' query, and place matching entries
- // in 'stateManagementTable'
- for (final StateManagementEntity stateManagementEntity : stateManagementEntityTableQuery.getResultList()) {
- stateManagementTable.put(stateManagementEntity.getResourceName(), stateManagementEntity);
- }
+ // perform 'StateManagementEntity' query, and place matching entries
+ // in 'stateManagementTable'
+ for (final StateManagementEntity stateManagementEntity : stateManagementResultList) {
+ stateManagementTable.put(stateManagementEntity.getResourceName(), stateManagementEntity);
+ }
- // perform 'ResourceRegistrationQuery', and place matching entries
- // in 'resourceRegistrationTable' ONLY if there is also an associated
- // 'stateManagementTable' entry
- for (final ResourceRegistrationEntity resourceRegistrationEntity : resourceRegistryEntityTableQuery
- .getResultList()) {
- final String resourceName = resourceRegistrationEntity.getResourceName();
- if (stateManagementTable.get(resourceName) != null) {
- // only include entries that have a corresponding
- // state table entry -- silently ignore the rest
- resourceRegistrationTable.put(resourceName, resourceRegistrationEntity);
+ // perform 'ResourceRegistrationQuery', and place matching entries
+ // in 'resourceRegistrationTable' ONLY if there is also an associated
+ // 'stateManagementTable' entry
+ for (final ResourceRegistrationEntity resourceRegistrationEntity : resourceRegistrationResultList) {
+ final String resourceName = resourceRegistrationEntity.getResourceName();
+ if (stateManagementTable.get(resourceName) != null) {
+ // only include entries that have a corresponding
+ // state table entry -- silently ignore the rest
+ resourceRegistrationTable.put(resourceName, resourceRegistrationEntity);
+ }
}
- }
- if (resourceRegistrationTable.size() == 0) {
- System.out.println(arg0 + ": No matching entries");
- System.exit(4);
- }
+ if (resourceRegistrationTable.isEmpty()) {
+ final String message = arg0 + ": No matching entries";
+ printable.println(message);
+ throw new NoMatchingEntryFoundException(message);
+ }
- if ("setAdminState".equalsIgnoreCase(arg0)) {
- // update admin state on all of the nodes
- final String adminState = argList.get(1);
- final EntityTransaction et = em.getTransaction();
- et.begin();
- try {
+ if (SET_ADMIN_STATE.getValue().equalsIgnoreCase(arg0)) {
+ // update admin state on all of the nodes
+ final String adminState = argList.get(1);
// iterate over all matching 'ResourceRegistrationEntity' instances
for (final ResourceRegistrationEntity r : resourceRegistrationTable.values()) {
// we know the corresponding 'StateManagementEntity' exists --
@@ -288,79 +166,44 @@ public class Main {
// update the admin state, and save the changes
s.setAdminState(adminState);
- em.persist(s);
}
- } finally {
- // do the commit
- em.flush();
- et.commit();
- }
- } else if ("lock".equalsIgnoreCase(arg0) || "unlock".equalsIgnoreCase(arg0)) {
- // these use the JMX interface
- for (final ResourceRegistrationEntity r : resourceRegistrationTable.values()) {
- // lock or unlock the entity
- jmxOp(arg0, r);
-
- // change should be reflected in 'adminState'
- em.refresh(stateManagementTable.get(r.getResourceName()));
+ accessService.persist(stateManagementTable.values());
+
+ } else if (LOCK.getValue().equalsIgnoreCase(arg0) || UNLOCK.getValue().equalsIgnoreCase(arg0)) {
+ // these use the JMX interface
+ for (final ResourceRegistrationEntity r : resourceRegistrationTable.values()) {
+ // lock or unlock the entity
+ jmxOp(arg0, r, printable);
+
+ // change should be reflected in 'adminState'
+ accessService.refreshEntity(stateManagementTable.get(r.getResourceName()));
+ }
}
+ } catch (final Exception exception) {
+ printable.println(exception.getMessage());
}
- // free connection to the database
- em.close();
-
// display all entries
display();
}
/**
- * Process a 'lock' or 'unlock' operation on a single 'ResourceRegistrationEntity'.
+ * Compare two strings, either of which may be null
*
- * @param arg0 this is the string "lock" or "unlock"
- * @param resourceRegistrationEntity this is the ResourceRegistrationEntity to lock or unlock
+ * @param first the first string
+ * @param second the second string
+ * @return a negative value if s1<s2, 0 if they are equal, and positive if s1>s2
*/
- static void jmxOp(final String arg0, final ResourceRegistrationEntity resourceRegistrationEntity) {
- final String resourceName = resourceRegistrationEntity.getResourceName();
- final String jmxUrl = resourceRegistrationEntity.getResourceUrl();
- if (jmxUrl == null) {
- System.out.println(arg0 + ": no resource URL for '" + resourceName + "'");
- return;
+ private static int stringCompare(final String first, final String second) {
+ if (first == null ^ second == null) {
+ return (first == null) ? -1 : 1;
}
- JMXConnector connector = null;
- try {
- connector = JMXConnectorFactory.connect(new JMXServiceURL(jmxUrl));
- final ComponentAdminMBean admin = JMX.newMXBeanProxy(connector.getMBeanServerConnection(),
- new ObjectName("ONAP_POLICY_COMP:name=" + resourceName), ComponentAdminMBean.class);
-
- if ("lock".equals(arg0)) {
- admin.lock();
- } else {
- admin.unlock();
- }
- } catch (final Exception e) {
- // e.printStackTrace();
- System.out.println(arg0 + " failed for '" + resourceName + "': " + e);
- } finally {
- if (connector != null) {
- try {
- connector.close();
- } catch (final Exception e) {
- System.err.println(e);
- }
- }
+ if (first == null && second == null) {
+ return 0;
}
- }
- /**
- * Compare two strings, either of which may be null.
- *
- * @param s1 the first string
- * @param s2 the second string
- * @return a negative value if s1 < s2, 0 if they are equal, and positive if s1 > s2
- */
- private static int stringCompare(final String s1, final String s2) {
- return ((s1 == null) ? (s2 == null ? 0 : -1) : (s2 == null ? 1 : s1.compareTo(s2)));
+ return first.compareTo(second);
}
/**
@@ -369,12 +212,11 @@ public class Main {
*
* @param current this is an array of length 7, containing the current maximum lengths of each
* column in the tabular dump
- * @param strings this is an array of length 7, containing the current String entry for each
- * column
+ * @param s this is an array of length 7, containing the current String entry for each column
*/
- private static void updateLengths(final int[] current, final String[] strings) {
+ private static void updateLengths(final int[] current, final String[] s) {
for (int i = 0; i < 7; i += 1) {
- final String str = strings[i];
+ final String str = s[i];
final int newLength = (str == null ? 4 : str.length());
if (current[i] < newLength) {
// this column needs to be expanded
@@ -384,29 +226,25 @@ public class Main {
}
/**
- * Ordered display -- dump out all of the entries.
+ * Ordered display -- dump out all of the entries, in
*/
static void display() {
- final TreeSet<String[]> treeset = new TreeSet<String[]>(new Comparator<String[]>() {
- @Override
- public int compare(final String[] r1, final String[] r2) {
- int rval = 0;
-
- // the first 3 columns are 'Site', 'NodeType', and 'ResourceName',
- // and are used to sort the entries
- for (int i = 0; i < 3; i += 1) {
- if ((rval = stringCompare(r1[i], r2[i])) != 0) {
- break;
- }
- }
- return (rval);
+ final TreeSet<String[]> treeset = new TreeSet<>((final String[] r1, final String[] r2) -> {
+ int rval = 0;
+
+ // the first 3 columns are 'Site', 'NodeType', and 'ResourceName',
+ // and are used to sort the entries
+ for (int i = 0; i < 3; i += 1) {
+ if ((rval = stringCompare(r1[i], r2[i])) != 0)
+ break;
}
+ return (rval);
});
final String[] labels = new String[] {"Site", "NodeType", "ResourceName", "AdminState", "OpState",
- "AvailStatus", "StandbyStatus"};
+ "AvailStatus", "StandbyStatus"};
final String[] underlines = new String[] {"----", "--------", "------------", "----------", "-------",
- "-----------", "-------------"};
+ "-----------", "-------------"};
// each column needs to be at least wide enough to fit the column label
final int[] lengths = new int[7];
@@ -445,62 +283,15 @@ public class Main {
}
}
- private static Properties getProperties(final String propertiesFileName) {
- final File propertiesFile = new File(propertiesFileName);
-
- if (propertiesFileName == null || !propertiesFile.exists()) {
- helpProperties(propertiesFileName);
- System.exit(3);
- }
- final Properties properties = getProperties(propertiesFile.toPath());
-
- // verify that we have all of the properties needed
- if (properties.getProperty("javax.persistence.jdbc.driver") == null
- || properties.getProperty("javax.persistence.jdbc.url") == null
- || properties.getProperty("javax.persistence.jdbc.user") == null
- || properties.getProperty("javax.persistence.jdbc.password") == null) {
- // one or more missing properties
- helpProperties(propertiesFileName);
- System.exit(3);
- }
- return properties;
+ DatabaseAccessService getDatabaseAccessService(final String persistenceUnitName, final Properties properties) {
+ return new DatabaseAccessServiceImpl(persistenceUnitName, properties);
}
- private static Properties getProperties(final Path filePath) {
- final Properties properties = new Properties();
- try (final BufferedReader bufferedReader = Files.newBufferedReader(filePath);) {
- properties.load(bufferedReader);
- } catch (final Exception e) {
- System.out.println("Exception loading properties: " + e);
- helpProperties(filePath.getFileName().toString());
- System.exit(3);
- }
- return properties;
- }
-
- private static CommandLine getCommandLine(final String[] args) {
- final Options options = new Options();
- options.addOption("s", true, "specify site");
- options.addOption("r", true, "specify resource name");
- options.addOption("h", false, "display help");
- options.addOption("?", false, "display help");
-
- // parse options
- final CommandLineParser parser = new DefaultParser();
- CommandLine cmd = null;
-
- try {
- cmd = parser.parse(options, args);
- } catch (final ParseException e) {
- System.out.println(e.getMessage());
- help();
- System.exit(1);
- }
+ private static class PrintableImpl implements Printable {
- if (cmd == null || cmd.getOptionValue('h') != null || cmd.getOptionValue('?') != null) {
- help();
- System.exit(0);
+ @Override
+ public void println(final String value) {
+ System.out.println(value);
}
- return cmd;
}
}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/data/service/DatabaseAccessService.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/data/service/DatabaseAccessService.java
new file mode 100644
index 00000000..513ba174
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/data/service/DatabaseAccessService.java
@@ -0,0 +1,55 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.data.service;
+
+import java.util.Collection;
+import java.util.List;
+import org.onap.policy.common.im.jpa.ResourceRegistrationEntity;
+import org.onap.policy.common.im.jpa.StateManagementEntity;
+
+public interface DatabaseAccessService extends AutoCloseable {
+
+ <T> List<T> execute(final Class<T> clazz, final String query, final String paramName, final String paramValue);
+
+ <T> List<T> execute(final Class<T> clazz, final String query);
+
+ /**
+ * Get {@link StateManagementEntity} entities from database
+ *
+ * @param rOption resource name (optional)
+ * @param sOption site name (optional)
+ * @return list of {@link StateManagementEntity} entities found
+ */
+ List<StateManagementEntity> getStateManagementEntities(final String rOption, final String sOption);
+
+ /**
+ * Get {@link ResourceRegistrationEntity} entities from database
+ *
+ * @param rOption resource name (optional)
+ * @param sOption site name (optional)
+ * @return list of {@link ResourceRegistrationEntity} entities found
+ */
+ List<ResourceRegistrationEntity> getResourceRegistrationEntities(final String rOption, final String sOption);
+
+ <T> void persist(final Collection<T> entities);
+
+ <T> void refreshEntity(final T enity);
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/data/service/DatabaseAccessServiceImpl.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/data/service/DatabaseAccessServiceImpl.java
new file mode 100644
index 00000000..ee98fc29
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/data/service/DatabaseAccessServiceImpl.java
@@ -0,0 +1,120 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.data.service;
+
+import static org.onap.policy.common.sitemanager.utils.Constants.RESOURCE_NAME;
+import static org.onap.policy.common.sitemanager.utils.Constants.RESOURCE_REGISTRATION_QUERY;
+import static org.onap.policy.common.sitemanager.utils.Constants.SITE_NAME;
+import static org.onap.policy.common.sitemanager.utils.Constants.STATE_MANAGEMENT_QUERY;
+import static org.onap.policy.common.sitemanager.utils.Constants.WHERE_R_RESOURCE_NAME;
+import static org.onap.policy.common.sitemanager.utils.Constants.WHERE_R_SITE_NAME;
+import static org.onap.policy.common.sitemanager.utils.Constants.WHERE_S_RESOURCE_NAME;
+import java.util.Collection;
+import java.util.List;
+import java.util.Properties;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import javax.persistence.TypedQuery;
+import org.onap.policy.common.im.jpa.ResourceRegistrationEntity;
+import org.onap.policy.common.im.jpa.StateManagementEntity;
+import org.onap.policy.common.utils.jpa.EntityTransCloser;
+
+public class DatabaseAccessServiceImpl implements DatabaseAccessService {
+
+ private final EntityManagerFactory entityManagerFactory;
+ private EntityManager entityManager;
+
+ public DatabaseAccessServiceImpl(final String persistenceUnitName, final Properties properties) {
+ this.entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName, properties);
+ this.entityManager = entityManagerFactory.createEntityManager();
+ }
+
+ public DatabaseAccessServiceImpl(final EntityManagerFactory entityManagerFactory) {
+ this.entityManagerFactory = entityManagerFactory;
+ this.entityManager = entityManagerFactory.createEntityManager();
+ }
+
+ @Override
+ public <T> List<T> execute(final Class<T> clazz, final String query, final String paramName,
+ final String paramValue) {
+ final TypedQuery<T> typedQuery = entityManager.createQuery(query, clazz);
+ typedQuery.setParameter(paramName, paramValue);
+ return typedQuery.getResultList();
+
+ }
+
+ @Override
+ public <T> List<T> execute(final Class<T> clazz, final String query) {
+ final TypedQuery<T> typedQuery = entityManager.createQuery(query, clazz);
+ return typedQuery.getResultList();
+ }
+
+ @Override
+ public List<StateManagementEntity> getStateManagementEntities(final String rOption, final String sOption) {
+ if (rOption != null) {
+ final String query = STATE_MANAGEMENT_QUERY + WHERE_S_RESOURCE_NAME + RESOURCE_NAME;
+ return execute(StateManagementEntity.class, query, RESOURCE_NAME, rOption);
+ } else if (sOption != null) {
+ return execute(StateManagementEntity.class, STATE_MANAGEMENT_QUERY);
+ }
+ return execute(StateManagementEntity.class, STATE_MANAGEMENT_QUERY);
+
+ }
+
+ @Override
+ public List<ResourceRegistrationEntity> getResourceRegistrationEntities(final String rOption,
+ final String sOption) {
+ if (rOption != null) {
+ final String query = RESOURCE_REGISTRATION_QUERY + WHERE_R_RESOURCE_NAME + RESOURCE_NAME;
+ return execute(ResourceRegistrationEntity.class, query, RESOURCE_NAME, rOption);
+ } else if (sOption != null) {
+ final String query = RESOURCE_REGISTRATION_QUERY + WHERE_R_SITE_NAME + SITE_NAME;
+ return execute(ResourceRegistrationEntity.class, query, SITE_NAME, sOption);
+ }
+ return execute(ResourceRegistrationEntity.class, RESOURCE_REGISTRATION_QUERY);
+ }
+
+ @Override
+ public <T> void persist(final Collection<T> entities) {
+ try (final EntityTransCloser et = new EntityTransCloser(entityManager.getTransaction())) {
+ for (final T entity : entities) {
+ entityManager.persist(entity);
+ }
+ entityManager.flush();
+ et.commit();
+ }
+ }
+
+ @Override
+ public <T> void refreshEntity(final T enity) {
+ entityManager.refresh(enity);
+
+ }
+
+ @Override
+ public void close() {
+ if (entityManager.isOpen()) {
+ entityManager.close();
+ }
+ }
+
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/IllegalCommandLineArgumentException.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/IllegalCommandLineArgumentException.java
new file mode 100644
index 00000000..db374c38
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/IllegalCommandLineArgumentException.java
@@ -0,0 +1,30 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.exception;
+
+public class IllegalCommandLineArgumentException extends RuntimeException {
+
+ private static final long serialVersionUID = 4229478147993769997L;
+
+ public IllegalCommandLineArgumentException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/MissingPropertyException.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/MissingPropertyException.java
new file mode 100644
index 00000000..b5c10883
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/MissingPropertyException.java
@@ -0,0 +1,31 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.exception;
+
+public class MissingPropertyException extends RuntimeException {
+
+ private static final long serialVersionUID = 1224494625143527218L;
+
+ public MissingPropertyException(final String message) {
+ super(message);
+ }
+
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/NoMatchingEntryFoundException.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/NoMatchingEntryFoundException.java
new file mode 100644
index 00000000..f77cdce2
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/NoMatchingEntryFoundException.java
@@ -0,0 +1,31 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.exception;
+
+public class NoMatchingEntryFoundException extends RuntimeException {
+
+ private static final long serialVersionUID = -1118517375170348132L;
+
+ public NoMatchingEntryFoundException(final String message) {
+ super(message);
+ }
+
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/PropertyFileProcessingException.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/PropertyFileProcessingException.java
new file mode 100644
index 00000000..2c4bcb9f
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/exception/PropertyFileProcessingException.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.exception;
+
+public class PropertyFileProcessingException extends RuntimeException {
+
+ private static final long serialVersionUID = 6507640341242930149L;
+
+ public PropertyFileProcessingException(final String message) {
+ super(message);
+ }
+
+ public PropertyFileProcessingException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/CommandLineHelper.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/CommandLineHelper.java
new file mode 100644
index 00000000..58db7bc8
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/CommandLineHelper.java
@@ -0,0 +1,116 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+import java.util.List;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.DefaultParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.onap.policy.common.sitemanager.exception.IllegalCommandLineArgumentException;
+
+public class CommandLineHelper {
+
+ private static final String HELP_QUESTION_MARK_ARGUMENT_NAME = "?";
+
+ private static final String HELP_ARGUMENT_NAME = "h";
+
+ private static final String RESOURCE_ARGUMENT_NAME = "r";
+
+ private static final String SITE_ARGUMENT_NAME = "s";
+
+ private final CommandLine commandLine;
+
+ private static final CommandLineParser PARSER = new DefaultParser();
+
+ private final Printable printable;
+
+ public CommandLineHelper(final String[] args, final Printable printable) {
+ this.commandLine = getCommandLine(getOptions(), args);
+ this.printable = printable;
+ }
+
+ private Options getOptions() {
+ final Options options = new Options();
+ options.addOption(Option.builder(SITE_ARGUMENT_NAME).hasArg(true).desc("specify site").build());
+ options.addOption(Option.builder(RESOURCE_ARGUMENT_NAME).hasArg(true).desc("specify resource name").build());
+ options.addOption(Option.builder(HELP_ARGUMENT_NAME).hasArg(false).desc("display help").build());
+ options.addOption(Option.builder(HELP_QUESTION_MARK_ARGUMENT_NAME).hasArg(false).desc("display help").build());
+
+ return options;
+ }
+
+ public String getSite() {
+ return commandLine.getOptionValue(SITE_ARGUMENT_NAME);
+ }
+
+ public String getResourceName() {
+ return commandLine.getOptionValue(RESOURCE_ARGUMENT_NAME);
+ }
+
+ private CommandLine getCommandLine(final Options options, final String[] args) {
+ try {
+ return PARSER.parse(options, args);
+ } catch (final ParseException | NullPointerException exception) {
+ throw new IllegalCommandLineArgumentException(exception.getMessage(), exception);
+ }
+ }
+
+ public boolean isValid() {
+ // fetch options, and remaining arguments
+ final String sOption = commandLine.getOptionValue(SITE_ARGUMENT_NAME);
+ final String rOption = commandLine.getOptionValue(RESOURCE_ARGUMENT_NAME);
+ final List<String> argList = commandLine.getArgList();
+
+ // a number of commands require either the '-r' option or '-s' option
+ final boolean optionLetterSpecified = (rOption != null || sOption != null);
+
+ if (argList.isEmpty()) {
+ printable.println(ErrorMessages.NO_COMMAND_SPECIFIED);
+ return false;
+ }
+ // a number of commands require either the '-r' option or '-s' option
+ final String arg0 = argList.get(0);
+ final ExtraCommandLineArgument argument = ExtraCommandLineArgument.getExtraCommandLineArgument(arg0);
+
+ if (!argument.isValid(argList, printable, optionLetterSpecified)) {
+ return false;
+ }
+
+ if (sOption != null && rOption != null) {
+ printable.println(arg0 + ErrorMessages.R_AND_S_OPTIONS_ARE_MUTUALLY_EXCLUSIVE);
+ return false;
+ }
+
+ return true;
+ }
+
+ public boolean isHelpArgumentSet() {
+ return commandLine.hasOption(HELP_ARGUMENT_NAME) || commandLine.hasOption(HELP_QUESTION_MARK_ARGUMENT_NAME);
+ }
+
+ public List<String> getArgList() {
+ return commandLine.getArgList();
+ }
+
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/Constants.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/Constants.java
new file mode 100644
index 00000000..0f2d9a49
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/Constants.java
@@ -0,0 +1,54 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+public final class Constants {
+
+ public static final String SITE_NAME = "site";
+
+ public static final String WHERE_R_SITE_NAME = " WHERE r.site = :";
+
+ public static final String WHERE_R_RESOURCE_NAME = " WHERE r.resourceName = :";
+
+ public static final String RESOURCE_NAME = "resourceName";
+
+ public static final String WHERE_S_RESOURCE_NAME = " WHERE s.resourceName = :";
+
+ public static final String RESOURCE_REGISTRATION_QUERY = "SELECT r FROM ResourceRegistrationEntity r";
+
+ public static final String STATE_MANAGEMENT_QUERY = "SELECT s FROM StateManagementEntity s";
+
+ public static final String JDBC_PASSWORD_PROPERTY_NAME = "javax.persistence.jdbc.password";
+
+ public static final String JDBC_USER_PROPERTY_NAME = "javax.persistence.jdbc.user";
+
+ public static final String JDBC_URL_PROPERTY_NAME = "javax.persistence.jdbc.url";
+
+ public static final String JDBC_DRIVER_PROPERTY_NAME = "javax.persistence.jdbc.driver";
+
+ public static final String OPERATIONAL_PERSISTENCE_UNIT = "operationalPU";
+
+ public static final String SITE_MANAGER_PROPERTIES_PROPERTY_NAME = "siteManager.properties";
+
+ private Constants() {
+ super();
+ }
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/ErrorMessages.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/ErrorMessages.java
new file mode 100644
index 00000000..81145462
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/ErrorMessages.java
@@ -0,0 +1,76 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+public class ErrorMessages {
+
+ public static final String EXTRA_ARGUMENTS = "Extra arguments";
+
+ public static final String EITHER_S_OR_R_OPTION_IS_NEEDED = "Either '-s' or '-r' option is needed";
+
+ public static final String R_AND_S_OPTIONS_ARE_MUTUALLY_EXCLUSIVE = ": 'r' and 's' options are mutually exclusive";
+
+ public static final String UNKNOWN_COMMAND = ": Unknown command";
+
+ public static final String UNLOCK_EITHER_S_OR_R_OPTION_IS_NEEDED = "unlock: " + EITHER_S_OR_R_OPTION_IS_NEEDED;
+
+ public static final String UNLOCK_EXTRA_ARGUMENTS = "unlock: " + EXTRA_ARGUMENTS;
+
+ public static final String LOCK_EITHER_S_OR_R_OPTION_IS_NEEDED = "lock: " + EITHER_S_OR_R_OPTION_IS_NEEDED;
+
+ public static final String LOCK_EXTRA_ARGUMENTS = "lock: " + EXTRA_ARGUMENTS;
+
+ public static final String SET_ADMIN_STATE_EITHER_S_OR_R_OPTION_IS_NEEDED =
+ "setAdminState: " + EITHER_S_OR_R_OPTION_IS_NEEDED;
+
+ public static final String SET_ADMIN_STATE_EXTRA_ARGUMENTS = "setAdminState: " + EXTRA_ARGUMENTS;
+
+ public static final String SET_ADMIN_STATE_MISSING_NEW_STATE_VALUE = "setAdminState: Missing <new-state> value";
+
+ public static final String SHOW_EXTRA_ARGUMENTS = "show: " + EXTRA_ARGUMENTS;
+
+ public static final String NO_COMMAND_SPECIFIED = "No command specified";
+
+ public static final String HELP_STRING = "Usage:\n" + " siteManager show [ -s <site> | -r <resourceName> ] :\n"
+ + " display node information\n" + " siteManager setAdminState { -s <site> | -r <resourceName> }"
+ + " <new-state> :\n" + " update admin state on selected nodes\n"
+ + " siteManager lock { -s <site> | -r <resourceName> } :\n" + " lock selected nodes\n"
+ + " siteManager unlock { -s <site> | -r <resourceName> } :\n" + " unlock selected nodes\n";
+
+ public static final String SITE_MANAGER_PROPERY_FILE_MISSING_PROPERTY =
+ "The following properties need to be specified:\n\n" + " javax.persistence.jdbc.driver -"
+ + " typically 'org.mariadb.jdbc.Driver'\n"
+ + " javax.persistence.jdbc.url - URL referring to the database,\n"
+ + " which typically has the form:" + " 'jdbc:mariadb://<host>:<port>/<db>'\n"
+ + " ('<db>' is probably 'xacml' in this case)\n"
+ + " javax.persistence.jdbc.user - the user id for accessing the" + " database\n"
+ + " javax.persistence.jdbc.password - password for accessing the" + " database\n";
+
+ public static final String SITE_MANAGER_PROPERY_FILE_NOT_DEFINED_MESSAGE =
+ "'siteManager' needs to be passed the system property\n"
+ + "'siteManager.properties', which is the file name of a\n"
+ + "properties file containing database access information\n\n";
+
+ private ErrorMessages() {
+ super();
+ }
+
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/ExtraCommandLineArgument.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/ExtraCommandLineArgument.java
new file mode 100644
index 00000000..a28deece
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/ExtraCommandLineArgument.java
@@ -0,0 +1,138 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+import java.util.List;
+
+public enum ExtraCommandLineArgument {
+ SHOW("show") {
+
+ @Override
+ public boolean isValid(final List<String> argList, final Printable printable) {
+ if (argList.size() != 1) {
+ printable.println(ErrorMessages.SHOW_EXTRA_ARGUMENTS);
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public boolean isValid(final List<String> argList, final Printable printable,
+ final boolean optionLetterSpecified) {
+ return isValid(argList, printable);
+ }
+ },
+ SET_ADMIN_STATE("setAdminState") {
+ @Override
+ public boolean isValid(final List<String> argList, final Printable printable,
+ final boolean optionLetterSpecified) {
+ boolean isValid = true;
+ switch (argList.size()) {
+ case 1:
+ printable.println(ErrorMessages.SET_ADMIN_STATE_MISSING_NEW_STATE_VALUE);
+ isValid = false;
+ break;
+ case 2:
+ isValid = true;
+ break;
+ default:
+ printable.println(ErrorMessages.SET_ADMIN_STATE_EXTRA_ARGUMENTS);
+ isValid = false;
+ }
+ if (!optionLetterSpecified) {
+ printable.println(ErrorMessages.SET_ADMIN_STATE_EITHER_S_OR_R_OPTION_IS_NEEDED);
+ return false;
+ }
+
+ return isValid;
+ }
+
+ },
+ LOCK("lock") {
+
+ @Override
+ public boolean isValid(final List<String> argList, final Printable printable,
+ final boolean optionLetterSpecified) {
+ boolean isValid = true;
+ if (argList.size() != 1) {
+ printable.println(ErrorMessages.LOCK_EXTRA_ARGUMENTS);
+ isValid = false;
+ }
+ if (!optionLetterSpecified) {
+ printable.println(ErrorMessages.LOCK_EITHER_S_OR_R_OPTION_IS_NEEDED);
+ isValid = false;
+ }
+ return isValid;
+ }
+ },
+ UNLOCK("unlock") {
+
+ @Override
+ public boolean isValid(final List<String> argList, final Printable printable,
+ final boolean optionLetterSpecified) {
+ boolean isValid = true;
+ if (argList.size() != 1) {
+ printable.println(ErrorMessages.UNLOCK_EXTRA_ARGUMENTS);
+ isValid = false;
+ }
+ if (!optionLetterSpecified) {
+ printable.println(ErrorMessages.UNLOCK_EITHER_S_OR_R_OPTION_IS_NEEDED);
+ isValid = false;
+ }
+ return isValid;
+ }
+ },
+ INVALID("") {
+ @Override
+ public boolean isValid(final List<String> argList, final Printable printable,
+ final boolean optionLetterSpecified) {
+ printable.println(argList.get(0) + ErrorMessages.UNKNOWN_COMMAND);
+ return false;
+ }
+ };
+
+ private final String value;
+
+ private ExtraCommandLineArgument(final String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public static ExtraCommandLineArgument getExtraCommandLineArgument(final String value) {
+ for (final ExtraCommandLineArgument argument : ExtraCommandLineArgument.values()) {
+ if (argument.getValue().equals(value)) {
+ return argument;
+ }
+ }
+ return ExtraCommandLineArgument.INVALID;
+ }
+
+ public boolean isValid(final List<String> argList, final Printable printable) {
+ return isValid(argList, printable, false);
+ }
+
+ public abstract boolean isValid(final List<String> argList, final Printable printable,
+ final boolean optionLetterSpecified);
+
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/JmxOpProcessor.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/JmxOpProcessor.java
new file mode 100644
index 00000000..2e354d3b
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/JmxOpProcessor.java
@@ -0,0 +1,71 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+import java.io.IOException;
+import javax.management.JMX;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
+import org.onap.policy.common.im.IntegrityMonitorException;
+import org.onap.policy.common.im.jmx.ComponentAdminMBean;
+import org.onap.policy.common.im.jpa.ResourceRegistrationEntity;
+
+public class JmxOpProcessor {
+
+ private JmxOpProcessor() {
+ super();
+ }
+
+ /**
+ * Process a 'lock' or 'unlock' operation on a single 'ResourceRegistrationEntity'
+ *
+ * @param action this is the string "lock" or "unlock"
+ * @param resourceRegistrationEntity this is the ResourceRegistrationEntity to lock or unlock
+ */
+ public static void jmxOp(final String action, final ResourceRegistrationEntity resourceRegistrationEntity,
+ final Printable printable) {
+ final String resourceName = resourceRegistrationEntity.getResourceName();
+ final String jmxUrl = resourceRegistrationEntity.getResourceUrl();
+ if (jmxUrl == null) {
+ printable.println(action + ": no resource URL for '" + resourceName + "'");
+ return;
+ }
+
+ try (final JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(jmxUrl))) {
+ final ComponentAdminMBean admin = JMX.newMXBeanProxy(connector.getMBeanServerConnection(),
+ new ObjectName("ONAP_POLICY_COMP:name=" + resourceName), ComponentAdminMBean.class);
+
+ if ("lock".equals(action)) {
+ admin.lock();
+ } else if ("unlock".equals(action)) {
+ admin.unlock();
+ } else {
+ printable.println("Unknown action: " + action);
+ }
+ } catch (final IOException | MalformedObjectNameException | IntegrityMonitorException exception) {
+ printable.println(action + " failed for '" + resourceName + "': " + exception);
+ }
+ }
+
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/PersistenceUnitPropertiesProvider.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/PersistenceUnitPropertiesProvider.java
new file mode 100644
index 00000000..5d7abe7d
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/PersistenceUnitPropertiesProvider.java
@@ -0,0 +1,94 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+import static org.onap.policy.common.sitemanager.utils.Constants.JDBC_DRIVER_PROPERTY_NAME;
+import static org.onap.policy.common.sitemanager.utils.Constants.JDBC_PASSWORD_PROPERTY_NAME;
+import static org.onap.policy.common.sitemanager.utils.Constants.JDBC_URL_PROPERTY_NAME;
+import static org.onap.policy.common.sitemanager.utils.Constants.JDBC_USER_PROPERTY_NAME;
+import static org.onap.policy.common.sitemanager.utils.ErrorMessages.SITE_MANAGER_PROPERY_FILE_MISSING_PROPERTY;
+import static org.onap.policy.common.sitemanager.utils.ErrorMessages.SITE_MANAGER_PROPERY_FILE_NOT_DEFINED_MESSAGE;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Properties;
+import org.onap.policy.common.sitemanager.exception.MissingPropertyException;
+import org.onap.policy.common.sitemanager.exception.PropertyFileProcessingException;
+
+public class PersistenceUnitPropertiesProvider {
+
+ private PersistenceUnitPropertiesProvider() {
+ super();
+ }
+
+ public static Properties getProperties(final String propertiesFileName, final Printable printable) {
+ if (propertiesFileName == null) {
+ printable.println(SITE_MANAGER_PROPERY_FILE_NOT_DEFINED_MESSAGE);
+ printable.println(SITE_MANAGER_PROPERY_FILE_MISSING_PROPERTY);
+ throw new PropertyFileProcessingException("Property file name is null :" + propertiesFileName);
+ }
+
+ final Path filePath = Paths.get(propertiesFileName);
+ final Properties properties = getProperties(filePath, printable);
+
+ // verify that we have all of the properties needed
+ if (isNotValid(properties, JDBC_DRIVER_PROPERTY_NAME, JDBC_URL_PROPERTY_NAME, JDBC_USER_PROPERTY_NAME,
+ JDBC_PASSWORD_PROPERTY_NAME)) {
+ // one or more missing properties
+ printable.println(SITE_MANAGER_PROPERY_FILE_MISSING_PROPERTY);
+ throw new MissingPropertyException("missing mandatory attributes");
+ }
+ return properties;
+ }
+
+ private static boolean isNotValid(final Properties properties, final String... values) {
+ if (values == null || values.length == 0) {
+ return true;
+ }
+ for (final String val : values) {
+ if (properties.get(val) == null) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static Properties getProperties(final Path filePath, final Printable printable) {
+ if (!filePath.toFile().exists()) {
+ printable.println(SITE_MANAGER_PROPERY_FILE_NOT_DEFINED_MESSAGE);
+ printable.println(SITE_MANAGER_PROPERY_FILE_MISSING_PROPERTY);
+ throw new PropertyFileProcessingException("Property file not found");
+ }
+
+ try (final BufferedReader bufferedReader = Files.newBufferedReader(filePath);) {
+ final Properties properties = new Properties();
+ properties.load(bufferedReader);
+ return properties;
+ } catch (final IOException exception) {
+ printable.println("Exception loading properties: " + exception);
+ printable.println(ErrorMessages.SITE_MANAGER_PROPERY_FILE_NOT_DEFINED_MESSAGE);
+ printable.println(ErrorMessages.SITE_MANAGER_PROPERY_FILE_MISSING_PROPERTY);
+ throw new PropertyFileProcessingException("Exception loading properties: ", exception);
+ }
+ }
+}
diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/Printable.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/Printable.java
new file mode 100644
index 00000000..757268a7
--- /dev/null
+++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/utils/Printable.java
@@ -0,0 +1,28 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+@FunctionalInterface
+public interface Printable {
+
+ void println(final String value);
+
+}
diff --git a/site-manager/src/test/java/org/onap/policy/common/sitemanager/MainTest.java b/site-manager/src/test/java/org/onap/policy/common/sitemanager/MainTest.java
new file mode 100644
index 00000000..d8cb5f5f
--- /dev/null
+++ b/site-manager/src/test/java/org/onap/policy/common/sitemanager/MainTest.java
@@ -0,0 +1,495 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.common.sitemanager;
+
+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 java.io.BufferedWriter;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.Persistence;
+import javax.persistence.TypedQuery;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.onap.policy.common.im.jpa.ResourceRegistrationEntity;
+import org.onap.policy.common.im.jpa.StateManagementEntity;
+import org.onap.policy.common.sitemanager.MainTestRunner.ExitCodeTestException;
+import org.onap.policy.common.sitemanager.data.service.DatabaseAccessService;
+import org.onap.policy.common.sitemanager.data.service.DatabaseAccessServiceImpl;
+import org.onap.policy.common.sitemanager.utils.Constants;
+import org.onap.policy.common.sitemanager.utils.ErrorMessages;
+import org.onap.policy.common.sitemanager.utils.PrintableImpl;
+import org.onap.policy.common.utils.jpa.EntityMgrCloser;
+import org.onap.policy.common.utils.jpa.EntityTransCloser;
+
+/**
+ * This class contains the main entry point for Site Manager.
+ */
+public class MainTest {
+
+ private static final String SITE_NAME = "SITE";
+
+ private static final String PROPERTY_FILE_NAME = "siteManagerPropertyFile.properties";
+
+ private static final String RESOURCE_LOCAL = "RESOURCE_LOCAL";
+
+ private static final String DROP_AND_CREATE_TABLES = "drop-and-create-tables";
+
+ private static final String NULL_STRING = "NULL";
+
+ private static final String DATABASE_H2_PLATFORM = "org.eclipse.persistence.platform.database.H2Platform";
+
+ private static final String ECLIPSELINK_ID_VALIDATION = "eclipselink.id-validation";
+
+ private static final String ECLIPSELINK_TARGET_DATABASE = "eclipselink.target-database";
+
+ private static final String DDL_GENERATION = "eclipselink.ddl-generation";
+
+ private static final String TRANSACTION_TYPE = "javax.persistence.transactionType";
+
+ private static final String RESOURCE_NAME = "RESOURCE_NAME";
+
+ private static final String ADMIN_STATE_NEW_VALUE = "NEW_VALUE";
+
+ private static final Date CURRENT_DATE = new Date();
+
+ private static final String COMMENTS = "";
+
+ private static final String DEFAULT_DB_URL_PREFIX = "jdbc:h2:mem:";
+
+ private static final String IN_MEMORY_DB_URL = DEFAULT_DB_URL_PREFIX + "myDb";
+
+ private static final String H2_DB_DRIVER = "org.h2.Driver";
+
+ private final Properties properties = new Properties();
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ private EntityManagerFactory managerFactory;
+
+ private final MainTestRunner testRunner = new MainTestRunner();
+
+ @Before
+ public void setUp() throws Exception {
+
+ properties.put(Constants.JDBC_DRIVER_PROPERTY_NAME, H2_DB_DRIVER);
+ properties.put(Constants.JDBC_URL_PROPERTY_NAME, IN_MEMORY_DB_URL);
+ properties.put(Constants.JDBC_USER_PROPERTY_NAME, "test");
+ properties.put(Constants.JDBC_PASSWORD_PROPERTY_NAME, "test");
+ properties.put(TRANSACTION_TYPE, RESOURCE_LOCAL);
+ properties.put(DDL_GENERATION, DROP_AND_CREATE_TABLES);
+ properties.put(ECLIPSELINK_TARGET_DATABASE, DATABASE_H2_PLATFORM);
+ properties.put(ECLIPSELINK_ID_VALIDATION, NULL_STRING);
+
+ final File file = temporaryFolder.newFile(PROPERTY_FILE_NAME);
+ creatPropertyFile(file, properties);
+ System.setProperty(Constants.SITE_MANAGER_PROPERTIES_PROPERTY_NAME, file.toString());
+ managerFactory = Persistence.createEntityManagerFactory(Constants.OPERATIONAL_PERSISTENCE_UNIT, properties);
+
+ testRunner.setUp();
+ }
+
+ @After
+ public void destroy() {
+ Main.stateManagementTable.clear();
+ Main.resourceRegistrationTable.clear();
+ testRunner.destroy();
+ properties.clear();;
+ if (managerFactory.isOpen()) {
+ managerFactory.close();
+ }
+ }
+
+ @Test
+ public void test_process_initializitonWithOutException() throws IOException {
+
+ persist(managerFactory.createEntityManager(), getStateManagementEntity());
+
+ persist(managerFactory.createEntityManager(), getResourceRegistrationEntity());
+
+ final String[] args = new String[] {"show"};
+ final PrintableImpl printable = new PrintableImpl();
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+
+ assertEquals(1, Main.resourceRegistrationTable.size());
+ assertEquals(1, Main.stateManagementTable.size());
+ assertTrue(printable.getResult().isEmpty());
+
+ }
+
+ @Test
+ public void test_process_setAdminStateWithResourceNameArgument() throws IOException {
+ persist(managerFactory.createEntityManager(), getStateManagementEntity());
+ persist(managerFactory.createEntityManager(), getResourceRegistrationEntity());
+
+ final String[] args = new String[] {"setAdminState", "-r", RESOURCE_NAME, ADMIN_STATE_NEW_VALUE};
+ final PrintableImpl printable = new PrintableImpl();
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+
+ assertEquals(1, Main.resourceRegistrationTable.size());
+ assertEquals(1, Main.stateManagementTable.size());
+ assertTrue(printable.getResult().isEmpty());
+
+ final List<StateManagementEntity> execute = execute(managerFactory.createEntityManager(),
+ StateManagementEntity.class, Constants.STATE_MANAGEMENT_QUERY);
+
+ assertEquals(ADMIN_STATE_NEW_VALUE, execute.get(0).getAdminState());
+
+ }
+
+ @Test
+ public void test_process_setAdminStateWithStateArgument() throws IOException {
+ persist(managerFactory.createEntityManager(), getStateManagementEntity());
+ persist(managerFactory.createEntityManager(), getResourceRegistrationEntity());
+
+ final String[] args = new String[] {"setAdminState", "-s", SITE_NAME, RESOURCE_NAME};
+ final PrintableImpl printable = new PrintableImpl();
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+
+ assertEquals(1, Main.resourceRegistrationTable.size());
+ assertEquals(1, Main.stateManagementTable.size());
+ final List<String> result = printable.getResult();
+ assertTrue(result.isEmpty());
+
+ }
+
+ @Test
+ public void test_process_propertyFileNotAvailable() throws IOException {
+
+ final File file = temporaryFolder.newFile("New" + PROPERTY_FILE_NAME);
+ System.setProperty(Constants.SITE_MANAGER_PROPERTIES_PROPERTY_NAME, file.toString());
+
+ final String[] args = new String[] {"setAdminState", "-s", SITE_NAME, RESOURCE_NAME};
+ final PrintableImpl printable = new PrintableImpl();
+ try {
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+ fail("ExitCodeTestException must be thrown in MainTestRunner class when System.exit() is called in Main class");
+ } catch (final ExitCodeTestException exitCodeTestException) {
+ assertEquals(3, exitCodeTestException.exitCode);
+
+ }
+ assertTrue(Main.stateManagementTable.isEmpty());
+ assertTrue(Main.resourceRegistrationTable.isEmpty());
+ assertFalse(printable.getResult().isEmpty());
+
+ }
+
+ @Test
+ public void test_process_emptyPropertyFile() throws IOException {
+
+ final File file = temporaryFolder.newFile("New" + PROPERTY_FILE_NAME);
+ System.setProperty(Constants.SITE_MANAGER_PROPERTIES_PROPERTY_NAME, file.toString());
+ creatPropertyFile(file, new Properties());
+ final String[] args = new String[] {"setAdminState", "-s", SITE_NAME, RESOURCE_NAME};
+ final PrintableImpl printable = new PrintableImpl();
+ try {
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+ fail("ExitCodeTestException must be thrown in MainTestRunner class when System.exit() is called in Main class");
+ } catch (final ExitCodeTestException exitCodeTestException) {
+ assertEquals(3, exitCodeTestException.exitCode);
+
+ }
+ assertTrue(Main.stateManagementTable.isEmpty());
+ assertTrue(Main.resourceRegistrationTable.isEmpty());
+ assertFalse(printable.getResult().isEmpty());
+
+ }
+
+ @Test
+ public void test_process_MissingAttributesInPropertyFile() throws IOException {
+
+ final File file = temporaryFolder.newFile("New" + PROPERTY_FILE_NAME);
+ System.setProperty(Constants.SITE_MANAGER_PROPERTIES_PROPERTY_NAME, file.toString());
+ final Properties properties = new Properties();
+ properties.put(Constants.JDBC_DRIVER_PROPERTY_NAME, H2_DB_DRIVER);
+ creatPropertyFile(file, properties);
+ final String[] args = new String[] {"setAdminState", "-s", SITE_NAME, RESOURCE_NAME};
+ final PrintableImpl printable = new PrintableImpl();
+ try {
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+ fail("ExitCodeTestException must be thrown in MainTestRunner class when System.exit() is called in Main class");
+ } catch (final ExitCodeTestException exitCodeTestException) {
+ assertEquals(3, exitCodeTestException.exitCode);
+
+ }
+ assertTrue(Main.stateManagementTable.isEmpty());
+ assertTrue(Main.resourceRegistrationTable.isEmpty());
+ assertFalse(printable.getResult().isEmpty());
+
+ }
+
+ @Test
+ public void test_process_MissingOneAttributesInPropertyFile() throws IOException {
+
+ final File file = temporaryFolder.newFile("New" + PROPERTY_FILE_NAME);
+ System.setProperty(Constants.SITE_MANAGER_PROPERTIES_PROPERTY_NAME, file.toString());
+ final Properties properties = new Properties();
+ properties.put(Constants.JDBC_DRIVER_PROPERTY_NAME, H2_DB_DRIVER);
+ properties.put(Constants.JDBC_URL_PROPERTY_NAME, IN_MEMORY_DB_URL);
+ properties.put(Constants.JDBC_USER_PROPERTY_NAME, "test");
+ creatPropertyFile(file, properties);
+ final String[] args = new String[] {"setAdminState", "-s", SITE_NAME, RESOURCE_NAME};
+ final PrintableImpl printable = new PrintableImpl();
+ try {
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+ fail("ExitCodeTestException must be thrown in MainTestRunner class when System.exit() is called in Main class");
+ } catch (final ExitCodeTestException exitCodeTestException) {
+ assertEquals(3, exitCodeTestException.exitCode);
+
+ }
+ assertTrue(Main.stateManagementTable.isEmpty());
+ assertTrue(Main.resourceRegistrationTable.isEmpty());
+ assertFalse(printable.getResult().isEmpty());
+
+ }
+
+ @Test
+ public void test_process_emptyArguments_printError() throws IOException {
+
+ final PrintableImpl printable = new PrintableImpl();
+ try {
+ final String[] args = new String[] {};
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+ fail("ExitCodeTestException must be thrown in MainTestRunner class when System.exit() is called in Main class");
+ } catch (final ExitCodeTestException exitCodeTestException) {
+ assertEquals(2, exitCodeTestException.exitCode);
+
+ }
+
+ assertTrue(Main.stateManagementTable.isEmpty());
+ assertTrue(Main.resourceRegistrationTable.isEmpty());
+ final List<String> actualMessages = printable.getResult();
+ assertFalse(actualMessages.isEmpty());
+
+ assertEquals(Arrays.asList(ErrorMessages.NO_COMMAND_SPECIFIED, ErrorMessages.HELP_STRING), actualMessages);
+
+ }
+
+ @Test
+ public void test_process_nonEmptyWithHelpArguments_printHelp() throws IOException {
+
+ final PrintableImpl printable = new PrintableImpl();
+ try {
+ final String[] args = new String[] {"---", ""};
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+ fail("ExitCodeTestException must be thrown in MainTestRunner class when System.exit() is called in Main class");
+ } catch (final ExitCodeTestException exitCodeTestException) {
+ assertEquals(1, exitCodeTestException.exitCode);
+
+ }
+ assertTrue(Main.stateManagementTable.isEmpty());
+ assertTrue(Main.resourceRegistrationTable.isEmpty());
+ final List<String> actualMessages = printable.getResult();
+ assertFalse(actualMessages.isEmpty());
+ assertEquals(Arrays.asList("Unrecognized option: ---", ErrorMessages.HELP_STRING), actualMessages);
+
+ }
+
+ @Test
+ public void test_process_HelpArguments_printHelp() {
+
+ final PrintableImpl printable = new PrintableImpl();
+ try {
+ final String[] args = new String[] {"-h"};
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+ fail("ExitCodeTestException must be thrown in MainTestRunner class when System.exit() is called in Main class");
+ } catch (final ExitCodeTestException exitCodeTestException) {
+ assertEquals(0, exitCodeTestException.exitCode);
+
+ }
+ assertTrue(Main.stateManagementTable.isEmpty());
+ assertTrue(Main.resourceRegistrationTable.isEmpty());
+ final List<String> actualMessages = printable.getResult();
+ assertFalse(actualMessages.isEmpty());
+ assertEquals(Arrays.asList(ErrorMessages.HELP_STRING), actualMessages);
+
+ }
+
+ @Test
+ public void test_process_missingArguments_printHelpAndErrorMessage() {
+
+ final PrintableImpl printable = new PrintableImpl();
+ try {
+ final String[] args = new String[] {"setAdminState", "-s", RESOURCE_NAME};
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+ fail("ExitCodeTestException must be thrown in MainTestRunner class when System.exit() is called in Main class");
+ } catch (final ExitCodeTestException exitCodeTestException) {
+ assertEquals(2, exitCodeTestException.exitCode);
+
+ }
+ assertTrue(Main.stateManagementTable.isEmpty());
+ assertTrue(Main.resourceRegistrationTable.isEmpty());
+ final List<String> actualMessages = printable.getResult();
+ assertFalse(actualMessages.isEmpty());
+ assertEquals(Arrays.asList(ErrorMessages.SET_ADMIN_STATE_MISSING_NEW_STATE_VALUE, ErrorMessages.HELP_STRING),
+ actualMessages);
+
+ }
+
+ @Test
+ public void test_process_extraShowArguments_printHelpAndErrorMessage() {
+ final String[] args = new String[] {"show", RESOURCE_NAME};
+
+ runAndAssertErrorMessage(args, ErrorMessages.SHOW_EXTRA_ARGUMENTS, ErrorMessages.HELP_STRING);
+ }
+
+ @Test
+ public void test_process_lockShowArguments_printHelpAndErrorMessage() {
+ final String[] args = new String[] {"lock", RESOURCE_NAME};
+
+ runAndAssertErrorMessage(args, ErrorMessages.LOCK_EXTRA_ARGUMENTS,
+ ErrorMessages.LOCK_EITHER_S_OR_R_OPTION_IS_NEEDED, ErrorMessages.HELP_STRING);
+ }
+
+ @Test
+ public void test_process_unknowArguments_printHelpAndErrorMessage() {
+ final String[] args = new String[] {"x", RESOURCE_NAME};
+
+ runAndAssertErrorMessage(args, "x" + ErrorMessages.UNKNOWN_COMMAND, ErrorMessages.HELP_STRING);
+ }
+
+ @Test
+ public void test_process_SetAdminStateArguments_printHelpAndErrorMessage() {
+ final String[] args = new String[] {"setAdminState", RESOURCE_NAME, RESOURCE_NAME};
+
+ runAndAssertErrorMessage(args, ErrorMessages.SET_ADMIN_STATE_EXTRA_ARGUMENTS,
+ ErrorMessages.SET_ADMIN_STATE_EITHER_S_OR_R_OPTION_IS_NEEDED, ErrorMessages.HELP_STRING);
+ }
+
+ @Test
+ public void test_process_SetAdminStateArguments_printHelpAndErrorMessage2() {
+ final String[] args = new String[] {"lock", "-s", SITE_NAME, "-r", RESOURCE_NAME};
+
+ runAndAssertErrorMessage(args, "lock" + ErrorMessages.R_AND_S_OPTIONS_ARE_MUTUALLY_EXCLUSIVE,
+ ErrorMessages.HELP_STRING);
+ }
+
+ @Test
+ public void test_process_unlockShowArguments_printHelpAndErrorMessage() {
+ final String[] args = new String[] {"unlock", RESOURCE_NAME};
+
+ runAndAssertErrorMessage(args, ErrorMessages.UNLOCK_EXTRA_ARGUMENTS,
+ ErrorMessages.UNLOCK_EITHER_S_OR_R_OPTION_IS_NEEDED, ErrorMessages.HELP_STRING);
+ }
+
+ @Test
+ public void test_process_StateAndResourceArguments_printHelpAndErrorMessage() {
+ final String[] args = new String[] {"-s", SITE_NAME, "-r", RESOURCE_NAME};
+
+ runAndAssertErrorMessage(args, ErrorMessages.NO_COMMAND_SPECIFIED, ErrorMessages.HELP_STRING);
+
+ }
+
+ private void runAndAssertErrorMessage(final String[] args, final String... expectedErrorMessages) {
+ final PrintableImpl printable = new PrintableImpl();
+ try {
+ final Main objUnderTest = getMain();
+ objUnderTest.process(args, printable);
+ fail("ExitCodeTestException must be thrown in MainTestRunner class when System.exit() is called in Main class");
+ } catch (final ExitCodeTestException exitCodeTestException) {
+ assertEquals(2, exitCodeTestException.exitCode);
+
+ }
+ assertTrue(Main.stateManagementTable.isEmpty());
+ assertTrue(Main.resourceRegistrationTable.isEmpty());
+ final List<String> actualMessages = printable.getResult();
+ assertFalse(actualMessages.isEmpty());
+ assertEquals(Arrays.asList(expectedErrorMessages), actualMessages);
+ }
+
+ private <T> void persist(final EntityManager entityManager, final T entity) {
+ final EntityTransaction entityTransaction = entityManager.getTransaction();
+ try (final EntityMgrCloser emc = new EntityMgrCloser(entityManager);
+ final EntityTransCloser transaction = new EntityTransCloser(entityTransaction)) {
+ entityManager.persist(entity);
+ transaction.commit();
+ }
+ }
+
+ public <T> List<T> execute(final EntityManager entityManager, final Class<T> clazz, final String query) {
+ try (final EntityMgrCloser entityMgrCloser = new EntityMgrCloser(entityManager);) {
+ final TypedQuery<T> typedQuery = entityManager.createQuery(query, clazz);
+ return typedQuery.getResultList();
+ }
+ }
+
+ private Main getMain() {
+ final Main objUnderTest = new Main() {
+ @Override
+ DatabaseAccessService getDatabaseAccessService(final String persistenceUnitName,
+ final Properties properties) {
+ return new DatabaseAccessServiceImpl(managerFactory);
+ };
+ };
+ return objUnderTest;
+ }
+
+ private StateManagementEntity getStateManagementEntity() {
+ final StateManagementEntity entity = new StateManagementEntity();
+ entity.setModifiedDate(CURRENT_DATE);
+ entity.setAdminState("AdminState");
+ entity.setResourceName(RESOURCE_NAME);
+ entity.setAvailStatus("AvailStatus");
+ entity.setOpState("OpState");
+ entity.setStandbyStatus("StandbyStatus");
+ return entity;
+ }
+
+ private ResourceRegistrationEntity getResourceRegistrationEntity() {
+ final ResourceRegistrationEntity entity = new ResourceRegistrationEntity();
+ entity.setLastUpdated(CURRENT_DATE);
+ entity.setNodeType("NODE_NAME");
+ entity.setResourceName(RESOURCE_NAME);
+ entity.setResourceUrl("/path/to/something");
+ entity.setSite(SITE_NAME);
+ return entity;
+ }
+
+ private void creatPropertyFile(final File file, final Properties properties) throws IOException {
+ try (final BufferedWriter bufferedWriter = Files.newBufferedWriter(file.toPath());) {
+ properties.store(bufferedWriter, COMMENTS);
+ }
+ }
+}
diff --git a/site-manager/src/test/java/org/onap/policy/common/sitemanager/MainTestRunner.java b/site-manager/src/test/java/org/onap/policy/common/sitemanager/MainTestRunner.java
new file mode 100644
index 00000000..f763d4a4
--- /dev/null
+++ b/site-manager/src/test/java/org/onap/policy/common/sitemanager/MainTestRunner.java
@@ -0,0 +1,73 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager;
+
+import java.security.Permission;
+
+public class MainTestRunner {
+
+ private SecurityManager savedSecurityManager;
+ private final ExitCodeSecurityManager exitCodeSecurityManager = new ExitCodeSecurityManager();;
+ private boolean isSetUp = false;
+
+ public void setUp() {
+ if (!isSetUp) {
+ savedSecurityManager = System.getSecurityManager();
+ System.setSecurityManager(exitCodeSecurityManager);
+ isSetUp = true;
+ }
+ }
+
+ public void destroy() {
+ if (isSetUp) {
+ System.setSecurityManager(savedSecurityManager);
+ isSetUp = false;
+ }
+ }
+
+ class ExitCodeTestException extends SecurityException {
+ private static final long serialVersionUID = 2690072276259821984L;
+ public final int exitCode;
+
+ public ExitCodeTestException(final int exitCode) {
+ super("Test specific exit code exception to handle System.exit, value: " + exitCode);
+ this.exitCode = exitCode;
+ }
+ }
+
+ private class ExitCodeSecurityManager extends SecurityManager {
+
+ @Override
+ public void checkPermission(final Permission perm) {
+ }
+
+ @Override
+ public void checkPermission(final Permission perm, final Object context) {
+ }
+
+ @Override
+ public void checkExit(final int status) {
+ super.checkExit(status);
+ throw new ExitCodeTestException(status);
+ }
+
+ }
+}
diff --git a/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/IllegalCommandLineArgumentExceptionTest.java b/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/IllegalCommandLineArgumentExceptionTest.java
new file mode 100644
index 00000000..73a56919
--- /dev/null
+++ b/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/IllegalCommandLineArgumentExceptionTest.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.exception;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+import org.onap.policy.common.sitemanager.exception.IllegalCommandLineArgumentException;
+import org.onap.policy.common.utils.test.ExceptionsTester;
+
+public class IllegalCommandLineArgumentExceptionTest extends ExceptionsTester {
+
+ @Test
+ public void testIllegalCommandLineArgumentException() throws Exception {
+ assertEquals(1, test(IllegalCommandLineArgumentException.class));
+ }
+
+}
diff --git a/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/MissingPropertyExceptionTest.java b/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/MissingPropertyExceptionTest.java
new file mode 100644
index 00000000..7a9963f2
--- /dev/null
+++ b/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/MissingPropertyExceptionTest.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.exception;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+import org.onap.policy.common.sitemanager.exception.MissingPropertyException;
+import org.onap.policy.common.utils.test.ExceptionsTester;
+
+public class MissingPropertyExceptionTest extends ExceptionsTester {
+
+ @Test
+ public void testMissingPropertyException() throws Exception {
+ assertEquals(1, test(MissingPropertyException.class));
+ }
+
+}
diff --git a/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/NoMatchingEntryFoundExceptionTest.java b/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/NoMatchingEntryFoundExceptionTest.java
new file mode 100644
index 00000000..1b7bfa32
--- /dev/null
+++ b/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/NoMatchingEntryFoundExceptionTest.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.exception;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+import org.onap.policy.common.sitemanager.exception.NoMatchingEntryFoundException;
+import org.onap.policy.common.utils.test.ExceptionsTester;
+
+public class NoMatchingEntryFoundExceptionTest extends ExceptionsTester {
+
+ @Test
+ public void testNoMatchingEntryFoundException() throws Exception {
+ assertEquals(1, test(NoMatchingEntryFoundException.class));
+ }
+
+}
diff --git a/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/PropertyFileProcessingExceptionTest.java b/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/PropertyFileProcessingExceptionTest.java
new file mode 100644
index 00000000..5289a816
--- /dev/null
+++ b/site-manager/src/test/java/org/onap/policy/common/sitemanager/exception/PropertyFileProcessingExceptionTest.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.exception;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+import org.onap.policy.common.sitemanager.exception.PropertyFileProcessingException;
+import org.onap.policy.common.utils.test.ExceptionsTester;
+
+public class PropertyFileProcessingExceptionTest extends ExceptionsTester {
+
+ @Test
+ public void testPropertyFileProcessingException() throws Exception {
+ assertEquals(2, test(PropertyFileProcessingException.class));
+ }
+
+}
diff --git a/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/CommandLineHelperTest.java b/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/CommandLineHelperTest.java
new file mode 100644
index 00000000..d15c1dc9
--- /dev/null
+++ b/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/CommandLineHelperTest.java
@@ -0,0 +1,194 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.LOCK;
+import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.SET_ADMIN_STATE;
+import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.SHOW;
+import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.UNLOCK;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import org.junit.Test;
+import org.onap.policy.common.sitemanager.exception.IllegalCommandLineArgumentException;
+
+public class CommandLineHelperTest {
+
+ private static final String STATE_NAME = "STATE_NAME";
+ private static final String RESOURCE_NAME = "RESOURCE_NAME";
+
+ @Test
+ public void test_CommandLineHelper_emptyArgs() throws IOException {
+ final String[] args = new String[] {};
+ final PrintableImpl printable = new PrintableImpl();
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertFalse(objUnderTest.isValid());
+ assertEquals(Arrays.asList(ErrorMessages.NO_COMMAND_SPECIFIED), printable.getResult());
+ }
+
+ @Test
+ public void test_CommandLineHelper_NullArgs() throws IOException {
+ final String[] args = null;
+ final PrintableImpl printable = new PrintableImpl();
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertFalse(objUnderTest.isValid());
+ assertEquals(Arrays.asList(ErrorMessages.NO_COMMAND_SPECIFIED), printable.getResult());
+ }
+
+ @Test
+ public void test_CommandLineHelper_ShowValidArgs() throws IOException {
+ final String[] args = new String[] {SHOW.getValue(), "-s", RESOURCE_NAME};
+ final PrintableImpl printable = new PrintableImpl();
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertTrue(objUnderTest.isValid());
+ assertTrue(printable.getResult().isEmpty());
+ }
+
+ @Test
+ public void test_CommandLineHelper_LockValidArgs() throws IOException {
+ final String[] args = new String[] {LOCK.getValue(), "-s", RESOURCE_NAME};
+ final PrintableImpl printable = new PrintableImpl();
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertTrue(objUnderTest.isValid());
+ assertTrue(printable.getResult().isEmpty());
+ }
+
+ @Test
+ public void test_CommandLineHelper_UnLockValidArgs() throws IOException {
+ final String[] args = new String[] {UNLOCK.getValue(), "-s", RESOURCE_NAME};
+ final PrintableImpl printable = new PrintableImpl();
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertTrue(objUnderTest.isValid());
+ assertTrue(printable.getResult().isEmpty());
+ }
+
+ @Test
+ public void test_CommandLineHelper_SetAdminStateValidArgs() throws IOException {
+ final String[] args = new String[] {SET_ADMIN_STATE.getValue(), RESOURCE_NAME, "-r", RESOURCE_NAME};
+ final PrintableImpl printable = new PrintableImpl();
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertTrue(objUnderTest.isValid());
+ assertTrue(printable.getResult().isEmpty());
+ assertEquals(RESOURCE_NAME, objUnderTest.getResourceName());
+ }
+
+ @Test
+ public void test_CommandLineHelper_SetAdminStateWithStateValidArgs() throws IOException {
+ final String[] args = new String[] {SET_ADMIN_STATE.getValue(), RESOURCE_NAME, "-s", STATE_NAME};
+ final PrintableImpl printable = new PrintableImpl();
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertTrue(objUnderTest.isValid());
+ assertTrue(printable.getResult().isEmpty());
+ assertEquals(STATE_NAME, objUnderTest.getSite());
+
+ assertEquals(Arrays.asList(SET_ADMIN_STATE.getValue(), RESOURCE_NAME), objUnderTest.getArgList());
+ }
+
+ @Test
+ public void test_CommandLineHelper_HelpValidArgs() throws IOException {
+ final String[] args = new String[] {"-h"};
+ final PrintableImpl printable = new PrintableImpl();
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+ assertTrue(objUnderTest.isHelpArgumentSet());
+ }
+
+ @Test(expected = IllegalCommandLineArgumentException.class)
+ public void test_CommandLineHelper_invaidArgs_printHelp() throws IOException {
+
+ final PrintableImpl printable = new PrintableImpl();
+
+ final String[] args = new String[] {"---", ""};
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertFalse(objUnderTest.isValid());
+
+ }
+
+ @Test
+ public void test_CommandLineHelper_invaidArgsMissingAttributes_printHelp() throws IOException {
+
+ final PrintableImpl printable = new PrintableImpl();
+ final String[] args = new String[] {SET_ADMIN_STATE.getValue(), "-s", RESOURCE_NAME};
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertFalse(objUnderTest.isValid());
+ final List<String> actualMessages = printable.getResult();
+
+ assertEquals(Arrays.asList(ErrorMessages.SET_ADMIN_STATE_MISSING_NEW_STATE_VALUE), actualMessages);
+
+ }
+
+ @Test
+ public void test_CommandLineHelper_invaidShowArgsExtraAttributes_printHelp() throws IOException {
+
+ final PrintableImpl printable = new PrintableImpl();
+ final String[] args = new String[] {SHOW.getValue(), RESOURCE_NAME};
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertFalse(objUnderTest.isValid());
+ final List<String> actualMessages = printable.getResult();
+
+ assertEquals(Arrays.asList(ErrorMessages.SHOW_EXTRA_ARGUMENTS), actualMessages);
+
+ }
+
+ @Test
+ public void test_CommandLineHelper_invaidLockArgsExtraAttributes_printHelp() throws IOException {
+
+ final PrintableImpl printable = new PrintableImpl();
+ final String[] args = new String[] {LOCK.getValue(), RESOURCE_NAME};
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertFalse(objUnderTest.isValid());
+ final List<String> actualMessages = printable.getResult();
+
+ assertEquals(
+ Arrays.asList(ErrorMessages.LOCK_EXTRA_ARGUMENTS, ErrorMessages.LOCK_EITHER_S_OR_R_OPTION_IS_NEEDED),
+ actualMessages);
+
+ }
+
+ @Test
+ public void test_CommandLineHelper_invaidUnLockArgsExtraAttributes_printHelp() throws IOException {
+
+ final PrintableImpl printable = new PrintableImpl();
+ final String[] args = new String[] {UNLOCK.getValue(), RESOURCE_NAME};
+ final CommandLineHelper objUnderTest = new CommandLineHelper(args, printable);
+
+ assertFalse(objUnderTest.isValid());
+ final List<String> actualMessages = printable.getResult();
+
+ assertEquals(Arrays.asList(ErrorMessages.UNLOCK_EXTRA_ARGUMENTS,
+ ErrorMessages.UNLOCK_EITHER_S_OR_R_OPTION_IS_NEEDED), actualMessages);
+
+ }
+
+}
diff --git a/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/ExtraCommandLineArgumentTest.java b/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/ExtraCommandLineArgumentTest.java
new file mode 100644
index 00000000..b1b465b7
--- /dev/null
+++ b/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/ExtraCommandLineArgumentTest.java
@@ -0,0 +1,84 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.LOCK;
+import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.SET_ADMIN_STATE;
+import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.SHOW;
+import java.io.IOException;
+import java.util.Arrays;
+import org.junit.Test;
+
+public class ExtraCommandLineArgumentTest {
+
+ private static final String EMPTY_STRING = "";
+ private static final String RESOURCE_NAME = "RESOURCE_NAME";
+
+ @Test
+ public void test_ExtraCommandLineArgument_ShowValidArgs() throws IOException {
+ final PrintableImpl printable = new PrintableImpl();
+
+ final ExtraCommandLineArgument objUnderTest =
+ ExtraCommandLineArgument.getExtraCommandLineArgument(SHOW.getValue());
+
+ assertTrue(objUnderTest.isValid(Arrays.asList(SHOW.getValue()), printable));
+ assertTrue(printable.getResult().isEmpty());
+ }
+
+ @Test
+ public void test_ExtraCommandLineArgument_SetAdminStateValidArgs() throws IOException {
+ final PrintableImpl printable = new PrintableImpl();
+
+ final ExtraCommandLineArgument objUnderTest =
+ ExtraCommandLineArgument.getExtraCommandLineArgument(SET_ADMIN_STATE.getValue());
+
+ assertTrue(objUnderTest.isValid(Arrays.asList(SET_ADMIN_STATE.getValue(), RESOURCE_NAME), printable, true));
+ assertTrue(printable.getResult().isEmpty());
+ }
+
+ @Test
+ public void test_ExtraCommandLineArgument_LockStateValidArgs() throws IOException {
+ final PrintableImpl printable = new PrintableImpl();
+
+ final ExtraCommandLineArgument objUnderTest =
+ ExtraCommandLineArgument.getExtraCommandLineArgument(LOCK.getValue());
+
+ assertTrue(objUnderTest.isValid(Arrays.asList(LOCK.getValue()), printable, true));
+ assertTrue(printable.getResult().isEmpty());
+ }
+
+ @Test
+ public void test_ExtraCommandLineArgument_InValidArgs() throws IOException {
+ final PrintableImpl printable = new PrintableImpl();
+
+ final ExtraCommandLineArgument objUnderTest =
+ ExtraCommandLineArgument.getExtraCommandLineArgument(EMPTY_STRING);
+
+ assertTrue(objUnderTest.equals(ExtraCommandLineArgument.INVALID));
+ assertFalse(objUnderTest.isValid(Arrays.asList(EMPTY_STRING), printable, false));
+ assertFalse(printable.getResult().isEmpty());
+ assertEquals(Arrays.asList(ErrorMessages.UNKNOWN_COMMAND), printable.getResult());
+ }
+
+}
diff --git a/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/PersistenceUnitPropertiesProviderTest.java b/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/PersistenceUnitPropertiesProviderTest.java
new file mode 100644
index 00000000..5f4e4eb1
--- /dev/null
+++ b/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/PersistenceUnitPropertiesProviderTest.java
@@ -0,0 +1,97 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+import static org.junit.Assert.assertEquals;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.Properties;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.onap.policy.common.sitemanager.exception.MissingPropertyException;
+import org.onap.policy.common.sitemanager.exception.PropertyFileProcessingException;
+
+public class PersistenceUnitPropertiesProviderTest {
+ private static final String PROPERTIES_FILE_NAME = "file.properties";
+
+ private static final String COMMENTS = "";
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ @Test(expected = PropertyFileProcessingException.class)
+ public void test_getProperties_null_throwException() {
+ final Printable printable = new PrintableImpl();
+
+ PersistenceUnitPropertiesProvider.getProperties(null, printable);
+ }
+
+ @Test(expected = PropertyFileProcessingException.class)
+ public void test_getProperties_emptyString_throwException() {
+ final Printable printable = new PrintableImpl();
+
+ PersistenceUnitPropertiesProvider.getProperties("", printable);
+ }
+
+ @Test(expected = MissingPropertyException.class)
+ public void test_getProperties_emptyPropertyFile_throwException() throws IOException {
+ final Printable printable = new PrintableImpl();
+ final File file = temporaryFolder.newFile(PROPERTIES_FILE_NAME);
+ creatPropertyFile(file, new Properties());
+ PersistenceUnitPropertiesProvider.getProperties(file.toString(), printable);
+ }
+
+ @Test(expected = MissingPropertyException.class)
+ public void test_getProperties_PropertyFileWithMissingProperties_throwException() throws IOException {
+ final Printable printable = new PrintableImpl();
+ final File file = temporaryFolder.newFile(PROPERTIES_FILE_NAME);
+ final Properties properties = new Properties();
+ properties.put(Constants.JDBC_DRIVER_PROPERTY_NAME, "org.h2");
+ creatPropertyFile(file, properties);
+ PersistenceUnitPropertiesProvider.getProperties(file.toString(), printable);
+ }
+
+ @Test
+ public void test_getProperties_PropertyFileValidProperties_throwException() throws IOException {
+ final Printable printable = new PrintableImpl();
+ final File file = temporaryFolder.newFile(PROPERTIES_FILE_NAME);
+
+ final Properties properties = new Properties();
+ properties.put(Constants.JDBC_DRIVER_PROPERTY_NAME, "Driver");
+ properties.put(Constants.JDBC_URL_PROPERTY_NAME, "inMem:Database");
+ properties.put(Constants.JDBC_USER_PROPERTY_NAME, "test");
+ properties.put(Constants.JDBC_PASSWORD_PROPERTY_NAME, "test");
+ creatPropertyFile(file, properties);
+ final Properties actualProperties = PersistenceUnitPropertiesProvider.getProperties(file.toString(), printable);
+
+ assertEquals(properties, actualProperties);
+ }
+
+ private void creatPropertyFile(final File file, final Properties properties) throws IOException {
+ try (final BufferedWriter bufferedWriter = Files.newBufferedWriter(file.toPath());) {
+ properties.store(bufferedWriter, COMMENTS);
+ }
+ }
+
+}
diff --git a/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/PrintableImpl.java b/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/PrintableImpl.java
new file mode 100644
index 00000000..dd0512fa
--- /dev/null
+++ b/site-manager/src/test/java/org/onap/policy/common/sitemanager/utils/PrintableImpl.java
@@ -0,0 +1,39 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * site-manager
+ * ================================================================================
+ * Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.sitemanager.utils;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class PrintableImpl implements Printable {
+
+ private final List<String> result = new ArrayList<>();
+
+ @Override
+ public void println(final String value) {
+ result.add(value);
+ }
+
+ public List<String> getResult() {
+ return result;
+ }
+
+}