Splunk Dev

Not able to get response using SplunkRestClient in java

dezmadi
Path Finder

Hi Folks,

 

I am trying to get Splunk response from java using below method

----------------

public String executeSearch(String searchQuery) throws IOException {
//String apiUrl = hostName + "/__raw/services/search/jobs/export?search=" + URLEncoder.encode(searchQuery, "UTF-8").replace("+", "%20");
String apiUrl = hostName + "/__raw/services/search/jobs/export?search=" + URLEncoder.encode(searchQuery, "UTF-8")
.replace("+", "%2B")
.replace("%3D", "=")
.replace("%20", "+")
.replace("%2A", "*")
.replace("%3F", "?")
.replace("%40", "@")
.replace("%2C", ",");

URL url = new URL(apiUrl);
System.out.println("Value of Splunk URL is " + url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");

String credentials = userName + ":" + password;
String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);

StringBuilder response = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Response Line: " + inputLine); // Print each line of the response
response.append(inputLine);
}
}
return response.toString();
}




public static void main(String[] args) {
if (args.length < 10) {
System.out.println("Insufficient arguments provided. Please provide all required arguments.");
System.exit(1); // Exit with error code 1
}

String hostName = args[0];
String userName = args[1];
String password = args[2];
String query = args[3];
String logFileLocation = args[4];
String fileName = args[5];
String fileType = args[6];
String startDate = args[7];
String endDate = args[8];
String time = args[9];

try {
SplunkRestClient client = new SplunkRestClient(hostName, userName, password);
String searchResult = client.executeSearch(query);
System.out.println(searchResult);

// Write search result to file
String filePath = logFileLocation + File.separator + fileName + "." + fileType;
Files.write(Paths.get(filePath), searchResult.getBytes());

// Check if file is empty
File file = new File(filePath);
if (file.length() == 0) {
System.out.println("File is empty. Deleting...");
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete file.");
}
} else {
// Validate file contents (assuming JSON data)
try {
new JSONObject(new String(Files.readAllBytes(Paths.get(filePath))));
System.out.println("File contents are valid JSON.");
} catch (Exception e) {
System.out.println("File is corrupt. Deleting...");
/*if (file.delete()) {
System.out.println("Corrupt file deleted successfully.");
} else {
System.out.println("Failed to delete corrupt file.");
}*/
}
}

} catch (IOException e) {
System.out.println("Error occurred while executing search: " + e.getMessage());
System.exit(2); // Exit with error code 2
}
}



-------------------------------

I am calling this java file using bat file

:: All Splunk host name
set host_nam=https://log01.oss.mykronos.com/en-US/app/search/search?earliest=@d&latest=now

set host_cfn=https://cfn-log01.oss.mykronos.com/en-US/app/search/search?earliest=@d&latest=now
set host_dcust=https://koss01-log01.oss.mykronos.com/en-US/app/search/search?earliest=@d&latest=now

:: Splunk user name
set username=********
:: Splunk user password
set password=********
:: Splunk search query for CAN, AUS, EUR
set query_kpi=index=*kpi* level=ERROR logger=KPI*
set query_wfm=index=*wfm* level=ERROR logger=KPI*
set file_type="JSON"
set start_date=""
set end_Date=""
set time="3600"

%JAVA_PATH% com.kronos.hca.daily.monitoring.processor.SplunkRestClient %host_nam% %username% %password% "%query_nam_kpi%" "%logFileLocation%" "%file_name_nam_kpi%" %file_type% %start_date% %end_Date% %time%,

 

Labels (1)
0 Karma
Got questions? Get answers!

Join the Splunk Community Slack to learn, troubleshoot, and make connections with fellow Splunk practitioners in real time!

Meet up IRL or virtually!

Join Splunk User Groups to connect and learn in-person by region or remotely by topic or industry.

Get Updates on the Splunk Community!

Rounding off the Splunk Dashboard Contest

What does a contest-winning Splunk dashboard look like? In this case, it isn't in a browser tab at all. It ...

A Four Part Event Series: AI + Observability: AI Agents, LLMs, Apps, & Infrastructure

AI &#43; Observability: AI Agents, LLMs, Apps, & Infrastructure The rapid evolution of artificial intelligence ...

Splunk Technical Support Is Moving to Cisco Support Tools

Introduction Splunk technical support is transitioning to Cisco’s support environment. This change brings ...