How to write your first program using the Splunk SDK for Java project type

The most common scenarios for using the Splunk® SDK for Java are included with the Splunk Plug-in for Eclipse as templates. To write our first program, we'll use two of these templates to connect to a Splunk Enterprise instance, run a search, and print the results.

  1. Create a new Splunk SDK for Java project (here's how). You don't need to specify any parsing or logging options.

  2. In the project's Package Explorer, click the triangle next to your project's name to expand its contents.

  3. Right-click the src folder, point to New, and then click Class.

  4. In the New Java Class window, give the class a name and, under Which method stubs would you like to create?, select the check box next to public static void main(String[] args). Click Finish.

    Screen shot of the Java New Class wizard
  5. In the editor for the new class, click inside the main method and type spl. Press Ctrl + Spacebar (or whichever key combination you've bound to Content Assist in your Eclipse environment) to display a list of Splunk templates (the names of which all begin with "spl").

    Screen shot of the template proposals after typing spl
  6. Double-click the splconnect list item to select it. Eclipse replaces the spl string you typed with the splconnect template and adds all required import statements to the top of the file.

    The template is intended for you to set the connection parameters using the ServiceArgs object. It creates the object; uses four setter methods to set the username, password, host, and port; and then creates a Service instance and logs in with the values that were set.

  7. Fill in the values, pressing the Tab key to proceed to the next field. Specify the values that correspond to the Splunk instance you will be testing against. The default values for a local Splunk Enterprise instance are:

    • Username: "admin"
    • Password: "changeme"
    • Host: "localhost"
    • Port: 8089
  8. Place the cursor at the bottom of the main method before its closing brace (}). Type sploneshot, and then press Ctrl + Spacebar (or your custom Content Assist key combination). Double-click the first option in the list, and the sploneshot string you typed is replaced by the code necessary to run a oneshot search and print the fields of each event returned by that search.

    Screen shot of the sploneshot template after expansion
  9. Change the searchQuery placeholder to "search index=_internal | head 5" (include the quotation marks).

  10. Save the file, and then run the program by clicking the green Run button at the top of the Eclipse window.

The program runs and the console window shows a large number of key-value pairs from the search. You can check these against the results of the same search in Splunk Web.