GithubHelp home page GithubHelp logo

splunk / splunk-sdk-java Goto Github PK

View Code? Open in Web Editor NEW
144.0 52.0 121.0 39.66 MB

Splunk Software Development Kit for Java

Home Page: http://dev.splunk.com

License: Apache License 2.0

Python 0.44% Shell 0.24% Java 97.78% C++ 0.99% C 0.35% CSS 0.11% Ruby 0.02% Makefile 0.07%

splunk-sdk-java's Introduction

Java SDK Test

The Splunk Software Development Kit for Java

Version 1.9.5

The Splunk Software Development Kit (SDK) for Java contains library code and examples designed to enable developers to build applications using Splunk.

Splunk is a search engine and analytic environment that uses a distributed map-reduce architecture to efficiently index, search and process large time-varying data sets.

The Splunk product is popular with system administrators for aggregation and monitoring of IT machine data, security, compliance and a wide variety of other scenarios that share a requirement to efficiently index, search, analyze and generate real-time notifications from large volumes of time series data.

The Splunk developer platform enables developers to take advantage of the same technology used by the Splunk product to build exciting new applications that are enabled by Splunk's unique capabilities.

Getting started with the Splunk SDK for Java

The Splunk SDK for Java contains library code and examples that show how to programmatically interact with Splunk for a variety of scenarios including searching, saved searches, data inputs, and many more, along with building complete applications.

The information in this Readme provides steps to get going quickly, but for more in-depth information be sure to visit the Splunk Developer Portal.

Requirements

Here's what you need to get going with the Splunk SDK for Java.

Splunk

If you haven't already installed Splunk, download it here. For more about installing and running Splunk and system requirements, see Installing & Running Splunk. The Splunk SDK for Java has been tested with Splunk Enterprise 9.0 and 8.2.

Splunk SDK for Java

Get the Splunk SDK for Java—download the SDK as a ZIP, then extract the files and build the SDK. Or, download the JAR and add it to your project.

If you want to contribute to the SDK, clone the repository from GitHub.

Java using Maven

You can use Apache Maven to build your Splunk SDK for Java projects. With a few updates to your project's pom.xml file, it will retrieve all necessary dependencies and seamlessly build your project.

To add the Splunk SDK for Java .JAR file as a dependency:

  1. Add the repository to your project's pom.xml file:
<repositories>
  ...
  <repository>
    <id>splunk-artifactory</id>
    <name>Splunk Releases</name>
    <url>http://splunk.jfrog.io/splunk/ext-releases-local</url>
  </repository>
</repositories>
  1. Add the dependency to the pom.xml file:
<dependencies>
  ...
  <dependency>
    <groupId>com.splunk</groupId>
    <artifactId>splunk</artifactId>
    <version>1.9.5</version>
  </dependency>
</dependencies>

Be sure to update the version number to match the version of the Splunk SDK for Java that you are using.

Note: You can make similar changes to use Gradle as well.

Building the SDK and documentation

To build the SDK, open a command prompt in the /splunk-sdk-java directory and enter:

mvn

or

mvn package

This command builds all of the .class and .jar files. If you just want to build the .class files, enter:

mvn compile

To remove all build artifacts from the repository, enter:

mvn clean

To build the documentation for the SDK, it is being automatically generated with mvn package, otherwise enter:

cd splunk
mvn javadoc:javadoc

Usage

Login using username and password

import com.splunk.Service;
import com.splunk.ServiceArgs;

/**
 * Login using username and password
 */
public class SplunkLogin {

    static Service service = null;
    public static void main(String args[]) {
        ServiceArgs loginArgs = new ServiceArgs();
        loginArgs.setPort(8089);
        loginArgs.setHost("localhost");
        loginArgs.setScheme("https");
        loginArgs.setUsername("USERNAME"); // Use your username
        loginArgs.setPassword("PASSWORD"); // Use your password

        // Initialize the SDK client
        service = Service.connect(loginArgs);
    }
}

Login using Session Token

import com.splunk.Service;
import com.splunk.ServiceArgs;

/**
 * Login using Session token
 */
public class SplunkLogin {

    static Service service = null;
    /**
     * Session Token.
     * Actual token length would be longer than this token length.
     */
    static String token = "1k_Ostpl6NBe4iVQ5d6I3Ohla_U5";
    
    public static void main(String args[]) {
        ServiceArgs loginArgs = new ServiceArgs();
        loginArgs.setPort(8089);
        loginArgs.setHost("localhost");
        loginArgs.setScheme("https");
        loginArgs.setToken(String.format("Splunk %s", token));

        // Initialize the SDK client
        service = Service.connect(loginArgs);
    }
}
  • Login using username and password will create Session token internally.
  • Login using Credentials (username & password) OR directly using Session token are similar.
  • In above two approaches, there is one limitation that expiration time of Session token cannot be extended. User has to re-login every time when token expires.
  • To overcome this limitation, Authentication token is used instead of Session token.
  • In Authentication token, user has a provision to set token expiration time. Splunk allows user to set relative/absolute time for token expiration.
  • In other words, Authentication token is configurable whereas Session token cannot be configured.

Login using Authentication Token (RECOMMENDED)

import com.splunk.Service;
import com.splunk.ServiceArgs;

/**
 * Login using Authentication token
 */
public class SplunkLogin {

    static Service service = null;
    /**
     * Authentication Token.
     * Actual token length would be longer than this token length.
     */
    static String token = "1k_Ostpl6NBe4iVQ5d6I3Ohla_U5";
    
    public static void main(String args[]) {
        ServiceArgs loginArgs = new ServiceArgs();
        loginArgs.setPort(8089);
        loginArgs.setHost("localhost");
        loginArgs.setScheme("https");
        loginArgs.setToken(String.format("Bearer %s", token));

        // Initialize the SDK client
        service = Service.connect(loginArgs);
    }
}

