Splunk® Enterprise

Module System Reference

Splunk Enterprise version 7.2 is no longer supported as of April 30, 2021. See the Splunk Software Support Policy for details. For information about upgrading to a supported version, see How to upgrade Splunk Enterprise.
This documentation does not apply to the most recent version of Splunk® Enterprise. For documentation on the most recent version, go to the latest release.

Splunk.util

Important notice: As part of Advanced XML deprecation, the Module System is officially deprecated beginning with Splunk Enterprise 6.3. For more information, see Advanced XML Deprecation.

addLeadingSearchCommand()

The addLeadingSearchCommand() method prefixes a search string to the specified search string if it does not already begin with search or a pipe (¦) symbol. This method is typically used to verify that user-provided search is formatted correctly for the search API.

Synopsis

qSearch = Splunk.util.addLeadingSearchCommand( search, isUserEntered )

Parameters

search String Search string to be qualified.
isUserEntered Boolean Unqualified search string indication:
true = The search parameter is expected to be unqualified.
false = The search parameter is not expected to be unqualified.

Return Value

String Qualified search string.

Example

getUserEnteredSearch: function() {

   var q = this.input.attr('value')    '*';
   q = Splunk.util.addLeadingSearchCommand(q, true);
   return q;

},

See Also

stripLeadingSearchCommand()

discoverReplacementTokens()

The discoverReplacementTokens() method gets an array of unique replacement tokens found in the specified string or object fragment. If fragment is an object, the method identifies tokens in both keys and values. Replacement tokens are formatted as $token$.

Synopsis

results = Splunk.util.discoverReplacementTokens( fragment )

Parameters

fragment String, Object Fragment to examine for replacement tokens.

Return Value

Array List of unique replacement tokens.

Example

if (USE_AUTOMATIC_STRING_REPLACEMENT) {

   var context = this.getContext();
   var baseSearch = search.toString();
   var tokens = Splunk.util.discoverReplacementTokens(baseSearch);  
   for (var i=0; i<tokens.length; i++) {
       var replacer = new RegExp("\\$" + tokens[i] + "\\$");
       baseSearch = Splunk.util.replaceTokens(baseSearch, replacer, context.get(tokens[i]));
       search.setBaseSearch(baseSearch);
   }  

}

See Also

replaceTokens()

escapeBackslash()

The escapeBackslash() method escapes backslash characters found in the specified input string.

Synopsis

results = Splunk.util.escapeBackslash( input )

Parameters

input String String to search for backslash characters.

Return Value

String The input string with any backslash characters escaped.

Example

var input = "foo//bar"; var input = Splunk.util.escapeBackslash(input);

alert(input); // will be "foo////bar"

See Also

escapeHtml()

escapeHtml()

The escapeHtml() method escapes HTML entities in the specified input string.

Note: This method should only be used as a convenience method, because client-side escaping is not trustworthy.

Synopsis

results = Splunk.util.escapeHtml( input )

Parameters

input String String containing HTML entities.

Return Value

String The input string with HTML entities escaped.

Example

var input = '"<&bar&>"'; var input = Splunk.util.escapeHtml(input);

alert(input);

See Also

escapeBackslash()

fieldListToString()

The fieldListToString() method serializes a specified fieldArray array into a comma-separated string.

Synopsis

results = Splunk.util.fieldListToString( fieldArray )

Parameters

fieldArray Array Array of fields to serialize.

Return Value

String Comma-separated field list.

Example

var fieldList = ['foo\bar ', ' "bar"', 'biz,']; var fieldString = Splunk.util.fieldListToString(fieldList);

alert(fieldString);

See Also

stringToFieldList()

getCommaFormattedNumber()

The getCommaFormattedNumber() method converts numbers in the specified input string to comma-notated format.

Synopsis

results = Splunk.util.getCommaFormattedNumber( input )

Parameters

input String String, possibly containing numbers.

Return Value

String The input string with numbers converted to comma-notated representations.

Example

var num = '10000000001';

numb = Splunk.util.getCommaFormattedNumber(numb); alert(num);

getComputedStyleHelper()

The getComputedStyleHelper() method gets the value of the specified style for the specified element.

Synopsis

results = Splunk.util.getComputedStyleHelper( element, styleProp )

Parameters

element Object Element to interrogate.
styleProp String Style property to interrogate.

Return Value

Boolean Value of the element style property, styleProp. Returns null, if element or styleProp do not exist.

Example

var myVal = Splunk.util.getComputedStyleHelper(myElement, 'display'); alert(myVal);

getConfigValue()

The getConfigValue() method gets SplunkWeb configuration values stored in the DOM.

