aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDominic Lunanuova <dgl@research.att.com>2019-03-25 13:17:22 +0000
committerGerrit Code Review <gerrit@onap.org>2019-03-25 13:17:22 +0000
commitd2e4071456ec1d8b64aa18fdeeeb30f85e173d9a (patch)
tree1b571d124b0af48fb4af9f0c0af43d8b43cb7d21
parent4e368be013e91f0df6be905893678be1b0ca52a4 (diff)
parent31cbc922a7971a5f20d5790a1fbbd6b38a49af13 (diff)
Merge changes from topic 'required_checker'
* changes: Extract required(...) method Extract class StopWatch from ApiService
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/model/ApiError.java3
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/resources/DR_NodeResource.java17
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/resources/DR_PubResource.java23
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/resources/DR_SubResource.java37
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/resources/DmaapResource.java59
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/resources/FeedResource.java19
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/resources/MR_ClientResource.java37
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResource.java21
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/resources/RequiredChecker.java53
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/resources/RequiredFieldException.java28
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/resources/TopicResource.java23
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/service/ApiService.java359
-rw-r--r--src/main/java/org/onap/dmaap/dbcapi/service/StopWatch.java64
-rw-r--r--src/test/java/org/onap/dmaap/dbcapi/resources/RequiredCheckerTest.java86
-rw-r--r--src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java18
-rw-r--r--src/test/java/org/onap/dmaap/dbcapi/service/StopWatchTest.java49
16 files changed, 530 insertions, 366 deletions
diff --git a/src/main/java/org/onap/dmaap/dbcapi/model/ApiError.java b/src/main/java/org/onap/dmaap/dbcapi/model/ApiError.java
index 2e05740..c67e55b 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/model/ApiError.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/model/ApiError.java
@@ -21,10 +21,11 @@
package org.onap.dmaap.dbcapi.model;
import javax.xml.bind.annotation.XmlRootElement;
+import java.io.Serializable;
import java.util.Objects;
@XmlRootElement
-public class ApiError {
+public class ApiError implements Serializable {
private int code;
private String message;
private String fields;
diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/DR_NodeResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/DR_NodeResource.java
index 029222e..49dc69a 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/resources/DR_NodeResource.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/resources/DR_NodeResource.java
@@ -57,6 +57,7 @@ public class DR_NodeResource extends BaseLoggingClass {
private DR_NodeService dr_nodeService = new DR_NodeService();
private ResponseBuilder responseBuilder = new ResponseBuilder();
+ private RequiredChecker checker = new RequiredChecker();
@GET
@ApiOperation( value = "return DR_Node details",
@@ -88,8 +89,8 @@ public class DR_NodeResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "dcaeLocation", node.getDcaeLocationName(), "");
- resp.required( "fqdn", node.getFqdn(), "");
+ checker.required( "dcaeLocation", node.getDcaeLocationName());
+ checker.required( "fqdn", node.getFqdn());
} catch ( RequiredFieldException rfe ) {
return responseBuilder.error(new ApiError(BAD_REQUEST.getStatusCode(),
"missing required field", "dcaeLocation, fqdn"));
@@ -117,10 +118,10 @@ public class DR_NodeResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "dcaeLocation", name, "");
- resp.required( "fqdn", node.getFqdn(), "");
+ checker.required( "dcaeLocation", name);
+ checker.required( "fqdn", node.getFqdn());
} catch ( RequiredFieldException rfe ) {
- return responseBuilder.error(resp.getErr());
+ return responseBuilder.error(rfe.getApiError());
}
node.setFqdn(name);
DR_Node nNode = dr_nodeService.updateDr_Node(node, resp.getErr());
@@ -146,10 +147,10 @@ public class DR_NodeResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "fqdn", name, "");
+ checker.required( "fqdn", name);
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
dr_nodeService.removeDr_Node(name, resp.getErr());
if ( resp.getErr().is2xx() ) {
diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/DR_PubResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/DR_PubResource.java
index 9c2ae21..1054b03 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/resources/DR_PubResource.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/resources/DR_PubResource.java
@@ -60,6 +60,7 @@ public class DR_PubResource extends BaseLoggingClass {
private DR_PubService dr_pubService = new DR_PubService();
private ResponseBuilder responseBuilder = new ResponseBuilder();
+ private RequiredChecker checker = new RequiredChecker();
@GET
@ApiOperation( value = "return DR_Pub details",
@@ -96,13 +97,13 @@ public class DR_PubResource extends BaseLoggingClass {
logger.info( "Entry: POST /dr_pubs");
try {
- resp.required( "feedId", pub.getFeedId(), "");
+ checker.required( "feedId", pub.getFeedId());
} catch ( RequiredFieldException rfe ) {
try {
- resp.required( "feedName", pub.getFeedName(), "");
+ checker.required( "feedName", pub.getFeedName());
}catch ( RequiredFieldException rfe2 ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe2.getApiError().toString() );
+ return responseBuilder.error(rfe2.getApiError());
}
// if we found a FeedName instead of a FeedId then try to look it up.
List<Feed> nfeeds = feeds.getAllFeeds( pub.getFeedName(), pub.getFeedVersion(), "equals");
@@ -113,10 +114,10 @@ public class DR_PubResource extends BaseLoggingClass {
fnew = nfeeds.get(0);
}
try {
- resp.required( "dcaeLocationName", pub.getDcaeLocationName(), "");
+ checker.required( "dcaeLocationName", pub.getDcaeLocationName());
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.getErr().toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
@@ -189,9 +190,9 @@ public class DR_PubResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "pubId", id, "");
+ checker.required( "pubId", id);
} catch ( RequiredFieldException rfe ) {
- return responseBuilder.error(resp.getErr());
+ return responseBuilder.error(rfe.getApiError());
}
DR_Pub pub = dr_pubService.getDr_Pub( id, resp.getErr() );
@@ -245,9 +246,9 @@ public class DR_PubResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "feedId", id, "");
+ checker.required( "feedId", id);
} catch ( RequiredFieldException rfe ) {
- return responseBuilder.error(resp.getErr());
+ return responseBuilder.error(rfe.getApiError());
}
DR_Pub pub = dr_pubService.getDr_Pub( id, resp.getErr() );
diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/DR_SubResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/DR_SubResource.java
index 01ac059..b74d5a1 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/resources/DR_SubResource.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/resources/DR_SubResource.java
@@ -62,6 +62,7 @@ import static javax.ws.rs.core.Response.Status.CREATED;
public class DR_SubResource extends BaseLoggingClass {
private ResponseBuilder responseBuilder = new ResponseBuilder();
+ private RequiredChecker checker = new RequiredChecker();
@GET
@ApiOperation( value = "return DR_Sub details",
@@ -96,13 +97,13 @@ public class DR_SubResource extends BaseLoggingClass {
FeedService feeds = new FeedService();
Feed fnew = null;
try {
- resp.required( "feedId", sub.getFeedId(), "");
+ checker.required( "feedId", sub.getFeedId());
} catch ( RequiredFieldException rfe ) {
try {
- resp.required( "feedName", sub.getFeedName(), "");
+ checker.required( "feedName", sub.getFeedName());
}catch ( RequiredFieldException rfe2 ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe2.getApiError().toString() );
+ return responseBuilder.error(rfe2.getApiError());
}
// if we found a FeedName instead of a FeedId then try to look it up.
List<Feed> nfeeds = feeds.getAllFeeds( sub.getFeedName(), sub.getFeedVersion(), "equals");
@@ -114,10 +115,10 @@ public class DR_SubResource extends BaseLoggingClass {
}
try {
- resp.required( "dcaeLocationName", sub.getDcaeLocationName(), "");
+ checker.required( "dcaeLocationName", sub.getDcaeLocationName());
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
// we may have fnew already if located by FeedName
if ( fnew == null ) {
@@ -161,13 +162,13 @@ public class DR_SubResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "subId", name, "");
- resp.required( "feedId", sub.getFeedId(), "");
- resp.required( "dcaeLocationName", sub.getDcaeLocationName(), "");
+ checker.required( "subId", name);
+ checker.required( "feedId", sub.getFeedId());
+ checker.required( "dcaeLocationName", sub.getDcaeLocationName());
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
FeedService feeds = new FeedService();
Feed fnew = feeds.getFeed( sub.getFeedId(), resp.getErr() );
@@ -201,10 +202,10 @@ public class DR_SubResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "subId", id, "");
+ checker.required( "subId", id);
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
DR_SubService dr_subService = new DR_SubService();
dr_subService.removeDr_Sub(id, resp.getErr() );
@@ -229,10 +230,10 @@ public class DR_SubResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "subId", id, "");
+ checker.required( "subId", id);
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
DR_SubService dr_subService = new DR_SubService();
DR_Sub sub = dr_subService.getDr_Sub( id, resp.getErr() );
diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/DmaapResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/DmaapResource.java
index d7fb507..955cab7 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/resources/DmaapResource.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/resources/DmaapResource.java
@@ -7,9 +7,9 @@
* 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.
@@ -24,11 +24,14 @@
package org.onap.dmaap.dbcapi.resources;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
+import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
+import org.onap.dmaap.dbcapi.model.ApiError;
+import org.onap.dmaap.dbcapi.model.Dmaap;
+import org.onap.dmaap.dbcapi.service.DmaapService;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
@@ -41,13 +44,6 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
-import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
-import org.onap.dmaap.dbcapi.model.ApiError;
-import org.onap.dmaap.dbcapi.model.Dmaap;
-import org.onap.dmaap.dbcapi.service.ApiService;
-import org.onap.dmaap.dbcapi.service.DmaapService;
-
-
@Path("/dmaap")
@Api( value= "dmaap", description = "Endpoint for this instance of DMaaP object containing values for this OpenDCAE deployment" )
@@ -59,7 +55,8 @@ public class DmaapResource extends BaseLoggingClass {
private DmaapService dmaapService = new DmaapService();
private ResponseBuilder responseBuilder = new ResponseBuilder();
-
+ private RequiredChecker checker = new RequiredChecker();
+
@GET
@ApiOperation( value = "return dmaap details", notes = "returns the `dmaap` object, which contains system wide configuration settings", response = Dmaap.class)
@ApiResponses( value = {
@@ -71,7 +68,7 @@ public class DmaapResource extends BaseLoggingClass {
Dmaap d = dmaapService.getDmaap();
return responseBuilder.success(d);
}
-
+
@POST
@ApiOperation( value = "return dmaap details", notes = "Create a new DMaaP set system wide configuration settings for the *dcaeEnvironment*. Deprecated with introduction of persistence in 1610.", response = Dmaap.class)
@ApiResponses( value = {
@@ -79,26 +76,22 @@ public class DmaapResource extends BaseLoggingClass {
@ApiResponse( code = 400, message = "Error", response = ApiError.class )
})
public Response addDmaap( Dmaap obj ) {
- ApiService check = new ApiService();
- try { //check for required fields
- check.required( "dmaapName", obj.getDmaapName(), "^\\S+$" ); //no white space allowed in dmaapName
- check.required( "dmaapProvUrl", obj.getDrProvUrl(), "" );
- check.required( "topicNsRoot", obj.getTopicNsRoot(), "" );
- check.required( "bridgeAdminTopic", obj.getBridgeAdminTopic(), "" );
+ try {
+ validateRequiredFields(obj);
} catch( RequiredFieldException rfe ) {
- return responseBuilder.error(check.getErr());
+ return responseBuilder.error(rfe.getApiError());
}
-
+
Dmaap d = dmaapService.addDmaap(obj);
if ( d == null ) {
return responseBuilder.notFound();
- }
+ }
return responseBuilder.success(d);
}
-
+
@PUT
@ApiOperation( value = "return dmaap details", notes = "Update system settings for *dcaeEnvironment*.", response = Dmaap.class)
@ApiResponses( value = {
@@ -106,23 +99,25 @@ public class DmaapResource extends BaseLoggingClass {
@ApiResponse( code = 400, message = "Error", response = ApiError.class )
})
public Response updateDmaap( Dmaap obj ) {
- ApiService check = new ApiService();
- try { //check for required fields
- check.required( "dmaapName", obj.getDmaapName(), "^\\S+$" ); //no white space allowed in dmaapName
- check.required( "dmaapProvUrl", obj.getDrProvUrl(), "" );
- check.required( "topicNsRoot", obj.getTopicNsRoot(), "" );
- check.required( "bridgeAdminTopic", obj.getBridgeAdminTopic(), "" );
+ try {
+ validateRequiredFields(obj);
} catch( RequiredFieldException rfe ) {
- return responseBuilder.error(check.getErr());
+ return responseBuilder.error(rfe.getApiError());
}
+
Dmaap d = dmaapService.updateDmaap(obj);
if ( d != null ) {
return responseBuilder.success(d);
} else {
return responseBuilder.notFound();
- }
+ }
+ }
+
+ private void validateRequiredFields(Dmaap obj) throws RequiredFieldException {
+ checker.required( "dmaapName", obj.getDmaapName(), "^\\S+$" ); //no white space allowed in dmaapName
+ checker.required( "dmaapProvUrl", obj.getDrProvUrl());
+ checker.required( "topicNsRoot", obj.getTopicNsRoot());
+ checker.required( "bridgeAdminTopic", obj.getBridgeAdminTopic());
}
-
-
}
diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/FeedResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/FeedResource.java
index 382d88c..86a79f2 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/resources/FeedResource.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/resources/FeedResource.java
@@ -58,6 +58,7 @@ import org.onap.dmaap.dbcapi.service.FeedService;
public class FeedResource extends BaseLoggingClass {
private ResponseBuilder responseBuilder = new ResponseBuilder();
+ private RequiredChecker checker = new RequiredChecker();
@GET
@ApiOperation( value = "return Feed details",
@@ -96,13 +97,13 @@ public class FeedResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "feedName", feed.getFeedName(), "");
- resp.required( "feedVersion", feed.getFeedVersion(), "");
- resp.required( "owner", feed.getOwner(), "" );
- resp.required( "asprClassification", feed.getAsprClassification(), "" );
+ checker.required( "feedName", feed.getFeedName());
+ checker.required( "feedVersion", feed.getFeedVersion());
+ checker.required( "owner", feed.getOwner());
+ checker.required( "asprClassification", feed.getAsprClassification());
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
@@ -152,10 +153,10 @@ public class FeedResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "feedId", id, "");
+ checker.required( "feedId", id);
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
Feed nfeed = feedService.getFeed( id, resp.getErr() );
diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/MR_ClientResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/MR_ClientResource.java
index a67ac8f..a65007d 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/resources/MR_ClientResource.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/resources/MR_ClientResource.java
@@ -62,6 +62,7 @@ public class MR_ClientResource extends BaseLoggingClass {
private MR_ClientService mr_clientService = new MR_ClientService();
private ResponseBuilder responseBuilder = new ResponseBuilder();
+ private RequiredChecker checker = new RequiredChecker();
@GET
@ApiOperation( value = "return MR_Client details",
@@ -95,18 +96,18 @@ public class MR_ClientResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "fqtn", client.getFqtn(), "");
- resp.required( "dcaeLocationName", client.getDcaeLocationName(), "");
+ checker.required( "fqtn", client.getFqtn());
+ checker.required( "dcaeLocationName", client.getDcaeLocationName());
String s = client.getClientRole();
if ( s == null ) {
s = client.getClientIdentity();
}
- resp.required( "clientRole or clientIdentity", s, "" );
- resp.required( "action", client.getAction(), "");
+ checker.required( "clientRole or clientIdentity", s);
+ checker.required( "action", client.getAction());
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
MR_ClusterService clusters = new MR_ClusterService();
@@ -161,14 +162,14 @@ public class MR_ClientResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "fqtn", client.getFqtn(), "");
- resp.required( "dcaeLocationName", client.getDcaeLocationName(), "");
- resp.required( "clientRole", client.getClientRole(), "" );
- resp.required( "action", client.getAction(), "");
+ checker.required( "fqtn", client.getFqtn());
+ checker.required( "dcaeLocationName", client.getDcaeLocationName());
+ checker.required( "clientRole", client.getClientRole());
+ checker.required( "action", client.getAction());
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
client.setMrClientId(clientId);
MR_Client nClient = mr_clientService.updateMr_Client(client, resp.getErr() );
@@ -196,10 +197,10 @@ public class MR_ClientResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "clientId", id, "");
+ checker.required( "clientId", id);
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
mr_clientService.removeMr_Client(id, true, resp.getErr() );
if ( resp.getErr().is2xx()) {
@@ -224,10 +225,10 @@ public class MR_ClientResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "clientId", id, "");
+ checker.required( "clientId", id);
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return responseBuilder.error(resp.getErr());
+ logger.debug( rfe.getApiError().toString() );
+ return responseBuilder.error(rfe.getApiError());
}
MR_Client nClient = mr_clientService.getMr_Client( id, resp.getErr() );
if ( resp.getErr().is2xx()) {
diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResource.java
index 5d2d379..598fcc2 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResource.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResource.java
@@ -56,6 +56,7 @@ public class MR_ClusterResource extends BaseLoggingClass {
private MR_ClusterService mr_clusterService = new MR_ClusterService();
private ResponseBuilder responseBuilder = new ResponseBuilder();
+ private RequiredChecker checker = new RequiredChecker();
@GET
@ApiOperation( value = "return MR_Cluster details",
@@ -86,10 +87,10 @@ public class MR_ClusterResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "dcaeLocationName", cluster.getDcaeLocationName(), "" );
- resp.required( "fqdn", cluster.getFqdn(), "" );
+ checker.required( "dcaeLocationName", cluster.getDcaeLocationName());
+ checker.required( "fqdn", cluster.getFqdn());
} catch( RequiredFieldException rfe ) {
- return responseBuilder.error(resp.getErr());
+ return responseBuilder.error(rfe.getApiError());
}
MR_Cluster mrc = mr_clusterService.addMr_Cluster(cluster, resp.getErr() );
if ( mrc != null && mrc.isStatusValid() ) {
@@ -115,10 +116,10 @@ public class MR_ClusterResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "fqdn", clusterId, "" );
- resp.required( "dcaeLocationName", cluster.getDcaeLocationName(), "" );
+ checker.required( "fqdn", clusterId);
+ checker.required( "dcaeLocationName", cluster.getDcaeLocationName());
} catch( RequiredFieldException rfe ) {
- return responseBuilder.error(resp.getErr());
+ return responseBuilder.error(rfe.getApiError());
}
cluster.setDcaeLocationName(clusterId);
MR_Cluster mrc = mr_clusterService.updateMr_Cluster(cluster, resp.getErr() );
@@ -143,9 +144,9 @@ public class MR_ClusterResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "fqdn", id, "" );
+ checker.required( "fqdn", id);
} catch( RequiredFieldException rfe ) {
- return responseBuilder.error(resp.getErr());
+ return responseBuilder.error(rfe.getApiError());
}
mr_clusterService.removeMr_Cluster(id, resp.getErr() );
if ( resp.getErr().is2xx()) {
@@ -169,9 +170,9 @@ public class MR_ClusterResource extends BaseLoggingClass {
ApiService resp = new ApiService();
try {
- resp.required( "dcaeLocationName", id, "" );
+ checker.required( "dcaeLocationName", id);
} catch( RequiredFieldException rfe ) {
- return responseBuilder.error(resp.getErr());
+ return responseBuilder.error(rfe.getApiError());
}
MR_Cluster mrc = mr_clusterService.getMr_Cluster( id, resp.getErr() );
if ( mrc != null && mrc.isStatusValid() ) {
diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/RequiredChecker.java b/src/main/java/org/onap/dmaap/dbcapi/resources/RequiredChecker.java
new file mode 100644
index 0000000..36f0215
--- /dev/null
+++ b/src/main/java/org/onap/dmaap/dbcapi/resources/RequiredChecker.java
@@ -0,0 +1,53 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dmaap.dbcapi.resources;
+
+import org.onap.dmaap.dbcapi.model.ApiError;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
+
+public class RequiredChecker {
+
+ public void required(String name, Object val) throws RequiredFieldException {
+ if (val == null) {
+ throw new RequiredFieldException(new ApiError(BAD_REQUEST.getStatusCode(),
+ "missing required field", name));
+ }
+ }
+
+ public void required(String name, String val, String expr) throws RequiredFieldException {
+
+ required(name, val);
+
+ if (expr != null && !expr.isEmpty()) {
+ Pattern pattern = Pattern.compile(expr);
+ Matcher matcher = pattern.matcher(val);
+ if (!matcher.find()) {
+ throw new RequiredFieldException(new ApiError(BAD_REQUEST.getStatusCode(),
+ "value '" + val + "' violates regexp check '" + expr + "'", name));
+ }
+ }
+ }
+
+}
diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/RequiredFieldException.java b/src/main/java/org/onap/dmaap/dbcapi/resources/RequiredFieldException.java
index 74af356..2968d18 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/resources/RequiredFieldException.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/resources/RequiredFieldException.java
@@ -7,9 +7,9 @@
* 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.
@@ -20,11 +20,27 @@
package org.onap.dmaap.dbcapi.resources;
+import org.onap.dmaap.dbcapi.model.ApiError;
+
public class RequiredFieldException extends Exception {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 2L;
+
+ private final ApiError apiError;
+
+ public RequiredFieldException(ApiError apiError) {
+ super();
+ this.apiError = apiError;
+ }
+
+ public ApiError getApiError() {
+ return apiError;
+ }
+ @Override
+ public String toString() {
+ return "RequiredFieldException{" +
+ "apiError=" + apiError +
+ '}';
+ }
}
diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/TopicResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/TopicResource.java
index 4f442c9..96b6a4a 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/resources/TopicResource.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/resources/TopicResource.java
@@ -63,6 +63,7 @@ public class TopicResource extends BaseLoggingClass {
private static String defaultReplicationCount;
private TopicService mr_topicService = new TopicService();
private ResponseBuilder responseBuilder = new ResponseBuilder();
+ private RequiredChecker checker = new RequiredChecker();
public TopicResource() {
DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
@@ -109,12 +110,12 @@ public class TopicResource extends BaseLoggingClass {
ApiService check = new ApiService();
try {
- check.required( "topicName", topic.getTopicName(), "^\\S+$" ); //no white space allowed in topicName
- check.required( "topicDescription", topic.getTopicDescription(), "" );
- check.required( "owner", topic.getOwner(), "" );
+ checker.required( "topicName", topic.getTopicName(), "^\\S+$" ); //no white space allowed in topicName
+ checker.required( "topicDescription", topic.getTopicDescription());
+ checker.required( "owner", topic.getOwner());
} catch( RequiredFieldException rfe ) {
- logger.error("Error", rfe);
- return responseBuilder.error(check.getErr());
+ logger.error("Error", rfe.getApiError());
+ return responseBuilder.error(rfe.getApiError());
}
ReplicationType t = topic.getReplicationCase();
@@ -182,10 +183,10 @@ public class TopicResource extends BaseLoggingClass {
ApiService check = new ApiService();
try {
- check.required( "fqtn", id, "" );
+ checker.required( "fqtn", id);
} catch( RequiredFieldException rfe ) {
- logger.error("Error", rfe);
- return responseBuilder.error(check.getErr());
+ logger.error("Error", rfe.getApiError());
+ return responseBuilder.error(rfe.getApiError());
}
mr_topicService.removeTopic(id, check.getErr());
@@ -212,10 +213,10 @@ public class TopicResource extends BaseLoggingClass {
ApiService check = new ApiService();
try {
- check.required( "topicName", id, "^\\S+$" ); //no white space allowed in topicName
+ checker.required( "topicName", id, "^\\S+$" ); //no white space allowed in topicName
} catch( RequiredFieldException rfe ) {
- logger.error("Error", rfe);
- return responseBuilder.error(check.getErr());
+ logger.error("Error", rfe.getApiError());
+ return responseBuilder.error(rfe.getApiError());
}
Topic mrc = mr_topicService.getTopic( id, check.getErr() );
if ( mrc == null ) {
diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/ApiService.java b/src/main/java/org/onap/dmaap/dbcapi/service/ApiService.java
index 23f4fef..35e61db 100644
--- a/src/main/java/org/onap/dmaap/dbcapi/service/ApiService.java
+++ b/src/main/java/org/onap/dmaap/dbcapi/service/ApiService.java
@@ -7,9 +7,9 @@
* 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.
@@ -20,261 +20,172 @@
package org.onap.dmaap.dbcapi.service;
-import static com.att.eelf.configuration.Configuration.MDC_BEGIN_TIMESTAMP;
-import static com.att.eelf.configuration.Configuration.MDC_ELAPSED_TIME;
-import static com.att.eelf.configuration.Configuration.MDC_END_TIMESTAMP;
import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
import static com.att.eelf.configuration.Configuration.MDC_PARTNER_NAME;
import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.TimeZone;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.ws.rs.core.Response.Status;
import javax.xml.bind.DatatypeConverter;
-
import org.onap.dmaap.dbcapi.aaf.DmaapPerm;
import org.onap.dmaap.dbcapi.authentication.ApiPolicy;
import org.onap.dmaap.dbcapi.authentication.AuthenticationErrorException;
import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
import org.onap.dmaap.dbcapi.model.ApiError;
import org.onap.dmaap.dbcapi.model.Dmaap;
-import org.onap.dmaap.dbcapi.resources.RequiredFieldException;
import org.onap.dmaap.dbcapi.util.DmaapConfig;
import org.onap.dmaap.dbcapi.util.RandomString;
import org.slf4j.MDC;
public class ApiService extends BaseLoggingClass {
- private class StopWatch {
- private long clock = 0;
- private long elapsed = 0;
-
-
-
- public StopWatch() {
- clock = 0;
- elapsed = 0;
- }
-
- public void reset() {
- clock = System.currentTimeMillis();
- elapsed = 0;
- }
- public void stop() {
- Long stopTime = System.currentTimeMillis();
- elapsed += stopTime - clock;
- clock = 0;
- MDC.put( MDC_END_TIMESTAMP, isoFormatter.format(new Date(stopTime)));
- MDC.put( MDC_ELAPSED_TIME, String.valueOf(elapsed));
- }
- public void start() {
- if ( clock != 0 ) {
- //not stopped
- return;
- }
- clock = System.currentTimeMillis();
- MDC.put( MDC_BEGIN_TIMESTAMP, isoFormatter.format(new Date(clock)));
- }
- private long getElapsed() {
- return elapsed;
- }
- }
-
- private String apiNamespace;
-
- private String uri;
- private String uriPath;
- private String method;
- private String authorization;
- private String requestId;
- private ApiError err;
- private StopWatch stopwatch;
- private ApiPolicy apiPolicy;
-
- public static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
- public final static TimeZone utc = TimeZone.getTimeZone("UTC");
- public final static SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
-
- static {
- isoFormatter.setTimeZone(utc);
- }
- public ApiService() {
-
- stopwatch = new StopWatch();
- stopwatch.start();
- err = new ApiError();
- requestId = (new RandomString(10)).nextString();
-
- if (apiNamespace == null) {
- DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
- apiNamespace = p.getProperty("ApiNamespace", "org.openecomp.dmaapBC.api");
- logger.info( "config param usePE has been deprecated. Use ApiPermission.Class property instead.");
- }
- apiPolicy = new ApiPolicy();
-
- logger.info( "apiNamespace=" + apiNamespace);
- }
-
- public ApiService setAuth( String auth ) {
- this.authorization = auth;
- logger.info( "setAuth: authorization={} ", authorization);
- return this;
- }
- private void setServiceName(){
- String svcRequest = new String( this.method + " " + this.uriPath );
- MDC.put(MDC_SERVICE_NAME, svcRequest );
- }
- public ApiService setHttpMethod( String httpMethod ) {
- this.method = httpMethod;
- logger.info( "setHttpMethod: method={} ", method);
- setServiceName();
- return this;
- }
- public ApiService setUriPath( String uriPath ) {
- this.uriPath = uriPath;
- this.uri = setUriFromPath( uriPath );
- logger.info( "setUriPath: uriPath={} uri={}", uriPath, uri);
- setServiceName();
- return this;
- }
- private String setUriFromPath( String uriPath ) {
- int ch = uriPath.indexOf("/");
- if ( ch > 0 ) {
- return( (String) uriPath.subSequence(0, ch ) );
- } else {
- return uriPath;
- }
- }
-
- public ApiError getErr() {
- return err;
- }
-
-
- public void setErr(ApiError err) {
- this.err = err;
- }
-
-
- // test for presence of a required field
- public void required( String name, Object val, String expr ) throws RequiredFieldException {
- err.setCode(0);
- if ( val == null ) {
- err.setCode(Status.BAD_REQUEST.getStatusCode());
- err.setMessage("missing required field");
- err.setFields( name );
- throw new RequiredFieldException();
- }
- if ( expr != null && ! expr.isEmpty() ) {
- Pattern pattern = Pattern.compile(expr);
- Matcher matcher = pattern.matcher((CharSequence) val);
- if ( ! matcher.find() ) {
- err.setCode(Status.BAD_REQUEST.getStatusCode());
- err.setMessage( "value '" + val + "' violates regexp check '" + expr + "'");
- err.setFields( name );
- throw new RequiredFieldException();
- }
- }
- }
-
- // utility to serialize ApiErr object
- public String toString() {
- return String.format( "code=%d msg=%s fields=%s", err.getCode(), err.getMessage(), err.getFields() );
- }
+ private String apiNamespace;
+ private String uri;
+ private String uriPath;
+ private String method;
+ private String authorization;
+ private String requestId;
+ private ApiError err;
+ private ApiPolicy apiPolicy;
+
+ public ApiService() {
+
+ err = new ApiError();
+ requestId = (new RandomString(10)).nextString();
+
+ if (apiNamespace == null) {
+ DmaapConfig p = (DmaapConfig) DmaapConfig.getConfig();
+ apiNamespace = p.getProperty("ApiNamespace", "org.openecomp.dmaapBC.api");
+ logger.info("config param usePE has been deprecated. Use ApiPermission.Class property instead.");
+ }
+ apiPolicy = new ApiPolicy();
+
+ logger.info("apiNamespace=" + apiNamespace);
+ }
+
+ public ApiService setAuth(String auth) {
+ this.authorization = auth;
+ logger.info("setAuth: authorization={} ", authorization);
+ return this;
+ }
+
+ private void setServiceName() {
+ String svcRequest = new String(this.method + " " + this.uriPath);
+ MDC.put(MDC_SERVICE_NAME, svcRequest);
+ }
+
+ public ApiService setHttpMethod(String httpMethod) {
+ this.method = httpMethod;
+ logger.info("setHttpMethod: method={} ", method);
+ setServiceName();
+ return this;
+ }
+
+ public ApiService setUriPath(String uriPath) {
+ this.uriPath = uriPath;
+ this.uri = setUriFromPath(uriPath);
+ logger.info("setUriPath: uriPath={} uri={}", uriPath, uri);
+ setServiceName();
+ return this;
+ }
+
+ private String setUriFromPath(String uriPath) {
+ int ch = uriPath.indexOf("/");
+ if (ch > 0) {
+ return ((String) uriPath.subSequence(0, ch));
+ } else {
+ return uriPath;
+ }
+ }
+
+ public ApiError getErr() {
+ return err;
+ }
+
+
+ public void setErr(ApiError err) {
+ this.err = err;
+ }
public void setCode(int statusCode) {
err.setCode(statusCode);
}
- public void setMessage(String string) {
- err.setMessage(string);
- }
+ public void setMessage(String string) {
+ err.setMessage(string);
+ }
public void setFields(String string) {
err.setFields(string);
}
-
- public void checkAuthorization( String auth, String uriPath, String httpMethod ) throws AuthenticationErrorException, Exception {
- authorization = auth;
- setUriFromPath( uriPath );
- method = httpMethod;
-
- checkAuthorization();
- }
-
- public void checkAuthorization() throws AuthenticationErrorException, Exception {
-
- MDC.put(MDC_KEY_REQUEST_ID, requestId);
-
- logger.info("request: uri={} method={} auth={}", uri, method, authorization );
-
- if ( uri == null || uri.isEmpty()) {
- String errmsg = "No URI value provided ";
- err.setMessage(errmsg);
- logger.info( errmsg );
- throw new AuthenticationErrorException( );
- }
- if ( method == null || method.isEmpty()) {
- String errmsg = "No method value provided ";
- err.setMessage(errmsg);
- logger.info( errmsg );
- throw new AuthenticationErrorException( );
- }
- DmaapService dmaapService = new DmaapService();
- Dmaap dmaap = dmaapService.getDmaap();
- String env = dmaap.getDmaapName();
-
- // special case during bootstrap of app when DMaaP environment may not be set.
- // this allows us to authorize certain APIs used for initialization during this window.
- if ( env == null || env.isEmpty() ) {
- env = "boot";
- }
- if ( ! apiPolicy.getUseAuthClass() ) return; // skip authorization if not enabled
- if ( authorization == null || authorization.isEmpty()) {
- String errmsg = "No basic authorization value provided ";
- err.setMessage(errmsg);
- logger.info( errmsg );
- throw new AuthenticationErrorException( );
- }
- String credentials = authorization.substring("Basic".length()).trim();
+ public void checkAuthorization() throws Exception {
+
+ MDC.put(MDC_KEY_REQUEST_ID, requestId);
+
+ logger.info("request: uri={} method={} auth={}", uri, method, authorization);
+
+ if (uri == null || uri.isEmpty()) {
+ String errmsg = "No URI value provided ";
+ err.setMessage(errmsg);
+ logger.info(errmsg);
+ throw new AuthenticationErrorException();
+ }
+ if (method == null || method.isEmpty()) {
+ String errmsg = "No method value provided ";
+ err.setMessage(errmsg);
+ logger.info(errmsg);
+ throw new AuthenticationErrorException();
+ }
+ DmaapService dmaapService = new DmaapService();
+ Dmaap dmaap = dmaapService.getDmaap();
+ String env = dmaap.getDmaapName();
+
+ // special case during bootstrap of app when DMaaP environment may not be set.
+ // this allows us to authorize certain APIs used for initialization during this window.
+ if (env == null || env.isEmpty()) {
+ env = "boot";
+ }
+ if (!apiPolicy.getUseAuthClass()) {
+ return; // skip authorization if not enabled
+ }
+ if (authorization == null || authorization.isEmpty()) {
+ String errmsg = "No basic authorization value provided ";
+ err.setMessage(errmsg);
+ logger.info(errmsg);
+ throw new AuthenticationErrorException();
+ }
+ String credentials = authorization.substring("Basic".length()).trim();
byte[] decoded = DatatypeConverter.parseBase64Binary(credentials);
String decodedString = new String(decoded);
String[] actualCredentials = decodedString.split(":");
String ID = actualCredentials[0];
String Password = actualCredentials[1];
MDC.put(MDC_PARTNER_NAME, ID);
- try {
-
- DmaapPerm p = new DmaapPerm( apiNamespace + "." + uri, env, method );
- apiPolicy.check( ID, Password, p);
- } catch ( AuthenticationErrorException ae ) {
- String errmsg = "User " + ID + " failed authentication/authorization for " + apiNamespace + "." + uriPath + " " + env + " " + method;
- logger.info( errmsg );
- err.setMessage(errmsg);
- throw ae;
-
- }
-
-
- }
- public String getRequestId() {
- return requestId;
- }
- public ApiService setRequestId(String requestId) {
- if ( requestId == null || requestId.isEmpty()) {
- this.requestId = (new RandomString(10)).nextString();
- logger.warn( "X-ECOMP-RequestID not set in HTTP Header. Setting RequestId value to: " + this.requestId );
- } else {
- this.requestId = requestId;
- }
- MDC.put(MDC_KEY_REQUEST_ID, this.requestId);
- return this;
- }
+ try {
+
+ DmaapPerm p = new DmaapPerm(apiNamespace + "." + uri, env, method);
+ apiPolicy.check(ID, Password, p);
+ } catch (AuthenticationErrorException ae) {
+ String errmsg =
+ "User " + ID + " failed authentication/authorization for " + apiNamespace + "." + uriPath + " " + env
+ + " " + method;
+ logger.info(errmsg);
+ err.setMessage(errmsg);
+ throw ae;
+
+ }
+ }
+
+ public ApiService setRequestId(String requestId) {
+ if (requestId == null || requestId.isEmpty()) {
+ this.requestId = (new RandomString(10)).nextString();
+ logger.warn("X-ECOMP-RequestID not set in HTTP Header. Setting RequestId value to: " + this.requestId);
+ } else {
+ this.requestId = requestId;
+ }
+ MDC.put(MDC_KEY_REQUEST_ID, this.requestId);
+ return this;
+ }
}
+
diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/StopWatch.java b/src/main/java/org/onap/dmaap/dbcapi/service/StopWatch.java
new file mode 100644
index 0000000..6dc8fe9
--- /dev/null
+++ b/src/main/java/org/onap/dmaap/dbcapi/service/StopWatch.java
@@ -0,0 +1,64 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dmaap
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dmaap.dbcapi.service;
+
+import static com.att.eelf.configuration.Configuration.MDC_BEGIN_TIMESTAMP;
+import static com.att.eelf.configuration.Configuration.MDC_ELAPSED_TIME;
+import static com.att.eelf.configuration.Configuration.MDC_END_TIMESTAMP;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.TimeZone;
+import org.slf4j.MDC;
+
+
+public class StopWatch {
+
+ private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
+ private final static SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
+ private final static TimeZone utc = TimeZone.getTimeZone("UTC");
+
+ private long startTimestamp;
+ private long elapsedTime;
+
+ static {
+ isoFormatter.setTimeZone(utc);
+ }
+
+ public void start() {
+ startTimestamp = System.currentTimeMillis();
+ MDC.put(MDC_BEGIN_TIMESTAMP, isoFormatter.format(new Date(startTimestamp)));
+ }
+
+ public void stop() {
+ long endTimestamp = System.currentTimeMillis();
+ elapsedTime = endTimestamp - startTimestamp;
+ MDC.put(MDC_END_TIMESTAMP, isoFormatter.format(new Date(endTimestamp)));
+ MDC.put(MDC_ELAPSED_TIME, String.valueOf(elapsedTime));
+ }
+
+ public void resetElapsedTime() {
+ elapsedTime = 0;
+ }
+
+ public long getElapsedTime() {
+ return elapsedTime;
+ }
+}
diff --git a/src/test/java/org/onap/dmaap/dbcapi/resources/RequiredCheckerTest.java b/src/test/java/org/onap/dmaap/dbcapi/resources/RequiredCheckerTest.java
new file mode 100644
index 0000000..f07058b
--- /dev/null
+++ b/src/test/java/org/onap/dmaap/dbcapi/resources/RequiredCheckerTest.java
@@ -0,0 +1,86 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dmaap.dbcapi.resources;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.onap.dmaap.dbcapi.model.ApiError;
+
+import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
+import static org.junit.Assert.fail;
+
+public class RequiredCheckerTest {
+
+ private static final String NAME = "field_name";
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+ private RequiredChecker requiredChecker = new RequiredChecker();
+
+
+ @Test
+ public void required_shouldThrowExceptionWhenObjectIsNull() throws RequiredFieldException {
+ thrown.expect(RequiredFieldException.class);
+ thrown.expect(new ApiErrorMatcher(new ApiError(BAD_REQUEST.getStatusCode(),
+ "missing required field", NAME)));
+
+ requiredChecker.required(NAME, null);
+ }
+
+ @Test
+ public void required_shouldThrowExceptionWhenRegexValidationFailed() throws RequiredFieldException {
+ thrown.expect(RequiredFieldException.class);
+ thrown.expect(new ApiErrorMatcher(new ApiError(BAD_REQUEST.getStatusCode(),
+ "value 'with white space' violates regexp check '^\\S+$'", NAME)));
+
+ requiredChecker.required(NAME, "with white space", "^\\S+$");
+ }
+
+ @Test
+ public void required_shouldPassValidation() {
+ try {
+ requiredChecker.required(NAME, "value", "^\\S+$");
+ } catch (RequiredFieldException e) {
+ fail("No exception should be thrown");
+ }
+ }
+
+ class ApiErrorMatcher extends BaseMatcher {
+
+ private final ApiError expectedApiEror;
+
+ ApiErrorMatcher(ApiError expectedApiEror) {
+ this.expectedApiEror = expectedApiEror;
+ }
+
+ @Override
+ public boolean matches(Object exception) {
+ return expectedApiEror.equals(((RequiredFieldException) exception).getApiError());
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("Following ApiError is expected: ").appendValue(expectedApiEror);
+ }
+ }
+} \ No newline at end of file
diff --git a/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java b/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java
index 33cce9d..dccfadf 100644
--- a/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java
+++ b/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java
@@ -59,22 +59,4 @@ public class ApiServiceTest {
rh.reflect( "org.onap.dmaap.dbcapi.service.ApiService", "set", v );
}
-
- @Test
- public void test3() {
- ApiService nd = new ApiService();
- nd.setAuth( "auth" );
- try {
- nd.required( "aName", null, "anExpr" );
- } catch ( RequiredFieldException rfe ) {
- }
- try {
- nd.checkAuthorization( "authval", "/uri/Path", "GET" );
- nd.checkAuthorization();
- } catch ( AuthenticationErrorException aee ) {
- } catch ( Exception e ) {
- }
- }
-
-
}
diff --git a/src/test/java/org/onap/dmaap/dbcapi/service/StopWatchTest.java b/src/test/java/org/onap/dmaap/dbcapi/service/StopWatchTest.java
new file mode 100644
index 0000000..b4b6af2
--- /dev/null
+++ b/src/test/java/org/onap/dmaap/dbcapi/service/StopWatchTest.java
@@ -0,0 +1,49 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dmaap
+ * ================================================================================
+ * Copyright (C) 2019 Nokia Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dmaap.dbcapi.service;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
+
+public class StopWatchTest extends BaseLoggingClass {
+
+ private StopWatch stopWatch = new StopWatch();
+
+ @Test
+ public void stopWatchShouldReturnElapsedTime() throws InterruptedException {
+ stopWatch.start();
+ Thread.sleep(50);
+ stopWatch.stop();
+ assertTrue(stopWatch.getElapsedTime() > 0);
+ }
+
+ @Test
+ public void resetShouldSetElapsedTime() {
+ stopWatch.start();
+ stopWatch.stop();
+ stopWatch.resetElapsedTime();
+ assertEquals(0,stopWatch.getElapsedTime());
+
+ }
+
+} \ No newline at end of file