Example of running a simple search by first creating the search job

import com.splunk.Job;
import com.splunk.ResultsReader;
import com.splunk.ResultsReaderXml;
import com.splunk.Service;
import com.splunk.ServiceArgs;

/**
 * Logged in using Authentication token.
 * Assuming that authentication token is already created from Splunk web.
 * Create Job using search creation.
 * Read results and print _raw fields
 */
public class SearchExample {

    static Service service = null;

    /**
     * Authentication Token.
     * Actual token length would be longer than this token length.
     */
    static String token = "1k_Ostpl6NBe4iVQ5d6I3Ohla_U5";
    
    public static void main(String args[]) {

        ServiceArgs loginArgs = new ServiceArgs();
        loginArgs.setPort(8089);
        loginArgs.setHost("localhost");
        loginArgs.setScheme("https");
        loginArgs.setToken(String.format("Bearer %s", token));

        // Initialize the SDK client
        service = Service.connect(loginArgs);

        // Run a simple search by first creating the search job
        Job job = service.getJobs().create("search index=_internal | head 10");

        // Waiting for search results to be ready
        while (!job.isReady()) {
            try {
                Thread.sleep(500); // 500 ms
            } catch (Exception e) {
                // Handle exception here.
            }
        }

        // Read results
        try {
            ResultsReader reader = new ResultsReaderXml(job.getEvents());

            // Iterate over events and print _raw field
            reader.forEach(event -> System.out.println(event.get("_raw")));

        } catch (Exception e) {
            // Handle exception here.
        }
    }
}

For more information on authentication using tokens, please visit Splunk Docs.

Unit tests

The Splunk SDK for Java includes several unit tests that are run at the command line.

Set up the .splunkrc file

To connect to Splunk, many of the SDK examples and unit tests take command-line arguments that specify values for the host, port, and login credentials for Splunk. For convenience during development, you can store these arguments as key-value pairs in a text file named .splunkrc. Then, the SDK examples and unit tests use the values from the .splunkrc file when you don't specify them.

To use this convenience file, create a text file with the following format:

# Splunk host (default: localhost)
host=localhost
# Splunk admin port (default: 8089)
port=8089
# Splunk username
username=admin
# Splunk password
password=changeme
# Access scheme (default: https)
scheme=https
# Your version of Splunk (default: 5.0)
version=5.0

Save the file as .splunkrc in the current user's home directory.

  • For example, on Mac OS X, save the file as:

    ~/.splunkrc
    
  • On Windows, save the file as:

    C:\Users\currentusername\.splunkrc
    

    You might get errors in Windows when you try to name the file because ".splunkrc" looks like a nameless file with an extension. You can use the command line to create this file—go to the C:\Users\currentusername directory and enter the following command:

    Notepad.exe .splunkrc
    

    Click Yes, then continue creating the file.

Note: Storing login credentials in the .splunkrc file is only for convenience during development. This file isn't part of the Splunk platform and shouldn't be used for storing user credentials for production. And, if you're at all concerned about the security of your credentials, just enter them at the command line rather than saving them in this file.

Run unit tests

To run the SDK unit tests, open a command prompt in the /splunk-sdk-java directory and enter:

mvn test

You can also run specific test classes by passing the class to the -Dtest= option, e.g.,

mvn test -Dtest=AtomFeedTest

The maven configuration can also produce an HTML report of all the tests automatically when mvn package / mvn test are executed. Alternate way to generate report is using below command under splunk directory:

mvn jacoco:report

The report will be written in /splunk-sdk-java/splunk/target/site/surefire-report.html.

It's also possible to run the units within Java IDEs such as IntelliJ and Eclipse. For example, to open the Splunk SDK for Java project in Eclipse:

  1. Click File, Import.
  2. Click General, Existing Projects into Workspace, then click Next.
  3. In Select root directory, type the path to the Splunk SDK for Java root directory (or click Browse to locate it), then click Finish.

Measure code coverage

Measurement of code coverage is generated along with mvn package / mvn test:

mvn jacoco:report

To view the coverage report, open /splunk-sdk-java/splunk/target/test-report/index.html in your web browser.

Repository

/argsGenerator This directory is created by the build and contains intermediate build ouputs
/splunk/target This directory is created by the build and contains intermediate build ouputs
/splunk/src/main Source for com.splunk
/splunk/src/test Source for unit tests

Changelog

The CHANGELOG.md file in the root of the repository contains a description of changes for each version of the SDK. You can also find it online at https://github.com/splunk/splunk-sdk-java/blob/master/CHANGELOG.md.

Branches

The master branch always represents a stable and released version of the SDK. You can read more about our branching model on our Wiki at https://github.com/splunk/splunk-sdk-java/wiki/Branching-Model.

Documentation and resources

If you need to know more:

Community

Stay connected with other developers building on Splunk.

Email [email protected]
Issues https://github.com/splunk/splunk-sdk-java/issues/
Answers http://splunk-base.splunk.com/tags/java/
Blog http://blogs.splunk.com/dev/
Twitter @splunkdev

How to contribute

If you would like to contribute to the SDK, go here for more information:

Support

  1. You will be granted support if you or your company are already covered under an existing maintenance/support agreement. Send an email to [email protected] and include "Splunk SDK for Java" in the subject line.

  2. If you are not covered under an existing maintenance/support agreement, you can find help through the broader community at:

  3. Splunk will NOT provide support for SDKs if the core library (the code in the splunk directory) has been modified. If you modify an SDK and want support, you can find help through the broader community and Splunk answers (see above). We would also like to know why you modified the core library—please send feedback to [email protected].

  4. File any issues on GitHub.

