<file_sep>module.exports = function(config, grunt) {
  return {
    target: {
      options: {
        war_dist_folder: '<%= targetDir %>',    /* Folder where to generate the WAR. */
        war_name: 'kibana3.war',      /* The name fo the WAR file (.war will be the extension) */
        webxml_welcome: 'index.html',
        webxml_display_name: 'Kibana 3'
      },
      files: [
        {
          expand: true,
          cwd: '<%= destDir %>',
          src: ['**'],
          dest: ''
        }
      ]
    }
  };
};<file_sep>#Kibana JS API
-

Built by Ikanow to expose some internal kibana functionality via a simple JavaScript API. Currently only tested using Kibana 3. Some simple tests for this application exist as a FlashBuilder application. The test application opens Kibana within an IFrame and tests the exposed functionality. For more information and source code [Check out the BitBucket git repository](https://bitbucket.org/mike_grill/com.ikanow.infinite.kibana.tests/src).

**Function Summary**

Dashboard Functions
* installToParent( void )
* refreshDashboard( void )
* exportConfig
* exportConfigJson
* importConfig
* importConfigJson

Query & Filter Functions
* addQuery( void )
* getQueryList( void )
* getQueryListJson( void )
* setQueryList( newList, skipReset, appendOnly )
* setQueryListJson( newListJson, skipReset, appendOnly )
* resetQueryList( void )
* getFilters( void )
* getFiltersJson( void )
* setFilters( filters, skipReset, appendOnly ) 
* setFiltersJson( filtersJson, skipReset, appendOnly )
* removeFilters( void )

**Sample Objects**

Query Item
```javascript
{
  "alias": "",
  "type": "lucene",
  "enable": true,
  "id": 0,
  "pin": false,
  "color": "#7EB26D",
  "query": "*"
}
```

Filter
```javascript
{
  "alias": "",
  "type": "querystring",
  "mandate": "either",
  "query": "*",
  "id": 0,
  "active": true
}
```

**Sample Usage**

This distribution of Kibana has an additional Angular service. This service is already included in `/serc/app/services/all.js` and will be available upon app startup. Using Angular's dependency injection, we simply need to reference the service and the API will be avilable at `window.kibanaJsApi`.
>```javascript
>require(['app'], function (app) {
>  //Inject the kibanaJsApi when angular is done loading the app
>  app.run(function(kibanaJsApiSrv) {});
>});
>```

If the API needs to be installed on a parent window use the installToParent method during app startup.
>```javascript
>require(['app'], function (app) {
>  //Inject the kibanaJsApi when angular is done loading the app
>  app.run(function(kibanaJsApiSrv) {
>    //Add the api to the window and the window's parent if it exists
>    kibanaJsApiSrv.installToParent();
>  });
>});
>```

#Function List#
-
###.installToParent()###

  _Add this instance of the API to the window's parent element to expose this API to an IFrame's parent._

* **Params: none**
* **Returns:**

  void

###.refreshDashboard()###

  _Used to forcefully refresh the Kibana Dashboard after changes._

* **Params: none**
* **Returns: boolean**

  True on success

###.addQuery()###

  _Add a new (empty) query item._

* **Params: none**
* **Returns: boolean**

  True on success


###.getQueryList()###

  _Get the current queryList as an array of Query objects._

* **Returns:**

  An array of Query Objects.

###.getQueryListJson()###

  _Get the current query list as a JSON String. Useful for passing complex objects through simple interfaces. Eg. Flash's ExternalInterface._
  
* **Returns:**

  JSON String representation of .getQueryList();  
  
###.setQueryList( queryList, skipReset, appendOnly )###

  _Update the QueryList by replacing all elements in the query. Or optionally appending the elements from QueryList._

* **Params**

  **queryList: Array\<QueryItem\>**
  
  **skipReset: Boolean**
  
  When true,the current query list will not be removed before add or updating items.
  
  **appendOnly: Boolean**
  
  When append is boolean TRUE, IDs on new items will be ignored and all items are trested as new.

* **Returns: Boolean**

  true on success
  
###.setQueryListJson( queryListJson, skipReset, appendOnly )###

  _Same as setQueryList but accepts a JSON String as the source data. Useful for passing complex objects through simple interfaces. Eg. Flash's ExternalInterface._
  
###.resetQueryList()###

  _Reset the current query to a single '*' query.
  
* **Params: none**

* **Returns: boolean**

  True on success
  
###.getFilters()###

  _Get the current filters as an array of Filter objects._

* **Returns:**

  An array of Filter Objects.

###.getFiltersJson()###

  _Get the current filters list as a JSON String. Useful for passing complex objects through simple interfaces. Eg. Flash's ExternalInterface._
  
* **Returns:**

  JSON String representation of .getFilters();  
  
###.setFilters( filters, skipReset, appendOnly )###

  _Update the filters by replacing all filters. Or optionally only updating and appending using the new filters provided._

* **Params**

  **filters: Array\<Filter\>**
  
  **skipReset: Boolean**
  
  When true,the current query list will not be removed before add or updating items.
  
  **appendOnly: Boolean**
  
  When append is boolean TRUE, IDs on new items will be ignored and all items are trested as new.

* **Returns: boolean**

  True on success
  
###.setFiltersJson( filtersJson, skipReset, appendOnly )###

  _Same as setFilters but accepts a JSON String as the source data. Useful for passing complex objects through simple interfaces. Eg. Flash's ExternalInterface._

###.removeFilters()###

  _Remove all filters and refresh the dashboard._
  
* **Returns: boolean**

  True on success
  

<file_sep>module.exports = function(config, grunt) {
  return {
    options: {
      name: "ikanow-<%= pkg.name %>",
      version: "<%= pkg.version %>",
      release: "<%= pkg.buildNumber %>",
      buildArch: "noarch",
      summary: "Forked embeddable Kibana",
      description: "Kibana3 Fork to support parent controllers and iframe embedding",
      license: "AFL-2.0",
      vendor: "Ikanow LLC",
      rpmDestination: "<%= targetDir%>",
      requires: ["ikanow-management_db-engine"]
    },
    release: {
      files: [
        { cwd: "target", src: "*.war", dest: "/opt/tomcat-infinite/interface-engine/webapps/"}
      ]
    }
  };
};<file_sep>/**
 * This service also exposes an interface to a parent container, given this application
 * is within an IFrame. The file JSAPI.md in the root of this project has more information
 * on how to use this API.
 *
 * @typedef {{}} QueryItem; //See JSAPI.md for more information
 * @typedef {Object} Filter;    //See JSAPI.md for more information
 * @typedef {Config} Config;    //Not yet implemented.
 *
 */
define([
    'angular',
    'lodash'
  ], function (angular, _) {

    'use strict';

    var module = angular.module('kibana.services');
    module.service('kibanaJsApiSrv', function ($rootScope, dashboard, querySrv, filterSrv) {

      // Save a reference to this
      var self = this;

      /**
       * Attach event listeners to some internal kibana events so we can expose them.
       */
      self.init = function () {
        //console.log("[kibanaJsApi] init");

        window.kibanaJsApi = this;

        //Monitor Kibana events so we can expose them
        $rootScope.$on('refresh', function () {
          //console.log("[kibanaJsApi] Refresh observed");
          //TODO expose refresh event
        });
      };

      /**
       * Add the kibanaJsApi instance to this window's parent container.
       * @returns {Boolean} True on success.
       */
      self.installToParent = function(){
        //Install the KibanaJsApi to Kibana's container's document if it exists
        if (window.parent !== window) {
          //console.log("[kibanaJsApi->installToParent] Install API to IFrame Parent");
          window.parent.kibanaJsApi = this;
        }
        return true;
      };

      /**
       * Refresh the current dashboard
       * @returns {Boolean} True on success.
       */
      self.refreshDashboard = function () {
        //console.log("[KibanaJsApi->refreshDashboard] Refreshing dashboard");
        dashboard.refresh();
        $rootScope.$apply();
        return true;
      };

      /**
       * Add a new query item to the queryList
       * @param {QueryItem} queryItem Query item definition
       * @returns {Boolean} True on success.
       */
      self.addQuery = function( queryItem ) {
        //console.log("[KibanaJsApi->addQuery] New Item: ", queryItem);

        //If nothing was passed add an empty query item
        if( !queryItem ) {
          queryItem = {};
        }

        //Add an empty item
        querySrv.set(queryItem);

        //refresh and apply
        this.refreshDashboard();

        return true;
      };

      /**
       * Get the dashboards current queryList
       * @returns {Array<QueryItem>} An array of query items
       */
      self.getQueryList = function(){
        //console.log("[KibanaJsApi->getQueryList]");
        return querySrv.getQueryObjs();
      };

      /**
       * Get the dashboards current queryList as a JSON String
       * @returns {String} A JSON String representing the current array of query items
       */
      self.getQueryListJson = function () {
        //console.log("[KibanaJsApi->getQueryListJson]");
        var queryListJson = angular.toJson( this.getQueryList(), false);
        //console.log("[KibanaJsApi->getQueryListJson] Query: ", queryListJson);
        return queryListJson;
      };

      /**
       * Replace the current query list with a new one
       * @param {Array<QueryItem>} newList An array of query items
       * @param {Boolean} skipReset Don't reset the Query List to '*'
       * @param {Boolean} appendOnly Only add elements, don't update using IDs
       * @returns {Boolean} True on success.
       */
      self.setQueryList = function( newList, skipReset, appendOnly ){

        //console.log("[KibanaJsApi->setQueryList] Setting query", newList);

        //If skip reset wasn't set or isn't true, then we reset.
        if( skipReset !== true ) {
          //console.log("[KibanaJsApi->setQueryList]    Clearing query before setting items");
          //Empty the query but don't $apply yet
          this.resetQueryList(true /*No Refresh*/);
        }

        _.each( newList, function(q){

          if( appendOnly === true && q.hasOwnProperty('id') ) {
            delete q.id; //unset ID - Forces new item
          }

          if( q.hasOwnProperty('id') && q.id === 0 ) {
            querySrv.set( q, 0 );
          } else {
            querySrv.set( q );
          }
        });

        //refresh and apply
        this.refreshDashboard();

        return true;
      };

      /**
       * Replace the current query list with a new one using a json string
       * @param {String} queryListJson A JSON String representing an array of query items.
       * @param {Boolean} skipReset Don't reset the Query List to '*'
       * @param {Boolean} appendOnly Only add elements, don't update using IDs
       * @returns {Boolean} True on success.
       */
      self.setQueryListJson = function (queryListJson, skipReset, appendOnly) {
        //console.log("[KibanaJsApi->setQueryListJson] setting query list from json text");
        var queryList = angular.fromJson(queryListJson);
        return this.setQueryList(queryList, skipReset, appendOnly );
      };

      /**
       * Replace the current query list with a single '*'
       * @param {Boolean} noRefresh When boolean true, the dashboard will not be refreshed
       * @returns {Boolean} True on success.
       */
      self.resetQueryList = function( noRefresh ){
        //console.log("[KibanaJsApi->resetQueryList] Resetting query to single '*'");

        _.each(querySrv.ids(), function(qId){
          querySrv.remove(qId);
        });

        //Reset the first item to '*'
        querySrv.set({
          "query":"*",
          "alias":"",
          "color":"#7EB26D",
          "pin":false,
          "type":"lucene",
          "enable":true
        });

        //refresh and apply
        if( noRefresh !== true ) {
          this.refreshDashboard();
        }

        return true;
      };

      /**
       * Get the dashboards current filters as an array of Filters
       * @returns Array<Filter>
       */
      self.getFilters = function() {
        //console.log("[KibanaJsApi->getFilters]");
        return filterSrv.list();
      };

      /**
       * Get the dashboards current filters as a JSON string representing array of filters
       * @returns {String} JSON String representation of an array of Filters.
       */
      self.getFiltersJson = function () {
        //console.log("[KibanaJsApi->getFiltersJson]");
        var filtersJson = angular.toJson(this.getFilters(), false);
        //console.log("[KibanaJsApi->getFiltersJson] Filters: ", filtersJson);
        return filtersJson;
      };

      /**
       * Replace the dashboards current filters with a new set. UpdateOnly will not
       * remove any items before setting the new ones in place.
       * @param {Array<Filter>} filters An array of filters
       * @param {Boolean} skipReset Don't clear all filters before adding / setting new items.
       * @param {Boolean} appendOnly Only add elements, don't update using IDs
       * @returns {Boolean} True on success.
       */
      self.setFilters = function( filters, skipReset, appendOnly ){
        //console.log("[KibanaJsApi->setFilters] setting filters", filters);

        if (skipReset !== true) {
          this.removeFilters( true ); //true for no refresh
        }

        _.each(filters, function (filter) {

          if( appendOnly === true || !filter.hasOwnProperty('id') ) {

            //Remove IDs for less confusion
            if( filter.hasOwnProperty('id') ){
              delete filter.id;
            }

            //console.log("[KibanaJsApi->setFilters]   appending filter", filter);
            filterSrv.set(filter, undefined, true); // true for no refresh

          } else {

            //Even if the filter has an ID, if that ID does not exist we must add it. Updating will fail.
            var filterExists = false;
            _.each( self.getFilters(), function(f){
              if(f.id === filter.id) {
                filterExists = true;
              }
            });

            if( filterExists ) {
              //console.log("[KibanaJsApi->setFilters]   updating filter", filter);
              filterSrv.set(filter, filter.id, true); // true for no refresh
            } else {
              //console.log("[KibanaJsApi->setFilters]   adding filter", filter);
              filterSrv.set(filter, undefined, true); // true for no refresh
            }
          }

        });

        //refresh and apply
        this.refreshDashboard();

        return true;
      };

      /**
       * See setFilters above. Accepts a JSON String representing an array of filters.
       * @param {String} filtersJson JSON String representing an array of Filters.
       * @param {Boolean} skipReset Don't clear all filters before adding / setting new items.
       * @param {Boolean} appendOnly Only add elements, don't update using IDs
       * @returns {Boolean} True on success.
       */
      self.setFiltersJson = function (filtersJson, skipReset, appendOnly) {
        //console.log("[KibanaJsApi->setFiltersJson] setting filters", filtersJson);
        var filters = angular.fromJson(filtersJson);
        return this.setFilters(filters, skipReset, appendOnly);
      };

      /**
       * Remove all the filters from the dashboard
       * @returns {Boolean} True on success.
       */
      self.removeFilters = function ( noRefresh ) {
        //console.log("[KibanaJsApi->removeFilters]");
        _.each( filterSrv.ids(), function(fId){
          filterSrv.remove(fId, true); //true for noRefresh
        });
        if( noRefresh !== true ){
          this.refreshDashboard();
        }
        return true;
      };

      /**
       * Get an object representing the current state of the dashboard.
       * This object can be used for the import functionality.
       *
       * This has not been tested
       *
       * @returns {{queryList: Array.<QueryItem>, filters: Array.<Filter>}}
       */
      self.exportConfig = function(){
        return {
          queryList: this.getQueryList(),
          filters: this.getFilters()
        };
      };

      /**
       * Get a JSON String representing the current config. See exportConfig above.
       *
       * This has not been tested
       *
       * @returns {String} JSON String of current dashboard config
       */
      self.exportConfigJson = function(){
        return angular.toJson(this.exportConfig(), true);
      };

      /**
       * Import a previously exported dashboard state.
       *
       * This has not been tested.
       *
       * @param {Config} config
       * @returns {Boolean} True on success.
       */
      self.importConfig = function( config ){
        this.setFilters( config.filters );
        this.setQueryList( config.queryList );
        this.refreshDashboard();
        return true;
      };

      /**
       * Import a previously exported dashboard state from a JSON String.
       *
       * This has not been tested
       *
       * @param {String} configJson JSON String representing a Config object.
       * @returns {Boolean} True on success.
       */
      self.importConfigJson = function( configJson ){
        return this.importConfig( angular.fromJson(configJson) );
      };

      // Now init
      self.init();

    });
  }
);<file_sep>/*******************************************************************************
 * Copyright 2012 The Infinit.e Open Source Project
 *
 * 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.
 ******************************************************************************/

// INITIALIZATION

var infiniteJsConnector = infiniteJsConnector || {

	_flashMovie: null,			// Container FLEX Application
	_jsConnectorParent: null,
	_mode: 'stashed',			// 'stashed' or 'live'

	/**
	 * Initialization consists of defining flashMove in order to communicate
	 * with the actionscript
	 */
	init: function () {
		if (null == this._flashMovie) {
			if (document.getElementById) {
				this._flashMovie = parent.document.getElementById("Index");
			}
		}
	},

	getFlashMovie: function(){
		return this._flashMovie;
	},

	/**
	 * Grabs the infinit.e.parent js connector object;
	 */
	getJsConnectorParent: function(){
		this._jsConnectorParent = parent.infiniteJsConnectorParent;
		return parent.infiniteJsConnectorParent;
	},

	/**
 	 *	possible values:
	 *	- live 			... append: &mode=live
	 *	- stashed 		... append: &mode=stashed
	 *   ignore for now   - all records 	... append: &mode=all_records
	 **/
	getMode: function(){
		return this._mode;
	},

	/** sets mode **/
	setMode:function(modeString){
		this._mode = modeString;
		return this._mode;
	},

	/** returns set cids **/
	getCIds: function(url){
		return this.getCommunityIds(url);
	},

	getParentId: function() {
        var parentDoc = window;
        while(parentDoc !== parentDoc.parent)
        {
            parentDoc = parentDoc.parent;
        }
        parentDoc = parentDoc.document;
        var iFrames = parentDoc.getElementsByTagName('iframe');
        return iFrames[0].getAttribute("id");
	},

	/**
	* Asks actionscript for communityIds.
	*/
	getCommunityIds: function(url)
	{
		var me = this;
		try {
			var cIdsStr = me.getFlashMovie().getCommunityIds(url);
		}
		catch (e) {
		}
		return cIdsStr;
	},
	/**
	* Asks actionscript for data set flags (docs vs custom vs map/reduce).
	*/
	getDatasetFlags: function()
	{
		var me = this;
		try {
			var datasetFlags = me.getFlashMovie().getDatasetFlags();
		}
		catch (e) {
		}
		return datasetFlags;
	},

	/**
	*	grabs community ids and current search state
	*	returns string ex: ?cids=1,2,3&mode=live
	**/
	getExtraUrlParams:function(url)
	{
		try{
			var params =  { 'cids': this.getCIds(url), 'mode': this.getMode() };
			var datasetFlags = this.getDatasetFlags();
			if (datasetFlags && (datasetFlags.length > 0)) {
				var datasetFlagsObj = datasetFlags.split('&');
				for (var x in datasetFlagsObj) {
					var paramPair = datasetFlagsObj[x].split("=", 2);
					if ((2 == paramPair.length) && (paramPair[0].length > 0)) {
						params[paramPair[0]] = paramPair[1];
					}
				}
			}
			if (url.length > 512) { // use substitution 
				var startOfIndex = url.indexOf('/proxy/');
				if (startOfIndex > 0) {
					var indexSet = url.substring(startOfIndex + 7);
					var endOfIndex = indexSet.indexOf('/');
					if (endOfIndex > 0) {
						indexSet = indexSet.substring(0, endOfIndex);
						params.indexes = indexSet;
						url = url.replace(indexSet, '$indexes');
						params.url = url;
					}
				}
			}
			
			return params;
		}catch(error){
			console.log("getExtraUrlParams: " + error.message)
			return null;
		}
	},

	/**
	* Generally called from actionscript with a true if live, false if stashed.
	* This function will set the mode within the infiniteJsConnector object
	* to be grabbed whenever an httpservice call is made and "mode" is required.
	**/
	setLive:function(isLive){
		if(isLive==true){
			//development location
			//window.location = "kibanaBin/dist/index.html#Kibana_LiveTemplate.json";
			//production location
			window.location = "/infinit.e.records/static/kibana/index.html#/dashboard/file/Kibana_LiveTemplate.json";
			infiniteJsConnector.setMode('live');

		}else if(isLive==false){
			//development location
			//window.location = "kibanaBin/dist/index.html#Kibana_StashedTemplate.json";
			//production location
			window.location = "/infinit.e.records/static/kibana/index.html#/dashboard/file/Kibana_StashedTemplate.json";
			infiniteJsConnector.setMode('stashed');
		}
	},

	/**
	* Called before init when url parameters are provided.
	* URL parameters are only ever supplied when the widget is run outside
	* of an actionscript iframe.
	*
	* Takes the provided parameter string and grabs the cids and mode.
	* With this information, cids and mode are stored in the infiniteJsConnector
	* object to be used in anything kibana would need.
	*
	* (param) paramString:String example: "?cids=1,2,3&mode=live
	*/
	onWidgetLoadWithParameters:function(paramString){
		var str = paramString;
		var params = str.split("&");
		if (params.length > 0) {
			for (var x in params) {
				var keyval = params[x].split('=');
				if (keyval.length > 1) {
					var key = keyval[0];
					if ((key == '?cids') || (key == 'cids')) {
						infiniteJsConnector.setCIds(keyval[1]);
					}
					if ((key == '?mode') || (key == 'mode')) {
						infiniteJsConnector.setMode(keyval[1]);
					}
				}
			}
		}
	}
};

/**
 * If the widget is loaded on its own (outside of an iframe), the URL parameters
 * must be checked in order to get cids and search mode.
 *
 * On Page load added in order to check URL parameters and set them appropriately.
 */
window.onload = function(){
	try {

		if (window.location.search.length > 0){
			infiniteJsConnector.onWidgetLoadWithParameters(window.location.search);
		}

		infiniteJsConnector.init();
	}
	catch (e) {
		//alert("infinite init error: " + e);
	}
}

/**
 * Helper function to allow a parent container to trigger the installation on the parent.
 * After installation, window.kibanaJsApi should be available on the parent container.
 *
 * eg. ( from Flex )
 * kibanaFrame.callIFrameFunction('installKibanaJsApiToParent'); //Trigger parent install
 * ExternalInterface.call("kibanaJsApi.refreshDashboard");			 //Use API Locally
 */
function installKibanaJsApiToParent(){
	//console.log("Installing to parent via IFrame helper function.");
	kibanaJsApi.installToParent();
}

function QueryTerm(q, index)
{
    this.query = q;
    this.alias = "";
	this.id = index;
    this.pin = false;
    this.type = "lucene";
    this.enable = true;
    this.parent = index;
}

function TimeTerm(from_value, to_value)
{
	this.type = "time";
	this.field = "@timestamp";
	this.from = from_value;
	this.to = to_value;
	this.mandate = "must";
	this.active = true;
	this.alias = "";
}

function FilterString(q, index)
{
	this.id = index;
	this.type = "querystring";
	this.query = q;
	this.mandate = "must";
	this.active = true;
	this.alias = "";
}

mirrorQuery = function(query_string){
	var query = JSON.parse(query_string);
	var kibana_q = [];
    var kibana_f = [];
    for( var i = 0; i < query.qt.length; i++ ){
        var term = query.qt[i];
	    
	    if ( null != term)
	    {
	        if (null != term.etext)
	        {
	            kibana_q.push(new QueryTerm(term.etext, kibana_q.length));
	        }
	        else if ( null != term.ftext)
	        {
	        	kibana_q.push(new QueryTerm(term.ftext, kibana_q.length));
	        }
	        else if ( null != term.entity)
	        {
	        	kibana_q.push(new QueryTerm(term.entity.split("/")[0], kibana_q.length));
	        }
	        else if ( null != term.time && null != term.time.min && null != term.time.max)
	        {
	        	kibana_f.push(new TimeTerm(term.time.min, term.time.max));
	        }
	    }
	   
	}
    
    if (null != kibana_q)
	{
    	kibanaJsApi.setQueryList(kibana_q, false, false);
	}
    
    if (null != kibana_f)
	{
    	kibanaJsApi.setFilters(kibana_f, false, false);
	}
}

refreshKibana = function(){
	kibanaJsApi.refreshDashboard();
}

ikanowObjectsToKibana = function(ikanowControlObject){
	if (null != ikanowControlObject)
	{
		try{
			var obj = JSON.parse(ikanowControlObject.toString());
		}
		catch (err) {
			try{
				var obj = JSON.parse(ikanowControlObject.toString().replace(/[\b]/g, '\\b').replace(/[\f]/g, '\\f').replace(/[\n]/g, '\\n').replace(/[\r]/g, '\\r').replace(/[\t]/g, '\\t'));
			}
			catch (err2) {
				alert("Unable to Process Data:  " + err2);
			}
		}
		
		if (null != obj) {
	        var termsOverride = 'AND';
	        var decomposeInfiniteQuery = false;
	        var appendToExistingKibanaQueries = false;
	        var applyToFilter = false;
	        var singleQ = "";
	        var kibana_q = [];
	        var kibana_f = [];
	        
	        if (null != obj.termsOverride){
	             termsOverride = obj.termsOverride;   
	        }
	        if (null != obj.decomposeInfiniteQuery){
	             decomposeInfiniteQuery = obj.decomposeInfiniteQuery;   
	        }
	        if (null != obj.appendToExistingKibanaQueries){
	             appendToExistingKibanaQueries = obj.appendToExistingKibanaQueries;   
	        }
	        if (null != applyToFilter) {
	        	applyToFilter = obj.applyToFilter;
	        }
	        
	        //Entities
	        if ( null != obj.entities && null != obj.entities.source)
	        {
	            for( var i = 0; i < obj.entities.source.length; i++ ){
	                 var ent = obj.entities.source[i];
	                
	                if ( null != ent)
	                {        
	                	var ent_term = null;
	                	if (null != ent.actual_name)
	                	{
	                		ent_term = ent.actual_name;
	                	}
	                	else if ( null != ent.etext)
	                	{
	                		ent_term = ent.etext;
	                	}
	                	else if ( null != ent.ftext)
	                	{
	                		ent_term = ent.ftext;
	                	}
	                	else if ( null != ent.entity)
	                	{
	                		ent_term = ent.entity.substring(0,ent.entity.lastIndexOf("/"));
	                	}
	                	else if ( null != ent.time && null != ent.time.min && null != ent.time.max)
		     	        {
		     	        	kibana_f.push(new TimeTerm(ent.time.min, ent.time.max));
		     	        }
	                	
	                	if (null != ent_term)
	                	{
		                    if (decomposeInfiniteQuery == true)
		                    {
		                    	if (applyToFilter == true)
		                    		kibana_q.push(new FilterString('"' + ent_term + '"', kibana_q.length));
		                    	else
		                    		kibana_q.push(new QueryTerm('"' + ent_term + '"', kibana_q.length));
		                    }
		                    else
		                    {
		                        if (singleQ == '')
		                            singleQ = '"' + ent_term + '"';
		                        else
		                            singleQ += ' ' + termsOverride + ' "' + ent_term + '"';
		                    }
	                	}
	                }// if (null != ent)
	            } //for loop
	        } //if ( null != obj.entities && null != obj.entities.source)
	        
	        //Associations
	        if (null != obj.associations && null != obj.associations.source)
        	{
	        	for( var i = 0; i < obj.associations.source.length; i++ ){
	        		var association = obj.associations.source[i];
	        		var entity1 = null;
	        		var entity2 = null;
	        		if (null != association.entity1)
	        			entity1 = association.entity1;
	        		if (null != association.entity2)
	        			entity2 = association.entity2;
	        		if (null == entity1 && null != association.entity1_index)
	        			entity1 = association.entity1_index.substring(0,association.entity1_index.lastIndexOf("/"));
	        		if (null == entity2 && null != association.entity2_index)
	        			entity2 = association.entity2_index.substring(0,association.entity2_index.lastIndexOf("/"));
	        		
	        		if ( null != association && (null != entity1 || null != entity2))
	                {
	        			var term = '';
	        			if (null !=  entity1 && null != entity2)
	        			{
	        				term = '("' + entity1 + '" AND "' + entity2 + '")';
	        			}
	        			else
	        			{
	        				if (null !=  entity1)
	        					term = '"' + entity1 + "'";
	        				else if (null !=  entity2)
	        					term = '"' + entity2 + '"';
	        			}
	        			
	        			if (decomposeInfiniteQuery == true)
	                    {
        					if (applyToFilter == true)
        						kibana_q.push(new FilterString(term, kibana_q.length));
        					else
        						kibana_q.push(new QueryTerm(term, kibana_q.length));
	                    }
	                    else
	                    {
	                        if (singleQ == '')
	                            singleQ = term;
	                        else
	                            singleQ += ' ' + termsOverride + ' ' + term ;
	                    }
	        			
	                }
	        	}
        	}
	        
	        if (null != singleQ && singleQ != '')
	        {
	        	if (applyToFilter == true)
	        		kibana_q.push(new FilterString(singleQ, kibana_q.length)); 
	        	else
	        		kibana_q.push(new QueryTerm(singleQ, kibana_q.length)); 
	        }
	        
	        if (null != kibana_q && kibana_q.length > 0)
	        {
	        	if (applyToFilter == true)
	        		kibanaJsApi.setFilters(kibana_q, appendToExistingKibanaQueries, appendToExistingKibanaQueries);
	        	else
	        		kibanaJsApi.setQueryList(kibana_q, appendToExistingKibanaQueries, appendToExistingKibanaQueries);
	        } 
	        
	        if (null != kibana_f && kibana_f.length > 0)
	        {
	        	if (applyToFilter == true)
	        		kibanaJsApi.setFilters(kibana_f, true, true);
	        	else
	        		kibanaJsApi.setFilters(kibana_f, appendToExistingKibanaQueries, appendToExistingKibanaQueries);
	        }
	        
	    }//Null check on JsonParse
	}// Null Check on ikanowControlObject
}
