OCI Integration with Java SDK

Pratik Dandavate
4 min readMay 24, 2023
OCI Integration

OCI console has lot more interesting feature offering, however there are several spots OCI is offering in terms SDK and CLI but needs more clarity. Today I will be sharing few custom integration that I created with oci-java-sdk. Check this link for latest release.

Prerequisite

To connect java to OCI, we will need API keys of OCI to access it through code. You can download the API keys via OCI Dashboard -> Profile -> User Setting -> API Keys -> Add API key.
We will need following details to access OCI through java-sdk:

{
"tenancyId": "<tenancy-id>",
"userId": "<user-id>",
"fingerprint": "<fingerprint>",
"region": "us-phoenix-1",
"privateKey": "<private-key>"
}

Store it in some persistence storage for later use.

We will need following dependencies for AuthenticationDetailsProvider

<dependency>
<groupId>com.oracle.oci.sdk</groupId>
<artifactId>oci-java-sdk-common</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.oracle.oci.sdk</groupId>
<artifactId>oci-java-sdk-common-httpclient-jersey</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.oracle.oci.sdk</groupId>
<artifactId>oci-java-sdk-identity</artifactId>
<version>3.2.0</version>
</dependency>

Once store all the required details, get `AuthenticationDetailsProvider` using below code:

AuthenticationDetailsProvider will be needed to create OCI Client object

Accessing OCI Cost & Usage Report

  • If you want to get a granular view of spending or find the ways to save, you need detailed information about your Oracle Cloud Infrastructure consumption and associated cost. Cost & Usage reports enable you to gain more insight regarding your bill or create custom billing applications.
  • The reports contain one record per resource (for example, an Instance, a DB system, or an Object Storage Bucket) per hour with metadata and tags.
  • You can download the cost & usage reports through the web-based console or by using APIs.
Downloading above report using SDK

To download the report using java sdk or APIs , we will need to use Object storage APIs. The reports are stored in the tenancy’s home region. The Object Storage namespace used for the reports is bling and the bucket name is the tenancy OCID.

To use cost and usage reports, the following policy statement is required:

define tenancy usage-report as <tenancy-id>
endorse group <group> to read objects in tenancy usage-report

For more details please refer https://docs.oracle.com/en-us/iaas/Content/Billing/Concepts/usagereportsoverview.htm

We will need below dependency for accessing the report as it is by default store in object storage:

<dependency>
<groupId>com.oracle.oci.sdk</groupId>
<artifactId>oci-java-sdk-objectstorage</artifactId>
<version>${oci-sdk-version}</version>
</dependency>

Refer following code for downloading the report from ‘bling’ namespace:

Object storage client to access OCI Cost csv file

In the above example, we are parsing the CSV file using opencsv library. We have used fields like “time-created, name etc” for tracking the newly created files. Once we get required java list, we can perform any operation that is required. We have already created a class to get authenticationProvider object that we can reuse to create ObjectStorage client.

Accessing Buckets of OCI

We can use same class with little modification to get the files stored in OCI buckets. For that we should know the region and compartment-id in which bucket is present, following code will return required ListObjectsResponse object and rest of the code will be same as above ObjectStorageClientExample class.

private static String getObjectStorageNamespace(String compartmentId) {
log.debug("Querying for Object Storage namespace");
// Get Object Storage Namespace
// https://docs.oracle.com/en-us/iaas/api/#/en/objectstorage/20160918/Namespace/GetNamespace
GetNamespaceRequest namespaceRequest = GetNamespaceRequest.builder()
.compartmentId(compartmentId)
.build();
GetNamespaceResponse getNamespaceResponse = ObjectStorageClient.builder().build(AuthenticationProvider.getAuthenticationProvider()).getNamespace(namespaceRequest);
int getNamespaceResponseCode = getNamespaceResponse.get__httpStatusCode__();
if (getNamespaceResponseCode != 200) {
log.error("GetNamespace failed - HTTP {}", getNamespaceResponseCode);
}
String osNamespace = getNamespaceResponse.getValue();
return osNamespace;
}