Contact Us

You can reach the Developer Platform team at [email protected].

License

The Splunk Java Software Development Kit is licensed under the Apache License 2.0. Details can be found in the LICENSE file.

splunk-sdk-java's People

Contributors

adamryman avatar akaila-splunk avatar amysutedja avatar apruneda avatar ashah-splunk avatar balasubramanyamevani avatar blovering avatar bparmar-splunk avatar brucewu-fly avatar dan1 avatar davidfstr avatar eerobinson avatar fantavlik avatar hsy3 avatar itay avatar jkozlowski avatar liketic avatar ljiang1 avatar mdrozdovz avatar mtevenan-splunk avatar pax95 avatar pking70 avatar rmaheshwari-splunk avatar ryanguest avatar shakeelmohamed avatar skylasam avatar sodle avatar wimcolgate avatar wpoch avatar zenmoto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

splunk-sdk-java's Issues

Modular Input - Set Token - vs "login" - sessionkey and kvstore

method "setToken" doesn't append "Splunk " at the start of the sessionKey. Method login will set the token as "Splunk " + sessionKey (see below).

public Service login(String username, String password) {
...
this.token = "Splunk " + sessionKey;
...
}

This can cause issues when working with a modular input and wanting to make REST calls to say.....kvstore

I have to add the "Splunk " + sessionKey -- which is fine, but i feel like their should be a documented example and maybe an explicit method.

ServiceArgs serviceArgs = new ServiceArgs();

serviceArgs.setHost("localhost");
serviceArgs.setToken("Splunk " + sessionKey);
serviceArgs.setPort(8089);
serviceArgs.setScheme("https");
serviceArgs.setApp("kvstore");

Service splunkService = Service.connect(serviceArgs);

RequestMessage requestMessage = new RequestMessage("GET");
ResponseMessage rm = splunkService.send(..., requestMessage);

Namespace breaks Index.submit

If you set a namespace in your session, you can't Index.submit.

I have a test framework which allows for test cases to submit data to Splunk, then ensure it's parsed correctly - but they share the same session.

// Create session
ServiceArgs loginArgs = new ServiceArgs();
loginArgs.setApp("testapp");
... set user/pass ...
service = Service.connect(loginArgs);

// Retrieve the index for the data
Index myIndex = service.getIndexes().get( "main" );

// Specify  values to apply to the event
Args eventArgs = new Args();
eventArgs.put("sourcetype", sourcetype);
eventArgs.put("host", "local");

// Submit an event over HTTP
myIndex.submit(eventArgs, data);

Error

com.splunk.HttpException: HTTP 404 -- Not Found
        at com.splunk.HttpException.create(HttpException.java:84)
        at com.splunk.HttpService.send(HttpService.java:452)
        at com.splunk.Service.send(Service.java:1293)
        at com.splunk.Receiver.submit(Receiver.java:169)
        at com.splunk.Index.submit(Index.java:1097)

Easy workaround is to have a seperate session for reading / writing. Maybe this is by design?

SDK should be updated to support secure connections

Due to Poodle most security conscious organizations have disable SSLv3 on many of their servers. Java has also disabled SSLv3 in several releases. While some people have recommended commenting out: jdk.tls.disabledAlgorithms=SSLv3 it would be better if the sdk supported TLS. There are several forks that have changed this.

Related links:
http://answers.splunk.com/answers/210201/i-changed-splunk-from-using-sslv3-to-tlsv12-and-th.html
http://answers.splunk.com/answers/209379/no-appropriate-protocol-protocol-is-disabled-or-ci.html

Documentation is unclear. Should ResultsReaderJson handle JSON_ROWS data?

The following code results in an IllegalStateException: Expected a name but was END_OBJECT at line x column y. on ResultsReaderJson line 127:

JobResultsPreviewArgs jobArgs = new JobResultsPreviewArgs ();
jobArgs.setOutputMode(JobResultsPreviewArgs.OutputMode.JSON_ROWS);

ResultsReaderJson resultsReader = new ResultsReaderJson(splunkJob.getResultsPreview(jobArgs));

It looks like ResultsReaderJson is only looking for the 'preview' and 'results' fields, but JSON_ROWS returns the results in the 'rows' field.

The documentation mentions that ResultsReaderJson should handle JSON results, but it appears to only handle JSON and not JSON_ROWS or JSON_COLS. The JavaDoc and SDK documentation should be more clear in stating that if you use JSON_ROWS or JSON_COLS, you will have to write your own parser.

It would be great to add these parsers to the SDK :) But I think that the documentation could at least be made obvious.

ResultsReaderXml doesn't work with preview results

When I try and use the ResultsReaderXml class with preview results (e.g. from /results_preview), I don't seem to get anything back. Probably related is that when I use it with an export search (i.e. search/jobs/export), I only get the final results and no previews either.

I can not run the example

Now I download the project and want to run example in eclipse.When I debug,for example,I debug at "package com.splunk.examples.index" ,execute the main method,I found that it get a url http://localhost:8000/services/auth/login ,but return com.splunk.HttpException: HTTP 404.
I had download and install splunk by click "download it here".And I can login in http://localhost:8000,using the splunk at browser.
My file ".splunkrc" is:
host=localhost
port=8000
username=admin
password=123.QWER
scheme=http
version=5.0

When I want to run example,erros at com.splunk.Service.login(Service.java:1128).
How can I run exampls?Is my environment wrong?

Entity object does not contain the "updated" field

When we send splunkd a rest api to get the entity, there exists a field "updated" in the response which means the last modified time of this entity. This value may be useful in some cases. For example, some apps want to sort the objects according to the last modified time.