Synopsis

results = Splunk.util.getConfigValue( configKey, optionalDefault )

Parameters

configKey String Configuration key to get.
optionalDefault String (Optional) Fallback value if configKey does not exist or has no value.

Return Value

String Value of specified configKey.

Throws

'getConfigValue - ' + configKey + ' not set, no default provided'

Example

var f = Splunk.util.getConfigValue("SEARCH_RESULTS_TIME_== getCurrentDisplayView()==

The getCurrentDisplayView() method gets the current displayView name, which is the view label stored in the DOM.

Synopsis

name = Splunk.util.getCurrentDisplayView()

Return Value

String Current displayView name if different from the view name. Otherwise, the current view name.

Example

var displayView = Splunk.util.getCurrentDisplayView();

See Also

getCurrentApp()
getCurrentView()
getCurrentViewConfig()

FORMAT"); var f = Splunk.util.getConfigValue("DEFAULT_SPACECAKE_VENDOR", "Barneys");

getCumlativeOffsetLeft()

The getCumlativeOffsetLeft() method gets the cumulative offset of the specified DOM element property.

Synopsis

offset = Splunk.util.getCumlativeOffsetLeft( element )

Parameters

element Object DOM element: offsetLeft or offsetParent.

Return Value

Integer Cumulative offset value.

Example

var height = ($(window).height() + Splunk.util.getPageYOffset() + pixelAdjustment) - \

   Splunk.util.getCumlativeOffsetTop(this.container[0]);

See Also

getCumlativeOffsetTop()
getPageYOffset()

getCumlativeOffsetTop()

The getCumlativeOffsetTop() method gets the value of the specified DOM element parameter.

Synopsis

offset = Splunk.util.getCumlativeOffsetTop( element )

Parameters

element Object DOM element: offsetTop or offsetParent.

Return Value

Integer Cumulative DOM element value.

Example

var height = ($(window).height() + Splunk.util.getPageYOffset() + pixelAdjustment) - \

   Splunk.util.getCumlativeOffsetTop(this.container[0]);

See Also

getCumlativeOffsetLeft()
getPageYOffset()

getCurrentApp()

The getCurrentApp() method gets the current app name as stored in the DOM, which is not the friendly name, or label, of the current app.

Synopsis

app = Splunk.util.getCurrentApp()

Return Value

String Current app name or UNKNOWN_APP, if app name is undefined in the DOM.

Example

document.location = Splunk.util.make_url('app', Splunk.util.getCurrentApp());

See Also

getCurrentDiplayView()
getCurrentView()
getCurrentViewConfig()
make_url()

getCurrentDisplayView()

The getCurrentDisplayView() method gets the current displayView name, which is the view label stored in the DOM.

Synopsis

name = Splunk.util.getCurrentDisplayView()

Return Value

String Current displayView name if different from the view name. Otherwise, the current view name.

Example

var displayView = Splunk.util.getCurrentDisplayView();

See Also

getCurrentApp()
getCurrentView()
getCurrentViewConfig()

getCurrentView()

The getCurrentView() method gets the current view value, which is the actual view name stored in the DOM.

Synopsis

results = Splunk.util.getCurrentView()

Return Value

String Current view value, as stored in the DOM, or UNKNOWN_VIEW if undefined.

Example

var view = Splunk.util.getCurrentView();

See Also

getCurrentApp()
getCurrentDisplayView()
getCurrentViewConfig()

getCurrentViewConfig()

The getCurrentViewConfig() method gets a dictionary of app, view, and saved search configuration data in the DOM, for the current view.

Synopsis

config = Splunk.util.getCurrentViewConfig()

Return Value

Object The app, view, and saved search configuration data in the DOM, for the current view.

Example

var config = Splunk.util.getCurrentViewConfig();

See Also

getCurrentApp()
getCurrentDisplayView()
getCurrentView()

getEpochTimeFromISO()

The getEpochTimeFromISO() method gets an epoch time equivalent to the specified ISO time.

Synopsis

epoch = Splunk.util.getEpochTimeFromISO( isoStr )

Parameters

isoStr String ISO-formatted time

Return Value

String Epoch time equivalent to isoStr, including milliseconds.

Example

getTimeRange: function() {

   if (!this._earliestTime  !this._latestTime) {
       return new Splunk.TimeRange();
   }  
   var startTime = Splunk.util.getEpochTimeFromISO(this._earliestTime);
   var endTime  = Splunk.util.getEpochTimeFromISO(this._latestTime); 
   if (isNaN(startTime)) {
       startTime = this._earliestTime;
       endTime  = this._latestTime;
   }  
   if (startTime == 0) startTime = null;
   if (endTime  == 0) endTime  = null;
   return new Splunk.TimeRange(startTime, endTime); 

},

getHEX()

The getHEX() method gets the hexadecimal equivalent of the specified RGB value.

Synopsis

hexVal = Splunk.util.getHEX( rgbVal )

Parameters

rgbVal String RGB value. Format: 'rgb(rrr, ggg, bbb)'

Return Value

String Hexadecimal equivalent of rgbVal, with preceding # symbol.

Example

var myHEX = Splunk.util.getHEX('rgb(255, 0, 0)');

alert(myHEX);

See Also

normalizeColor()

getPageYOffset()

The getPageYOffset() method gets the amount of content hidden by scrolling down.

Synopsis

offset = Splunk.util.getPageYOffset()

Return Value

Number Amount of content hidden, vertically, by scrolling down, in pixels.

Example

var height = ($(window).height() + Splunk.util.getPageYOffset() + pixelAdjustment) - \

   Splunk.util.getCumlativeOffsetTop(this.container[0]);

See Also

getCumlativeOffsetLeft()
getCumlativeOffsetTop()

getParameter()

The getParameter() method gets the GET parameter from window.location or an optional string.

Synopsis

getParam = Splunk.util.getParameter( paramVal, string )

Parameters

paramVal String Parameter value to get.
string String (Optional) String to search instead of window.location.search

Return Value

String Parameter value, or none if paramVal has no value.

Example

var fooVal = Splunk.util.getParameter('foo');

See Also

getPath()

getPath()

The getPath() method gets the current location path without the localization segment.

Synopsis

results = Splunk.util.getPath()

Return Value

String Current location path without localization.

Example

var pathVal = Splunk.util.getPath();

See Also

getParameter()
make_url()
queryStringToProp()

getServerTimezoneOffset()

The getServerTimezoneOffset() method gets the current server timezone offset.

Synopsis

offset = Splunk.util.getServerTimezoneOffset()

Return Value

String Current server timezone offset, in milliseconds.

Example

var serverOffsetSeconds = Splunk.util.getServerTimezoneOffset();

See Also

getTimezoneOffsetDelta()

getTimezoneOffsetDelta()

The getTimezoneOffsetDelta() method gets the time delta between the specified offset and date.

Synopsis

offset = Splunk.util.getTimezoneOffsetDelta( serverOffsetThen, date )

Parameters

serverOffsetThen Integer Timezone offset, in minutes.
date Object JavaScript Date() object from which to calculate offset.

Return Value

Integer Difference between serverOffsetThen and date, in milliseconds.

Example

var earliestDelta = \

   Splunk.util.getTimezoneOffsetDelta(this.serverOffsetAtEarliest, earliest);

var latestDelta = \

   Splunk.util.getTimezoneOffsetDelta(this.serverOffsetAtLatest, latest);

See Also

getServerTimezoneOffset()

getWindowDimensions()

The getWindowDimensions() method gets the inner dimensions of the current window.

Synopsis

dims = Splunk.util.getWindowDimensions()

Return Value

Object JSON-formatted height and width. Example: { 'height': 600, 'width': 800 }

Example

var dimensions = Splunk.util.getWindowDimensions();

isInt()

The isInt() method tests if the specified value is an integer, implying it can be parsed into an integer using the JavaScript parseInt() method.

Synopsis

status = Splunk.util.isInt( int )

Parameters

int String, Integer Value to test for an integer.

Return Value

Boolean Value is integer indication:
true = Value is an integer or can be converted to an integer.
false = Value is not an integer.

Example

var int1 = 42; var int2 = function() { return false; }; var int3 = '42'; var int4 = ['foo', 'bar']; var int5 = { the_answer_to_life_the_universe_and_everything: 42}

alert(Splunk.util.isInt(int1)); alert(Splunk.util.isInt(int2)); alert(Splunk.util.isInt(int3)); alert(Splunk.util.isInt(int4)); alert(Splunk.util.isInt(int5));


make_full_url()

The make_full_url() method builds a qualified query string given the specified path and, optional, dictionary of options.

Synopsis

fullURL = Splunk.util.make_full_url( url, options)

Parameters

url String Endpoint path.
options Object Query string parameters dictionary.

Return Value

String Full URL created from url and options.

Example

var bounce_url = Splunk.util.make_full_url('/account/login', \

                                          { return_to: 'apps/search/' });

See Also

make_url()

make_url

The make_url() function returns a URL for the specified path.

The method builds a URL from a relative or absolute URL with optional query string. A relative URL is returned, if relative is set to True, otherwise, an absolute URL is returned. The string /splunk or the configuration root_path is prefixed to the URL unless translate is set to False.

Static paths are constructed with an embedded cache defeater segment :

/static/@<build_number>[.<push_number>]/

This results in static paths like the following example:

/static/@12345/js/foo/static/@12345.1/js/foo

Static assets for apps have an additional cache defeater number correlating to the application build number as defined in the app.conf file:

/static/@12345.1:2/app/unix/static/foo.png

The URL handler in root.py strips out any requests having this schema.

Synopsis

targURL = make_url(target, _qs=None, translate=True, relative=False, __app_cache={})

Parameters

target String
_qs Object Query string as a list of tuples or a dictionary. Example: _qs=[('q', 'search val to quote')] (Default = None )
translate Boolean Prefix the application server root path flag:
True = Prefix root path (Default).
False = Do not prefix root path.
relative Boolean Relative returned path indication:
True = Returned targetURL is relative.
False = Returned targetURL is absolute (Default)

Return Value

String The specified target as a full URL.

Raises

InvalidURLException "Illegal characters in URL"
ValueError 'Illegal escape from parent directory "%s": %s' %(basepath, fullpath)

Example

from splunk.appserver.mrsparkle.lib import util

targetURL = '/en-US/api/search/jobs?job=1234&action=delete' example1URL = util.make_url('/api/search/jobs', job=1234, action=delete) example2URL = util.make_url('/api/search/jobs, _qs=dict(job=1234,action=delete))

See Also

strip_url()
url_has_valid_charset()

normalizeBoolean()

The normalizeBoolean() method normalizes various boolean syntax idioms into a Boolean response.

Synopsis

results = Splunk.util.normalizeBoolean( test, strictMode)

Parameters

test String, Integer, Boolean Item to be normalized.
strictMode Boolean Notification on failure:
true = Throw exception if normalization fails.
false = Do not throw exception if normalization fails.

Return Value

Boolean Normalized test value.

Throws

TypeError Unable to cast value into boolean: < test >

Example

var myBool = Splunk.util.normalizeBoolean(1); var myBool = Splunk.util.normalizeBoolean(0); var myBool = Splunk.util.normalizeBoolean('Yes'); var myBool = Splunk.util.normalizeBoolean('nO'); var myBool = Splunk.util.normalizeBoolean('1');

var myBool = Splunk.util.normalizeBoolean('0'); var myBool = Splunk.util.normalizeBoolean('on'); var myBool = Splunk.util.normalizeBoolean('OFF'); var myBool = Splunk.util.normalizeBoolean('foobar', true);

normalizeColor()

The normalizeColor() method converts an RGB or hexadecimal color value to a fully-qualified hexadecimal equivalent.

Synopsis

hexColor = Splunk.util.normalizeColor( color )

Parameters

color String RGB or hexadecimal color value.

Return Value

String Fully-qualified, six-digit hexadecimal color value with leading number symbol ( # ), or null if color cannot be processed.

Example

getCSSColor: function(specificity, cssProperty){

   var color;
   for (var i=0; i<specificity.length; i++){
       var computedColor = specificity[i].css(cssProperty);
       color = Splunk.util.normalizeColor(computedColor);
       if (color){
           return color;
       }  
   }  
   return null;

},

See Also

getHex()

objectSimilarity()

The objectSimilarity() method compares two objects.

Synopsis

similar = Splunk.util.objectSimilarity( obj1, obj2)

Parameters

obj1 Object Object to compare against obj2.
obj2 Object Object to compare against obj1.

Return Value

Boolean Object similarity indication:
true = obj1 and obj2 are similar.
false = obj1 and obj2 are not similar.

Example

haveResultParamsChanged: function() {

   var currentResultParams = this.getResultParams();
   return (!Splunk.util.objectSimilarity(this._previousResultParams, \
                                         currentResultParams));

},

propToQueryString()

The propToQueryString() method serializes the specified properties dictionary into an query string.

Synopsis

query = Splunk.util.propToQueryString( dictionary )

Parameters

dictionary String One-level properties dictionary.

Return Value

String Serialized query string representation of dictionary.

Example

var dictionary = {'foo': 'bar', 'fiz': 'baz'}; var qStr = Splunk.util.propToQueryString(dictionary); alert(qStr);

See Also

getPath()
queryStringToProp()

queryStringToProp()

The queryStringToProp() method de-serializes the specified query string into an object literal.

Synopsis

obj = Splunk.util.queryStringToProp( query )

Parameters

query String Query string to de-serialize.

Return Value

Object De-serialized query string, in JSON fomat.

Example

var qsDict = Splunk.util.queryStringToProp(document.location.search); alert(qsDict['foo']);

See Also

getPath()
propToQueryString()

redirect_to()

The redirect_to() method is a window.document.location wrapper.

Synopsis

Splunk.util.redirect_to( uri, options, windowObj, focus)

Parameters

uri String Location to redirect to.
options Object Redirection options:
sid = Attaches optional sid in valid format.
s = Attaches optional saved search name.
q = Attaches optional search string in valid format.
windowObj Window Object (Optional) Window object to target the location change.
focus Boolean Window receives focus indication:
true = New window receives focus.
false = New window does not receive focus.

Return Value

Undefined

Example

Splunk.util.redirect_to(['app', Splunk.util.getCurrentApp(), '@go'].join('/'), \

                       {'sid': '12345678901.123'});

See Also

make_url()

replaceTokens()

The replaceTokens() method performs regular expression-based token replacement in the specified fragment. If the given fragment is an object, replacement will be performed in both keys and values.

Synopsis

result = Splunk.util.replaceTokens( fragment, reg, val)

Parameters

fragment String, Object Fragment to perform replacement on.
reg String Regular expression used for replacement.
val String Value with which to replace tokens matching reg.

Return Value

String, Object Fragment with tokens replaced.

Example

if (USE_AUTOMATIC_STRING_REPLACEMENT) {

   var context = this.getContext();
   var baseSearch = search.toString();
   var tokens = Splunk.util.discoverReplacementTokens(baseSearch);  
   for (var i=0; i<tokens.length; i++) {
       var replacer = new RegExp("\\$" + tokens[i] + "\\$");
       baseSearch = Splunk.util.replaceTokens(baseSearch, \
                                              replacer, \
                                              context.get(tokens[i]));
       search.setBaseSearch(baseSearch);
   }  

}

See Also

discoverReplacementTokens()

smartTrim()

The smartTrim() method gets a string trimmed to a specified maxLength by replacing characters in the middle of the string with ellipses.

Synopsis

trimString = Splunk.util.smartTrim( inString, maxLength)

Parameters

inString String String to trim.
maxLength Integer Maximum length of the field.

Return Value

String Trimmed representation of inString.

Example

var smartString = Splunk.util.smartTrim('1234567890', 5); alert(smartString);

stringToFieldList()

The stringToFieldList() method de-serializes a specified comma-separated string into an array.

Synopsis

items = Splunk.util.stringToFieldList( strList )

Parameters

strList String String list to de-serialize.

Return Value

Array De-serialized representation of strList.

Example

var fieldStr = '"foo\bar","\"bar\"","biz,"'; var fieldList = Splunk.util.stringToFieldList(fieldStr);

alert(fieldList);

See Also

fieldListToString()

stripLeadingSearchCommand()

The stripLeadingSearchCommand() method gets an unqualified search string by stripping any leading search string from the specified string.

Synopsis

unqualified = Splunk.util.stripLeadingSearchCommand( qSearch )

Parameters

qSearch String Search string to be unqualified.

Return Value

String Unqualified search string.

Example

onContextChange: function() {

   var context = this.getContext();
   var search  = context.get("search");
   search.absorbIntentions(function(newQ) {
       this.setInputField(Splunk.util.stripLeadingSearchCommand(newQ));
   }.bind(this));

},

See Also

addLeadingSearchCommand()

Last modified on 12 August, 2019
Splunk.TimeRange   Splunk.Module

This documentation applies to the following versions of Splunk® Enterprise: 7.0.0, 7.0.1, 7.0.2, 7.0.3, 7.0.4, 7.0.5, 7.0.6, 7.0.7, 7.0.8, 7.0.9, 7.0.10, 7.0.11, 7.0.13, 7.1.0, 7.1.1, 7.1.2, 7.1.3, 7.1.4, 7.1.5, 7.1.6, 7.1.7, 7.1.8, 7.1.9, 7.1.10, 7.2.0, 7.2.1, 7.2.2, 7.2.3, 7.2.4, 7.2.5, 7.2.6, 7.2.7, 7.2.8, 7.2.9, 7.2.10, 7.3.0, 7.3.1, 7.3.2, 7.3.3, 7.3.4, 7.3.5, 7.3.6, 7.3.7, 7.3.8, 7.3.9


Was this topic useful?







You must be logged into splunk.com in order to post comments. Log in now.

Please try to keep this discussion focused on the content covered in this documentation topic. If you have a more general question about Splunk functionality or are experiencing a difficulty with Splunk, consider posting a question to Splunkbase Answers.

0 out of 1000 Characters