+++ /dev/null
-{
- "code" : {
- "200" :
- [
- {
- "Reason" : "OK",
- "ErrorCode": ["OK","Event message has been accepted"]
- }
- ],
-
- "204": [
- {
- "Reason" : "Accepted",
- "ErrorCode": ["OK","Event message has been accepted"]
- }
- ],
- "400" :
- [
- {
- "Reason" : "BadParameter",
- "ErrorCode": ["SVC0002","Bad Parameter" ]
- },
-
- {
- "Reason" : "Error",
- "ErrorCode": ["SVC2000","General Service Error with details"]
- },
- {
- "Reason" : "exceeded",
- "ErrorCode": ["POL9003","Message content size exceeded" ]
- }
-
- ],
- "401" :
- [
- {
- "Reason" : "Unauthorized",
- "ErrorCode": ["POL2000","Unauthorized user"]
- }
- ]
- }
-}
\ No newline at end of file
collector.dmaap.streamid=fault=ves_fault|syslog=ves_syslog|heartbeat=ves_heartbeat|measurementsForVfScaling=ves_measurement|mobileFlow=ves_mobileflow|other=ves_other|stateChange=ves_statechange|thresholdCrossingAlert=ves_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling\r
collector.dmaapfile=./etc/DmaapConfig.json\r
\r
-## Custom ExceptionConfiguration\r
-exceptionConfig=./etc/ExceptionConfig.json\r
-\r
## authflag control authentication by the collector\r
## If enabled (1) - then authlist has to be defined\r
## When authflag is enabled, only secure port will be supported\r
\r
public static final String KSETTING_SCHEMAFILE = "collector.schema.file";\r
public static final String KDEFAULT_SCHEMAFILE = "{\"v5\":\"./etc/CommonEventFormat_28.3.json\"}";\r
- public static final String KSETTING_EXCEPTIONCONFIG = "exceptionConfig";\r
\r
public static final String KSETTING_DMAAPSTREAMID = "collector.dmaap.streamid";\r
\r
public static int eventTransformFlag = 1;\r
public static String schemaFile;\r
public static JSONObject schemaFileJson;\r
- public static String exceptionConfig;\r
public static String cambriaConfigFile;\r
private boolean listnerstatus;\r
public static String streamid;\r
schemaFileJson = new JSONObject(schemaFile);\r
\r
}\r
- exceptionConfig = settings.getString(KSETTING_EXCEPTIONCONFIG, null);\r
authflag = settings.getInt(CommonStartup.KSETTING_AUTHFLAG, CommonStartup.KDEFAULT_AUTHFLAG);\r
String[] currentconffile = settings.getStrings(CommonStartup.KSETTING_DMAAPCONFIGS,\r
CommonStartup.KDEFAULT_DMAAPCONFIGS);\r
fTomcatServer = new ApiServer.Builder(connectors, new RestfulCollectorServlet(settings)).encodeSlashes(true)\r
.name("collector").build();\r
\r
- // Load override exception map\r
- CustomExceptionLoader.LoadMap();\r
setListnerstatus(true);\r
}\r
\r
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 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.dcae.commonFunction;
-
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.HashMap;
-
-import java.util.Map.Entry;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonIOException;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
-
-public class CustomExceptionLoader {
-
- protected static HashMap<String, JsonArray> map = null;
- private static final Logger log = LoggerFactory.getLogger(CustomExceptionLoader.class);
-
- // For standalone test
- // LoadMap Invoked from servletSetup
- /*
- * public static void main(String[] args) {
- *
- * System.out.
- * println("CustomExceptionLoader.main --> Arguments -- ExceptionConfig file: "
- * + args[0] + "StatusCode:" + args[1]+ " Error Msg:" + args[2]);
- * CommonStartup.exceptionConfig = args[0];
- *
- * //Read the Custom exception JSON file into map LoadMap(); System.out.
- * println("CustomExceptionLoader.main --> Map info post LoadMap:" + map);
- *
- * String[] str= LookupMap(args[1],args[2]); if (! (str==null)) {
- * System.out.
- * println("CustomExceptionLoader.main --> Return from lookup function" +
- * str[0] + "value:" + str[1]); }
- *
- * }
- */
-
- public static void LoadMap() {
-
- map = new HashMap<String, JsonArray>();
- FileReader fr = null;
- try {
- JsonElement root = null;
- fr = new FileReader(CommonStartup.exceptionConfig);
- root = new JsonParser().parse(fr);
- JsonObject jsonObject = root.getAsJsonObject().get("code").getAsJsonObject();
-
- for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
- map.put(entry.getKey(), (JsonArray) entry.getValue());
- }
-
- log.debug("CustomExceptionLoader.LoadMap --> Map loaded - " + map);
- } catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) {
- log.error("Exception in LoadMap:" + e.getMessage());
- map = null;
- } finally {
- if (fr != null) {
- try {
- fr.close();
- } catch (IOException e) {
- log.error("Error closing file reader stream : " + e.toString());
- map = null;
- }
- }
- }
- }
-
- public static String[] LookupMap(String error, String errormsg) {
-
- String[] retarray = null;
-
- log.debug("CustomExceptionLoader.LookupMap -->" + " HTTP StatusCode:" + error + " Msg:" + errormsg);
- try {
-
- JsonArray jarray = map.get(error);
- for (int i = 0; i < jarray.size(); i++) {
-
- JsonElement val = jarray.get(i).getAsJsonObject().get("Reason");
- JsonArray ec = (JsonArray) jarray.get(i).getAsJsonObject().get("ErrorCode");
- log.trace("CustomExceptionLoader.LookupMap Parameter -> Error msg : " + errormsg
- + " Reason text being matched:" + val);
- if (errormsg.contains(val.toString().replace("\"", ""))) {
- log.trace(
- "CustomExceptionLoader.LookupMap Successful! Exception matched to error message StatusCode:"
- + ec.get(0).toString() + "ErrorMessage:" + ec.get(1).toString());
- retarray = new String[2];
- retarray[0] = ec.get(0).toString();
- retarray[1] = ec.get(1).toString();
- return retarray;
- }
- }
-
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
-
- return retarray;
- }
-
-}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.collectors.ves
+ * ================================================================================
+ * Copyright (C) 2018 Nokia. 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.dcae.restapi;
+
+import com.google.common.base.CaseFormat;
+import org.json.JSONObject;
+
+/**
+ * @author Pawel Szalapski (pawel.szalapski@nokia.com)
+ */
+public enum ApiException {
+
+ INVALID_JSON_INPUT(ExceptionType.SERVICE_EXCEPTION, "SVC0002", "Incorrect JSON payload", 400),
+ SCHEMA_VALIDATION_FAILED(ExceptionType.SERVICE_EXCEPTION, "SVC0002", "Bad Parameter (JSON does not conform to schema)", 400),
+ INVALID_CONTENT_TYPE(ExceptionType.SERVICE_EXCEPTION, "SVC0002", "Bad Parameter (Incorrect request Content-Type)", 400),
+ UNAUTHORIZED_USER(ExceptionType.POLICY_EXCEPTION, "POL2000", "Unauthorized user", 401),
+ NO_SERVER_RESOURCES(ExceptionType.SERVICE_EXCEPTION, "SVC1000", "No server resources (internal processing queue full)", 503);
+
+ public final ExceptionType type;
+ public final String code;
+ public final String details;
+ public final int httpStatusCode;
+
+ ApiException(ExceptionType type, String code, String details, int httpStatusCode) {
+ this.type = type;
+ this.code = code;
+ this.details = details;
+ this.httpStatusCode = httpStatusCode;
+ }
+
+ public enum ExceptionType {
+ SERVICE_EXCEPTION, POLICY_EXCEPTION;
+
+ @Override
+ public String toString() {
+ return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, this.name());
+ }
+ }
+
+ public JSONObject toJSON() {
+ JSONObject exceptionTypeNode = new JSONObject();
+ exceptionTypeNode.put("messageId", code );
+ exceptionTypeNode.put("text", details);
+
+ JSONObject requestErrorNode = new JSONObject();
+ requestErrorNode.put(type.toString(), exceptionTypeNode);
+
+ JSONObject rootNode = new JSONObject();
+ rootNode.put("requestError", requestErrorNode);
+ return rootNode;
+ }
+
+}
import com.att.nsa.logging.log4j.EcompFields;\r
import com.att.nsa.security.db.simple.NsaSimpleApiKey;\r
import com.google.gson.JsonParser;\r
+import java.io.FileReader;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.nio.charset.Charset;\r
+import java.util.Base64;\r
+import java.util.UUID;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
import org.json.JSONArray;\r
import org.json.JSONException;\r
import org.json.JSONObject;\r
import org.json.JSONTokener;\r
import org.onap.dcae.commonFunction.CommonStartup;\r
import org.onap.dcae.commonFunction.CommonStartup.QueueFullException;\r
-import org.onap.dcae.commonFunction.CustomExceptionLoader;\r
import org.onap.dcae.commonFunction.VESLogger;\r
+import org.onap.dcae.restapi.ApiException;\r
import org.slf4j.Logger;\r
import org.slf4j.LoggerFactory;\r
\r
-\r
-import java.io.FileReader;\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.nio.charset.Charset;\r
-import java.util.Base64;\r
-import java.util.UUID;\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
-\r
public class EventReceipt extends NsaBaseEndpoint {\r
\r
private static final Logger log = LoggerFactory.getLogger(EventReceipt.class);\r
//log.info("Invalid user request :" + userId + " FROM " + ctx.request().getRemoteAddress() + " " + ctx.request().getContentType() + MESSAGE + jsonObject);\r
log.info(String.format("Unauthorized request %s FROM %s %s %s %s", getUser(ctx), ctx.request().getRemoteAddress(), ctx.request().getContentType(), MESSAGE, jsonObject));\r
CommonStartup.eplog.info("EVENT_RECEIPT_FAILURE: Unauthorized user" + userId + x);\r
- respondWithCustomMsginJson(ctx, HttpStatusCodes.k401_unauthorized, "Invalid user");\r
+ respondWithCustomMsginJson(ctx, ApiException.UNAUTHORIZED_USER);\r
return;\r
}\r
\r
log.error(String.format("Couldn't parse JSON Array - HttpStatusCodes.k400_badRequest%d%s%s",\r
HttpStatusCodes.k400_badRequest, MESSAGE, x.getMessage()));\r
CommonStartup.eplog.info("EVENT_RECEIPT_FAILURE: Invalid user request " + x);\r
- respondWithCustomMsginJson(ctx, HttpStatusCodes.k400_badRequest, "Couldn't parse JSON object");\r
+ respondWithCustomMsginJson(ctx, ApiException.INVALID_JSON_INPUT);\r
return;\r
} catch (QueueFullException e) {\r
log.error("Collector internal queue full :" + e.getMessage(), e);\r
CommonStartup.eplog.info("EVENT_RECEIPT_FAILURE: QueueFull" + e);\r
- respondWithCustomMsginJson(ctx, HttpStatusCodes.k503_serviceUnavailable, "Queue full");\r
+ respondWithCustomMsginJson(ctx, ApiException.NO_SERVER_RESOURCES);\r
return;\r
} finally {\r
if (fr != null) {\r
log.info("Validation successful");\r
} else if (valresult.equals("false")) {\r
log.info("Validation failed");\r
- respondWithCustomMsginJson(ctx, HttpStatusCodes.k400_badRequest,\r
- "Schema validation failed");\r
+ respondWithCustomMsginJson(ctx, ApiException.SCHEMA_VALIDATION_FAILED);\r
ErrorStatus=true;\r
return ErrorStatus;\r
} else {\r
log.error("Validation errored" + valresult);\r
- respondWithCustomMsginJson(ctx, HttpStatusCodes.k400_badRequest,\r
- "Couldn't parse JSON object");\r
+ respondWithCustomMsginJson(ctx, ApiException.INVALID_JSON_INPUT);\r
ErrorStatus=true;\r
return ErrorStatus;\r
}\r
} else {\r
log.info("Validation failed");\r
- respondWithCustomMsginJson(ctx, HttpStatusCodes.k400_badRequest, "Schema validation failed");\r
+ respondWithCustomMsginJson(ctx, ApiException.SCHEMA_VALIDATION_FAILED);\r
ErrorStatus=true;\r
return ErrorStatus;\r
}\r
if (!ctx.request().getContentType().equalsIgnoreCase("application/json")) {\r
log.info(String.format("Rejecting request with content type %s Message:%s",\r
ctx.request().getContentType(), jsonObject));\r
- respondWithCustomMsginJson(ctx, HttpStatusCodes.k400_badRequest,\r
- "Incorrect message content-type; only accepts application/json messages");\r
+ respondWithCustomMsginJson(ctx, ApiException.INVALID_CONTENT_TYPE);\r
ErrorStatus=true;\r
return ErrorStatus;\r
}\r
} else {\r
log.info(String.format("Unauthorized request %s FROM %s %s %s %s", getUser(ctx), ctx.request().getRemoteAddress(), ctx.request().getContentType(), MESSAGE,\r
jsonObject));\r
- respondWithCustomMsginJson(ctx, HttpStatusCodes.k401_unauthorized, "Unauthorized user");\r
+ respondWithCustomMsginJson(ctx, ApiException.UNAUTHORIZED_USER);\r
ErrorStatus=true;\r
return ErrorStatus;\r
}\r
return ErrorStatus;\r
}\r
\r
- public static void respondWithCustomMsginJson(DrumlinRequestContext ctx, int sc, String msg) {\r
- String[] str;\r
- String exceptionType = "GeneralException";\r
-\r
- str = CustomExceptionLoader.LookupMap(String.valueOf(sc), msg);\r
- log.info("Post CustomExceptionLoader.LookupMap" + str);\r
-\r
- if (str != null) {\r
-\r
- if (str[0].matches("SVC")) {\r
- exceptionType = "ServiceException";\r
- } else if (str[1].matches("POL")) {\r
- exceptionType = "PolicyException";\r
- }\r
-\r
- JSONObject jb = new JSONObject().put("requestError",\r
- new JSONObject().put(exceptionType, new JSONObject().put("MessagID", str[0]).put("text", str[1])));\r
-\r
- log.debug("Constructed json error : " + jb);\r
- ctx.response().sendErrorAndBody(sc, jb.toString(), MimeTypes.kAppJson);\r
- } else {\r
- JSONObject jb = new JSONObject().put("requestError",\r
- new JSONObject().put(exceptionType, new JSONObject().put("Status", sc).put("Error", msg)));\r
- ctx.response().sendErrorAndBody(sc, jb.toString(), MimeTypes.kAppJson);\r
- }\r
-\r
+ public static void respondWithCustomMsginJson(DrumlinRequestContext ctx, ApiException apiException) {\r
+ ctx.response()\r
+ .sendErrorAndBody(apiException.httpStatusCode,\r
+ apiException.toJSON().toString(), MimeTypes.kAppJson);\r
}\r
\r
public static void safeClose(FileReader fr) {\r
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dcaegen2.collectors.ves
+ * ================================================================================
+ * Copyright (C) 2018 Nokia. 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.dcae.commonFunction;
+
+import static org.junit.Assert.assertEquals;
+
+import org.json.JSONObject;
+import org.junit.Test;
+import org.onap.dcae.restapi.ApiException;
+import org.onap.dcae.restapi.ApiException.ExceptionType;
+
+/**
+ * @author Pawel Szalapski (pawel.szalapski@nokia.com)
+ */
+public class ApiExceptionTest {
+
+ @Test
+ public void shouldStringifyServiceExceptionTypeAccordingToSpecification() {
+ assertEquals(ExceptionType.SERVICE_EXCEPTION.toString(), "ServiceException");
+ }
+
+ @Test
+ public void shouldStringifyPolicyExceptionTypeAccordingToSpecification() {
+ assertEquals(ExceptionType.POLICY_EXCEPTION.toString(), "PolicyException");
+ }
+
+ @Test
+ public void shouldConvertExceptionToBackwardCompatibleFormat() {
+ JSONObject responseBody = ApiException.UNAUTHORIZED_USER.toJSON();
+ assertJSONEqual(responseBody, asJSON(""
+ + "{ "
+ + " 'requestError': { "
+ + " 'PolicyException': { "
+ + " 'messageId': 'POL2000', "
+ + " 'text': 'Unauthorized user' "
+ + " } "
+ + " } "
+ + "} "
+ ));
+ }
+
+ private JSONObject asJSON(String jsonString) {
+ return new JSONObject(jsonString.replace("'", "\""));
+ }
+
+ private void assertJSONEqual(JSONObject o1, JSONObject o2) {
+ assertEquals(o1.toString(), o2.toString());
+ }
+}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 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.dcae.vestest;
-
-import static java.lang.String.format;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.onap.dcae.commonFunction.CustomExceptionLoader.LookupMap;
-
-import com.att.nsa.drumlin.service.standards.HttpStatusCodes;
-import org.junit.Test;
-import org.onap.dcae.commonFunction.CommonStartup;
-import org.onap.dcae.commonFunction.CustomExceptionLoader;
-
-public class TestCustomExceptionLoader {
-
- @Test
- public void shouldLoadMapWithoutExceptions() {
- CommonStartup.exceptionConfig = "./etc/ExceptionConfig.json";
- CustomExceptionLoader.LoadMap();
- }
-
- @Test
- public void shouldLookupErrorMessageOutOfStatusCodeAndReason() {
- // given
- CommonStartup.exceptionConfig = "./etc/ExceptionConfig.json";
- CustomExceptionLoader.LoadMap();
- int statusCode = HttpStatusCodes.k401_unauthorized;
- String message = "Unauthorized user";
-
- // when
- String[] retarray = LookupMap(String.valueOf(statusCode), message);
-
- // then
- if (retarray == null) {
- fail(format(
- "Lookup failed, did not find value for a valid status code %s and message %s", statusCode, message));
- } else {
- assertEquals("\"POL2000\"", retarray[0]);
- }
- }
-}
-