But in java sdk, this field is skipped after parsing the response to an entity, and we can't get the value. I think it's necessary for sdk to provide this field in entity object.

Normal Search results in infinite loop in sdk 1.4

Running search something like this and results into infinite loop on !isDone() although original job has been completed on Splunk Server. Same code works fine with SDK 1.3.1

LOGGER.info("\n**************** Normal Search Starts ****************\n");
        Job job = _getService().getJobs().create(searchQuery, jobargs);
        LOGGER.info("Job Id is: " + job.getSid());

        // Wait for the search to finish
        while (!job.isDone()) {
            try {
                LOGGER.info(" Still waiting for the job to complete ... ");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

Handshake_failure

Hi Team,

I am run the test case canSendEventUsingJavaLoggingWithOptions() but I get he hand shake failure error mentioned below.
I have setup splunk enterprise locally and I can see the logs when I use the follwoing curl command

curl -k https://localhost:8088/services/collector/event -H "Authorization: Splunk 137b49d5-f111-45ac-ba04-96abcef5ec7f1" -d '{"event": "hello world5"}'

java.lang.RuntimeException: Received fatal alert: handshake_failure
at com.splunk.HttpService.send(HttpService.java:409)
at com.splunk.Service.send(Service.java:1293)
at com.splunk.HttpService.post(HttpService.java:308)
at com.splunk.Service.login(Service.java:1122)
at com.splunk.Service.login(Service.java:1101)
at com.splunk.Service.connect(Service.java:187)
at TestUtil.connectToSplunk(TestUtil.java:93)
at TestUtil.createHttpEventCollectorToken(TestUtil.java:132)
at HttpEventCollector_JavaLoggingTest.canSendEventUsingJavaLoggingWithOptions(HttpEventCollector_JavaLoggingTest.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1979)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1086)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1092)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at com.splunk.HttpService.send(HttpService.java:403)
... 31 more

bug: shim cpp not close the vmopts file handler

There is a java modular input running, and I added some jvm options in the .vmopts file. Then I found this file is occupied by the shim.exe. It seems that this file is not closed after reading.

Saved search throws a Null pointer exception

when running a saved search instance through splunk API , i get the following exception

"main" java.lang.NullPointerException
at com.splunk.ResourceCollection.namespace(ResourceCollection.java:262)
at com.splunk.ResourceCollection.createItem(ResourceCollection.java:161)
at com.splunk.ResourceCollection.load(ResourceCollection.java:295)
at com.splunk.ResourceCollection.refresh(ResourceCollection.java:334)
at com.splunk.ResourceCollection.refresh(ResourceCollection.java:1)
at com.splunk.Resource.validate(Resource.java:174)
at com.splunk.ResourceCollection.validate(ResourceCollection.java:350)
at com.splunk.ResourceCollection.get(ResourceCollection.java:184)
at com.splunk.SavedSearch.dispatch(SavedSearch.java:87)
at com.splunk.SavedSearch.dispatch(SavedSearch.java:106)
at com.splunk.SavedSearch.dispatch(SavedSearch.java:63)

Command.class is missing from jar

Some of older packages expect that Command.class is under com.splunk, which is absent in jar (moved to util/com/splunk/). Breaks some older code.

[Fatal Error] :-1:-1: Premature end of file.

Splunk: 5.0.6
Splunk Java SDK: 1.2.1.0

This is printed from an exception that is thrown from the parsing of XML when there is an HTTP Status code of >= 400. It is coming from the Xml.parse method being called below.

Line 67 from HttpException.class

 try {
            // Attempt to read the error detail from the error response content as XML
            Document document = Xml.parse(new ByteArrayInputStream(detail.getBytes()));
            NodeList msgs = document.getElementsByTagName("msg");
            if (msgs.getLength() > 0)
                detail = msgs.item(0).getTextContent();
        }
        catch (Exception e) {
            // Not an XML document; return the raw string.
            detail = s.toString();
        }

Why is this being logged or is this really a fatal error? Everything seems to still function properly and I can catch the HTTPException. I would like to get ride of the logged error.

To test this out I was just creating a search job with an invalid search string.

Any help is greatly appreciated.

Thanks

splunk-1.6.2.0.jar contains classes twice

#83 is marked closed with 1.6.2 - but upgrading the version did not fix the issue on our side. A look into the jar revealed that old classes seem to reside next to the new ones. Can you please verify and re-package please?

NetBeans

Hello,

does anyone have NetBean project which contans all waht I need to connect to my local splunk? I need some java web apps which will connect to my splank and show me ANY details or dahsboards...

Please anything, am killing myself with available tutorials...

Thanks!

Modular Input - textInNode throwing exception when input string is empty

Version of this project you're using 1.6.4
Platform version osx 10.13.3 (high sierra)
Framework version java 1.8.0_131
Splunk version 7.0.2 - 03bbabbd5c0f

Other relevant information (ex: local/remote environment, Splunk network configuration)

I tracked down this bug because at surface level, it appeared that input validation was not being executed. Indeed it wasn't being executed because XmlUtil.textInNode would throw an exception when encountering an argument with a null/empty value.

I have a proposed fix below that seems to work on 7.0.2, but i can't speak to backwards compatibility with older versions of splunk

com.splunk.modularinput.XmlUtil.textInNode(XmlUtil.java:38)\com.splunk.modularinput.Parameter.nodeToParameterList(Parameter.java:72)\com.splunk.modularinput.ValidationDefinition.parseDefinition(ValidationDefinition.java:245)\com.splunk.modularinput.Script.run(Script.java:85)\com.splunk.modularinput.Script.run(Script.java:44)...