private static String getObjectStorageNamespace(String compartmentId) {
String objectStorageNamespace = getObjectStorageNamespace(compartmentId);
ListObjectsResponse listObjectsResponseForCost =
collection.getObjectStorageClient()
.listObjects(ListObjectsRequest.builder()
.namespaceName(objectStorageNamespace)
.bucketName("bucket-name")
.prefix("cost-csv")
.fields("name,size,timeCreated").build());
System.out.println(listObjectResponseForCost);
}

Accessing Block storage in OCI

The Oracle Cloud Infrastructure Block Volume service lets you dynamically provision and manage block storage volumes . There are two types of volumes:

  • Block volume: A detachable block storage device that allows you to dynamically expand the storage capacity of an instance.
  • Boot volume: A detachable boot volume device that contains the image used to boot a Compute instance. See Boot Volumes for more information.

We will need following dependencies for accessing Block storage

<dependency>
<groupId>com.oracle.oci.sdk</groupId>
<artifactId>oci-java-sdk-core</artifactId>
<version>${oci-sdk-version}</version>
</dependency>

Same AuthenticationProvider can be used here for accessing the client, below code will create a BlockStorageClient and return the list of Volume/Block Volume

import com.oracle.bmc.core.BlockstorageClient;
import com.oracle.bmc.core.model.BootVolume;
import com.oracle.bmc.core.model.Volume;
import com.oracle.bmc.core.requests.ListBootVolumesRequest;
import com.oracle.bmc.core.requests.ListVolumesRequest;
import com.oracle.bmc.core.responses.ListBootVolumesResponse;
import com.oracle.bmc.core.responses.ListVolumesResponse;
import java.util.List;


public class OCIMultipleClient {


public static BlockstorageClient getBlockStorageClient() {
BlockstorageClient blockstorageClient = BlockstorageClient.builder().build(AuthenticationProvider.getAuthenticationProvider());
return blockstorageClient;
}

public static List<BootVolume> getBootVolumeListFromOCI(String compartmentId) {
ListBootVolumesResponse listBootVolumesResponse = getBlockStorageClient()
.listBootVolumes(ListBootVolumesRequest.builder()
.compartmentId(compartmentId)
.build());
return listBootVolumesResponse.getItems();
}

public static List<Volume> getVolumeListFromOCI(String compartmentId) {
ListVolumesResponse listVolumesResponse = getBlockStorageClient()
.listVolumes(ListVolumesRequest.builder()
.compartmentId(compartmentId)
.build());
return listVolumesResponse.getItems();
}

}

Accessing Monitoring Metrics in OCI

You can monitor the health, capacity, and performance of your compute instances by using metrics, alarms, and notifications. oci_computeagent should be running on your instance to see these metrics. For more info see here : https://docs.oracle.com/en-us/iaas/Content/Monitoring/Concepts/monitoringoverview.htm

We will need following dependencies for accessing the Monitoring metrics:

<dependency>
<groupId>com.oracle.oci.sdk</groupId>
<artifactId>oci-java-sdk-monitoring</artifactId>
<version>${oci-sdk-version}</version>
</dependency>

For accessing monitoring metrics, we need to know the instanceId for that instance. To get the instanceId we first need to collect the compute instance details. Following code will first collect all the instances and then call the monitoring metrics API to get the metrics for the resource.

If you face any issues while creating or accessing the OCI APIs in Oracle Cloud Infrastructure, please post in the comment section & stay tuned for my upcoming blog posts where I will be sharing some Oracle Cloud Infrastructure (OCI) related useful content.

Please share any thoughts or comments you have. Feel free to ask and correct me if I’ve made some mistakes.

Thanks for your time! If you like this post, give a Cheer!!!

--

--

Pratik Dandavate

I’m a passionate software engineer. I love to explore new technology and spread the knowledge I have with all the enthusiastic engineer.