diff options
26 files changed, 682 insertions, 774 deletions
diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/AppcProviderAdapterActivator.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/AppcProviderAdapterActivator.java index 006cb9408..75dadae58 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/AppcProviderAdapterActivator.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/AppcProviderAdapterActivator.java @@ -98,11 +98,11 @@ public class AppcProviderAdapterActivator implements BundleActivator { configuration = ConfigurationFactory.getConfiguration(); String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); logger.info(Msg.COMPONENT_INITIALIZING, appName, "IAAS adapter"); - try{ + try { adapter = new ProviderAdapterImpl(configuration.getProperties()); - }catch(Throwable t){ - logger.error("Error initializing APPC IAAS ProviderAdapterImpl",t); - throw t; + } catch(Exception e){ + logger.error("Error initializing APPC IAAS ProviderAdapterImpl",e); + throw e; } if (registration == null) { diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java index 6dced63b5..4a5d8ea16 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java @@ -190,11 +190,11 @@ public class CreateSnapshot extends ProviderServerOperation { logger.error(msg); metricsLogger.error(msg, e); doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - } catch (Throwable t) { - msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), Operation.SNAPSHOT_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, t); + logger.error(msg, e1); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } } catch (RequestFailedException e) { diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java index 26fbe8d1b..2902ea7e0 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java @@ -263,12 +263,12 @@ public class EvacuateServer extends ProviderServerOperation { doFailure(rc, HttpStatus.NOT_FOUND_404, msg); } catch (RequestFailedException e) { doFailure(rc, e.getStatus(), e.getMessage()); - } catch (Throwable t) { - msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), Operation.EVACUATE_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, t); - metricsLogger.error(msg, t); + logger.error(msg, e1); + metricsLogger.error(msg, e1); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } } catch (RequestFailedException e) { diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/LookupServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/LookupServer.java index eb63f11a1..3d9bc0e39 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/LookupServer.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/LookupServer.java @@ -97,10 +97,11 @@ public class LookupServer extends ProviderServerOperation { //exception closing context String msg = EELFResourceManager.format(Msg.CLOSE_CONTEXT_FAILED, e, vm_url); logger.error(msg); - } catch (Throwable t) { - String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, + e1, e1.getClass().getSimpleName(), Operation.LOOKUP_SERVICE.toString(), vm_url, "Unknown" ); - logger.error(msg, t); + logger.error(msg, e1); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/MigrateServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/MigrateServer.java index 20b4f1061..2ca9e3e4e 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/MigrateServer.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/MigrateServer.java @@ -194,10 +194,10 @@ public class MigrateServer extends ProviderServerOperation { logger.error(msg); metricsLogger.error(msg); doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - } catch (Throwable t) { - msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), MIGRATE_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, t); + logger.error(msg, e1); metricsLogger.error(msg); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RebuildServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RebuildServer.java index a5b9b3fd7..ed219ac67 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RebuildServer.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RebuildServer.java @@ -392,11 +392,11 @@ public class RebuildServer extends ProviderServerOperation { logger.error(msg); metricsLogger.error(msg); doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - } catch (Throwable t) { - msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), STOP_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); ctx.setAttribute("REBUILD_STATUS", "ERROR"); - logger.error(msg, t); + logger.error(msg, e1); metricsLogger.error(msg); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestartServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestartServer.java index dd825f9c9..b57d076e7 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestartServer.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestartServer.java @@ -229,11 +229,11 @@ public class RestartServer extends ProviderServerOperation { logger.error(msg); metricsLogger.error(msg); doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - } catch (Throwable t) { - String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), RESTART_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, t); - metricsLogger.error(msg, t); + logger.error(msg, e1); + metricsLogger.error(msg, e1); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } } catch (RequestFailedException e) { diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestoreStack.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestoreStack.java index 8ce1707ad..24b2471f8 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestoreStack.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestoreStack.java @@ -137,11 +137,12 @@ public class RestoreStack extends ProviderStackOperation { logger.error(EELFResourceManager.format(Msg.MISSING_PARAMETER_IN_REQUEST, e.getReason(), "restoreStack")); doFailure(rc, e.getStatus(), e.getMessage(), e); - } catch (Throwable t) { - String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, + e1, e1.getClass().getSimpleName(), "restoreStack", vm_url, null == context ? "n/a" : context.getTenantName()); - logger.error(msg, t); - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, t); + logger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, e1); } return stack; } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java index 35bbae3ae..07053961a 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java @@ -155,12 +155,13 @@ public class SnapshotStack extends ProviderStackOperation { metricsLogger.error(EELFResourceManager.format(Msg.MISSING_PARAMETER_IN_REQUEST, e.getReason(), "snapshotStack")); doFailure(rc, e.getStatus(), e.getMessage(), e); - } catch (Throwable t) { - String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, + e1, e1.getClass().getSimpleName(), "snapshotStack", vm_url, null == context ? "n/a" : context.getTenantName()); - logger.error(msg, t); + logger.error(msg, e1); metricsLogger.error(msg); - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, t); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, e1); } return stack; } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StartServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StartServer.java index f2186e195..be30a8c46 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StartServer.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StartServer.java @@ -164,10 +164,10 @@ public class StartServer extends ProviderServerOperation { String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); logger.error(msg); doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - } catch (Throwable t) { - String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), START_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, t); + logger.error(msg, e1); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } } catch (RequestFailedException e) { diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StopServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StopServer.java index e5a6e8e4a..fcffa12ce 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StopServer.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StopServer.java @@ -179,10 +179,10 @@ public class StopServer extends ProviderServerOperation { String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); logger.error(msg); doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - } catch (Throwable t) { - String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), STOP_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, t); + logger.error(msg, e1); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } } catch (RequestFailedException e) { diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateServer.java index c6ea1f40f..3f3749a6d 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateServer.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateServer.java @@ -221,10 +221,11 @@ public class TerminateServer extends ProviderServerOperation { logger.error(msg); doFailure(rc, HttpStatus.NOT_FOUND_404, msg); ctx.setAttribute("TERMINATE_STATUS", "SERVER_NOT_FOUND"); - } catch (Throwable t) { - String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), - RESTART_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, t); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, + e1, e1.getClass().getSimpleName(), RESTART_SERVICE.toString(), + vm_url, context == null ? "Unknown" : context.getTenantName()); + logger.error(msg, e1); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } } catch (RequestFailedException e) { diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateStack.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateStack.java index 4a82e160b..7400877e5 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateStack.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateStack.java @@ -107,10 +107,10 @@ public class TerminateStack extends ProviderStackOperation { String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vm_url); logger.error(msg); doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - } catch (Throwable t) { - String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), Operation.TERMINATE_STACK.toString(), vm_url, context.getTenantName()); - logger.error(msg, t); + logger.error(msg, e1); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } } catch (RequestFailedException e) { diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java index e5464302a..5a3e92cf3 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java @@ -136,10 +136,11 @@ public class VmStatuschecker extends ProviderServerOperation { String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); logger.error(msg); doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - } catch (Throwable t) { - String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(), - RESTART_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, t); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, + e1, e1.getClass().getSimpleName(), RESTART_SERVICE.toString(), + vm_url, context == null ? "Unknown" : context.getTenantName()); + logger.error(msg, e1); doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); } } catch (RequestFailedException e) { diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java index d55e3f5c2..04088166d 100644 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java @@ -24,22 +24,19 @@ package org.openecomp.appc.adapter.netconf.internal; -import javax.sql.rowset.CachedRowSet; - +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; import org.openecomp.appc.adapter.netconf.ConnectionDetails; import org.openecomp.appc.adapter.netconf.NetconfConnectionDetails; import org.openecomp.appc.adapter.netconf.NetconfDataAccessService; import org.openecomp.appc.adapter.netconf.exception.DataAccessException; import org.openecomp.appc.adapter.netconf.util.Constants; -import org.openecomp.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; import org.openecomp.sdnc.sli.resource.dblib.DbLibService; +import javax.sql.rowset.CachedRowSet; import java.sql.SQLException; import java.util.ArrayList; - public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { private static EELFLogger logger = EELFManager.getInstance().getLogger(NetconfDataAccessServiceImpl.class); @@ -66,13 +63,11 @@ public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { argList.add(xmlID); try { - final CachedRowSet data = dbLibService.getData(queryString, argList, schema); if (data.first()) { fileContent = data.getString(Constants.FILE_CONTENT_TABLE_FIELD_NAME); } - - } catch (Throwable e) { + } catch (Exception e) { logger.error("Error Accessing Database " + e); throw new DataAccessException(e); } @@ -85,7 +80,8 @@ public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { DataAccessException { boolean recordFound = false; - String queryString = "select " + Constants.USER_NAME_TABLE_FIELD_NAME + "," + Constants.PASSWORD_TABLE_FIELD_NAME + "," + Constants.PORT_NUMBER_TABLE_FIELD_NAME + " " + + String queryString = "select " + Constants.USER_NAME_TABLE_FIELD_NAME + "," + + Constants.PASSWORD_TABLE_FIELD_NAME + "," + Constants.PORT_NUMBER_TABLE_FIELD_NAME + " " + "from " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME + " " + "where " + Constants.VNF_TYPE_TABLE_FIELD_NAME + " = ?"; @@ -93,7 +89,6 @@ public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { argList.add(vnfType); try { - final CachedRowSet data = dbLibService.getData(queryString, argList, schema); if (data.first()) { connectionDetails.setUsername(data.getString(Constants.USER_NAME_TABLE_FIELD_NAME)); @@ -101,7 +96,6 @@ public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { connectionDetails.setPort(data.getInt(Constants.PORT_NUMBER_TABLE_FIELD_NAME)); recordFound = true; } - } catch (SQLException e) { logger.error("Error Accessing Database " + e); throw new DataAccessException(e); @@ -111,9 +105,8 @@ public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { } @Override - public boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) throws - DataAccessException - { + public boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) + throws DataAccessException { ConnectionDetails connDetails = new ConnectionDetails(); if(this.retrieveConnectionDetails(vnfType, connDetails)) { @@ -126,9 +119,8 @@ public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { } @Override - public boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) throws - DataAccessException { - + public boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) + throws DataAccessException { String queryString = "INSERT INTO "+ Constants.DEVICE_INTERFACE_LOG_TABLE_NAME+"("+ Constants.SERVICE_INSTANCE_ID_FIELD_NAME+","+ Constants.REQUEST_ID_FIELD_NAME+","+ @@ -143,9 +135,7 @@ public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { argList.add(logText); try { - dbLibService.writeData(queryString, argList, schema); - } catch (SQLException e) { logger.error("Logging Device interaction failed - "+ queryString); throw new DataAccessException(e); diff --git a/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/AsdcCallback.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/AsdcCallback.java index 345149686..b5307d697 100644 --- a/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/AsdcCallback.java +++ b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/AsdcCallback.java @@ -83,15 +83,16 @@ public class AsdcCallback implements INotificationCallback { BundleContext bctx = FrameworkUtil.getBundle(EventSender.class).getBundleContext(); ServiceReference sref = bctx.getServiceReference(EventSender.class); eventSender = (EventSender) bctx.getService(sref); - } catch (Throwable t) { - logger.error("AsdcCallback failed on initializing EventSender", t); + } catch (Exception e) { + logger.error("AsdcCallback failed on initializing EventSender", e); } } if (isRunning.get()) { for(IArtifactInfo artifact:data.getServiceArtifacts()){ - ArtifactProcessor artifactProcessor = ArtifactProcessorFactory.getArtifactProcessor(client, eventSender, data, null, artifact, storeUri); + ArtifactProcessor artifactProcessor = ArtifactProcessorFactory.getArtifactProcessor( + client, eventSender, data, null, artifact, storeUri); if(artifactProcessor!=null){ executor.submit(artifactProcessor); } diff --git a/appc-asdc-listener/appc-asdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/AsdcCallbackTest.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/AsdcCallbackTest.java index b4ee459f2..3971ec248 100644 --- a/appc-asdc-listener/appc-asdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/AsdcCallbackTest.java +++ b/appc-asdc-listener/appc-asdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/AsdcCallbackTest.java @@ -25,6 +25,7 @@ package org.openecomp.appc.sdc.listener; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; @@ -69,42 +70,45 @@ import java.util.List; ArtifactProcessorFactory.class}) public class AsdcCallbackTest { - IDistributionClient client; + private IDistributionClient client; private EventSender eventSender; private INotificationCallback asdcCallback; private ArtifactStorageService storageService; private ToscaCsarArtifactProcessor artifactProcessor; - @Before public void setup() throws Exception { client = PowerMockito.mock(IDistributionClient.class); eventSender = PowerMockito.mock(EventSender.class); asdcCallback = new AsdcCallback(null,client); - artifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor(client,eventSender,getNotificationData(),getResources().get(0) - ,getServiceArtifacts().get(0),null)); + artifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor( + client, eventSender, getNotificationData(), getResources().get(0), + getServiceArtifacts().get(0),null)); storageService = PowerMockito.mock(ArtifactStorageService.class); Whitebox.setInternalState(artifactProcessor,"artifactStorageService", storageService); - PowerMockito.doCallRealMethod().when(artifactProcessor).processArtifact((IDistributionClientDownloadResult) Matchers.anyObject()); + PowerMockito.doCallRealMethod().when(artifactProcessor) + .processArtifact((IDistributionClientDownloadResult) Matchers.anyObject()); PowerMockito.doCallRealMethod().when(artifactProcessor).run(); - PowerMockito.mockStatic(ArtifactProcessorFactory.class); - PowerMockito.when(ArtifactProcessorFactory.getArtifactProcessor((IDistributionClient)Matchers.anyObject(), (EventSender)Matchers.anyObject(), + PowerMockito.when(ArtifactProcessorFactory.getArtifactProcessor((IDistributionClient)Matchers.anyObject(), + (EventSender)Matchers.anyObject(), (INotificationData)Matchers.anyObject(), (IResourceInstance)Matchers.anyObject(), (IArtifactInfo)Matchers.anyObject(), (URI)Matchers.anyObject())).thenReturn(artifactProcessor); Whitebox.setInternalState(asdcCallback,"eventSender", eventSender); PowerMockito.doReturn(readDownloadResult()).when(client).download((IArtifactInfo) Matchers.anyObject()); - PowerMockito.doReturn(null).when(client).sendDownloadStatus((IDistributionStatusMessage) Matchers.anyObject()); + PowerMockito.doReturn(null).when(client).sendDownloadStatus( + (IDistributionStatusMessage) Matchers.anyObject()); - PowerMockito.doReturn(null).when(storageService).retrieveSDCArtifact(Matchers.anyString(),Matchers.anyString(),Matchers.anyString()); + PowerMockito.doReturn(null).when(storageService).retrieveSDCArtifact(Matchers.anyString(), + Matchers.anyString(), Matchers.anyString()); PowerMockito.doAnswer(new Answer<Object>() { @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { + public Object answer(InvocationOnMock invocationOnMock) throws Exception { System.out.print(invocationOnMock.getArguments()[0].toString()); return null; } @@ -112,7 +116,8 @@ public class AsdcCallbackTest { } private IDistributionClientDownloadResult readDownloadResult() throws IOException, URISyntaxException { - DistributionClientDownloadResultImpl downloadResult = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS,"Download success"); + DistributionClientDownloadResultImpl downloadResult = new DistributionClientDownloadResultImpl( + DistributionActionResultEnum.SUCCESS,"Download success"); File file = new File(this.getClass().getResource("/csar/service-ServiceAppc-csar.csar").toURI()); byte[] bFile = new byte[(int) file.length()]; @@ -124,14 +129,12 @@ public class AsdcCallbackTest { return downloadResult; } - -// @Test - public void testASDCListener() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { - - + @Ignore + @Test + public void testASDCListener() + throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { INotificationData notificationData = getNotificationData(); asdcCallback.activateCallback(notificationData); - // pause(); } @@ -143,9 +146,11 @@ public class AsdcCallbackTest { // } // } - private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { + private INotificationData getNotificationData() + throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { - INotificationData notificationData = (INotificationData)getObject("org.openecomp.sdc.impl.NotificationDataImpl"); + INotificationData notificationData = (INotificationData)getObject( + "org.openecomp.sdc.impl.NotificationDataImpl"); List<IArtifactInfo> serviceArtifacts = getServiceArtifacts(); @@ -153,9 +158,11 @@ public class AsdcCallbackTest { return notificationData; } - private List<IResourceInstance> getResources() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { + private List<IResourceInstance> getResources() + throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { List<IResourceInstance> resources = new ArrayList<>(); - IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance"); + IResourceInstance resource = (IResourceInstance)getObject( + "org.openecomp.sdc.impl.JsonContainerResourceInstance"); List<IArtifactInfo> serviceArtifacts = getServiceArtifacts(); invokeMethod(resource,"setArtifacts",serviceArtifacts); @@ -166,7 +173,8 @@ public class AsdcCallbackTest { return resources; } - private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException { + private void invokeMethod(Object object, String methodName,Object... arguments) + throws IllegalAccessException, InvocationTargetException { Method[] methods = object.getClass().getDeclaredMethods(); for(Method method:methods){ if(methodName.equalsIgnoreCase(method.getName())){ @@ -176,13 +184,15 @@ public class AsdcCallbackTest { } } - private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { + private Object getObject(String fqcn) + throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { Constructor constructor = Class.forName(fqcn).getDeclaredConstructors()[0]; constructor.setAccessible(true); return constructor.newInstance(); } - private List<IArtifactInfo> getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { + private List<IArtifactInfo> getServiceArtifacts() + throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { List<IArtifactInfo> serviceArtifacts = new ArrayList<>(); IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR"); diff --git a/appc-common/src/main/java/org/openecomp/appc/configuration/DefaultConfiguration.java b/appc-common/src/main/java/org/openecomp/appc/configuration/DefaultConfiguration.java index 9ec7dc09c..96d9be86c 100644 --- a/appc-common/src/main/java/org/openecomp/appc/configuration/DefaultConfiguration.java +++ b/appc-common/src/main/java/org/openecomp/appc/configuration/DefaultConfiguration.java @@ -25,7 +25,6 @@ package org.openecomp.appc.configuration; - import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -50,8 +49,8 @@ import org.slf4j.LoggerFactory; * This class provides the implementation of the <code>Configuration</code> interface. It is created by the * ConfigurationFactory and initialized with the configuration values for the process. * - * @since Mar 18, 2014 * @version $Id$ + * @since Mar 18, 2014 */ public final class DefaultConfiguration implements Configuration, Cloneable { @@ -66,6 +65,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * Construct the configuration object. */ public DefaultConfiguration() { + // do nothing } /** @@ -92,8 +92,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * Decrypts an encrypted value, if it is encrypted, and returns the clear text. Performs no operation on the string * if it is not encrypted. * - * @param value - * The value to (optionally) be decrypted + * @param value The value to (optionally) be decrypted * @return The clear text */ @SuppressWarnings("nls") @@ -102,17 +101,16 @@ public final class DefaultConfiguration implements Configuration, Cloneable { if (value.startsWith(EncryptionTool.ENCRYPTED_VALUE_PREFIX)) { try { return EncryptionTool.getInstance().decrypt(value); - } catch (Throwable e) { - String out = ""; + } catch (Exception e) { + StringBuilder out = new StringBuilder(); for (Provider p : Security.getProviders()) { for (Service s : p.getServices()) { String algo = s.getAlgorithm(); - out += - String.format("\n==Found Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, - p.getName(), s.getClassName()); + out.append(String.format("\n==Found Algorithm [ %s ] in provider [ %s ] and service [ %s ]", + algo, p.getName(), s.getClassName())); } } - logger.debug(out); + logger.debug(out.toString()); logger.warn(String.format("Could not decrypt the configuration value [%s]", value), e); } } @@ -139,23 +137,20 @@ public final class DefaultConfiguration implements Configuration, Cloneable { @Override public boolean equals(Object obj) { - if( obj == null ) { + if (obj == null) { return false; } - if( this.getClass() != obj.getClass() ) { + if (this.getClass() != obj.getClass()) { return false; } DefaultConfiguration other = (DefaultConfiguration) obj; - if ((this.properties.size() == other.properties.size()) - && (this.properties.entrySet().containsAll(other.properties.entrySet())) - && (other.properties.entrySet().containsAll(this.properties.entrySet()))) { - return true; - } + return (this.properties.size() == other.properties.size()) + && (this.properties.entrySet().containsAll(other.properties.entrySet())) + && (other.properties.entrySet().containsAll(this.properties.entrySet())); - return false; } /** @@ -164,14 +159,13 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * current configuration object, or system properties if undefined. If the value cannot be found, the variable is * removed and an empty string is used to replace the variable. * - * @param template - * The template to be expanded + * @param template The template to be expanded * @return The expanded template where each variable is replaced with its value */ @SuppressWarnings("nls") private String expandVariables(String template) { if (template == null) { - return template; + return null; } // Decrypt the template if needed @@ -201,24 +195,21 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for * Boolean.parseBoolean() are used. * - * @param key - * The property key + * @param key The property key * @return The value of the property expressed as a boolean, or false if it does not exist. */ @SuppressWarnings("nls") @Override public boolean getBooleanProperty(String key) { - return Boolean.valueOf(getProperty(key, "false")).booleanValue(); + return Boolean.valueOf(getProperty(key, "false")); } /** * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for * Boolean.valueOf(String) are used. * - * @param key - * The property key - * @param defaultValue - * The default value to be returned if the property does not exist + * @param key The property key + * @param defaultValue The default value to be returned if the property does not exist * @return The value of the property expressed as a boolean, or false if it does not exist. * @see org.openecomp.appc.configuration.Configuration#getBooleanProperty(java.lang.String, boolean) */ @@ -233,8 +224,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * Returns the indicated property value expressed as a floating point double-precision value (double). * - * @param key - * The property to retrieve + * @param key The property to retrieve * @return The value of the property, or 0.0 if not found * @see org.openecomp.appc.configuration.Configuration#getDoubleProperty(java.lang.String) */ @@ -242,7 +232,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { @Override public double getDoubleProperty(String key) { try { - return Double.valueOf(getProperty(key, "0.0")).doubleValue(); + return Double.valueOf(getProperty(key, "0.0")); } catch (NumberFormatException e) { return 0.0; } @@ -251,10 +241,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * This method is called to obtain a property as a string value * - * @param key - * The key of the property - * @param defaultValue - * The default value to be returned if the property does not exist + * @param key The key of the property + * @param defaultValue The default value to be returned if the property does not exist * @return The string value, or null if it does not exist. * @see org.openecomp.appc.configuration.Configuration#getDoubleProperty(java.lang.String, double) */ @@ -270,9 +258,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * Returns the property indicated expressed as an integer. The standard rules for * {@link Integer#parseInt(String, int)} using a radix of 10 are used. * - * @param key - * The property name to retrieve. - * @returns The value of the property, or 0 if it does not exist or is invalid. + * @param key The property name to retrieve. + * @return The value of the property, or 0 if it does not exist or is invalid. * @see org.openecomp.appc.configuration.Configuration#getIntegerProperty(java.lang.String) */ @SuppressWarnings("nls") @@ -289,10 +276,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * Returns the property indicated expressed as an integer. The standard rules for Integer.parseInt(String, int) * using a radix of 10 are used. * - * @param key - * The property name to retrieve. - * @param defaultValue - * The default value to be returned if the property does not exist + * @param key The property name to retrieve. + * @param defaultValue The default value to be returned if the property does not exist * @return The value of the property, or 0 if it does not exist or is invalid. * @see org.openecomp.appc.configuration.Configuration#getIntegerProperty(java.lang.String, int) */ @@ -307,10 +292,9 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * Returns the specified property as a long integer value, if it exists, or zero if it does not. * - * @param key - * The key of the property desired. + * @param key The key of the property desired. * @return The value of the property expressed as an integer long value, or zero if the property does not exist or - * is not a valid integer long. + * is not a valid integer long. * @see org.openecomp.appc.configuration.Configuration#getLongProperty(java.lang.String) */ @SuppressWarnings("nls") @@ -327,12 +311,10 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * Returns the specified property as a long integer value, if it exists, or the default value if it does not exist * or is invalid. * - * @param key - * The key of the property desired. - * @param defaultValue - * the value to be returned if the property is not valid or does not exist. + * @param key The key of the property desired. + * @param defaultValue the value to be returned if the property is not valid or does not exist. * @return The value of the property expressed as an integer long value, or the default value if the property does - * not exist or is not a valid integer long. + * not exist or is not a valid integer long. * @see org.openecomp.appc.configuration.Configuration#getLongProperty(java.lang.String, long) */ @Override @@ -359,8 +341,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * This method is called to obtain a property as a string value * - * @param key - * The key of the property + * @param key The key of the property * @return The string value, or null if it does not exist. */ @Override @@ -375,10 +356,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * This method is called to obtain a property as a string value * - * @param key - * The key of the property - * @param defaultValue - * The default value to be returned if the property does not exist + * @param key The key of the property + * @param defaultValue The default value to be returned if the property does not exist * @return The string value, or null if it does not exist. * @see org.openecomp.appc.configuration.Configuration#getProperty(java.lang.String, java.lang.String) */ @@ -406,8 +385,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * Returns true if the named property is defined, false otherwise. * - * @param key - * The key of the property we are interested in + * @param key The key of the property we are interested in * @return True if the property exists. */ @Override @@ -419,9 +397,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * Returns an indication of the validity of the boolean property. A boolean property is considered to be valid only * if it has the value "true" or "false" (ignoring case). * - * @param key - * The property to be checked - * @returns True if the value is a boolean constant, or false if it does not exist or is not a correct string + * @param key The property to be checked + * @return True if the value is a boolean constant, or false if it does not exist or is not a correct string * @see org.openecomp.appc.configuration.Configuration#isValidBoolean(java.lang.String) */ @SuppressWarnings("nls") @@ -438,10 +415,9 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * Returns an indication if the indicated property represents a valid double-precision floating point number. * - * @param key - * The property to be examined - * @returns True if the property is a valid representation of a double, or false if it does not exist or contains - * illegal characters. + * @param key The property to be examined + * @return True if the property is a valid representation of a double, or false if it does not exist or contains + * illegal characters. * @see org.openecomp.appc.configuration.Configuration#isValidDouble(java.lang.String) */ @Override @@ -461,10 +437,9 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * Returns an indication if the property is a valid integer value or not. * - * @param key - * The key of the property to check - * @returns True if the value is a valid integer string, or false if it does not exist or contains illegal - * characters. + * @param key The key of the property to check + * @return True if the value is a valid integer string, or false if it does not exist or contains illegal + * characters. * @see org.openecomp.appc.configuration.Configuration#isValidInteger(java.lang.String) */ @Override @@ -484,10 +459,9 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * Determines is the specified property exists and is a valid representation of an integer long value. * - * @param key - * The property to be checked + * @param key The property to be checked * @return True if the property is a valid representation of an integer long value, and false if it either does not - * exist or is not valid. + * exist or is not valid. * @see org.openecomp.appc.configuration.Configuration#isValidLong(java.lang.String) */ @Override @@ -507,8 +481,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * This method allows an implementation to load configuration properties that may override default values. * - * @param is - * An input stream that contains the properties to be loaded + * @param is An input stream that contains the properties to be loaded */ public void setProperties(InputStream is) { try { @@ -521,9 +494,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * This method allows an implementation to load configuration properties that may override default values. * - * @param props - * An optional Properties object to be merged into the configuration, replacing any same-named - * properties. + * @param props An optional Properties object to be merged into the configuration, replacing any same-named + * properties. * @see org.openecomp.appc.configuration.Configuration#setProperties(java.util.Properties) */ @Override @@ -537,10 +509,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * application to adjust or add to the current configuration. If the property already exists, it is replaced with * the new value. * - * @param key - * The key of the property to be defined - * @param value - * The value of the property to be defined + * @param key The key of the property to be defined + * @param value The value of the property to be defined * @see org.openecomp.appc.configuration.Configuration#setProperty(java.lang.String, java.lang.String) */ @Override @@ -555,7 +525,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { @Override public String toString() { return String.format("Configuration: %d properties, keys:[%s]", properties.size(), properties.keySet() - .toString()); + .toString()); } /** @@ -566,7 +536,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * @return The manifest object from the jar file, or null if the code is not packaged in a jar file. */ @SuppressWarnings({ - "unused", "nls" + "unused", "nls" }) private Manifest getManifest() { ProtectionDomain domain = getClass().getProtectionDomain(); diff --git a/appc-common/src/main/java/org/openecomp/appc/pool/CachedElement.java b/appc-common/src/main/java/org/openecomp/appc/pool/CachedElement.java index e5456114d..d2b3c0a9f 100644 --- a/appc-common/src/main/java/org/openecomp/appc/pool/CachedElement.java +++ b/appc-common/src/main/java/org/openecomp/appc/pool/CachedElement.java @@ -171,23 +171,27 @@ public class CachedElement<T extends Closeable> implements Closeable, Invocation "unchecked", "nls" }) @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) throws Exception { Object result = null; - if (method.getName().equals("close")) { - if (released.compareAndSet(false, true)) { - if (!pool.isDrained()) { - pool.release((T) proxy); + switch (method.getName()) { + case "close": + if (released.compareAndSet(false, true)) { + if (!pool.isDrained()) { + pool.release((T) proxy); + } } - } - } else if (method.getName().equals("equals")) { - CacheManagement cm = (CacheManagement) proxy; - T other = (T) cm.getWrappedObject(); - result = element.equals(other); - } else if (method.getName().equals("getWrappedObject")) { - return element; - } else { - result = method.invoke(element, args); + break; + case "equals": + CacheManagement cm = (CacheManagement) proxy; + T other = (T) cm.getWrappedObject(); + result = element.equals(other); + break; + case "getWrappedObject": + return element; + default: + result = method.invoke(element, args); + break; } return result; diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/CommandExecutionTaskTest.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/CommandExecutionTaskTest.java new file mode 100644 index 000000000..a46202c1b --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/CommandExecutionTaskTest.java @@ -0,0 +1,295 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.executor; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.openecomp.appc.domainmodel.lcm.ActionIdentifiers; +import org.openecomp.appc.domainmodel.lcm.CommonHeader; +import org.openecomp.appc.domainmodel.lcm.Flags; +import org.openecomp.appc.domainmodel.lcm.RequestContext; +import org.openecomp.appc.domainmodel.lcm.ResponseContext; +import org.openecomp.appc.domainmodel.lcm.RuntimeContext; +import org.openecomp.appc.domainmodel.lcm.Status; +import org.openecomp.appc.domainmodel.lcm.VNFContext; +import org.openecomp.appc.domainmodel.lcm.VNFOperation; +import org.openecomp.appc.executor.impl.CommandTask; +import org.openecomp.appc.executor.impl.CommandTaskFactory; +import org.openecomp.appc.executor.impl.LCMCommandTask; +import org.openecomp.appc.executor.impl.LCMReadonlyCommandTask; +import org.openecomp.appc.executor.objects.CommandResponse; +import org.openecomp.appc.lifecyclemanager.LifecycleManager; +import org.openecomp.appc.requesthandler.RequestHandler; +import org.openecomp.appc.workflow.WorkFlowManager; +import org.openecomp.appc.workflow.objects.WorkflowResponse; +import org.openecomp.sdnc.sli.SvcLogicContext; +import org.openecomp.sdnc.sli.SvcLogicException; +import org.openecomp.sdnc.sli.SvcLogicResource; +import org.openecomp.sdnc.sli.aai.AAIService; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.time.Instant; + +import static junit.framework.Assert.assertEquals; +import static org.mockito.Matchers.*; + +@SuppressWarnings("unchecked") +@RunWith(PowerMockRunner.class) +@PrepareForTest( {FrameworkUtil.class, CommandTask.class, LCMCommandTask.class}) +public class CommandExecutionTaskTest { + + private final String TTL_FLAG= "TTL"; + private final String API_VERSION= "2.0.0"; + private final String ORIGINATOR_ID= "1"; + private CommandTaskFactory factory ; + + private RequestHandler requestHandler; + private WorkFlowManager workflowManager; + private AAIService aaiService; + private LifecycleManager lifecyclemanager; + + private final BundleContext bundleContext=Mockito.mock(BundleContext.class); + private final Bundle bundleService=Mockito.mock(Bundle.class); + private final ServiceReference sref=Mockito.mock(ServiceReference.class); + + @Before + public void init() throws SvcLogicException { + + // *** + AAIService aaiService = Mockito.mock(AAIService.class); + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService); + PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref); + PowerMockito.when(bundleContext.<AAIService>getService(sref)).thenReturn(aaiService); + PowerMockito.when(aaiService.query(anyString(),anyBoolean(),anyString(),anyString(),anyString(), + anyString(), anyObject())).thenAnswer(invocation -> { + Object[] args = invocation.getArguments(); + SvcLogicContext ctx =(SvcLogicContext)args[6]; + String prefix = (String)args[4]; + String key = (String)args[3]; + if(key.contains("'28'")){ + return SvcLogicResource.QueryStatus.FAILURE ; + }else if ( key.contains("'8'")) { + return SvcLogicResource.QueryStatus.NOT_FOUND ; + }else { + ctx.setAttribute(prefix + ".vnf-type", "FIREWALL"); + ctx.setAttribute(prefix + ".orchestration-status", "INSTANTIATED"); + } + return SvcLogicResource.QueryStatus.SUCCESS ; + }); + PowerMockito.when(aaiService.update(anyString(), anyString(), anyObject(), anyString(), + anyObject())).thenReturn(SvcLogicResource.QueryStatus.SUCCESS); + + requestHandler = Mockito.mock(RequestHandler.class); + workflowManager = Mockito.mock(WorkFlowManager.class); + lifecyclemanager = Mockito.mock(LifecycleManager.class ); + + factory = new CommandTaskFactory(); + factory.setLifecyclemanager(lifecyclemanager); + factory.setWorkflowManager(workflowManager); + factory.setVnfRequestHandler(requestHandler); + Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse ()); + } + + + @Test + public void testFactory(){ + CommandTask task; + Instant timeStamp = Instant.now(); + String requestId = "1"; + RuntimeContext commandExecutorInputConfigure = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure,"15","") ; + task = factory.getExecutionTask(commandExecutorInputConfigure); + assertEquals(LCMCommandTask.class,task.getClass() ); + RuntimeContext commandExecutorInputSync = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ; + task = factory.getExecutionTask(commandExecutorInputSync); + assertEquals(LCMReadonlyCommandTask.class,task.getClass() ); + + } + + + + @Test + public void testOnRequestCompletion(){ + Mockito.doNothing().when(requestHandler).onRequestTTLEnd(anyObject(),anyBoolean()); + RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Configure, + "1", ""); + CommandResponse response = getCommandResponse(VNFOperation.Configure, true, "11", + "","1"); + LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); + executionTask.onRequestCompletion(response); + } + + @Test + public void testRunGetConfig(){ + RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, + "1", ""); + LCMReadonlyCommandTask readonlyCommandTask = new LCMReadonlyCommandTask( + request, requestHandler,workflowManager); + readonlyCommandTask.run(); + } + + @Test + public void testRun(){ + RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, + "1", ""); + LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); + executionTask.run(); + } + + @Test + public void testRunNegative(){ + RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, + "1", ""); + LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); + executionTask.run(); + } + + + private CommandResponse getCommandResponse(VNFOperation action, + boolean success, + String responseId, + String payload, + String vnfId){ + RuntimeContext runtimeContext = new RuntimeContext(); + ResponseContext responseContext = new ResponseContext(); + runtimeContext.setResponseContext(responseContext); + RequestContext requestContext = new RequestContext(); + runtimeContext.setRequestContext(requestContext); + CommonHeader commonHeader = new CommonHeader(); + requestContext.setCommonHeader(commonHeader); + responseContext.setCommonHeader(commonHeader); + commonHeader.setFlags(new Flags(null, false, 0)); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + requestContext.setActionIdentifiers(actionIdentifiers); + VNFContext vnfContext = new VNFContext(); + runtimeContext.setVnfContext(vnfContext); + requestContext.setAction(action); + runtimeContext.setRpcName(action.name().toLowerCase()); + commonHeader.setApiVer(API_VERSION); + responseContext.setStatus(new Status(100, null)); + commonHeader.setRequestId(responseId); + responseContext.setPayload(payload); + commonHeader.setTimestamp(Instant.now()); + vnfContext.setId(vnfId); + return new CommandResponse(runtimeContext); + } + + + + @Test + public void testPositiveFlow_configure() { + + String requestId = "1"; + + pouplateCommandExecutorInput("FIREWALL",30, + "1.0", Instant.now(), API_VERSION, requestId, ORIGINATOR_ID, "", + VNFOperation.Configure, "33", ""); + } + + public WorkflowResponse getWorkflowResponse (){ + WorkflowResponse wfResponse = new WorkflowResponse(); + ResponseContext responseContext = createResponseContextWithSuObjects(); + wfResponse.setResponseContext(responseContext); + responseContext.setPayload(""); + wfResponse.getResponseContext().setStatus(new Status(100, null)); + return wfResponse; + } + + private RuntimeContext pouplateCommandExecutorInput(String vnfType, + int ttl, + String vnfVersion, + Instant timeStamp, + String apiVersion, + String requestId, + String originatorID, + String subRequestID, + VNFOperation action, + String vnfId, + String payload){ + RuntimeContext commandExecutorInput = createCommandExecutorInputWithSubObjects(); + RequestContext requestContext = commandExecutorInput.getRequestContext(); + ResponseContext responseContext = createResponseContextWithSuObjects(); + commandExecutorInput.setResponseContext(responseContext); + + requestContext.getCommonHeader().setFlags(new Flags(null, false, ttl)); + requestContext.getCommonHeader().setApiVer(apiVersion); + requestContext.getCommonHeader().setTimestamp(timeStamp); + requestContext.getCommonHeader().setRequestId(requestId); + requestContext.getCommonHeader().setSubRequestId(subRequestID); + requestContext.getCommonHeader().setOriginatorId(originatorID); + requestContext.setAction(action); + requestContext.setPayload(payload); + requestContext.getActionIdentifiers().setVnfId(vnfId); + VNFContext vnfContext = commandExecutorInput.getVnfContext(); + vnfContext.setType(vnfType); + vnfContext.setId(vnfId); + vnfContext.setVersion(vnfVersion); + return commandExecutorInput; + } + + private RuntimeContext createCommandExecutorInputWithSubObjects() { + return createRuntimeContextWithSubObjects(); + } + + private RuntimeContext createRuntimeContextWithSubObjects() { + RuntimeContext runtimeContext = new RuntimeContext(); + RequestContext requestContext = new RequestContext(); + runtimeContext.setRequestContext(requestContext); + CommonHeader commonHeader = new CommonHeader(); + requestContext.setCommonHeader(commonHeader); + commonHeader.setFlags(new Flags(null, false, 0)); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + requestContext.setActionIdentifiers(actionIdentifiers); + VNFContext vnfContext = new VNFContext(); + runtimeContext.setVnfContext(vnfContext); + return runtimeContext; + + } + + private ResponseContext createResponseContextWithSuObjects(){ + ResponseContext responseContext = new ResponseContext(); + CommonHeader commonHeader = new CommonHeader(); + responseContext.setCommonHeader(commonHeader); + responseContext.setStatus(new Status(0, null)); + commonHeader.setFlags(new Flags(null, false, 0)); + return responseContext; + } + +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/TestCommandExecutionTask.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/TestCommandExecutionTask.java deleted file mode 100644 index 460f0e7ad..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/TestCommandExecutionTask.java +++ /dev/null @@ -1,300 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.appc.executor; -/** - * - */ - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.openecomp.appc.domainmodel.lcm.*; -import org.openecomp.appc.domainmodel.lcm.Flags.Mode; -import org.openecomp.appc.executor.impl.CommandTask; -import org.openecomp.appc.executor.impl.CommandTaskFactory; -import org.openecomp.appc.executor.impl.LCMCommandTask; -import org.openecomp.appc.executor.impl.LCMReadonlyCommandTask; -import org.openecomp.appc.executor.objects.*; -import org.openecomp.appc.lifecyclemanager.LifecycleManager; -import org.openecomp.appc.requesthandler.RequestHandler; -import org.openecomp.appc.workflow.WorkFlowManager; -import org.openecomp.appc.workflow.objects.WorkflowRequest; -import org.openecomp.appc.workflow.objects.WorkflowResponse; -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.openecomp.sdnc.sli.aai.AAIService; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.time.Instant; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.*; - - - -@RunWith(PowerMockRunner.class) -@PrepareForTest( {FrameworkUtil.class, CommandTask.class, LCMCommandTask.class}) -public class TestCommandExecutionTask { - - private static final String TTL_FLAG= "TTL"; - private static final String API_VERSION= "2.0.0"; - private static final String ORIGINATOR_ID= "1"; - private CommandTaskFactory factory ; - - private RequestHandler requestHandler; - private WorkFlowManager workflowManager; - private AAIService aaiService; - private LifecycleManager lifecyclemanager; - - private final BundleContext bundleContext=Mockito.mock(BundleContext.class); - private final Bundle bundleService=Mockito.mock(Bundle.class); - private final ServiceReference sref=Mockito.mock(ServiceReference.class); - - @Before - public void init() throws SvcLogicException { - - // *** - AAIService aaiService = Mockito.mock(AAIService.class);; - PowerMockito.mockStatic(FrameworkUtil.class); - PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService); - PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); - PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref); - PowerMockito.when(bundleContext.<AAIService>getService(sref)).thenReturn(aaiService); - PowerMockito.when(aaiService.query(anyString(),anyBoolean(),anyString(),anyString(),anyString(),anyString(),(SvcLogicContext)anyObject())).thenAnswer(new Answer<SvcLogicResource.QueryStatus>() { - @Override - public SvcLogicResource.QueryStatus answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - SvcLogicContext ctx =(SvcLogicContext)args[6]; - String prefix = (String)args[4]; - String key = (String)args[3]; - if(key.contains("'28'")){ - return SvcLogicResource.QueryStatus.FAILURE ; - }else if ( key.contains("'8'")) { - return SvcLogicResource.QueryStatus.NOT_FOUND ; - }else { - ctx.setAttribute(prefix + ".vnf-type", "FIREWALL"); - ctx.setAttribute(prefix + ".orchestration-status", "INSTANTIATED"); - } - return SvcLogicResource.QueryStatus.SUCCESS ; - } - }); - PowerMockito.when(aaiService.update(anyString(),anyString(),(Map)anyObject(),anyString(),(SvcLogicContext)anyObject())).thenReturn(SvcLogicResource.QueryStatus.SUCCESS); - - requestHandler = Mockito.mock(RequestHandler.class); - workflowManager = Mockito.mock(WorkFlowManager.class); - lifecyclemanager = Mockito.mock(LifecycleManager.class ); - - factory = new CommandTaskFactory(); - factory.setLifecyclemanager(lifecyclemanager); - factory.setWorkflowManager(workflowManager); - factory.setVnfRequestHandler(requestHandler); - Mockito.when(workflowManager.executeWorkflow((WorkflowRequest)anyObject())).thenReturn(getWorkflowResponse () ); - } - - - @Test - public void testFactory(){ - CommandTask task; - Instant timeStamp = Instant.now(); - String requestId = "1"; - RuntimeContext commandExecutorInputConfigure = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", - timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure,"15","") ; - task = factory.getExecutionTask(commandExecutorInputConfigure); - assertEquals(LCMCommandTask.class,task.getClass() ); - RuntimeContext commandExecutorInputSync = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", - timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ; - task = factory.getExecutionTask(commandExecutorInputSync); - assertEquals(LCMReadonlyCommandTask.class,task.getClass() ); - - } - - - - @Test - public void testOnRequestCompletion(){ - Mockito.doNothing().when(requestHandler).onRequestTTLEnd((RuntimeContext) anyObject(),anyBoolean()); - RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Configure, "1", ""); - CommandResponse response = getCommandResponse(VNFOperation.Configure, true, "11", "","1"); - LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); - executionTask.onRequestCompletion(response); - } - - @Test - public void testRunGetConfig(){ - RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, "1", ""); - LCMReadonlyCommandTask readonlyCommandTask = new LCMReadonlyCommandTask(request, requestHandler,workflowManager); - readonlyCommandTask.run(); - } - - @Test - public void testRun(){ - RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, "1", ""); - LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); - executionTask.run(); - } - - @Test - public void testRunNegative(){ - RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, "1", ""); - LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); - executionTask.run(); - } - - - CommandResponse getCommandResponse(VNFOperation action , boolean success, String responseId, String payload, String vnfId){ - RuntimeContext runtimeContext = new RuntimeContext(); - ResponseContext responseContext = new ResponseContext(); - runtimeContext.setResponseContext(responseContext); - RequestContext requestContext = new RequestContext(); - runtimeContext.setRequestContext(requestContext); - CommonHeader commonHeader = new CommonHeader(); - requestContext.setCommonHeader(commonHeader); - responseContext.setCommonHeader(commonHeader); - commonHeader.setFlags(new Flags(null, false, 0)); - ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); - requestContext.setActionIdentifiers(actionIdentifiers); - VNFContext vnfContext = new VNFContext(); - runtimeContext.setVnfContext(vnfContext); - requestContext.setAction(action); - runtimeContext.setRpcName(action.name().toLowerCase()); - commonHeader.setApiVer(API_VERSION); - responseContext.setStatus(new Status(100, null)); - commonHeader.setRequestId(responseId); - responseContext.setPayload(payload); - commonHeader.setTimestamp(Instant.now()); - vnfContext.setId(vnfId); - return new CommandResponse(runtimeContext); - } - - - - @Test - public void testPositiveFlow_configure() { - - String requestId = "1"; - - RuntimeContext commandExecutorInput = pouplateCommandExecutorInput("FIREWALL",30, "1.0", Instant.now(), API_VERSION, requestId, ORIGINATOR_ID, "", VNFOperation.Configure, "33", ""); - } - - - private Map<String,Object> setTTLInFlags( String value){ - Map<String,Object> flags = new HashMap<String,Object>(); - if( value != null || !("".equalsIgnoreCase(value))){ - flags.put(TTL_FLAG, value); - } - return flags; - } - - - private RuntimeContext getConfigCommandRequest(String vnfType , Integer ttl , Instant timeStamp, String requestId, - Map<String,Object> flags, VNFOperation command , String vnfId, String vnfVersion ){ - - RuntimeContext commandExecutorInput = pouplateCommandExecutorInput(vnfType, ttl, vnfVersion, timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "", command, vnfId, ""); - - return commandExecutorInput; - } - - private RuntimeContext getLCMCommandRequest(String vnfType , Integer ttl ,Instant timeStamp, String requestId, - Map<String,Object> flags, VNFOperation command , String vnfId, String vnfVersion ){ - - RuntimeContext commandExecutorInput = pouplateCommandExecutorInput(vnfType, ttl, vnfVersion, timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "", command, vnfId, ""); - - return commandExecutorInput; - } - - public WorkflowResponse getWorkflowResponse (){ - WorkflowResponse wfResponse = new WorkflowResponse(); - ResponseContext responseContext = createResponseContextWithSuObjects(); - wfResponse.setResponseContext(responseContext); - responseContext.setPayload(""); - wfResponse.getResponseContext().setStatus(new Status(100, null)); - return wfResponse; - } - - private RuntimeContext pouplateCommandExecutorInput(String vnfType, int ttl, String vnfVersion, Instant timeStamp, String apiVersion, String requestId, String originatorID, String subRequestID, VNFOperation action, String vnfId , String payload){ - RuntimeContext commandExecutorInput = createCommandExecutorInputWithSubObjects(); - RequestContext requestContext = commandExecutorInput.getRequestContext(); - ResponseContext responseContext = createResponseContextWithSuObjects(); - commandExecutorInput.setResponseContext(responseContext); - - requestContext.getCommonHeader().setFlags(new Flags(null, false, ttl)); - requestContext.getCommonHeader().setApiVer(apiVersion); - requestContext.getCommonHeader().setTimestamp(timeStamp); - requestContext.getCommonHeader().setRequestId(requestId); - requestContext.getCommonHeader().setSubRequestId(subRequestID); - requestContext.getCommonHeader().setOriginatorId(originatorID); - requestContext.setAction(action); - requestContext.setPayload(payload); - requestContext.getActionIdentifiers().setVnfId(vnfId); - VNFContext vnfContext = commandExecutorInput.getVnfContext(); - vnfContext.setType(vnfType); - vnfContext.setId(vnfId); - vnfContext.setVersion(vnfVersion); - return commandExecutorInput; - } - - private RuntimeContext createCommandExecutorInputWithSubObjects() { - return createRuntimeContextWithSubObjects(); - } - - private RuntimeContext createRuntimeContextWithSubObjects() { - RuntimeContext runtimeContext = new RuntimeContext(); - RequestContext requestContext = new RequestContext(); - runtimeContext.setRequestContext(requestContext); - CommonHeader commonHeader = new CommonHeader(); - requestContext.setCommonHeader(commonHeader); - commonHeader.setFlags(new Flags(null, false, 0)); - ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); - requestContext.setActionIdentifiers(actionIdentifiers); - VNFContext vnfContext = new VNFContext(); - runtimeContext.setVnfContext(vnfContext); - return runtimeContext; - - } - - private ResponseContext createResponseContextWithSuObjects(){ - ResponseContext responseContext = new ResponseContext(); - CommonHeader commonHeader = new CommonHeader(); - responseContext.setCommonHeader(commonHeader); - responseContext.setStatus(new Status(0, null)); - commonHeader.setFlags(new Flags(null, false, 0)); - return responseContext; - } - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestValidator.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/RequestValidatorTest.java index 2cdf37e48..24fd37834 100644 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestValidator.java +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/RequestValidatorTest.java @@ -24,37 +24,31 @@ package org.openecomp.appc.requesthandler; - -import static junit.framework.TestCase.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; - -import java.time.Instant; -import java.util.Map; -import java.util.UUID; - +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.openecomp.appc.domainmodel.lcm.*; -import org.openecomp.appc.executor.UnstableVNFException; +import org.openecomp.appc.domainmodel.lcm.ActionIdentifiers; +import org.openecomp.appc.domainmodel.lcm.CommonHeader; +import org.openecomp.appc.domainmodel.lcm.Flags; +import org.openecomp.appc.domainmodel.lcm.RequestContext; +import org.openecomp.appc.domainmodel.lcm.ResponseContext; +import org.openecomp.appc.domainmodel.lcm.RuntimeContext; +import org.openecomp.appc.domainmodel.lcm.Status; +import org.openecomp.appc.domainmodel.lcm.VNFContext; +import org.openecomp.appc.domainmodel.lcm.VNFOperation; import org.openecomp.appc.lifecyclemanager.LifecycleManager; -import org.openecomp.appc.lifecyclemanager.objects.LifecycleException; import org.openecomp.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.openecomp.appc.requesthandler.exceptions.*; +import org.openecomp.appc.requesthandler.exceptions.InvalidInputException; +import org.openecomp.appc.requesthandler.exceptions.LCMOperationsDisabledException; import org.openecomp.appc.requesthandler.impl.RequestHandlerImpl; import org.openecomp.appc.requesthandler.impl.RequestValidatorImpl; import org.openecomp.appc.requesthandler.objects.RequestHandlerInput; import org.openecomp.appc.transactionrecorder.TransactionRecorder; import org.openecomp.appc.workflow.WorkFlowManager; import org.openecomp.appc.workflow.objects.WorkflowExistsOutput; -import org.openecomp.appc.workflow.objects.WorkflowRequest; import org.openecomp.appc.workingstatemanager.WorkingStateManager; import org.openecomp.sdnc.sli.SvcLogicContext; import org.openecomp.sdnc.sli.SvcLogicResource; @@ -67,161 +61,83 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; +import java.time.Instant; +import java.util.UUID; +import static junit.framework.TestCase.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Matchers.*; +@SuppressWarnings("unchecked") @RunWith(PowerMockRunner.class) -@PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class,RequestValidatorImpl.class, TransactionRecorder.class}) -public class TestRequestValidator { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestRequestHandler.class); - - private static final String TTL_FLAG= "TTL"; +@PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class, + RequestValidatorImpl.class, TransactionRecorder.class}) +public class RequestValidatorTest { + private final EELFLogger logger = EELFManager.getInstance().getLogger(TestRequestHandler.class); private RequestValidatorImpl requestValidator; - AAIService aaiAdapter ; - LifecycleManager lifecyclemanager; - WorkFlowManager workflowManager; - WorkingStateManager workingStateManager ; - LCMStateManager lcmStateManager; -// AppcDAOImpl dao ; + private AAIService aaiAdapter ; + private LifecycleManager lifecyclemanager; + private WorkFlowManager workflowManager; + private WorkingStateManager workingStateManager ; + private LCMStateManager lcmStateManager; private final BundleContext bundleContext= Mockito.mock(BundleContext.class); private final Bundle bundleService=Mockito.mock(Bundle.class); private final ServiceReference sref=Mockito.mock(ServiceReference.class); - - @Before public void init() throws Exception { - -// dao = Mockito.mock(AppcDAOImpl.class); -// PowerMockito.whenNew(AppcDAOImpl.class).withNoArguments().thenReturn(dao); -// Mockito.doNothing().when(dao).storeTransactionRecord((TransactionRecord)anyObject()); - // PowerMockito.when(dao.queryWorkflow(anyString(),anyString())).thenReturn(true); - // *** - AAIService aaiService = Mockito.mock(AAIService.class);; + AAIService aaiService = Mockito.mock(AAIService.class); PowerMockito.mockStatic(FrameworkUtil.class); PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService); PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref); PowerMockito.when(bundleContext.<AAIService>getService(sref)).thenReturn(aaiService); - PowerMockito.when(aaiService.query(anyString(),anyBoolean(),anyString(),anyString(),anyString(),anyString(),(SvcLogicContext)anyObject())).thenAnswer(new Answer<SvcLogicResource.QueryStatus>() { - @Override - public SvcLogicResource.QueryStatus answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - SvcLogicContext ctx =(SvcLogicContext)args[6]; - String prefix = (String)args[4]; - String key = (String)args[3]; - if(key.contains("'28'")){ - return SvcLogicResource.QueryStatus.FAILURE ; - }else if ( key.contains("'8'")) { - return SvcLogicResource.QueryStatus.NOT_FOUND ; - }else { - ctx.setAttribute(prefix + ".vnf-type", "FIREWALL"); - ctx.setAttribute(prefix + ".orchestration-status", "Instantiated"); - } - return SvcLogicResource.QueryStatus.SUCCESS ; - } - }); - PowerMockito.when(aaiService.update(anyString(),anyString(),(Map)anyObject(),anyString(),(SvcLogicContext)anyObject())).thenReturn(SvcLogicResource.QueryStatus.SUCCESS); - //PowerMockito.when(requestHandler.getVnfdata(anyString(), anyString(), (SvcLogicContext)anyObject())).thenReturn() + PowerMockito.when(aaiService.query(anyString(),anyBoolean(),anyString(),anyString(),anyString(),anyString(), + anyObject())).thenAnswer(invocation -> { + Object[] args = invocation.getArguments(); + SvcLogicContext ctx =(SvcLogicContext)args[6]; + String prefix = (String)args[4]; + String key = (String)args[3]; + if(key.contains("'28'")){ + return SvcLogicResource.QueryStatus.FAILURE ; + }else if ( key.contains("'8'")) { + return SvcLogicResource.QueryStatus.NOT_FOUND ; + }else { + ctx.setAttribute(prefix + ".vnf-type", "FIREWALL"); + ctx.setAttribute(prefix + ".orchestration-status", "Instantiated"); + } + return SvcLogicResource.QueryStatus.SUCCESS ; + }); + PowerMockito.when(aaiService.update(anyString(),anyString(), anyObject(),anyString(), anyObject())) + .thenReturn(SvcLogicResource.QueryStatus.SUCCESS); // *** - aaiAdapter = Mockito.mock(AAIService.class); lifecyclemanager= Mockito.mock(LifecycleManager.class); workflowManager= Mockito.mock(WorkFlowManager.class); workingStateManager = Mockito.mock(WorkingStateManager.class); lcmStateManager = Mockito.mock(LCMStateManager.class); - // transactionRecorder= spy(TransactionRecorder.class); requestValidator = new RequestValidatorImpl(); -// requestValidator = Mockito.mock(RequestValidator.class); requestValidator.setWorkflowManager(workflowManager); requestValidator.setLifecyclemanager(lifecyclemanager); requestValidator.setWorkingStateManager(workingStateManager); requestValidator.setLcmStateManager(lcmStateManager); Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(true); - /* Mockito.when(workingStateManager.isVNFStable("1")).thenReturn(true); - Mockito.when(aaiAdapter.requestGenericVnfData("1")).thenReturn(getGenericVnf("FIREWALL","INSTNATIATED"));*/ - // Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(true); - - /*PowerMockito.when(getAaiadapter().requestGenericVnfData("39")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("39")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("8")).thenThrow(new AAIAdapterException("404")); - Mockito.when(workingStateManager.isVNFStable("8")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("9")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("9")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("10")).thenReturn(getGenericVnf("WrongRouter","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("10")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("11")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("11")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("12")).thenReturn(getGenericVnf("FIREWALL","NOT_INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("12")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("13")).thenReturn(getGenericVnf("FIREWALL","TESTING")); - Mockito.when(workingStateManager.isVNFStable("13")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("14")).thenReturn(getGenericVnf("FIREWALL","REBUILDING")); - Mockito.when(workingStateManager.isVNFStable("14")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("26")).thenReturn(getGenericVnf("FIREWALL","NOT_INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("26")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("27")).thenReturn(getGenericVnf("FIREWALL","RESTARTING")); - Mockito.when(workingStateManager.isVNFStable("27")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("28")).thenThrow(new RuntimeException("AAI Down Excpetion")); - Mockito.when(workingStateManager.isVNFStable("28")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("35")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("35")).thenReturn(true);*/ - - /*for(Integer i=130; i<=140 ; i++) - { - PowerMockito.when(getAaiadapter().requestGenericVnfData(i.toString())).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable(i.toString())).thenReturn(true); - } - PowerMockito.when(getAaiadapter().requestGenericVnfData("39")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("39")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("40")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("40")).thenReturn(true).thenReturn(false); - - - PowerMockito.when(getAaiadapter().requestGenericVnfData("38")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("38")).thenReturn(true).thenReturn(false); - - - PowerMockito.when(getAaiadapter().requestGenericVnfData("201")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")).thenReturn(getGenericVnf("FIREWALL","CONFIGURED")); - Mockito.when(workingStateManager.isVNFStable("201")).thenReturn(true); - PowerMockito.when(getAaiadapter().requestGenericVnfData("202")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")).thenReturn(getGenericVnf("FIREWALL","ERROR")); - Mockito.when(workingStateManager.isVNFStable("202")).thenReturn(true).thenReturn(false); - - PowerMockito.when(getAaiadapter().requestGenericVnfData("301")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("301")).thenReturn(true).thenReturn(false); - - PowerMockito.when(getAaiadapter().requestGenericVnfData("302")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("302")).thenReturn(true).thenReturn(true); - - PowerMockito.when(getAaiadapter().requestGenericVnfData("303")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("303")).thenReturn(true).thenReturn(true); - - PowerMockito.when(getAaiadapter().requestGenericVnfData("309")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("309")).thenReturn(true).thenReturn(true); - - PowerMockito.when(getAaiadapter().requestGenericVnfData("310")).thenReturn(getGenericVnf("FIREWALL","INSTANTIATED")); - Mockito.when(workingStateManager.isVNFStable("310")).thenReturn(true).thenReturn(true);*/ } + public AAIService getAaiadapter() { return this.aaiAdapter; } -/* public GenericVnf getGenericVnf(String vnfType, String operationalState) { - GenericVnf genericVnf = new GenericVnf(); - genericVnf.setVnfType(vnfType); - // genericVnf.setOperationalState(operationalState); - genericVnf.setOrchestrationStatus(operationalState); - return genericVnf; - }*/ - private RequestHandlerInput getRequestHandlerInput(String vnfID, VNFOperation action, int ttl, boolean force, String originatorId, String requestId, String subRequestId, Instant timeStamp){ + + private RequestHandlerInput getRequestHandlerInput(String vnfID, VNFOperation action, int ttl, + boolean force, String originatorId, String requestId, + String subRequestId, Instant timeStamp){ String API_VERSION= "2.0.0"; RequestHandlerInput input = new RequestHandlerInput(); RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); @@ -231,8 +147,7 @@ public class TestRequestValidator { requestContext.setAction(action); if (action != null) { input.setRpcName(convertActionNameToUrl(action.name())); - } - else{ + } else{ input.setRpcName(null); } requestContext.getCommonHeader().setRequestId(requestId); @@ -244,12 +159,15 @@ public class TestRequestValidator { requestContext.getCommonHeader().setTimestamp(timeStamp); return input; } + @Test - public void testNullVnfID() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + public void testNullVnfID() throws Exception { logger.debug("=====================testNullVnfID============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); RequestHandlerInput input = this.getRequestHandlerInput(null, VNFOperation.Configure, 30, - false, UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false, UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -257,18 +175,19 @@ public class TestRequestValidator { }catch(InvalidInputException e ) { ex = e; } -// assertEquals(new InvalidInputException("vnfID or command is null") ,ex); assertNotNull(ex); logger.debug("=====================testNullVnfID============================="); } @Test - public void testPositiveFlowWithConfigure() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void testPositiveFlowWithConfigure() throws Exception { logger.debug("=====================testPositiveFlowWithConfigure============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); Mockito.when(workingStateManager.isVNFStable("1")).thenReturn(true); RequestHandlerInput input = this.getRequestHandlerInput("1", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -282,11 +201,13 @@ public class TestRequestValidator { } @Test - public void testVnfNotFound() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void testVnfNotFound() throws Exception { logger.debug("=====================testVnfNotFound============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); RequestHandlerInput input = this.getRequestHandlerInput("8", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -298,14 +219,14 @@ public class TestRequestValidator { logger.debug("=====================testVnfNotFound============================="); } - - @Test - public void testNullCommand() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + public void testNullCommand() throws Exception { logger.debug("=====================testNullCommand============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); RequestHandlerInput input = this.getRequestHandlerInput("7", null,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -318,11 +239,13 @@ public class TestRequestValidator { } @Test - public void testNullVnfIDAndCommand() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + public void testNullVnfIDAndCommand() throws Exception { logger.debug("=====================testNullVnfIDAndCommand============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); RequestHandlerInput input = this.getRequestHandlerInput(null, null,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -335,11 +258,13 @@ public class TestRequestValidator { } @Test - public void testWorkflowNotFound() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void testWorkflowNotFound() throws Exception { logger.debug("=====================testWorkflowNotFound============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(false,false)); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(false,false)); RequestHandlerInput input = this.getRequestHandlerInput("10", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -352,13 +277,16 @@ public class TestRequestValidator { } @Test - public void testUnstableVnfWithConfigure() throws LifecycleException, NoTransitionDefinedException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void testUnstableVnfWithConfigure() throws Exception { logger.debug("=====================testUnstableVnfWithConfigure============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())).thenThrow( new NoTransitionDefinedException("","","")); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); RequestHandlerInput input = this.getRequestHandlerInput("11", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -371,12 +299,15 @@ public class TestRequestValidator { } @Test - public void testUnstableVnfWithTest() throws LifecycleException, NoTransitionDefinedException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void testUnstableVnfWithTest() throws Exception { logger.debug("=====================testUnstableVnfWithTest============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())).thenThrow( new NoTransitionDefinedException("","","")); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); RequestHandlerInput input = this.getRequestHandlerInput("12", VNFOperation.Test,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -389,12 +320,14 @@ public class TestRequestValidator { } @Test - public void testUnstableVnfWithStart() throws LifecycleException, NoTransitionDefinedException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void testUnstableVnfWithStart() throws Exception { logger.debug("=====================testUnstableVnfWithStart============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())).thenThrow( new NoTransitionDefinedException("","","")); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); RequestHandlerInput input = this.getRequestHandlerInput("13", VNFOperation.Start,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -407,11 +340,13 @@ public class TestRequestValidator { } @Test - public void testUnstableVnfWithTerminate() throws LifecycleException, NoTransitionDefinedException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void testUnstableVnfWithTerminate() throws Exception { logger.debug("=====================testUnstableVnfWithTerminate============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())).thenThrow( new NoTransitionDefinedException("","","")); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); RequestHandlerInput input = this.getRequestHandlerInput("14", VNFOperation.Terminate,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -424,12 +359,14 @@ public class TestRequestValidator { } @Test - public void testUnstableVnfWithRestart() throws LifecycleException, NoTransitionDefinedException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void testUnstableVnfWithRestart() throws Exception { logger.debug("=====================testUnstableVnfWithRestart============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())).thenThrow( new NoTransitionDefinedException("","","")); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); RequestHandlerInput input = this.getRequestHandlerInput("26", VNFOperation.Restart,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -442,13 +379,14 @@ public class TestRequestValidator { } @Test - public void testUnstableVnfWithRebuild() throws LifecycleException, NoTransitionDefinedException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void testUnstableVnfWithRebuild() throws Exception { logger.debug("=====================testUnstableVnfWithRebuild============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())).thenThrow( new NoTransitionDefinedException("","","")); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); - // Mockito.doReturn(this.getGenericVnf("Firewall", "NOT_INSTANTIATED")).when(getAaiadapter()).requestGenericVnfData("8"); RequestHandlerInput input = this.getRequestHandlerInput("27", VNFOperation.Rebuild,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { @@ -460,22 +398,16 @@ public class TestRequestValidator { logger.debug("=====================testUnstableVnfWithRebuild============================="); } - - - @Test public void testAAIDown() throws Exception { logger.debug("=====================testAAIDown============================="); - // AAIAdapter aaiAdapter = Mockito.mock(AAIAdapterImpl.class); - // RequestHandler requestHandler=RequestHandlerSingleton.getRequestHandler(new WorkFlowManagerImpl(),aaiAdapter,new LifecycleManagerImpl()); - // RequestHandler requestHandler = new RequestHandlerImpl(new WorkFlowManagerImpl(),aaiAdapter,new LifecycleManagerImpl()); RequestHandlerInput input = this.getRequestHandlerInput("28", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - Exception ex =null; + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); try { requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { ex = e; } @@ -484,7 +416,7 @@ public class TestRequestValidator { } @Test - public void testNegativeFlowWithTimeStamp() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void testNegativeFlowWithTimeStamp() throws Exception { logger.debug("=====================testNegativeFlowWithTimeStamp============================="); Instant now = Instant.now(); Instant past = now.minusMillis(1000000); @@ -503,19 +435,21 @@ public class TestRequestValidator { logger.debug("=====================testNegativeFlowWithTimeStamp============================="); } - @Test - public void rejectDuplicateRequest() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException,DGWorkflowNotFoundException { + public void rejectDuplicateRequest() throws Exception { String originatorID = UUID.randomUUID().toString(); String requestID = UUID.randomUUID().toString(); String subRequestID = UUID.randomUUID().toString(); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); Mockito.when(workingStateManager.isVNFStable("301")).thenReturn(true); Mockito.when(workingStateManager.isVNFStable("309")).thenReturn(true); - RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure,0,false, + originatorID, requestID, subRequestID, Instant.now()); - RequestHandlerInput input1 = this.getRequestHandlerInput("309", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + RequestHandlerInput input1 = this.getRequestHandlerInput("309", VNFOperation.Configure,0,false, + originatorID, requestID, subRequestID, Instant.now()); Exception ex =null; RuntimeContext runtimeContext = putInputToRuntimeContext(input); RuntimeContext runtimeContext1 = putInputToRuntimeContext(input1); @@ -536,60 +470,63 @@ public class TestRequestValidator { } @Test - public void testLockOperation() throws RequestExpiredException, DuplicateRequestException, DGWorkflowNotFoundException, VNFNotFoundException, WorkflowNotFoundException, LifecycleException, UnstableVNFException, NoTransitionDefinedException, InvalidInputException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + public void testLockOperation() throws Exception { Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); testOperation("no-matter", VNFOperation.Lock); } @Test - public void testUnlockOperation() throws RequestExpiredException, DuplicateRequestException, DGWorkflowNotFoundException, VNFNotFoundException, WorkflowNotFoundException, LifecycleException, UnstableVNFException, NoTransitionDefinedException, InvalidInputException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + public void testUnlockOperation() throws Exception { Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); testOperation("no-matter", VNFOperation.Unlock); } @Test - public void testCheckLockOperation() throws RequestExpiredException, DuplicateRequestException, DGWorkflowNotFoundException, VNFNotFoundException, WorkflowNotFoundException, LifecycleException, UnstableVNFException, NoTransitionDefinedException, InvalidInputException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + public void testCheckLockOperation() throws Exception { Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); testOperation("no-matter", VNFOperation.CheckLock); } @Test(expected = NoTransitionDefinedException.class) - public void testLockOperationNegative() throws RequestExpiredException, DuplicateRequestException, DGWorkflowNotFoundException, VNFNotFoundException, WorkflowNotFoundException, LifecycleException, UnstableVNFException, NoTransitionDefinedException, InvalidInputException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Lock.toString()))).thenThrow(new NoTransitionDefinedException("", "", "")); + public void testLockOperationNegative() throws Exception { + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Lock.toString()))) + .thenThrow(new NoTransitionDefinedException("", "", "")); Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); testOperation("no-matter", VNFOperation.Lock); } @Test(expected = NoTransitionDefinedException.class) - public void testUnlockOperationNegative() throws RequestExpiredException, DuplicateRequestException, DGWorkflowNotFoundException, VNFNotFoundException, WorkflowNotFoundException, LifecycleException, UnstableVNFException, NoTransitionDefinedException, InvalidInputException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Unlock.toString()))).thenThrow(new NoTransitionDefinedException("", "", "")); + public void testUnlockOperationNegative() throws Exception { + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Unlock.toString()))) + .thenThrow(new NoTransitionDefinedException("", "", "")); Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); testOperation("no-matter", VNFOperation.Unlock); } @Test(expected = NoTransitionDefinedException.class) - public void testCheckLockOperationNegative() throws RequestExpiredException, DuplicateRequestException, DGWorkflowNotFoundException, VNFNotFoundException, WorkflowNotFoundException, LifecycleException, UnstableVNFException, NoTransitionDefinedException, InvalidInputException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.CheckLock.toString()))).thenThrow(new NoTransitionDefinedException("", "", "")); + public void testCheckLockOperationNegative() throws Exception { + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.CheckLock.toString()))) + .thenThrow(new NoTransitionDefinedException("", "", "")); Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); testOperation("no-matter", VNFOperation.CheckLock); } @Test(expected = LCMOperationsDisabledException.class) - public void testLCMOperationsDisabled() throws RequestExpiredException, DuplicateRequestException, DGWorkflowNotFoundException, VNFNotFoundException, WorkflowNotFoundException, LifecycleException, UnstableVNFException, NoTransitionDefinedException, InvalidInputException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + public void testLCMOperationsDisabled() throws Exception { Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(false); testOperation("no-matter", VNFOperation.Configure); } - private void testOperation(String resource, VNFOperation operation) throws WorkflowNotFoundException, DuplicateRequestException, DGWorkflowNotFoundException, VNFNotFoundException, InvalidInputException, LifecycleException, UnstableVNFException, NoTransitionDefinedException, RequestExpiredException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + private void testOperation(String resource, VNFOperation operation) throws Exception { String originatorID = UUID.randomUUID().toString(); String requestID = UUID.randomUUID().toString(); String subRequestID = UUID.randomUUID().toString(); - RequestHandlerInput input = this.getRequestHandlerInput(resource, operation, 0, false, originatorID, requestID, subRequestID, Instant.now()); + RequestHandlerInput input = this.getRequestHandlerInput(resource, operation, 0, false, originatorID, + requestID, subRequestID, Instant.now()); RuntimeContext runtimeContext = putInputToRuntimeContext(input); requestValidator.validateRequest(runtimeContext); } - private RuntimeContext createRuntimeContextWithSubObjects() { RuntimeContext runtimeContext = new RuntimeContext(); RequestContext requestContext = new RequestContext(); @@ -628,9 +565,6 @@ public class TestRequestValidator { runtimeContext.setRequestContext(input.getRequestContext()); runtimeContext.setRpcName(input.getRpcName()); runtimeContext.getVnfContext().setId(input.getRequestContext().getActionIdentifiers().getVnfId()); - //runtimeContext.getRequestContext().getActionIdentifiers().setVnfId(input.getRequestContext().getActionIdentifiers().getVnfId()); return runtimeContext; - - //String vnfID, VNFOperation action, int ttl, boolean force, String originatorId, String requestId, String subRequestId, Date timeStamp } } diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/EventHandlerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/EventHandlerImpl.java index 1f1154f78..506593ed1 100644 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/EventHandlerImpl.java +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/EventHandlerImpl.java @@ -23,10 +23,9 @@ */ package org.openecomp.appc.listener.impl; + import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; - -import org.openecomp.appc.adapter.factory.DmaapMessageAdapterFactoryImpl; import org.openecomp.appc.adapter.factory.MessageService; import org.openecomp.appc.adapter.message.Consumer; import org.openecomp.appc.adapter.message.MessageAdapterFactory; @@ -40,12 +39,15 @@ import org.osgi.framework.FrameworkUtil; import org.osgi.framework.ServiceReference; import org.slf4j.MDC; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; /** - * This class is a wrapper for the DMaaP client provided in appc-dmaap-adapter. Its aim is to ensure that only well formed - * messages are sent and received on DMaaP. - * + * This class is a wrapper for the DMaaP client provided in appc-dmaap-adapter. Its aim is to ensure + * that only well formed messages are sent and received on DMaaP. */ public class EventHandlerImpl implements EventHandler { @@ -100,10 +102,10 @@ public class EventHandlerImpl implements EventHandler { private Consumer reader = null; private Producer producer = null; - + public EventHandlerImpl(ListenerProperties props) { - pool = new HashSet<String>(); - writeTopics = new HashSet<String>(); + pool = new HashSet<>(); + writeTopics = new HashSet<>(); if (props != null) { readTopic = props.getProperty(ListenerProperties.KEYS.TOPIC_READ); @@ -115,7 +117,7 @@ public class EventHandlerImpl implements EventHandler { filter_json = props.getProperty(ListenerProperties.KEYS.TOPIC_READ_FILTER); READ_TIMEOUT = Integer - .valueOf(props.getProperty(ListenerProperties.KEYS.TOPIC_READ_TIMEOUT, String.valueOf(READ_TIMEOUT))); + .valueOf(props.getProperty(ListenerProperties.KEYS.TOPIC_READ_TIMEOUT, String.valueOf(READ_TIMEOUT))); String hostnames = props.getProperty(ListenerProperties.KEYS.HOSTS); if (hostnames != null && !hostnames.isEmpty()) { @@ -134,8 +136,8 @@ public class EventHandlerImpl implements EventHandler { messageService = MessageService.parse(props.getProperty(ListenerProperties.KEYS.MESSAGE_SERVICE)); LOG.info(String.format( - "Configured to use %s client on host pool [%s]. Reading from [%s] filtered by %s. Wriring to [%s]. Authenticated using %s", - messageService, hostnames, readTopic, filter_json, writeTopics, apiKey)); + "Configured to use %s client on host pool [%s]. Reading from [%s] filtered by %s. Wriring to [%s]. Authenticated using %s", + messageService, hostnames, readTopic, filter_json, writeTopics, apiKey)); } } @@ -146,24 +148,18 @@ public class EventHandlerImpl implements EventHandler { @Override public List<String> getIncomingEvents(int limit) { - List<String> out = new ArrayList<String>(); + List<String> out = new ArrayList<>(); LOG.info(String.format("Getting up to %d incoming events", limit)); // reuse the consumer object instead of creating a new one every time if (reader == null) { - LOG.info("Getting Consumer..."); - reader = getConsumer(); + LOG.info("Getting Consumer..."); + reader = getConsumer(); } - - List<String> items = null; - try{ - items = reader.fetch(READ_TIMEOUT * 1000, limit); - }catch(Error r){ - LOG.error("EvenHandlerImpl.getIncomingEvents",r); - } - - - for (String item : items) { - out.add(item); + if (reader != null) { + List<String> items = reader.fetch(READ_TIMEOUT * 1000, limit); + for (String item : items) { + out.add(item); + } } LOG.info(String.format("Read %d messages from %s as %s/%s.", out.size(), readTopic, clientName, clientId)); return out; @@ -189,51 +185,52 @@ public class EventHandlerImpl implements EventHandler { public void postStatus(String partition, String event) { LOG.debug(String.format("Posting Message [%s]", event)); if (producer == null) { - LOG.info("Getting Producer..."); - producer = getProducer(); + LOG.info("Getting Producer..."); + producer = getProducer(); } producer.post(partition, event); } /** * Returns a consumer object for direct access to our Cambria consumer interface - * + * * @return An instance of the consumer interface */ protected Consumer getConsumer() { LOG.debug(String.format("Getting Consumer: %s %s/%s/%s", pool, readTopic, clientName, clientId)); if (filter_json == null && writeTopics.contains(readTopic)) { LOG.error( - "*****We will be writing and reading to the same topic without a filter. This will cause an infinite loop.*****"); + "*****We will be writing and reading to the same topic without a filter. This will cause an infinite loop.*****"); } - - Consumer out=null; + + Consumer out = null; BundleContext ctx = FrameworkUtil.getBundle(EventHandlerImpl.class).getBundleContext(); if (ctx != null) { - ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); - if (svcRef != null) { - try{ - out = ((MessageAdapterFactory) ctx.getService(svcRef)).createConsumer(pool, readTopic, clientName, clientId, filter_json, apiKey, apiSecret); - }catch(Error e){ - //TODO:create eelf message - LOG.error("EvenHandlerImp.getConsumer calling MessageAdapterFactor.createConsumer",e); - } - if( out != null ) { - for (String url : pool) { - if (url.contains("3905") || url.contains("https")) { - out.useHttps(true); - break; - } - } - } - } + ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); + if (svcRef != null) { + try { + out = ((MessageAdapterFactory) ctx.getService(svcRef)) + .createConsumer(pool, readTopic, clientName, clientId, filter_json, apiKey, apiSecret); + } catch (Exception e) { + //TODO:create eelf message + LOG.error("EvenHandlerImp.getConsumer calling MessageAdapterFactor.createConsumer", e); + } + if (out != null) { + for (String url : pool) { + if (url.contains("3905") || url.contains("https")) { + out.useHttps(true); + break; + } + } + } + } } return out; } /** * Returns a consumer object for direct access to our Cambria producer interface - * + * * @return An instance of the producer interface */ protected Producer getProducer() { @@ -242,33 +239,34 @@ public class EventHandlerImpl implements EventHandler { Producer out = null; BundleContext ctx = FrameworkUtil.getBundle(EventHandlerImpl.class).getBundleContext(); if (ctx != null) { - ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); - if (svcRef != null) { - out = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopics,apiKey, apiSecret); - if( out != null ) { - for (String url : pool) { - if (url.contains("3905") || url.contains("https")) { - out.useHttps(true); - break; - } - } - } - } + ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); + if (svcRef != null) { + out = ((MessageAdapterFactory) ctx.getService(svcRef)) + .createProducer(pool, writeTopics, apiKey, apiSecret); + if (out != null) { + for (String url : pool) { + if (url.contains("3905") || url.contains("https")) { + out.useHttps(true); + break; + } + } + } + } } return out; } @Override public void closeClients() { - LOG.debug("Closing Consumer and Producer DMaaP clients"); + LOG.debug("Closing Consumer and Producer DMaaP clients"); if (reader != null) { - reader.close(); + reader.close(); } if (producer != null) { - producer.close(); + producer.close(); } } - + @Override public String getClientId() { return clientId; diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseProcessor.java index c9ba0efa7..784beccc3 100644 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseProcessor.java +++ b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseProcessor.java @@ -92,8 +92,8 @@ public abstract class BaseProcessor extends BaseCommon { preProcess(requestInput); timeoutSeconds = operationHelper.getParamRequestTimeout(requestInput); scheduleAsyncTask(); - } catch (Throwable t) { - setErrorStatus(t); + } catch (Exception e) { + setErrorStatus(e); } finally { postProcess(); } diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamMmodeProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamMmodeProcessor.java index d0d946aed..973d0af36 100644 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamMmodeProcessor.java +++ b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamMmodeProcessor.java @@ -129,8 +129,8 @@ public class OamMmodeProcessor extends BaseProcessor { } setStatus(OAMCommandStatus.SUCCESS); - } catch (Throwable t) { - setErrorStatus(t); + } catch (Exception e) { + setErrorStatus(e); hasError = true; } diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/AsyncTaskHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/AsyncTaskHelper.java index 25467da04..db6033752 100644 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/AsyncTaskHelper.java +++ b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/AsyncTaskHelper.java @@ -158,6 +158,7 @@ public class AsyncTaskHelper { task.cancel(false); if (task == backgroundOamTask) { backgroundOamTask = null; + taskRunnable = null; logDebug("Cancelling background task in cancel task."); } } |