fix in my env
static String textInNode(Node node, String errorMessage) throws MalformedDataException {
Node child = node.getFirstChild();

  •    if (child.getNodeType() != Node.TEXT_NODE) {
    
  •        throw new MalformedDataException(errorMessage);
    
  •    } else {
    
  •        return ((Text)child).getData();
    
  •    if(child != null) {
    
  •       if (child.getNodeType() != Node.TEXT_NODE) {
    
  •           throw new MalformedDataException(errorMessage);
    
  •       } else {
    
  •           return ((Text)child).getData();
    
  •       }
       }
    
  •    return("");
    
    }

job.getEventCount() throws null pointer exception when too many events

We have a couple of events in our Splunk deployment and we can't get the eventCount (actually no result at all because the exception is catched at higher level) when the number of event is too big.

This is only for a week of data so it's very problematic in our case.

Splunk.java.lang.NumberFormatException: For input string: "2335707040"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
at java.lang.Integer.parseInt(Integer.java:527)
at com.splunk.Value.toInteger(Value.java:136)
at com.splunk.Record.getInteger(Record.java:121)
at com.splunk.Entity.getInteger(Entity.java:213)
at com.splunk.Job.getEventCount(Job.java:252)

Change the code to toLong() should be enough of a fix.

XML Parsing Exceptions when using metro and wstx-asl

When working in a container or a classpath that includes metro (specifically webservices-rt.jar) or Woodstox (specifically wstx-asl.jar), I get the following exception trying to parse the results from a search:

com.ctc.wstx.exc.WstxEOFException: Unexpected EOF; was expecting a close
tag for element
at [row,col {unknown-source}]: [1,27]
java.lang.RuntimeException: com.ctc.wstx.exc.WstxEOFException: Unexpected
EOF; was expecting a close tag for element
at [row,col {unknown-source}]: [1,27]
at
com.splunk.ResultsReaderXml.advanceStreamToNextSet(ResultsReaderXml.java:430)
at com.splunk.ResultsReader.getNextElement(ResultsReader.java:105)
at com.splunk.ResultsReader.getNextEvent(ResultsReader.java:66)

Note that I saw a similar comment in the following pull request:

#45

Thanks,

Will

Search via Java SDK orders of magnitude slower than REST API

We have been using the splunk-sdk-java for over a year now. So far we've been very happy with it, but we are starting to run into some performance issues.

This started when we noticed that the minimum time that we could receive a response from our back-end server was around 3 seconds even for the smallest possible search. When kicking off multiple searches serially this becomes a significant delay.

We performed some profiling and discovered that all calls through the splunk-sdk-java were adding a delay of 2.1 to 2.8 seconds in addition to the overhead we have for our own Play controllers. We've since done some experiments with having our back-end use the Splunk REST API instead of the splunk-sdk-java. These have shown orders of magnitude of performance gains. We're seeing responses from the REST API in 100-200ms.

At this point, we're likely going to convert significant portions of our implementation to use the REST API instead of the splunk-sdk-java, but we wanted to report our results so that this could be investigated further.

For further information, our Splunk server is running 5.0.6 and we are using the latest splunk-sdk-java. Splunk is running on Linux and our back-end server is running on Windows. All testing was performed over the local area network over multiple days and time periods.

Thank you.

Adding Args option fro Saved Search history method

Hello,
I have a use-case where I need to get the latest run of a scheduled saved search.

I know SavedSearch class has a history method which gets me all the old jobs runs. But it looks like the results are being paginated to the earliest 30 results.

The history method itself doesn't have any options to pass arguments for the GET call.

Is there any other way to achieve this? I know the REST API does support sort_dir=desc option for getting the history jobs in descending order.

I would also be happy to do these changes.

Thanks,

-Vineeth

1.2.1 Release Checklist

These are instructions on the various steps necessary to put out a new release of the Splunk SDK for Java. Even though the instructions are public, these steps are only meant to be taken by the SDK maintainers.

Prerequisites

  • Update changelog.
  • Run test suite on full test matrix.
  • Install random_numbers.spl (found in dist/ after running ant dist on the repository) on Linux (32-bit and 64-bit), MacOS X (64-bit), and Windows (32-bit and 64-bit), for all supported versions of Splunk in the test matrix, create a new random_numbers input, and check that it generates events by running the search "*" with time range "Real time (all time)".
  • Run all examples.
  • Run all dev.splunk.com code samples.
  • Remove old temporary branches. This includes feature branches, old release branches, and most branches that have been merged to develop.
    • (Exception: The "promises-old" branch in the JavaScript SDK should be retained for the time being.)

Release Steps

  • Create release branch off of develop (release/1.2.1).
    • git checkout develop
    • git pull
    • git checkout -b release/1.2.1
  • Update the version number:
    • Update the version.number property in the build.xml
      file in the root directory.
    • Update the User-Agent field of the HttpService class.
    • Update README.md
    • Update the line declare -r version="??" in deploy.
    • Update the version everywhere in deploy.md.
  • Make sure the version number change didn't break anything:
    • Install the SDK in a clean VM.
    • Run test suite.
    • Run the SDK examples.
  • Build a new JAR and ZIP of the SDK:
    • Make sure the JAR is built with JDK 6.
    • Make sure the files reflect the current version (for example, splunk-splunk-sdk-java-1.2.1.zip, splunk-1.2.1.jar).
    • Commit the change to the release/1.2.1 branch.
    • Send the JAR and ZIP files to your Docs team.
  • Merge to master locally. Ensure the commit message is "Release 1.2.1".
    • git checkout master
    • git merge --no-ff -m "Release 1.2.1" release/1.2.1
    • git commit
  • Tag the above commit as 1.2.
    • git tag 1.2.1
  • Push the master and the 1.2.1 tag to GitHub.
    • git push origin master
    • git push --tags
  • Delete the release branch:
    • git push origin :release/1.2.1
    • git branch -d release/1.2.1
  • Sanity check that released version works:
    • Check with the Product Manager for what should be done here. (And update this bullet with the decision!)
  • Deploy to ArtifactoryOnline
    • Install Apache Maven 3.

    • Create or update ~/.m2/settings.xml with these settings.

      <!-- [Settings Reference]: http://maven.apache.org/settings.html -->
      <settings>
        <activeProfiles>
          <activeProfile>splunk</activeProfile>
        </activeProfiles>
        <profiles>
          <profile>
            <id>splunk</id>
            <repositories>
              <!-- [Splunk artifactory]: http://splunk.artifactoryonline.com -->
              <repository>
                <name>Splunk releases</name>
                <id>splunk-releases</id>
                <url>http://splunk.artifactoryonline.com/splunk/libs-releases/</url>
                <releases>
                  <enabled>true</enabled>
                </releases>
                <snapshots>
                  <enabled>false</enabled>
                </snapshots>
              </repository>
              <repository>
                <name>Splunk snapshots</name>
                <id>splunk-snapshots</id>
                <url>http://splunk.artifactoryonline.com/splunk/libs-snapshots/</url>
                <releases>
                  <enabled>false</enabled>
                </releases>
                <snapshots>
                  <enabled>true</enabled>
                </snapshots>
              </repository>
            </repositories>
          </profile>
        </profiles>
        <servers>
          <server>
            <id>splunk-production-artifactory</id>
            <filePermissions>664</filePermissions>
            <directoryPermissions>775</directoryPermissions>
            <username>deployer</username>
            <password>{IJnVXKkQLnQHBIg7IxYqXU8s/TNCnjw+ChQKVxAFPd0=}</password>
          </server>
          <server>
            <id>splunk-staging-artifactory</id>
            <filePermissions>664</filePermissions>
            <directoryPermissions>775</directoryPermissions>
            <username>deployer</username>
            <password>{4QWPly1kZPoHVqDWbIpDV0rgivMCQJ4LXH3ZLAMSrp8=}</password>
          </server>
        </servers>
      </settings>
      
    • ./deploy production

    • Verify the contents of http://splunk.artifactoryonline.com/splunk/libs-releases/com/splunk/splunk/. See deploy.md for guidance.

  • Work with Docs team to:
    • Post ZIP and JAR files.
    • Update Readme. For point releases, the version number needs to be updated at a minimum.
    • Update Changelog, includes a list of changes for the current version.
    • Update Dev Portal and push. For point releases, the "What's new" page and download links need to be updated at the very least.
    • Publish the API Reference (docs.splunk.com/Documentation/SDK).
    • Create both MD5 and SHA-512 hashes from final ZIP download. Docs will contact the Web team to upload these files.
  • Verify the posted JAR:
    • Download the JAR and make sure the checksum matches the original file.
  • Hand off to marketing to announce. See next section.

Announce!

Hurrah, the new release is basically done! You can now announce it on the
following channels:

Errors when requesting data in JSON output mode get parsed as XML

I'm trying to export data using JSON with the SDK. When I get an authentication error I get the following stack trace:

[Fatal Error] :1:1: Content is not allowed in prolog.
Exception in thread "ExportSearchManager" com.splunk.HttpException: HTTP 401
    at com.splunk.HttpException.create(HttpException.java:59)
    at com.splunk.HttpService.send(HttpService.java:355)
    at com.splunk.Service.send(Service.java:1211)
    at com.splunk.HttpService.get(HttpService.java:130)
    at com.splunk.Service.export(Service.java:196)
    at com.splunk.Service.export(Service.java:211)

Chasing it down to HttpException the response is being parsed as XML:

Document document = Xml.parse(response.getContent());

even though the response is JSON:

{"messages":[{"type":"WARN","text":"call not properly authenticated"}]}

HTTP 400 After Upgrade to Splunk 6.0

Hello,

I'm experiencing the following error when attempting to connect to my upgraded Splunk 6.0 instance via the Java client:

[Fatal Error] :1:3: The markup in the document preceding the root element must be well-formed.
Exception in thread "main" com.splunk.HttpException: HTTP 400
at com.splunk.HttpException.create(HttpException.java:59)
at com.splunk.HttpService.send(HttpService.java:355)
at com.splunk.Service.send(Service.java:1203)
at com.splunk.HttpService.post(HttpService.java:212)
at com.splunk.Service.login(Service.java:1040)
at com.splunk.Service.login(Service.java:1020)
at com.splunk.Service.connect(Service.java:161)
at Thing.main(Thing.java:28)

Code Snippet:

ServiceArgs loginArgs = new ServiceArgs();
loginArgs.setUsername(username);
loginArgs.setPassword(password);
loginArgs.setHost(hostname);
loginArgs.setPort(serviceport);

Service service = Service.connect(loginArgs);

String outputMode = "xml";// xml,json,csv
//String searchQuery = "search index=sweet sourcetype=dude";

Args queryArgs = new Args();
queryArgs.put("earliest_time", "-1m@m");
queryArgs.put("latest_time", "@m");
queryArgs.put("output_mode", outputMode);
queryArgs.put("count", 0);

InputStream stream = service.oneshotSearch(searchQuery,
queryArgs);

savedSearch.dispatch throws NullPointerException

I am getting an NPE when calling the dispatch method on a savedSearch. Tracing the code the NPE is occurring in ResourceCollection.java in the namespace(AtomEntry entry) method. The issue is entityMetadata is set using entry.content.get("eai:acl"), but this returns null and entityMetadata is never checked for null. Surrounding this call with a null check resolves the issue and gives the expected number of events back.

Also note this issue actually appears to be a timing related issue because if I debug starting at the dispatch method and step through the code until I reach the call to validate and step over validate everything runs fine, no null pointer and I get the expected results back.

The stack trace is below:

Exception in thread "main" java.lang.NullPointerException at com.splunk.ResourceCollection.namespace(ResourceCollection.java:262) at com.splunk.ResourceCollection.createItem(ResourceCollection.java:161) at com.splunk.ResourceCollection.load(ResourceCollection.java:295) at com.splunk.ResourceCollection.refresh(ResourceCollection.java:334) at com.splunk.ResourceCollection.refresh(ResourceCollection.java:29) at com.splunk.Resource.validate(Resource.java:174) at com.splunk.ResourceCollection.validate(ResourceCollection.java:350) at com.splunk.ResourceCollection.get(ResourceCollection.java:184) at com.splunk.SavedSearch.dispatch(SavedSearch.java:87) at com.splunk.SavedSearch.dispatch(SavedSearch.java:106) at com.splunk.SavedSearch.dispatch(SavedSearch.java:63)

java.io.IOException: Push back buffer is full when exporting data in XML

When calling the export API in XML,Splunkd might write a lot of spaces before the first XML tag (see attachment). The InsertRootElementFilterInputStream class assumes that a buffer of 512 bytes is enough to find the first opening tag. As a result the following exception is raised: [java.io|http://java.io/].IOException: Push back buffer is full

Internally tracked by DVPL-7313

Value.toDate(string value) is not thread safe

When running the sdk in multi-threaded environment, method static Date toDate(String value) in class Value is throwing exceptions from time to time:

  • Caused by: java.lang.NumberFormatException: For input string: ""
  • Caused by: java.lang.NumberFormatException: For input string: ".10201E.102014E4"
  • Caused by: java.lang.NumberFormatException: multiple points

This is preventing to get the status of a job.
Here is some hints to fix this issue
thanks

com.splunk.Job::getResults() throws an exception instead of blocking

I was using the Job::getResults() method in my project, and the documentation recommends that you use

try {
    while (!job.isDone()) {
        Thread.sleep(500);
    }
} catch (...) {
    // ...
}
result = job.getResults();

because Job::getResults() throws an exception if it is called and the search isn't finished.
I was wondering why Job::getResults() can't just block until the search is finished, instead of doing the blocking manually. I have tried to think of use cases for manually blocking, but I can't seem to think of any. I don't understand why throwing an exception is better than blocking until the search is done. If there is a good reason, please let me know. Otherwise, I can make the changes to make it block and send a pull request.

HttpService - Connection pooling

Any reason for not using http connection pool in HttpService?
If there are many requests are made to the splunk server then every time initializing a new connection will result in performance degrade, Can we write a service which uses http connection pool?

Need help to run Java Programs

Hello,

I am working on Splunk Java SDK. I wanted to run example Java programs given with Splunk Java SDK. But I am not able to run those programs. I have set enviornment variables. What additional setup do I need? Please give me the steps in detail. It will be very helpful for me.

Thanks & Regards,
Prajakta Javanjal

Message: Connection reset Caused by: java.lang.RuntimeException: java.lang.RuntimeException: ParseError at [row,col]:[18785,80]

I'm running a script that executes multiple queries and whenever the script runs for some time, It hits this:

Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58) Caused by: java.lang.RuntimeException: java.lang.RuntimeException: ParseError at [row,col]:[18785,80] Message: Connection reset at com.splunk.ResourceCollection.refresh(ResourceCollection.java:332) at com.splunk.ResourceCollection.refresh(ResourceCollection.java:29) at com.splunk.Resource.validate(Resource.java:174) at com.splunk.ResourceCollection.validate(ResourceCollection.java:350) at com.splunk.ResourceCollection.get(ResourceCollection.java:184) at com.splunk.SavedSearch.dispatch(SavedSearch.java:87) at com.splunk.SavedSearch.dispatch(SavedSearch.java:106) at com.splunk.SavedSearch.dispatch(SavedSearch.java:63) at cspAnomalyBaseline.SplunkDBCPU.runDBCPU(SplunkDBCPU.java:70) at cspAnomalyBaseline.mainRun.main(mainRun.java:98) at cspAnomalyBaseline.Automation.main(Automation.java:81) ... 5 more Caused by: java.lang.RuntimeException: ParseError at [row,col]:[18785,80] Message: Connection reset at com.splunk.AtomObject.scan(AtomObject.java:198) at com.splunk.AtomEntry.parseValue(AtomEntry.java:245) at com.splunk.AtomEntry.parseDict(AtomEntry.java:143) at com.splunk.AtomEntry.parseStructure(AtomEntry.java:189) at com.splunk.AtomEntry.parseValue(AtomEntry.java:230) at com.splunk.AtomEntry.parseDict(AtomEntry.java:143) at com.splunk.AtomEntry.parseContent(AtomEntry.java:118) at com.splunk.AtomEntry.init(AtomEntry.java:95) at com.splunk.AtomObject.load(AtomObject.java:121) at com.splunk.AtomEntry.parse(AtomEntry.java:77) at com.splunk.AtomFeed.init(AtomFeed.java:95) at com.splunk.AtomObject.load(AtomObject.java:121) at com.splunk.AtomFeed.parse(AtomFeed.java:80) at com.splunk.AtomFeed.parseStream(AtomFeed.java:59) at com.splunk.ResourceCollection.refresh(ResourceCollection.java:330) ... 15 more Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[18785,80] Message: Connection reset at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:591) at com.splunk.AtomObject.scan(AtomObject.java:193) ... 29 more

