diff options
author | Bharat saraswal <bharat.saraswal@huawei.com> | 2017-09-17 11:48:47 +0530 |
---|---|---|
committer | Bharat saraswal <bharat.saraswal@huawei.com> | 2017-09-17 09:39:51 +0000 |
commit | 31edebb539c80dafe9fbdce91813ef267695e95b (patch) | |
tree | a872ec7a77fd2015cdc881c04df0aebb955036b8 /src/main/java/org | |
parent | 6e63f2688ef741930943e46dd967b5b8f6513df2 (diff) |
Fixing sonar and javadoc issues.
minor code refactoring.
Issue-Id:DCAEGEN2-92
Change-Id: I5210dedf8545b670feac8b1304e3fd8903c74749
Signed-off-by: Bharat saraswal <bharat.saraswal@huawei.com>
Diffstat (limited to 'src/main/java/org')
-rw-r--r-- | src/main/java/org/onap/dcae/commonFunction/CommonStartup.java | 595 | ||||
-rw-r--r-- | src/main/java/org/onap/dcae/commonFunction/ConfigProcessors.java | 1065 |
2 files changed, 815 insertions, 845 deletions
diff --git a/src/main/java/org/onap/dcae/commonFunction/CommonStartup.java b/src/main/java/org/onap/dcae/commonFunction/CommonStartup.java index b743f134..b4c78f3b 100644 --- a/src/main/java/org/onap/dcae/commonFunction/CommonStartup.java +++ b/src/main/java/org/onap/dcae/commonFunction/CommonStartup.java @@ -21,43 +21,15 @@ package org.onap.dcae.commonFunction; - -import java.io.IOException; - -import java.net.URL; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import java.util.Queue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; - -import javax.servlet.ServletException; - -import org.apache.catalina.LifecycleException; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.onap.dcae.restapi.RestfulCollectorServlet; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - import com.att.nsa.apiServer.ApiServer; import com.att.nsa.apiServer.ApiServerConnector; import com.att.nsa.apiServer.endpoints.NsaBaseEndpoint; import com.att.nsa.cmdLine.NsaCommandLineUtil; import com.att.nsa.drumlin.service.framework.DrumlinServlet; -import com.att.nsa.drumlin.till.nv.rrNvReadable; import com.att.nsa.drumlin.till.nv.impl.nvPropertiesFile; import com.att.nsa.drumlin.till.nv.impl.nvReadableStack; import com.att.nsa.drumlin.till.nv.impl.nvReadableTable; +import com.att.nsa.drumlin.till.nv.rrNvReadable; import com.att.nsa.drumlin.till.nv.rrNvReadable.invalidSettingValue; import com.att.nsa.drumlin.till.nv.rrNvReadable.loadException; import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting; @@ -69,283 +41,302 @@ import com.github.fge.jsonschema.main.JsonSchemaFactory; import com.github.fge.jsonschema.report.ProcessingMessage; import com.github.fge.jsonschema.report.ProcessingReport; import com.github.fge.jsonschema.util.JsonLoader; +import org.apache.catalina.LifecycleException; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.dcae.restapi.RestfulCollectorServlet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.URL; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import javax.servlet.ServletException; + +public class CommonStartup extends NsaBaseEndpoint implements Runnable { + + public static final String kConfig = "c"; -public class CommonStartup extends NsaBaseEndpoint implements Runnable -{ - public static final String kConfig = "c"; - - public static final String kSetting_Port = "collector.service.port"; - public static final int kDefault_Port = 8080; - - public static final String kSetting_SecurePort = "collector.service.secure.port"; - public static final int kDefault_SecurePort = -1; - - public static final String kSetting_KeystorePassfile = "collector.keystore.passwordfile"; - public static final String kDefault_KeystorePassfile = "../etc/passwordfile"; - public static final String kSetting_KeystoreFile = "collector.keystore.file.location"; - public static final String kDefault_KeystoreFile = "../etc/keystore"; - public static final String kSetting_KeyAlias = "collector.keystore.alias"; - public static final String kDefault_KeyAlias = "tomcat"; - - public static final String kSetting_DmaapConfigs = "collector.dmaapfile"; - protected static final String[] kDefault_DmaapConfigs = new String[] { "/etc/DmaapConfig.json" }; - - public static final String kSetting_MaxQueuedEvents = "collector.inputQueue.maxPending"; - public static final int kDefault_MaxQueuedEvents = 1024*4; - - public static final String kSetting_schemaValidator = "collector.schema.checkflag"; - public static final int kDefault_schemaValidator = -1; - - public static final String kSetting_schemaFile = "collector.schema.file"; - public static final String kDefault_schemaFile = "{\"v5\":\"./etc/CommonEventFormat_28.3.json\"}"; - public static final String kSetting_ExceptionConfig = "exceptionConfig"; - - public static final String kSetting_dmaapStreamid = "collector.dmaap.streamid"; - - public static final String kSetting_authflag = "header.authflag"; - public static final int kDefault_authflag = 0; - - public static final String kSetting_authid = "header.authid"; - public static final String kSetting_authpwd = "header.authpwd"; - public static final String kSetting_authstore = "header.authstore"; - public static final String kSetting_authlist = "header.authlist"; - - public static final String kSetting_eventTransformFlag = "event.transform.flag"; - public static final int kDefault_eventTransformFlag = 1; - - - public static final Logger inlog = LoggerFactory.getLogger ("org.onap.dcae.commonFunction.input" ); - public static final Logger oplog = LoggerFactory.getLogger ("org.onap.dcae.commonFunction.output"); - public static final Logger eplog = LoggerFactory.getLogger ("org.onap.dcae.commonFunction.error"); - public static final Logger metriclog = LoggerFactory.getLogger ("com.att.ecomp.metrics" ); - - public static int schema_Validatorflag = -1; - public static int authflag = 1; - public static int eventTransformFlag = 1; - public static String schemaFile = null; - public static JSONObject schemaFileJson = null; - public static String exceptionConfig = null; - public static String cambriaConfigFile = null; - private boolean listnerstatus = false; - static String streamid = null; - - - private CommonStartup(rrNvReadable settings) throws loadException, missingReqdSetting, IOException, rrNvReadable.missingReqdSetting, rrNvReadable.invalidSettingValue, ServletException, InterruptedException - { - final List<ApiServerConnector> connectors = new LinkedList<ApiServerConnector> (); - - if (settings.getInt ( kSetting_Port, kDefault_Port ) > 0) - { - // http service - connectors.add ( - new ApiServerConnector.Builder ( settings.getInt ( kSetting_Port, kDefault_Port ) ) - .secure ( false ) - .build () - ); - } - - // optional https service - final int securePort = settings.getInt(kSetting_SecurePort, kDefault_SecurePort); - final String keystoreFile = settings.getString(kSetting_KeystoreFile, kDefault_KeystoreFile); - final String keystorePasswordFile = settings.getString(kSetting_KeystorePassfile, kDefault_KeystorePassfile); - final String keyAlias = settings.getString (kSetting_KeyAlias, kDefault_KeyAlias); - - - if (securePort > 0) - { - final String kSetting_KeystorePass = readFile(keystorePasswordFile, Charset.defaultCharset()); - connectors.add(new ApiServerConnector.Builder(securePort) - .secure(true) - .keystorePassword(kSetting_KeystorePass) - .keystoreFile(keystoreFile) - .keyAlias(keyAlias) - .build()); - - } - - //Reading other config properties - - schema_Validatorflag = settings.getInt(kSetting_schemaValidator, kDefault_schemaValidator ); - if (schema_Validatorflag > 0){ - schemaFile = settings.getString(kSetting_schemaFile,kDefault_schemaFile); - //System.out.println("SchemaFile:" + schemaFile); - schemaFileJson = new JSONObject(schemaFile); - - } - exceptionConfig = settings.getString(kSetting_ExceptionConfig, null); - authflag = settings.getInt(CommonStartup.kSetting_authflag, CommonStartup.kDefault_authflag ); - String [] currentconffile = settings.getStrings (CommonStartup.kSetting_DmaapConfigs, CommonStartup.kDefault_DmaapConfigs ) ; - cambriaConfigFile= currentconffile[0] ; - streamid = settings.getString(kSetting_dmaapStreamid,null); - eventTransformFlag = settings.getInt(kSetting_eventTransformFlag, kDefault_eventTransformFlag); - - fTomcatServer = new ApiServer.Builder(connectors, new RestfulCollectorServlet(settings)) - .encodeSlashes(true) - .name("collector") - .build(); - - - //Load override exception map - CustomExceptionLoader.LoadMap(); - setListnerstatus(true); - } - - public static void main ( String[] args ) - { - ExecutorService executor = null; - try - { - // process command line arguments - final Map<String, String> argMap = NsaCommandLineUtil.processCmdLine ( args, true ); - final String config = NsaCommandLineUtil.getSetting ( argMap, kConfig, "collector.properties" ); - final URL settingStream = DrumlinServlet.findStream ( config, CommonStartup.class ); - - final nvReadableStack settings = new nvReadableStack (); - settings.push ( new nvPropertiesFile ( settingStream ) ); - settings.push ( new nvReadableTable ( argMap ) ); - - fProcessingInputQueue = new LinkedBlockingQueue<JSONObject> (CommonStartup.kDefault_MaxQueuedEvents); - - VESLogger.setUpEcompLogging(); - - CommonStartup cs= new CommonStartup ( settings ); - - Thread csmain = new Thread(cs); - csmain.start(); - - - EventProcessor ep = new EventProcessor (); - //Thread epThread=new Thread(ep); - //epThread.start(); - executor = Executors.newFixedThreadPool(20); - executor.execute(ep); - - } - catch ( loadException | missingReqdSetting | IOException | invalidSettingValue | ServletException | InterruptedException e ) - { - CommonStartup.eplog.error("FATAL_STARTUP_ERROR" + e.getMessage() ); - throw new RuntimeException ( e ); - } - finally - { - // This will make the executor accept no new threads + public static final String kSetting_Port = "collector.service.port"; + public static final int kDefault_Port = 8080; + + public static final String kSetting_SecurePort = "collector.service.secure.port"; + public static final int kDefault_SecurePort = -1; + + public static final String kSetting_KeystorePassfile = "collector.keystore.passwordfile"; + public static final String kDefault_KeystorePassfile = "../etc/passwordfile"; + public static final String kSetting_KeystoreFile = "collector.keystore.file.location"; + public static final String kDefault_KeystoreFile = "../etc/keystore"; + public static final String kSetting_KeyAlias = "collector.keystore.alias"; + public static final String kDefault_KeyAlias = "tomcat"; + + public static final String kSetting_DmaapConfigs = "collector.dmaapfile"; + protected static final String[] kDefault_DmaapConfigs = new String[]{"/etc/DmaapConfig.json"}; + + public static final String kSetting_MaxQueuedEvents = "collector.inputQueue.maxPending"; + public static final int kDefault_MaxQueuedEvents = 1024 * 4; + + public static final String kSetting_schemaValidator = "collector.schema.checkflag"; + public static final int kDefault_schemaValidator = -1; + + public static final String kSetting_schemaFile = "collector.schema.file"; + public static final String kDefault_schemaFile = "{\"v5\":\"./etc/CommonEventFormat_28.3.json\"}"; + public static final String kSetting_ExceptionConfig = "exceptionConfig"; + + public static final String kSetting_dmaapStreamid = "collector.dmaap.streamid"; + + public static final String kSetting_authflag = "header.authflag"; + public static final int kDefault_authflag = 0; + + public static final String kSetting_authid = "header.authid"; + public static final String kSetting_authpwd = "header.authpwd"; + public static final String kSetting_authstore = "header.authstore"; + public static final String kSetting_authlist = "header.authlist"; + + public static final String kSetting_eventTransformFlag = "event.transform.flag"; + public static final int kDefault_eventTransformFlag = 1; + + + public static final Logger inlog = LoggerFactory + .getLogger("org.onap.dcae.commonFunction.input"); + public static final Logger oplog = LoggerFactory + .getLogger("org.onap.dcae.commonFunction.output"); + public static final Logger eplog = LoggerFactory + .getLogger("org.onap.dcae.commonFunction.error"); + public static final Logger metriclog = LoggerFactory.getLogger("com.att.ecomp.metrics"); + + public static int schema_Validatorflag = -1; + public static int authflag = 1; + public static int eventTransformFlag = 1; + public static String schemaFile; + public static JSONObject schemaFileJson; + public static String exceptionConfig; + public static String cambriaConfigFile; + private boolean listnerstatus; + static String streamid; + + + private CommonStartup(rrNvReadable settings) + throws loadException, IOException, rrNvReadable.missingReqdSetting, rrNvReadable.invalidSettingValue, ServletException, InterruptedException { + final List<ApiServerConnector> connectors = new LinkedList<ApiServerConnector>(); + + if (settings.getInt(kSetting_Port, kDefault_Port) > 0) { + // http service + connectors.add( + new ApiServerConnector.Builder(settings.getInt(kSetting_Port, kDefault_Port)) + .secure(false) + .build() + ); + } + + // optional https service + final int securePort = settings.getInt(kSetting_SecurePort, kDefault_SecurePort); + final String keystoreFile = settings + .getString(kSetting_KeystoreFile, kDefault_KeystoreFile); + final String keystorePasswordFile = settings + .getString(kSetting_KeystorePassfile, kDefault_KeystorePassfile); + final String keyAlias = settings.getString(kSetting_KeyAlias, kDefault_KeyAlias); + + if (securePort > 0) { + final String kSetting_KeystorePass = readFile(keystorePasswordFile, + Charset.defaultCharset()); + connectors.add(new ApiServerConnector.Builder(securePort) + .secure(true) + .keystorePassword(kSetting_KeystorePass) + .keystoreFile(keystoreFile) + .keyAlias(keyAlias) + .build()); + + } + + //Reading other config properties + + schema_Validatorflag = settings.getInt(kSetting_schemaValidator, kDefault_schemaValidator); + if (schema_Validatorflag > 0) { + schemaFile = settings.getString(kSetting_schemaFile, kDefault_schemaFile); + //System.out.println("SchemaFile:" + schemaFile); + schemaFileJson = new JSONObject(schemaFile); + + } + exceptionConfig = settings.getString(kSetting_ExceptionConfig, null); + authflag = settings + .getInt(CommonStartup.kSetting_authflag, CommonStartup.kDefault_authflag); + String[] currentconffile = settings + .getStrings(CommonStartup.kSetting_DmaapConfigs, CommonStartup.kDefault_DmaapConfigs); + cambriaConfigFile = currentconffile[0]; + streamid = settings.getString(kSetting_dmaapStreamid, null); + eventTransformFlag = settings + .getInt(kSetting_eventTransformFlag, kDefault_eventTransformFlag); + + fTomcatServer = new ApiServer.Builder(connectors, new RestfulCollectorServlet(settings)) + .encodeSlashes(true) + .name("collector") + .build(); + + //Load override exception map + CustomExceptionLoader.LoadMap(); + setListnerstatus(true); + } + + public static void main(String[] args) { + ExecutorService executor = null; + try { + // process command line arguments + final Map<String, String> argMap = NsaCommandLineUtil.processCmdLine(args, true); + final String config = NsaCommandLineUtil + .getSetting(argMap, kConfig, "collector.properties"); + final URL settingStream = DrumlinServlet.findStream(config, CommonStartup.class); + + final nvReadableStack settings = new nvReadableStack(); + settings.push(new nvPropertiesFile(settingStream)); + settings.push(new nvReadableTable(argMap)); + + fProcessingInputQueue = new LinkedBlockingQueue<JSONObject>( + CommonStartup.kDefault_MaxQueuedEvents); + + VESLogger.setUpEcompLogging(); + + CommonStartup cs = new CommonStartup(settings); + + Thread csmain = new Thread(cs); + csmain.start(); + + EventProcessor ep = new EventProcessor(); + //Thread epThread=new Thread(ep); + //epThread.start(); + executor = Executors.newFixedThreadPool(20); + executor.execute(ep); + + } catch (loadException | missingReqdSetting | IOException | invalidSettingValue | + ServletException | InterruptedException e) { + CommonStartup.eplog.error("FATAL_STARTUP_ERROR" + e.getMessage()); + throw new RuntimeException(e); + } finally { + // This will make the executor accept no new threads // and finish all existing threads in the queue - if (executor != null){ - executor.shutdown(); - } - - } - } - - public void run() { - try { - fTomcatServer.start (); - } catch (LifecycleException | IOException e) { - - e.printStackTrace(); - } - fTomcatServer.await (); - } + if (executor != null) { + executor.shutdown(); + } + + } + } + + public void run() { + try { + fTomcatServer.start(); + } catch (LifecycleException | IOException e) { + + e.printStackTrace(); + } + fTomcatServer.await(); + } public boolean isListnerstatus() { - return listnerstatus; - } - - public void setListnerstatus(boolean listnerstatus) { - this.listnerstatus = listnerstatus; - } - public static Queue<JSONObject> getProcessingInputQueue () - { - return fProcessingInputQueue; - } - - public static class QueueFullException extends Exception - { - private static final long serialVersionUID = 1L; - } - - - public static void handleEvents ( JSONArray a ) throws QueueFullException, JSONException, IOException - { - final Queue<JSONObject> queue = getProcessingInputQueue (); - try - { - - CommonStartup.metriclog.info("EVENT_PUBLISH_START" ); - for (int i = 0; i < a.length(); i++) { - if ( !queue.offer ( a.getJSONObject(i) ) ) { - throw new QueueFullException (); - } - - } - log.debug("CommonStartup.handleEvents:EVENTS has been published successfully!"); - CommonStartup.metriclog.info("EVENT_PUBLISH_END"); - //ecomplogger.debug(secloggerMessageEnum.SEC_COLLECT_AND_PULIBISH_SUCCESS); - - } - catch ( JSONException e ){ - throw e; - - } - } - - - static String readFile(String path, Charset encoding) - throws IOException - { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - String pwd = new String(encoded); - return pwd.substring(0,pwd.length()-1); - } - - - public static String schemavalidate( String jsonData, String jsonSchema) { - ProcessingReport report = null; - String result = "false"; - - try { - //System.out.println("Applying schema: @<@<"+jsonSchema+">@>@ to data: #<#<"+jsonData+">#>#"); - log.trace("Schema validation for event:" + jsonData); - JsonNode schemaNode = JsonLoader.fromString(jsonSchema); - JsonNode data = JsonLoader.fromString(jsonData); - JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); - JsonSchema schema = factory.getJsonSchema(schemaNode); - report = schema.validate(data); - } catch (JsonParseException e) { - log.error("schemavalidate:JsonParseException for event:" + jsonData ); - System.out.println(e.getMessage()); - return e.getMessage().toString(); - } catch (ProcessingException e) { - log.error("schemavalidate:Processing exception for event:" + jsonData ); - System.out.println(e.getMessage()); - return e.getMessage().toString(); - } catch (IOException e) { - log.error("schemavalidate:IO exception; something went wrong trying to read json data for event:" + jsonData); - System.out.println(e.getMessage()); - return e.getMessage().toString(); - } - if (report != null) { - Iterator<ProcessingMessage> iter = report.iterator(); - while (iter.hasNext()) { - ProcessingMessage pm = iter.next(); - log.trace("Processing Message: "+pm.getMessage()); - } - result = String.valueOf(report.isSuccess()); - } - try { - log.debug("Validation Result:" +result + " Validation report:" + report); - } - catch (NullPointerException e){ - log.error("schemavalidate:NullpointerException on report"); - } - return result; - } - - - - static LinkedBlockingQueue<JSONObject> fProcessingInputQueue; - private static ApiServer fTomcatServer = null; - private static final Logger log = LoggerFactory.getLogger ( CommonStartup.class ); + return listnerstatus; + } + + public void setListnerstatus(boolean listnerstatus) { + this.listnerstatus = listnerstatus; + } + + public static Queue<JSONObject> getProcessingInputQueue() { + return fProcessingInputQueue; + } + + public static class QueueFullException extends Exception { + + private static final long serialVersionUID = 1L; + } + + + public static void handleEvents(JSONArray a) + throws QueueFullException, JSONException, IOException { + final Queue<JSONObject> queue = getProcessingInputQueue(); + try { + + CommonStartup.metriclog.info("EVENT_PUBLISH_START"); + for (int i = 0; i < a.length(); i++) { + if (!queue.offer(a.getJSONObject(i))) { + throw new QueueFullException(); + } + + } + log.debug("CommonStartup.handleEvents:EVENTS has been published successfully!"); + CommonStartup.metriclog.info("EVENT_PUBLISH_END"); + //ecomplogger.debug(secloggerMessageEnum.SEC_COLLECT_AND_PULIBISH_SUCCESS); + + } catch (JSONException e) { + throw e; + + } + } + + + static String readFile(String path, Charset encoding) + throws IOException { + byte[] encoded = Files.readAllBytes(Paths.get(path)); + String pwd = new String(encoded); + return pwd.substring(0, pwd.length() - 1); + } + + + public static String schemavalidate(String jsonData, String jsonSchema) { + ProcessingReport report; + String result = "false"; + + try { + //System.out.println("Applying schema: @<@<"+jsonSchema+">@>@ to data: #<#<"+jsonData+">#>#"); + log.trace("Schema validation for event:" + jsonData); + JsonNode schemaNode = JsonLoader.fromString(jsonSchema); + JsonNode data = JsonLoader.fromString(jsonData); + JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); + JsonSchema schema = factory.getJsonSchema(schemaNode); + report = schema.validate(data); + } catch (JsonParseException e) { + log.error("schemavalidate:JsonParseException for event:" + jsonData); + System.out.println(e.getMessage()); + return e.getMessage().toString(); + } catch (ProcessingException e) { + log.error("schemavalidate:Processing exception for event:" + jsonData); + System.out.println(e.getMessage()); + return e.getMessage().toString(); + } catch (IOException e) { + log.error( + "schemavalidate:IO exception; something went wrong trying to read json data for event:" + + jsonData); + System.out.println(e.getMessage()); + return e.getMessage().toString(); + } + if (report != null) { + Iterator<ProcessingMessage> iter = report.iterator(); + while (iter.hasNext()) { + ProcessingMessage pm = iter.next(); + log.trace("Processing Message: " + pm.getMessage()); + } + result = String.valueOf(report.isSuccess()); + } + try { + log.debug("Validation Result:" + result + " Validation report:" + report); + } catch (NullPointerException e) { + log.error("schemavalidate:NullpointerException on report"); + } + return result; + } + + static LinkedBlockingQueue<JSONObject> fProcessingInputQueue; + private static ApiServer fTomcatServer = null; + private static final Logger log = LoggerFactory.getLogger(CommonStartup.class); } diff --git a/src/main/java/org/onap/dcae/commonFunction/ConfigProcessors.java b/src/main/java/org/onap/dcae/commonFunction/ConfigProcessors.java index ff6c328c..89319072 100644 --- a/src/main/java/org/onap/dcae/commonFunction/ConfigProcessors.java +++ b/src/main/java/org/onap/dcae/commonFunction/ConfigProcessors.java @@ -28,549 +28,528 @@ import org.slf4j.LoggerFactory; public class ConfigProcessors { - private static Logger log = LoggerFactory.getLogger(ConfigProcessors.class); - - public ConfigProcessors(JSONObject eventJson) - { - event = eventJson; - } - - /** - * - */ - public void getValue(JSONObject J) - { - //log.info("addAttribute"); - final String field = J.getString("field"); - //final String value = J.getString("value"); - final JSONObject filter = J.optJSONObject("filter"); - if (filter == null || isFilterMet(filter)) - { - //log.info("field ==" + field); - //log.info("value ==" + value); - getEventObjectVal(field); - } - else - log.info("Filter not met"); - } - - /** - * - */ - public void setValue(JSONObject J) - { - //log.info("addAttribute"); - final String field = J.getString("field"); - final String value = J.getString("value"); - final JSONObject filter = J.optJSONObject("filter"); - if (filter == null || isFilterMet(filter)) - { - //log.info("field ==" + field); - //log.info("value ==" + value); - setEventObjectVal(field, value); - } - else - log.info("Filter not met"); - } - - /** - * - */ - public void addAttribute(JSONObject J) - { - //log.info("addAttribute"); - final String field = J.getString("field"); - final String value = J.getString("value"); - final JSONObject filter = J.optJSONObject("filter"); - if (filter == null || isFilterMet(filter)) - { - //log.info("field ==" + field); - //log.info("value ==" + value); - setEventObjectVal(field, value); - } - else - log.info("Filter not met"); - } - - /** - * - */ - public void updateAttribute(JSONObject J) - { - //log.info("updateAttribute"); - final String field = J.getString("field"); - final String value = J.getString("value"); - final JSONObject filter = J.optJSONObject("filter"); - if (filter == null || isFilterMet(filter)) - { - //log.info("field ==" + field); - //log.info("value ==" + value); - setEventObjectVal(field, value); - } - else - log.info("Filter not met"); - } - - /** - * - */ - public void removeAttribute(JSONObject J) - { - //log.info("removeAttribute"); - final String field = J.getString("field"); - final JSONObject filter = J.optJSONObject("filter"); - - if (filter == null || isFilterMet(filter)) - { - removeEventKey(field); - } - else - log.info("Filter not met"); - } - - /** - * - */ - public void renameArrayInArray(JSONObject J) //map - { - log.info("renameArrayInArray"); - final String field = J.getString("field"); - final String oldField = J.getString("oldField"); - final JSONObject filter = J.optJSONObject("filter"); - //String value = ""; - if (filter == null || isFilterMet(filter)) - { - //log.info("field ==" + field); - final String[] fsplit = field.split("\\[\\]", field.length()); - final String[] oldfsplit = oldField.split("\\[\\]", oldField.length()); - /*for (int i=0; i< oldfsplit.length; i++ ) - { + private static final Logger LOG = LoggerFactory.getLogger(ConfigProcessors.class); + private static final String FIELD = "field"; + private static final String OLD_FIELD = "oldField"; + private static final String FILTER = "filter"; + private static final String VALUE = "value"; + private static final String REGEX = "\\[\\]"; + private static final String OBJECT_NOT_FOUND = "ObjectNotFound"; + + + public ConfigProcessors(JSONObject eventJson) { + event = eventJson; + } + + /** + * + * @param j json object + */ + public void getValue(JSONObject j) { + //log.info("addAttribute"); + final String field = j.getString(FIELD); + //final String value = J.getString(VALUE); + final JSONObject filter = j.optJSONObject(FILTER); + if (filter == null || isFilterMet(filter)) { + //log.info("field ==" + field); + //log.info("value ==" + value); + getEventObjectVal(field); + } else { + LOG.info("Filter not met"); + } + } + + /** + * + * @param j json object + */ + public void setValue(JSONObject j) { + //log.info("addAttribute"); + final String field = j.getString(FIELD); + final String value = j.getString(VALUE); + final JSONObject filter = j.optJSONObject(FILTER); + if (filter == null || isFilterMet(filter)) { + //log.info("field ==" + field); + //log.info("value ==" + value); + setEventObjectVal(field, value); + } else { + LOG.info("Filter not met"); + } + } + + /** + * + * @param j json object + */ + public void addAttribute(JSONObject j) { + //log.info("addAttribute"); + final String field = j.getString(FIELD); + final String value = j.getString(VALUE); + final JSONObject filter = j.optJSONObject(FILTER); + if (filter == null || isFilterMet(filter)) { + //log.info("field ==" + field); + //log.info("value ==" + value); + setEventObjectVal(field, value); + } else { + LOG.info("Filter not met"); + } + } + + /** + * + * @param j json object + */ + public void updateAttribute(JSONObject j) { + //log.info("updateAttribute"); + final String field = j.getString(FIELD); + final String value = j.getString(VALUE); + final JSONObject filter = j.optJSONObject(FILTER); + if (filter == null || isFilterMet(filter)) { + //log.info("field ==" + field); + //log.info("value ==" + value); + setEventObjectVal(field, value); + } else { + LOG.info("Filter not met"); + } + } + + /** + * + * @param j json object + */ + public void removeAttribute(JSONObject j) { + //log.info("removeAttribute"); + final String field = j.getString(FIELD); + final JSONObject filter = j.optJSONObject(FILTER); + + if (filter == null || isFilterMet(filter)) { + removeEventKey(field); + } else { + LOG.info("Filter not met"); + } + } + + /** + * + * @param j json object + */ + public void renameArrayInArray(JSONObject j) { //map + + LOG.info("renameArrayInArray"); + final String field = j.getString(FIELD); + final String oldField = j.getString(OLD_FIELD); + final JSONObject filter = j.optJSONObject(FILTER); + //String value = ""; + if (filter == null || isFilterMet(filter)) { + //log.info("field ==" + field); + final String[] fsplit = field.split(REGEX, field.length()); + final String[] oldfsplit = oldField.split(REGEX, oldField.length()); + /*for (int i=0; i< oldfsplit.length; i++ ) + { log.info( "renameArrayInArray " + i + " ==" + oldfsplit[i]); }*/ - - final String oldValue = getEventObjectVal(oldfsplit[0]).toString(); - if (!oldValue.equals("ObjectNotFound")){ - final String oldArrayName = oldfsplit[1].substring(1); - final String newArrayName = fsplit[1].substring(1); - final String value = oldValue.replaceAll(oldArrayName, newArrayName); - //log.info("oldArrayName ==" + oldArrayName); - //log.info("newArrayName ==" + newArrayName); - log.info("oldValue ==" + oldValue); - log.info("value ==" + value); - JSONArray ja = new JSONArray(value); - removeEventKey(oldfsplit[0]); - setEventObjectVal(fsplit[0], ja); - } - } - else - log.info("Filter not met"); - } - - /** - * - */ - public void map(JSONObject J) - { - //log.info("mapAttribute"); - final String field = J.getString("field"); - if (field.contains("[]")) - { - if (field.matches(".*\\[\\]\\..*\\[\\]")) - renameArrayInArray(J); - else - mapToJArray(J); - } - else - mapAttribute(J); - } - - /** - * - */ - public String performOperation(String operation, String value) - { - log.info("performOperation"); - if (operation != null) - { - if (operation.equals("convertMBtoKB")) - { - float kbValue = Float.parseFloat(value) * 1024; - value = String.valueOf(kbValue); - } - } - return value; - } - - /** - * - */ - //public void mapAttributeToArrayAttribute(JSONObject J) - public void mapAttribute(JSONObject J) - { - //log.info("mapAttribute"); - final String field = J.getString("field"); - final String oldField = J.getString("oldField"); - final JSONObject filter = J.optJSONObject("filter"); - final String operation = J.optString("operation"); - String value = ""; - if (filter == null || isFilterMet(filter)) - { - //log.info("field ==" + field); - - value = getEventObjectVal(oldField).toString(); - if (!value.equals("ObjectNotFound")) - { - if (operation != null && !operation.equals("")) - value = performOperation(operation, value); - //log.info("value ==" + value); - setEventObjectVal(field, value); - - removeEventKey(oldField); - } - } - else - log.info("Filter not met"); - } - - /** - * - */ - public void mapToJArray(JSONObject J) - { - log.info("mapToJArray"); - String field = J.getString("field"); - String oldField = J.getString("oldField"); - final JSONObject filter = J.optJSONObject("filter"); - final JSONObject attrMap = J.optJSONObject("attrMap"); - oldField = oldField.replaceAll("\\[\\]", ""); - field = field.replaceAll("\\[\\]", ""); - - //log.info("oldField ==" + field); - if (filter == null || isFilterMet(filter)) - { - //log.info("oldField ==" + field); - String value = getEventObjectVal(oldField).toString(); - if (!value.equals("ObjectNotFound")) - { - log.info("old value ==" + value.toString()); - //update old value based on attrMap - if (attrMap != null) - { - //loop thru attrMap and update attribute name to new name - for (String key : attrMap.keySet()) - { - //log.info("attr key==" + key + " value==" + attrMap.getString(key)); - value = value.replaceAll(key, attrMap.getString(key)); - } - } - - log.info("new value ==" + value); - char c = value.charAt(0); - if (c != '[') - { - //oldfield is JsonObject - JSONObject valueJO = new JSONObject(value); - // if the array already exists - - String existingValue = getEventObjectVal(field).toString(); - if (!existingValue.equals("ObjectNotFound")) - { - JSONArray ja = new JSONArray(existingValue); - JSONObject jo = ja.optJSONObject(0); - if (jo != null) - { - for (String key : valueJO.keySet()) - { - jo.put(key, valueJO.get(key)); - - } - ja.put(0, jo); - //log.info("jarray== " + ja.toString()); - setEventObjectVal(field,ja); - } - } - else //if new array - setEventObjectVal(field + "[0]", new JSONObject(value)); - } - else //oldfield is jsonArray - setEventObjectVal(field, new JSONArray(value)); - - removeEventKey(oldField); - } - } - else - log.info("Filter not met"); - } - - /** - * example - - { - "functionName": "concatenateValue", - "args":{ - "filter": {"event.commonEventHeader.event":"heartbeat"}, - "field":"event.commonEventHeader.eventName", - "concatenate": ["event.commonEventHeader.domain","event.commonEventHeader.eventType","event.commonEventHeader.alarmCondition"], - "delimiter":"_" - } - } - **/ - public void concatenateValue(JSONObject J) - { - //log.info("concatenateValue"); - final String field = J.getString("field"); - final String delimiter = J.getString("delimiter"); - final JSONArray values = J.getJSONArray("concatenate"); - final JSONObject filter = J.optJSONObject("filter"); - if (filter == null || isFilterMet(filter)) - { - String value = ""; - for (int i=0; i < values.length(); i++) - { - //log.info(values.getString(i)); - String tempVal = getEventObjectVal(values.getString(i)).toString(); - if (!tempVal.equals("ObjectNotFound")) - { - if (i ==0) - value = value + getEventObjectVal(values.getString(i)); - else - value = value + delimiter + getEventObjectVal(values.getString(i)); - } - } - //log.info("value ==" + value); - setEventObjectVal(field, value); - } - else - log.info("Filter not met"); - } - - /** - * - */ - private void removeEventKey(String field) - { - String[] keySet = field.split("\\.",field.length()); - JSONObject keySeries = event; - for (int i=0; i<(keySet.length -1); i++ ) - { - //log.info( i + " ==" + keySet[i]); - keySeries = keySeries.getJSONObject(keySet[i]); - } - //log.info(keySet[keySet.length -1]); - - keySeries.remove(keySet[keySet.length -1]); - - } - - /** - * - */ - private boolean checkFilter(JSONObject jo, String key, String logicKey) - { - String filterValue = jo.getString(key); - boolean retVal = true; - - if(filterValue.contains(":")) - { - String[] splitVal = filterValue.split(":"); - //log.info(splitVal[0] + " " + splitVal[1]); - if (splitVal[0].equals("matches")) - { - if (logicKey.equals("not")) - { - //log.info("not"); - //log.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "split1==" + splitVal[1]); - if (getEventObjectVal(key).toString().matches(splitVal[1])) - { - log.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "==false"); - return false; - } - } - else - { - if (!(getEventObjectVal(key).toString().matches(splitVal[1]))) - { - log.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "==false"); - return false; - } - } - - } - if (splitVal[0].equals("contains")) - { - if (logicKey.equals("not")) - { - //log.info("not"); - //log.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "split1==" + splitVal[1]); - if (getEventObjectVal(key).toString().contains(splitVal[1])) - { - log.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "==false"); - return false; - } - } - else - { - if (!(getEventObjectVal(key).toString().contains(splitVal[1]))) - { - log.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "==false"); - return false; - } - } - - } - } - else - { - if (logicKey.equals("not")) - { - if(getEventObjectVal(key).toString().equals(filterValue)) - { - log.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "==false"); - return false; - } - } - else - { - if(!(getEventObjectVal(key).toString().equals(filterValue))) - { - log.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "==false"); - return false; - } - } - } - return retVal; - } - /** - * - */ - public boolean isFilterMet(JSONObject jo) - { - boolean retval = true; - //log.info("Filter==" + jo.toString()); - for (String key : jo.keySet()) - { - if (key.equals("not")) - { - JSONObject njo = jo.getJSONObject(key); - for (String njoKey : njo.keySet()) - { - //log.info(njoKey); - retval = checkFilter(njo, njoKey, key); - if (retval == false) - return retval; - } - } - else - { - //log.info(key); - //final String filterKey = key; - retval = checkFilter(jo, key, key); - if (retval == false) - return retval; - } - } - return true; - } - - /** - * returns a string or JSONObject or JSONArray - **/ - public Object getEventObjectVal(String keySeriesStr) - { - keySeriesStr = keySeriesStr.replaceAll("\\[", "."); - keySeriesStr = keySeriesStr.replaceAll("\\]", "."); - if (keySeriesStr.contains("..")) - { - keySeriesStr = keySeriesStr.replaceAll("\\.\\.", "."); - } - //log.info(Integer.toString(keySeriesStr.lastIndexOf("."))); - //log.info(Integer.toString(keySeriesStr.length() -1)); - if (keySeriesStr.lastIndexOf(".") == keySeriesStr.length() -1 ) - keySeriesStr = keySeriesStr.substring(0,keySeriesStr.length()-1 ); - String[] keySet = keySeriesStr.split("\\.", keySeriesStr.length()); - Object keySeriesObj = event; - for (int i=0; i<(keySet.length); i++ ) - { - //log.info( "getEventObject " + i + " ==" + keySet[i]); - if (keySeriesObj != null) - { - if (keySeriesObj instanceof String) - { - //keySeriesObj = keySeriesObj.get(keySet[i]); - log.info("STRING==" + keySeriesObj); - } - else if (keySeriesObj instanceof JSONArray) { - keySeriesObj = ((JSONArray) keySeriesObj).optJSONObject(Integer.parseInt(keySet[i])); - //log.info("ARRAY==" + keySeriesObj); - } - else if (keySeriesObj instanceof JSONObject) { - keySeriesObj = ( (JSONObject) keySeriesObj).opt(keySet[i]); - //log.info("JSONObject==" + keySeriesObj); - } - else - { - log.info("unknown object==" + keySeriesObj); - } - } - } - - if (keySeriesObj == null) - return "ObjectNotFound"; - return keySeriesObj; - } - - /** - * returns a string or JSONObject or JSONArray - **/ - public void setEventObjectVal(String keySeriesStr, Object value) - { - keySeriesStr = keySeriesStr.replaceAll("\\[", "."); - keySeriesStr = keySeriesStr.replaceAll("\\]", "."); - if (keySeriesStr.contains("..")) - { - keySeriesStr = keySeriesStr.replaceAll("\\.\\.", "."); - } - //log.info(Integer.toString(keySeriesStr.lastIndexOf("."))); - //log.info(Integer.toString(keySeriesStr.length() -1)); - if (keySeriesStr.lastIndexOf(".") == keySeriesStr.length() -1 ) - keySeriesStr = keySeriesStr.substring(0,keySeriesStr.length()-1 ); - String[] keySet = keySeriesStr.split("\\.", keySeriesStr.length()); - Object keySeriesObj = event; - for (int i=0; i<(keySet.length -1); i++ ) - { - //log.info( "setEventObject " + i + " ==" + keySet[i]); - if (keySeriesObj instanceof JSONArray) { - //keySeriesObj = ((JSONArray) keySeriesObj).optJSONObject(Integer.parseInt(keySet[i])); - if (((JSONArray) keySeriesObj).optJSONObject(Integer.parseInt(keySet[i])) == null) //if the object is not there then add it - { - log.info("Object is null, must add it"); - if (keySet[i+1].matches("[0-9]*")) // if index then array - ((JSONArray) keySeriesObj).put(Integer.parseInt(keySet[i]), new JSONArray()); - else - ((JSONArray) keySeriesObj).put(Integer.parseInt(keySet[i]), new JSONObject()); - } - keySeriesObj = ((JSONArray) keySeriesObj).optJSONObject(Integer.parseInt(keySet[i])); - //log.info("ARRAY==" + keySeriesObj); - } - else if (keySeriesObj instanceof JSONObject) { - if (( (JSONObject) keySeriesObj).opt(keySet[i]) == null) //if the object is not there then add it - { - if (keySet[i+1].matches("[0-9]*")) // if index then array - ((JSONObject) keySeriesObj).put(keySet[i], new JSONArray()); - else - ((JSONObject) keySeriesObj).put(keySet[i], new JSONObject()); - log.info("Object is null, must add it"); - } - keySeriesObj = ( (JSONObject) keySeriesObj).opt(keySet[i]); - //log.info("JSONObject==" + keySeriesObj); - } - else - { - log.info("unknown object==" + keySeriesObj); - } - } - - ((JSONObject)keySeriesObj).put(keySet[keySet.length -1], value); - } - - private JSONObject event = new JSONObject(); + + final String oldValue = getEventObjectVal(oldfsplit[0]).toString(); + if (!OBJECT_NOT_FOUND.equals(oldValue)) { + final String oldArrayName = oldfsplit[1].substring(1); + final String newArrayName = fsplit[1].substring(1); + final String value = oldValue.replaceAll(oldArrayName, newArrayName); + //log.info("oldArrayName ==" + oldArrayName); + //log.info("newArrayName ==" + newArrayName); + LOG.info("oldValue ==" + oldValue); + LOG.info("value ==" + value); + JSONArray ja = new JSONArray(value); + removeEventKey(oldfsplit[0]); + setEventObjectVal(fsplit[0], ja); + } + } else { + LOG.info("Filter not met"); + } + } + + /** + * + * @param j json object + */ + public void map(JSONObject j) { + //log.info("mapAttribute"); + final String field = j.getString(FIELD); + if (field.contains("[]")) { + if (field.matches(".*\\[\\]\\..*\\[\\]")) { + renameArrayInArray(j); + } else { + mapToJArray(j); + } + } else { + mapAttribute(j); + } + } + + /** + * + * @param operation operation + * @param value kb value + * @return value + */ + public String performOperation(String operation, String value) { + LOG.info("performOperation"); + if (operation != null && "convertMBtoKB".equals(operation)) { + float kbValue = Float.parseFloat(value) * 1024; + value = String.valueOf(kbValue); + } + return value; + } + + //public void mapAttributeToArrayAttribute(JSONObject J) + + /** + * + * @param j json object + */ + public void mapAttribute(JSONObject j) { + //log.info("mapAttribute"); + final String field = j.getString(FIELD); + final String oldField = j.getString(OLD_FIELD); + final JSONObject filter = j.optJSONObject(FILTER); + final String operation = j.optString("operation"); + String value = ""; + if (filter == null || isFilterMet(filter)) { + //log.info("field ==" + field); + + value = getEventObjectVal(oldField).toString(); + if (!OBJECT_NOT_FOUND.equals(value)) { + if (operation != null && !operation.isEmpty()) { + value = performOperation(operation, value); + } + //log.info("value ==" + value); + setEventObjectVal(field, value); + + removeEventKey(oldField); + } + } else { + LOG.info("Filter not met"); + } + } + + /** + * + * @param j json object + */ + public void mapToJArray(JSONObject j) { + LOG.info("mapToJArray"); + String field = j.getString(FIELD); + String oldField = j.getString(OLD_FIELD); + final JSONObject filter = j.optJSONObject(FILTER); + final JSONObject attrMap = j.optJSONObject("attrMap"); + oldField = oldField.replaceAll(REGEX, ""); + field = field.replaceAll(REGEX, ""); + + //log.info("oldField ==" + field); + if (filter == null || isFilterMet(filter)) { + //log.info("oldField ==" + field); + String value = getEventObjectVal(oldField).toString(); + if (!OBJECT_NOT_FOUND.equals(value)) { + LOG.info("old value ==" + value); + //update old value based on attrMap + if (attrMap != null) { + //loop thru attrMap and update attribute name to new name + for (String key : attrMap.keySet()) { + //log.info("attr key==" + key + " value==" + attrMap.getString(key)); + value = value.replaceAll(key, attrMap.getString(key)); + } + } + + LOG.info("new value ==" + value); + char c = value.charAt(0); + if (c != '[') { + //oldfield is JsonObject + JSONObject valueJO = new JSONObject(value); + // if the array already exists + + String existingValue = getEventObjectVal(field).toString(); + if (!OBJECT_NOT_FOUND.equals(existingValue)) { + JSONArray ja = new JSONArray(existingValue); + JSONObject jo = ja.optJSONObject(0); + if (jo != null) { + for (String key : valueJO.keySet()) { + jo.put(key, valueJO.get(key)); + + } + ja.put(0, jo); + //log.info("jarray== " + ja.toString()); + setEventObjectVal(field, ja); + } + } else //if new array + { + setEventObjectVal(field + "[0]", new JSONObject(value)); + } + } else //oldfield is jsonArray + { + setEventObjectVal(field, new JSONArray(value)); + } + + removeEventKey(oldField); + } + } else { + LOG.info("Filter not met"); + } + } + + /* + * example - + { + "functionName": "concatenateValue", + "args":{ + "filter": {"event.commonEventHeader.event":"heartbeat"}, + "field":"event.commonEventHeader.eventName", + "concatenate": ["event.commonEventHeader.domain","event.commonEventHeader.eventType","event.commonEventHeader.alarmCondition"], + "delimiter":"_" + } + } + **/ + + /** + * + * @param j json object + */ + public void concatenateValue(JSONObject j) { + //log.info("concatenateValue"); + final String field = j.getString(FIELD); + final String delimiter = j.getString("delimiter"); + final JSONArray values = j.getJSONArray("concatenate"); + final JSONObject filter = j.optJSONObject(FILTER); + if (filter == null || isFilterMet(filter)) { + StringBuilder value = new StringBuilder(""); + for (int i = 0; i < values.length(); i++) { + //log.info(values.getString(i)); + String tempVal = getEventObjectVal(values.getString(i)).toString(); + if (!OBJECT_NOT_FOUND.equals(tempVal)) { + if (i == 0) { + value.append(getEventObjectVal(values.getString(i))); + } else { + value.append(delimiter).append(getEventObjectVal(values.getString(i))); + } + } + } + //log.info("value ==" + value); + setEventObjectVal(field, value.toString()); + } else { + LOG.info("Filter not met"); + } + } + + /** + * + */ + private void removeEventKey(String field) { + String[] keySet = field.split("\\.", field.length()); + JSONObject keySeries = event; + for (int i = 0; i < (keySet.length - 1); i++) { + //log.info( i + " ==" + keySet[i]); + keySeries = keySeries.getJSONObject(keySet[i]); + } + //log.info(keySet[keySet.length -1]); + + keySeries.remove(keySet[keySet.length - 1]); + + } + + /** + * + */ + private boolean checkFilter(JSONObject jo, String key, String logicKey) { + String filterValue = jo.getString(key); + boolean retVal = true; + + if (filterValue.contains(":")) { + String[] splitVal = filterValue.split(":"); + //log.info(splitVal[0] + " " + splitVal[1]); + if ("matches".equals(splitVal[0])) { + if ("not".equals(logicKey)) { + //log.info("not"); + //log.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "split1==" + splitVal[1]); + if (getEventObjectVal(key).toString().matches(splitVal[1])) { + loggerForCheckFilter(filterValue, key); + return false; + } + } else { + if (!getEventObjectVal(key).toString().matches(splitVal[1])) { + loggerForCheckFilter(filterValue, key); + return false; + } + } + + } + if ("contains".equals(splitVal[0])) { + if ("not".equals(logicKey)) { + //log.info("not"); + //log.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "split1==" + splitVal[1]); + if (getEventObjectVal(key).toString().contains(splitVal[1])) { + loggerForCheckFilter(filterValue, key); + return false; + } + } else { + if (!getEventObjectVal(key).toString().contains(splitVal[1])) { + loggerForCheckFilter(filterValue, key); + return false; + } + } + + } + } else { + if ("not".equals(logicKey)) { + if (getEventObjectVal(key).toString().equals(filterValue)) { + loggerForCheckFilter(filterValue, key); + return false; + } + } else { + if (!getEventObjectVal(key).toString().equals(filterValue)) { + loggerForCheckFilter(filterValue, key); + return false; + } + } + } + return retVal; + } + + /** + * + * @param jo json object + * @return true/false + */ + public boolean isFilterMet(JSONObject jo) { + boolean retval; + //log.info("Filter==" + jo.toString()); + for (String key : jo.keySet()) { + if ("not".equals(key)) { + JSONObject njo = jo.getJSONObject(key); + for (String njoKey : njo.keySet()) { + //log.info(njoKey); + retval = checkFilter(njo, njoKey, key); + if (!retval) { + return retval; + } + } + } else { + //log.info(key); + //final String filterKey = key; + retval = checkFilter(jo, key, key); + if (!retval) { + return retval; + } + } + } + return true; + } + + /** + * returns a string or JSONObject or JSONArray + * + * @param keySeriesStr key series string + * @return key string updated object + **/ + public Object getEventObjectVal(String keySeriesStr) { + keySeriesStr = keySeriesStr.replaceAll("\\[", "."); + keySeriesStr = keySeriesStr.replaceAll("\\]", "."); + if (keySeriesStr.contains("..")) { + keySeriesStr = keySeriesStr.replaceAll("\\.\\.", "."); + } + //log.info(Integer.toString(keySeriesStr.lastIndexOf("."))); + //log.info(Integer.toString(keySeriesStr.length() -1)); + if (keySeriesStr.lastIndexOf('.') == keySeriesStr.length() - 1) { + keySeriesStr = keySeriesStr.substring(0, keySeriesStr.length() - 1); + } + String[] keySet = keySeriesStr.split("\\.", keySeriesStr.length()); + Object keySeriesObj = event; + for (int i = 0; i < keySet.length; i++) { + //log.info( "getEventObject " + i + " ==" + keySet[i]); + if (keySeriesObj != null) { + if (keySeriesObj instanceof String) { + //keySeriesObj = keySeriesObj.get(keySet[i]); + LOG.info("STRING==" + keySeriesObj); + } else if (keySeriesObj instanceof JSONArray) { + keySeriesObj = ((JSONArray) keySeriesObj) + .optJSONObject(Integer.parseInt(keySet[i])); + //log.info("ARRAY==" + keySeriesObj); + } else if (keySeriesObj instanceof JSONObject) { + keySeriesObj = ((JSONObject) keySeriesObj).opt(keySet[i]); + //log.info("JSONObject==" + keySeriesObj); + } else { + LOG.info("unknown object==" + keySeriesObj); + } + } + } + + if (keySeriesObj == null) { + return "ObjectNotFound"; + } + return keySeriesObj; + } + + /** + * returns a string or JSONObject or JSONArray + * + * @param keySeriesStr key series string + * @param value value object + **/ + public void setEventObjectVal(String keySeriesStr, Object value) { + keySeriesStr = keySeriesStr.replaceAll("\\[", "."); + keySeriesStr = keySeriesStr.replaceAll("\\]", "."); + if (keySeriesStr.contains("..")) { + keySeriesStr = keySeriesStr.replaceAll("\\.\\.", "."); + } + //log.info(Integer.toString(keySeriesStr.lastIndexOf("."))); + //log.info(Integer.toString(keySeriesStr.length() -1)); + if (keySeriesStr.lastIndexOf('.') == keySeriesStr.length() - 1) { + keySeriesStr = keySeriesStr.substring(0, keySeriesStr.length() - 1); + } + String[] keySet = keySeriesStr.split("\\.", keySeriesStr.length()); + Object keySeriesObj = event; + for (int i = 0; i < (keySet.length - 1); i++) { + //log.info( "setEventObject " + i + " ==" + keySet[i]); + if (keySeriesObj instanceof JSONArray) { + //keySeriesObj = ((JSONArray) keySeriesObj).optJSONObject(Integer.parseInt(keySet[i])); + if (((JSONArray) keySeriesObj).optJSONObject(Integer.parseInt(keySet[i])) + == null) //if the object is not there then add it + { + LOG.info("Object is null, must add it"); + if (keySet[i + 1].matches("[0-9]*")) // if index then array + { + ((JSONArray) keySeriesObj) + .put(Integer.parseInt(keySet[i]), new JSONArray()); + } else { + ((JSONArray) keySeriesObj) + .put(Integer.parseInt(keySet[i]), new JSONObject()); + } + } + keySeriesObj = ((JSONArray) keySeriesObj) + .optJSONObject(Integer.parseInt(keySet[i])); + //log.info("ARRAY==" + keySeriesObj); + } else if (keySeriesObj instanceof JSONObject) { + if (((JSONObject) keySeriesObj).opt(keySet[i]) + == null) //if the object is not there then add it + { + if (keySet[i + 1].matches("[0-9]*")) // if index then array + { + ((JSONObject) keySeriesObj).put(keySet[i], new JSONArray()); + } else { + ((JSONObject) keySeriesObj).put(keySet[i], new JSONObject()); + } + LOG.info("Object is null, must add it"); + } + keySeriesObj = ((JSONObject) keySeriesObj).opt(keySet[i]); + //log.info("JSONObject==" + keySeriesObj); + } else { + LOG.info("unknown object==" + keySeriesObj); + } + } + + ((JSONObject) keySeriesObj).put(keySet[keySet.length - 1], value); + } + + private JSONObject event = new JSONObject(); + + private void loggerForCheckFilter(String filterValue, String key) { + LOG.info(filterValue + "==" + key + "==" + getEventObjectVal(key) + "==false"); + } } |