Sparrow On-Demand Java SDK
With the Java SDK, you can easily perform source code analysis, open source analysis, and web vulnerability analysis without directly calling the Sparrow On-Demand API.
Table of Contents
- Environment Setup
- Initialization
- Analysis Request
- Status Inquiry
- Download Analysis Result Files
- Read Analysis Results
- Stop Analysis
- Exception Handling
- Object Information
Environment Setup
-
Install JDK 17 or higher
-
Gradle Configuration
implementation 'io.github.sparrow-co-ltd:sparrow-ondemand-java-sdk:2.0.0' -
Sparrow On-Demand API Token required
Tip: Refer to Token Issuance.
Initialization
Create a client object OndemandClient to call the API. You can specify settings with OndemandClientConfig.
// config
OndemandClientConfig config = OndemandClientConfig.builder()
.apiKey("API_KEY")
.url("API_URL")
.build();
// create client
OndemandClient client = new OndemandClient(config);
- apiKey A token (API_KEY) issued by Sparrow On-Demand for authentication in API requests.
- url The API service URL (API_URL) of Sparrow On-Demand to send API requests to.
Analysis Request
Common Method
The Java SDK provides the following method based on analysis type, such as source code analysis, open source analysis, and web vulnerability analysis.
RequestInfo requestInfo = client.doAnalysis(analysisRequest);
- analysisRequest: Request object by analysis type
- SastAnalysisRequest Source Code Analysis
- ScaAnalysisRequest Open Source Analysis
- DastAnalysisRequest Web Vulnerability Analysis
Source Code Analysis
SastAnalysisRequest request1 = SastAnalysisReqeust.builder()
.callbacks(Arrays.asList(
callbacks.of("url",
Arrays.asList(CallbackType.ANALYSIS_PROGRESS),
Arrays.asList(CallbackHeader.of("key", "value"))
)))
.sastOptions(SastOptionRequest.builder()
.analysisSource(
AnalysisSourceRequest.VCS.builder()
.url("https://github.com/jhkim593/PayProject.git")
.branch("master")
.authToken("authToken")
.build())
.extensions(Arrays.asList("java"))
.issueSimilarity(true)
.build())
build();
RequestInfo requestInfo = client.doAnalysis(request);
- callbacks Callback list
List
You can set the callback list using theofmethod withCallbackTypeandCallbackHeaderclasses, or set callback format classes such asSrcUploadCallback,CompleteCallback,ProgressCallback,DastProgressCallbackinstead of the callback list.SrcUploadCallbackCompleteCallbackProgressCallbackDastProgressCallback
🔽 Source Code Analysis Options
-
sastOptions
-
analysisSource
-
VCS
- url VCS URL
RequiredString - branch Branch
String - commitId Commit ID
String - tag Tag
String - id VCS ID
String - password VCS Password
String - authToken VCS Token
String
Tip: If only the url is entered, files included in the latest commit of the branch set as default in the Git repository are analyzed.
- url VCS URL
-
ObjectStorage
- endPoint Storage endpoint
RequiredString - bucket Storage bucket
RequiredString - object Storage object name
RequiredString - accessKey Storage access key
String - secretKey Storage secret key
String
- endPoint Storage endpoint
-
-
extensions List of file extensions to analyze
Tip: Enter one of the following:
["java", "go"]["*"]For compressed files, if the extension of the compressed file is included in the analysis targets, all files inside the compressed file are included in the analysis.
-
excludedPath Paths to exclude from analysis
Tip: Case-insensitive and
*can be used.*AA*: Matches all strings containing AAAA*: Matches all strings starting with AA For other ways to set analysis exclusion paths, refer to the following.
-
maxSourceSize Maximum source size
integerThe maximum size of the analysis target to check in source code analysis or open source analysis. If the size of the analysis target downloaded during source code analysis or open source analysis is larger thanSOURCE_SIZE, the analysis is terminated. You can enter an integer between1and200(unit: MB)
-
Tip: Returns a RequestInfo object.
Open Source Analysis
ScaAnalysisReqeust request = ScaAnalysisReqeust.builder()
.callbacks(Arrays.asList(
Arrays.asList(
CallbackUrl.of("url",
Arrays.asList(CallbackType.ANALYSIS_PROGRESS),
Arrays.asList(CallbackHeader.of("key", "value"))
)))
.scaOptions(ScaOptionRequest.builder()
.analysisSource(
AnalysisSourceRequest.ObjectStorage.builder()
.endPoint("endpoint")
.bucket("bucket")
.object("object")
.accessKey("accessKey")
.secretKey("secretKey")
.build())
.sbomCreatorEmail("DD")
.build())
.build();
RequestInfo requestInfo = client.doAnalysis(request);
- callbacks Callback list
List
You can set the callback list using theofmethod withCallbackTypeandCallbackHeaderclasses, or set callback format classes such asSrcUploadCallback,CompleteCallback,ProgressCallback,DastProgressCallbackinstead of the callback list.SrcUploadCallbackCompleteCallbackProgressCallbackDastProgressCallback
🔽 Open Source Analysis Options
-
scaOptions
-
analysisSource
-
VCS
- url Git URL
RequiredString - branch Branch
String - commitId Commit ID
String - tag Tag
String - id VCS ID
String - password VCS Password
String - authToken VCS Token
String
Tip: If only the url is entered, files included in the latest commit of the branch set as default in the Git repository are analyzed.
- url Git URL
-
ObjectStorage
- endPoint Storage endpoint
RequiredString - bucket Storage bucket
RequiredString - object Storage object name
RequiredString - accessKey Storage access key
String - secretKey Storage secret key
String
- endPoint Storage endpoint
-
-
extensions List of file extensions to analyze
Tip: Enter one of the following:
["java", "go"]["*"]For compressed files, if the extension of the compressed file is included in the analysis targets, all files inside the compressed file are included in the analysis.
-
excludedPath Paths to exclude from analysis
Tip: Case-insensitive and
*can be used.*AA*: Matches all strings containing AAAA*: Matches all strings starting with AA For other ways to set analysis exclusion paths, refer to the following.
-
maxSourceSize Maximum source size
integerThe maximum size of the analysis target to check in source code analysis or open source analysis. If the size of the analysis target downloaded during source code analysis or open source analysis is larger thanSOURCE_SIZE, the analysis is terminated. You can enter an integer between1and200(unit: MB) -
sbomTypes SBOM type list If the list is empty, SBOM is not generated. You can enter the following values:
- SPDX 2.2:
SPDX22(.spdx),SPDX22_JSON(.json),SPDX22_SPREADSHEET(.xlsx),SPDX22_RDF(.rdf) - SPDX 2.3:
SPDX23(.spdx),SPDX23_JSON(.json),SPDX23_SPREADSHEET(.xlsx),SPDX23_RDF(.rdf) - SPDX 3.0:
SPDX30_JSON(.json) - CycloneDX:
CycloneDX14,CycloneDX15,CycloneDX16(.json) - SWID:
SWID(.zip) - NIS SBOM:
NIS_CSV(.csv),NIS_PDF(.pdf),NIS_JSON(.json)
- SPDX 2.2:
-
sbomCreatorUsername SBOM creator
string -
sbomCreatorEmail SBOM creator email
string
-
Tip: Returns a RequestInfo object.
Web Vulnerability Analysis
DastAnalysisRequest request = DastAnalysisRequest.builder()
.callbacks(Arrays.asList(
DastProgressCallback.of("https://example.com/callback")
))
.dastOptions(
DastOptionRequest.builder()
.crawlerTargetSeedUrls(Arrays.asList("http://52.78.58.6:38380/dcta-for-java/absolutePathDisclosure"))
.build())
.build();
RequestInfo requestInfo = client.doAnalysis(request);
- callbacks Callback list
List
You can set the callback list using theofmethod withCallbackTypeandCallbackHeaderclasses, or set callback format classes such asSrcUploadCallback,CompleteCallback,ProgressCallback,DastProgressCallbackinstead of the callback list.SrcUploadCallbackCompleteCallbackProgressCallbackDastProgressCallback
🔽 Web Vulnerability Analysis Options
-
crawlerTargetSeedUrls Target URL for analysis
RequiredString -
commonRecordsLogin Login record file
stringTip: Download Sparrow Event Clipboard and save the login process as a file to use.
-
crawlerTargetContainEntireSeed Collect only sub-paths
boolean -
crawlerRequestAcceptLanguage Client language
Tip: Enter in locale format such as
ko_KR. -
crawlerCrawlMaxUrl Maximum number of URLs to collect
integerTip: Enter the default value
0to not limit the number of URLs that can be collected. -
crawlerCrawlTimeout Maximum collection time
integerTip: Enter the default value
0to not limit the collection time. -
analyzerAnalyzeTimeout Maximum analysis time
integerTip: Enter the default value
0to not limit the analysis time. -
crawlerSkipUrl URLs to exclude from collection
string -
analyzerSkipUrl URLs to exclude from analysis
string -
crawlerSkipUrlSuffix URL suffix to exclude
string -
crawlerExcludeCssSelector Elements to exclude from event execution (CSS selector)
-
crawlerIncludeCssSelector Elements to include for event execution (CSS selector)
-
crawlerExcludeXpath Elements to exclude from event execution (XPath)
-
crawlerIncludeXpath Elements to include for event execution (XPath)
-
crawlerRequestCustomHeaders Custom HTTP headers
-
crawlerLimitUrlDepthDegree URL collection depth
Tip: Enter
high,medium, orlow. -
crawlerLimitDomDepthDegree DOM collection depth
Tip: Enter
high,medium, orlow. -
crawlerBrowserExplicitTimeout Event wait time
integer -
crawlerRequestCountPerSecond Number of HTTP requests
integerTip: Enter the default value
-1to not limit the number of HTTP requests that can be sent. -
crawlerClientTimeout HTTP client wait time
integer
Tip: Returns a RequestInfo object.
Status Inquiry
Request Status Inquiry
You can check the request status after requesting an analysis.
RequestInfo requestInfo = client.getRequest(requestId: Long)
- requestId Request ID
RequiredLong
Tip: Returns a RequestInfo object.
Analysis Status Inquiry
You can check the analysis status through the analysis ID after the analysis has started.
AnalysisInfo analysisInfo = client.getAnalysis(analysisId: Long)
- analysisId Analysis ID
RequiredLong
Tip: Returns an AnalysisInfo object.
Download Analysis Result Files
You can download the analysis results as a file after the analysis is completed.
client.downLoadAnalysisResult(analysisId: Long, filePath: String);
- downLoadAnalysisResult
-
analysisId Analysis ID
RequiredLong -
filePath Download path
RequiredStringTip : Enter a file name with a zip extension in the download path. /home/result.zip
-
Read Analysis Results
After the analysis is completed, you can download the result file, extract it, and read the results through tool-specific Reader objects.
Common Method
ResultReader resultReader = client.getAnalysiResultReader(analysisId: Long ,filePath: String);
- ResultReader Result reading object by analysis type
- SastResultReader Read Source Code Analysis Results
- ScaResultReader Read Open Source Analysis Results
- DastResultReader Read Web Vulnerability Analysis Results
Read Source Code Analysis Results
// 1. Create SastResultReader
SastResultReader sastResultReader = (SastResultReader) client.getAnalysiResultReader(analysisId: Long ,filePath: String);
// 2. Read analysis result summary
SastSummary sastSummary = sastResultReader.readSummary();
// 3. Read analysis asset list
List<String> assets = sastResultReader.readAsset();
// 4. Return the number of issue files
int size = sastResultReader.issueSize();
// 5. Return SastIssue list from issue file
List<SastIssue> sastIssues = sastResultReader.readIssue(index: int);
// 6. Return WorkMessage list from work messages
List<WorkMessage> workMessages = sastResultReader.readWorkMessage();
-
SastResultReader
- analysisId Analysis ID
RequiredLong - filePath Download path
RequiredString
- analysisId Analysis ID
-
readSummary Method to read analysis result summary
-
readAsset Method to read analysis asset list
Tip: Returns
List<String>. -
issueSize Method to return the number of issue files
Tip: Returns
size int. -
readIssue Method to return SastIssue list
- index
Tip: Returns
List<SastIssue>and the maximum value can be checked through theissueSize()method.
- index
-
readWorkMessage Method to return WorkMessage list
Tip: Returns
List<WorkMessage>.
Read Open Source Analysis Results
// 1. Create ScaResultReader
ScaResultReader scaResultReader = (ScaResultReader) client.getAnalysiResultReader(analysisId: Long ,filePath: String);
// 2. Read analysis result summary
ScaSummary scaSummary = scaResultReader.readSummary();
// 3. Read analysis asset list
List<String> assets = scaResultReader.readAsset();
// 4. Return the number of issue files
int size = scaResultReader.issueSize();
// 5. Return SastIssue list from issue file
List<ScaComponent> scaComponents = scaResultReader.readIssue(index: int);
// 6. Return WorkMessage list from work messages
List<WorkMessage> workMessages = scaResultReader.readWorkMessage();
// 7. Return SBOM file path
Path sbomPath = scaResultReader.getSbomPath(sbomType: SbomType);
// 8. Return license notice file (HTML) path
Path path = scaResultReader.getLicenseNoticeHtmlPath();
// 9. Return license notice file (Markdown) path
Path path = scaResultReader.getLicenseNoticeMarkDownPath();
// 10. Return license notice file (Text) path
Path path = scaResultReader.getLicenseNoticeTextPath();
-
SastResultReader
- analysisId Analysis ID
RequiredLong - filePath Download path
RequiredString
- analysisId Analysis ID
-
readSummary Method to read analysis result summary
-
readAsset Method to read analysis asset list
Tip: Returns
List<String>. -
issueSize Method to return the number of issue files
Tip: Returns
size int. -
readIssue Method to return SastIssue list
- index
Tip: Returns
List<SastIssue>and the maximum value can be checked through theissueSize()method.
- index
-
readWorkMessage Method to return WorkMessage list
Tip: Returns
List<WorkMessage>. -
getSbomPath Method to return SBOM file path
- sbomType SBOM type
Required
Tip: Returns SBOM file path sbomPath.
- sbomType SBOM type
-
getLicenseNoticeHtmlPath Method to return license notice file (HTML) path
Tip: Returns license notice file path path.
-
getLicenseNoticeMarkDownPath Method to return license notice file (Markdown) path
Tip: Returns license notice file path path.
-
getLicenseNoticeTextPath Method to return license notice file (Text) path
Tip: Returns license notice file path path.
Read Web Vulnerability Analysis Results
// 1. Create DastResultReader
DastResultReader dastResultReader = (DastResultReader) client.getAnalysiResultReader(analysisId: Long ,filePath: String);
// 2. Read analysis result summary
DastSummary dastSummary = dastResultReader.readSummary();
// 3. Read analysis asset list
List<String> assets = dastResultReader.readAsset();
// 4. Return the number of issue files
int size = dastResultReader.issueSize();
// 5. Return SastIssue list from issue file
List<DastIssue> dastIssues = dastResultReader.readIssue(index: int);
// 6. Return WorkMessage list from work messages
List<WorkMessage> workMessages = dastResultReader.readWorkMessage();
-
SastResultReader
- analysisId Analysis ID
RequiredLong - filePath Download path
RequiredString
- analysisId Analysis ID
-
readSummary Method to read analysis result summary
-
readAsset Method to read analysis asset list
Tip: Returns
List<String>. -
issueSize Method to return the number of issue files
Tip: Returns
size int. -
readIssue Method to return SastIssue list
- index
Tip: Returns
List<SastIssue>and the maximum value can be checked through theissueSize()method.
- index
-
readWorkMessage Method to return WorkMessage list
Tip: Returns
List<WorkMessage>.
Stop Analysis
You can stop an ongoing analysis.
client.stopAnalysis(analysisId: Long);
- analysisId Analysis ID
RequiredLong
Tip: Returns nothing.
Exception Handling
You can perform analysis by calling methods of the OndemandClient instance created in Initialization. When OndemandException occurs while executing a method, refer to the following for its meaning and handling. OndemandException delivers exceptions through RuntimeException and is classified into two types.
- OndmandClientException
May occur when the client sends a request to Sparrow On-Demand or processes a response from Sparrow On-Demand.
- resultCode Result code
StringDifferent codes are displayed depending on the cause of the exception. For details, refer to Result Codes. - message Message
StringA message about the cause of the exception.
- resultCode Result code
- OndmandServerException
Occurs when Sparrow On-Demand successfully receives a request but cannot process it.
- resultCode Result code
StringDifferent codes are displayed depending on the cause of the exception. For details, refer to Result Codes. - message Message
stringA message about the cause of the exception. - statusCode Status code
integerIndicates the response status code. - validationErrors Validation error message
StringA message returned from the server when validation of the request fails.
- resultCode Result code
Object Information
RequestInfo
- requestId Request ID
Long - result Request result
StringThe result when the analysis is terminated, which can have the following values:SUCCESS: Analysis successfully completedFAIL: Analysis failed without proper completionSTOP: Analysis stopped after receiving a stop request
- analysisList Analysis list
ListTip: A list of AnalysisInfo objects.
AnalysisInfo
- analysisId Analysis ID
Long - requestId Request ID
integer - status Analysis status
String
Status according to the analysis progress stage, displayed as one of the following:STOP_PROCESS: Stopping analysis after receiving a stop requestINIT: Preparing environment for analysisREADY: Environment configured and preparing analysis targetPRE_PROCESS: Preprocessing analysis target for analysisANALYSIS: Performing analysisPOST_PROCESS: Processing results after analysis completionCOMPLETE: Analysis terminated
- toolType Analysis type
String - memo Memo
String