Since this error occurs in random queries every time, I'm guessing this connection reset is not because of my code itself.
I've also read the previous issue that has been closed: it does give some explanation why this might happen but doesn't say anything about fixing it.
Does spunk connections automatically timeout after a given amount of time? More importantly, is there a way to prevent this from happening?

FYI, using JDK 1.8 and splunk 1.5

Overriding for Password.itemKey is not reasonable

In PasswordCollection.java

 /**
 * Returns the username for a credential.
 *
 * @param entry The {@code AtomEntry} object describing the credential.
 * @return The username.
 */
@Override protected String itemKey(AtomEntry entry) {
    return (String)entry.content.get("username");
}

I don't think this is is reasonable because a certain password is located by id "[realm]:[username]". Assuming you have 2 password, first is "realmA:admin" and second is "realmB:admin", passwordCollection.get("admin") can only return one of it

Suggesting overriding passwordCollection.get(String id) and an additional passwordCollection.get(String realm, String name).

Error Messages of a search

Hello Team,
My search results are incomplete due to some of the indexes were down
splunk
Got Some warnings and error messages, is there any way to retrieve them using splunk java sdk as its showing job has property called messages but i didnt find that property in sdk 1.5.0.

Please help me out in getting those error message as i need to send those errors to end users.

Thanks,
Ranaveer

update used version of minified $script

Hi,

I use the SDK together with Angular 2. Painting one chart was no problem, but as I wanted to paint a second one, it didn't work. I traced it down to the "UI.loadCharting" function. The passed callback is only called, if $script loads the file from the server. If using the function for creating a second chart, the callback will not be executed (as the file is already loaded).
I fixed it by replacing the included minified version of $script by the current one.

Migrate to maven/gradle

I think we can benefits from those dependency management tools for example update the 3rd party library version.

SSLHandshakeException on java 8

java version: 1.8.0_101
error:
Exception in thread "main" java.lang.RuntimeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate) at com.splunk.HttpService.send(HttpService.java:451) at com.splunk.Service.send(Service.java:1295) at com.splunk.HttpService.post(HttpService.java:348) at com.splunk.Service.login(Service.java:1124) at com.splunk.Service.login(Service.java:1103) at com.splunk.Service.connect(Service.java:189) at com.splunk.examples.search_saved.Program.main(Program.java:61) Caused by: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate) at sun.security.ssl.Handshaker.activate(Handshaker.java:503) at sun.security.ssl.SSLSocketImpl.kickstartHandshake(SSLSocketImpl.java:1482) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1351) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387) at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1283) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1258) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250) at com.splunk.HttpService.send(HttpService.java:445) ... 6 more
More related info:
https://answers.splunk.com/answers/209379/no-appropriate-protocol-protocol-is-disabled-or-ci.html
https://blogs.oracle.com/java-platform-group/diagnosing-tls,-ssl,-and-https

Please publish to maven central

I appreciate you do use Maven, and know that you host your own repository. Please consider publishing to Maven central. There are a slew of tools and integrations that know to look for dependencies in Maven central - then splunk.jar would "just work out of the box" as a dependency.

Support customized java cmd

In java sdk, jvm is always started by the default java cmd. But in some case, user will install multi java in their machine, the default java may not be the one they want to use.

It seems better to provide an interface to support customized java command. User can use default or customized java command to start the jvm according to their requirements.

bug: java modular input launchers in windows may not kill java process when it be terminated

I run modular input using shim.exe in windows.

When I stop splunk, I found that the shim.exe process will be killed, but the java process is still running. And in splunkd.log, there is a warning messages:

WARN  ProcessRunner - Process with pid 4840 did not exit within a given grace period after being signaled to exit. Will have to forcibly terminate.

Process 4840 is the shim.exe.

I read the code of shim.cpp. I found that shim.exe will wait splunkd and java process using function waitOutcome = WaitForMultipleObjects(2, processHandles, FALSE, INFINITE);. If splunkd is stopping, it will be signaled and this function will return. Then we can send CTRL+C signal to java process.

But as I found, shim.exe can't exit gracefully within the given grace period. So it is terminated by splunk and will not send CTRL+C signal to java process. I still don't know how long the given grace period.

I think even if the shim.exe be terminated, we should also ensure the related java process be killed.

Namespace is ignored when searching

When running a search that refers to an object outside the default namespace, I get errors (tried with savedsearch and macros).

To reproduce:

  1. Create new app named testapp
  2. Create a saved search in testapp named test
  3. Set permissions of saved search to "shared in app"
  4. Use Splunk Java SDK to search for | savedsearch "test"
    • (oneshot or submit job, doesn't matter)
    • Set namespace to "testapp" as per below methods

No matter how I spin it, I get this:

com.splunk.HttpException: HTTP 400 -- Error in 'savedsearch' command: Unable to find saved search named 'test'.

I've tried both setting the service app:

ServiceArgs loginArgs = new ServiceArgs();
loginArgs.setApp("testapp");
... set user/pass ...
service = Service.connect(loginArgs);

... and job namespace:

JobArgs jobArgs = new JobArgs();
jobArgs.setNamespace("testapp");
Job job = service.getJobs().create( search, jobArgs );

If I share the saved search as 'global' or if I move it to the 'search' app, it works fine. Leaves me to believe the namespace isn't working and that it's searching under the 'search' app regardless.

Java 8
Splunk SDK 1.6.0.0 / 1.6.2.0
Splunk 6.5.2 (via docker)

Add AutoCloseable to ResultsReader

ResultsReader already has an idempotent close method (it just called InputStream.close()), so I believe it would be as simple as adding AutoClosable to the list of interfaces ResultsReader implements. It wouldn't break backwards compatibility and would allow people to use try-with-resources.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.