io_nats_client_api - RichardHightower/jnats GitHub Wiki

StreamInfo
The StreamInfo class is a sub-class of ApiResponse that holds information about a JetStream stream.
MirrorInfo
The MirrorInfo class is a subclass of SourceInfoBase and provides information about an upstream stream source in a mirror.
ServerInfo
The ServerInfo class is a public class that provides information about a server. It contains various methods and properties that allow access to server details such as its IP address, hostname, port number, and other relevant information. This class is designed to handle server-related operations and provide essential server information for software engineers and developers.
ClusterInfo
The ClusterInfo class provides information about the cluster a stream is part of.
ObjectMetaOptions
The ObjectMetaOptions class is a public class that implements the JsonSerializable interface. It represents high-level information about an object in an object store. Please note that the implementation of the object store is currently experimental and is subject to change.
public String toJson()
@Override
public String toJson() {
StringBuilder sb = beginJson();
JsonUtils.addField(sb, LINK, link);
JsonUtils.addField(sb, MAX_CHUNK_SIZE, chunkSize);
return endJson(sb).toString();
}The toJson method is defined in the ObjectMetaOptions class in the io.nats.client.api package. This method returns a JSON representation of the object.
A StringBuilder object named sb is created to store the JSON data.
StringBuilder sb = beginJson();The LINK field is added to the JSON data using the JsonUtils.addField method.
JsonUtils.addField(sb, LINK, link);The MAX_CHUNK_SIZE field is added to the JSON data using the JsonUtils.addField method.
JsonUtils.addField(sb, MAX_CHUNK_SIZE, chunkSize);The finalized JSON data is returned as a string.
return endJson(sb).toString();The toJson method in the ObjectMetaOptions class is used to convert the object's properties into a JSON string format.
Inside the method, a StringBuilder called sb is initialized to build the JSON string. Then, the method adds the link and chunkSize properties to the JSON string using the JsonUtils.addField method.
Finally, the method ends the JSON string using the endJson method and returns the JSON string representation of the ObjectMetaOptions object.
This method is likely used when the ObjectMetaOptions object needs to be serialized or sent as JSON data.

External
The External class is a public class implementing the JsonSerializable interface. It represents an external configuration that references a stream source in another account.
public String toJson() {
StringBuilder sb = beginJson();
addField(sb, API, api);
addField(sb, DELIVER, deliver);
return endJson(sb).toString();
}The toJson() method in the External class located in io.nats.client.api is performing the following steps:
- Create a new
StringBuilderinstance namedsb. - Call the
beginJson()method, which is not provided in the given code snippet, and append the returned value to thesbStringBuilder object. This method might handle the starting point of the JSON object by adding an opening brace or performing any necessary initialization. - Call the
addField()method, passing thesbStringBuilder object, the constantAPI, and the value of theapivariable. This method is responsible for adding a JSON field with a corresponding value to thesbStringBuilder object. - Call the
addField()method again, passing thesbStringBuilder object, the constantDELIVER, and the value of thedelivervariable. This adds another JSON field with a corresponding value to thesbStringBuilder object. - Call the
endJson()method, which is not provided in the given code snippet, and pass thesbStringBuilder object. This method might handle the ending point of the JSON object by adding a closing brace or performing any necessary finalization. - Convert the
sbStringBuilder object to a String representation using thetoString()method and return it as the result of thetoJson()method.
Please note that the code snippet does not include the implementation details of the beginJson() and endJson() methods. These methods are assumed to handle the starting and ending points of the JSON object, respectively. Additional context or the complete code implementation is required to determine their actual functionality.
The toJson method in the io.nats.client.api.External class is responsible for converting the properties of an object into a JSON string representation.
The method creates a StringBuilder to build the JSON string. It then adds the values of the api and deliver properties to the JSON string using the addField method.
Finally, the method calls the endJson method to complete the JSON string and returns it as a String.
In summary, the toJson method converts the properties of an object into a JSON string representation by adding the values of specific properties to the JSON string and returning it.

StreamInfoOptions
The StreamInfoOptions class is used for making special stream info requests. It is a public class that implements the JsonSerializable interface. This class allows users to create objects to send requests for stream info.
public String toJson()
@Override
public String toJson() {
StringBuilder sb = beginJson();
addField(sb, SUBJECTS_FILTER, subjectsFilter);
addFldWhenTrue(sb, DELETED_DETAILS, deletedDetails);
return endJson(sb).toString();
}The toJson() method in the StreamInfoOptions class is used to convert the object's properties into a JSON string representation. Below is a step-by-step description of what this method is doing based on its body:
- Create a new
StringBuilderobject namedsbto build the JSON string. - Call the
beginJson()method, which is not shown here, to add the opening curly brace{to thesbStringBuilder. - Invoke the
addField()method, passingsb,SUBJECTS_FILTERconstant, and thesubjectsFilterproperty. This method adds a field to the JSON string if thesubjectsFilterproperty is not null. - Invoke the
addFldWhenTrue()method, passingsb,DELETED_DETAILSconstant, and thedeletedDetailsproperty. This method adds a field to the JSON string only if thedeletedDetailsproperty is true. - Invoke the
endJson()method, which is not shown here, to add the closing curly brace}to thesbStringBuilder. - Convert the
sbStringBuilder to a String using thetoString()method and return it as the JSON representation of the object.
The toJson() method in the StreamInfoOptions class is responsible for converting the instance of StreamInfoOptions to a JSON string.
Inside the method, it starts by creating a StringBuilder called sb to build the JSON string.
Then, it adds a field named subjectsFilter to the JSON string using the addField() method.
Next, it conditionally adds a field named deletedDetails to the JSON string, only if deletedDetails is true, using the addFldWhenTrue() method.
Finally, it returns the final JSON string by calling endJson(sb).toString(), which adds the closing brackets and converts the StringBuilder to a string.
Overall, the toJson() method serializes the StreamInfoOptions object into a JSON string representation.

Republish
The Republish class is a public class that implements the JsonSerializable interface. It represents a set of directives that are used for republishing purposes. These directives are based on specific criteria and guidelines that need to be considered during the republishing process.
public String toJson() {
StringBuilder sb = beginJson();
addField(sb, SRC, source);
addField(sb, DEST, destination);
addFldWhenTrue(sb, HEADERS_ONLY, headersOnly);
return endJson(sb).toString();
}The toJson method in the Republish class is responsible for converting the data of an instance of the class into a JSON string representation. The method follows the steps below:
- Create a new
StringBuilderobject namedsbto build the JSON string. - Invoke the
beginJsonmethod to add the starting{character to thesbStringBuilder. - Invoke the
addFieldmethod, passingsbalong with the constantSRCand the value of thesourcefield as arguments. This adds a field namedSRCwith thesourcevalue to the JSON string. - Invoke the
addFieldmethod, passingsbalong with the constantDESTand the value of thedestinationfield as arguments. This adds a field namedDESTwith thedestinationvalue to the JSON string. - Invoke the
addFldWhenTruemethod, passingsbalong with the constantHEADERS_ONLYand the value of theheadersOnlyfield as arguments. This adds a field namedHEADERS_ONLYwith the value of theheadersOnlyfield to the JSON string, only if theheadersOnlyfield istrue. - Invoke the
endJsonmethod, passingsbas an argument. This adds the closing}character to thesbStringBuilder. - Invoke the
toStringmethod on thesbStringBuilder to convert it to aString. - Return the resulting JSON string.
The toJson method takes no input parameters and returns a String representation of the instance data in JSON format.
The toJson method in the Republish class, found in the io.nats.client.api package, is used to convert the Republish object into a JSON string representation.
The method starts by initializing a StringBuilder object to build the JSON string. It then adds the source and destination fields, obtained from the instance variables of the Republish object, using the addField method.
Next, it conditionally adds the headersOnly field to the JSON string using the addFldWhenTrue method. The headersOnly field is only added if its value is true.
Finally, the JSON string is completed by calling the endJson method on the StringBuilder object. The endJson method adds the necessary closing brackets and returns the final JSON string as a String.
Overall, the toJson method is responsible for converting the Republish object into a properly formatted JSON string representation.

Subject
The Subject class is a public class that implements the Comparable interface for comparing objects of type Subject. It allows sorting and comparison operations to be performed on Subject objects.
static List<Subject> listOf(JsonValue vSubjects) {
List<Subject> list = new ArrayList<>();
if (vSubjects != null && vSubjects.map != null) {
for (String subject : vSubjects.map.keySet()) {
Long count = getLong(vSubjects.map.get(subject));
if (count != null) {
list.add(new Subject(subject, count));
}
}
}
return list;
}The listOf method in the Subject class takes a JsonValue as input and returns a List<Subject>. Here is a step-by-step description of what this method does:
- Initialize an empty
ArrayListcalledlistto store the subjects. - Check if the
vSubjectsis not null and if its map is not null. - If the above conditions are true, iterate over each subject in the key set of the
vSubjectsmap. - For each subject, retrieve the corresponding value from the map and attempt to convert it to a
Longusing thegetLongmethod. - If the conversion is successful (i.e., the value is not null), create a new
Subjectobject with the subject name and the count obtained from the map. - Add the newly created
Subjectobject to thelist. - After processing all the subjects, return the
list.
In summary, the listOf method parses a JsonValue and extracts subjects along with their counts, creating a list of Subject objects.
The listOf method in the io.nats.client.api.Subject class is used to convert a JSON representation of subjects into a list of Subject objects.
The method takes in a parameter vSubjects, which is a JsonValue object containing the JSON representation of subjects. It initializes an empty ArrayList<Subject> called list.
If the vSubjects parameter is not null and its map attribute is also not null, the method iterates through each subject in the map using a for loop. For each subject, it retrieves the count (representing the number of occurrences) of that subject using the getLong method.
If the count is not null, a new Subject object is created with the subject and count parameters, and added to the list.
Finally, the method returns the list containing all the subjects with their corresponding counts.

Mirror
The Mirror class is a public class that extends the SourceBase class. It represents a mirror of another stream, where the mirror maintains a 1:1 reflection of the stream. The mirror stream is identified by its name, which should match the name specified in the name property. It is important to note that when a mirror is configured, both the subjects and sources of the mirror must be empty.
ApiResponse
This class is a public abstract class called ApiResponse. It is a template class that takes a type parameter T. This class provides a framework for creating response objects in the context of an API. The purpose of this class is to encapsulate the response data and provide methods to access and manipulate it.
protected static JsonValue parseMessage(Message msg) {
if (msg == null) {
return null;
}
try {
return JsonParser.parse(msg.getData());
} catch (JsonParseException e) {
return JsonValueUtils.mapBuilder().put(ERROR, new Error(500, "Error parsing: " + e.getMessage())).put(TYPE, PARSE_ERROR_TYPE).toJsonValue();
}
}The parseMessage method is defined as a protected static method in the ApiResponse class in the io.nats.client.api package. Its purpose is to parse the message data and return a JsonValue object based on the given message.
Here is a step-by-step description of what the parseMessage method is doing based on its body:
- The method takes a
Messageobject as a parameter. - It first checks if the
msgparameter is null. If it is, the method returns null. - If the
msgparameter is not null, the method proceeds to parse the message data. - Inside a try-catch block, the
JsonParser.parsemethod is called on the message data to parse it and convert it into aJsonValueobject. - If the parsing is successful, the resulting
JsonValueobject is returned. - If an exception (
JsonParseException) occurs during the parsing process, the catch block is executed. - Inside the catch block, a new
Errorobject is created with a status code of 500 and a message indicating the parsing error. - The
Errorobject is then passed to amapBuilderobject fromJsonValueUtils. - The
mapBuilderis used to build aJsonValueobject, with theERRORkey set as theErrorobject and theTYPEkey set as "PARSE_ERROR_TYPE". - The
toJsonValuemethod is called on themapBuilderobject to convert it to aJsonValueobject. - The resulting
JsonValueobject is returned.
Overall, the parseMessage method takes a Message object, parses its data using a JsonParser, and returns a JsonValue object based on the parsing result. If an exception occurs during the parsing, it returns a JsonValue object representing a parsing error.
The parseMessage method in the io.nats.client.api.ApiResponse class is responsible for parsing a Message object into a JsonValue.
The method first checks if the input Message is null, in which case it returns null as there is nothing to parse.
If the Message is not null, the method attempts to parse the message data using a JsonParser. If the parsing is successful, the parsed JsonValue is returned.
If an exception of type JsonParseException occurs during parsing, the method constructs a special JsonValue containing an error message and type information. This error message indicates that there was a problem parsing the message data. The error message includes the specific details of the parsing exception that occurred. The constructed JsonValue is then returned.

public T throwOnHasError() throws JetStreamApiException
@SuppressWarnings("unchecked")
public T throwOnHasError() throws JetStreamApiException {
if (hasError()) {
throw new JetStreamApiException(this);
}
return (T) this;
}This method is a part of the io.nats.client.api.ApiResponse class and is used to check if the response has an error. If an error is found, it throws a JetStreamApiException. Otherwise, it returns the current instance.
public T throwOnHasError() throws JetStreamApiExceptionNone
- Returns the current instance of
T.
- Check if the response has an error by calling the
hasError()method. - If an error is found:
- Throw a
JetStreamApiExceptionwiththisas the parameter.
- Throw a
- If no error is found:
- Return the current instance of
T.
- Return the current instance of
- End of the method.
The throwOnHasError method in the ApiResponse class is used to check if the response has an error and throw a JetStreamApiException if it does.
First, it checks if the response has an error by calling the hasError() method. If the response has an error, it throws a new instance of JetStreamApiException with the current ApiResponse object as an argument.
If the response does not have an error, it returns the current ApiResponse object casted to type T.

LostStreamData
The LostStreamData class provides information about lost stream data.
ApiStats
The ApiStats class represents the JetStream Account Api Stats.
ObjectStoreStatus
The ObjectStoreStatus class contains information about an object store. Note that the object store implementation is experimental and subject to change.
PublishAck
The PublishAck class is a sub-class of ApiResponse and represents a JetStream enabled server acknowledgment received from a publish call. It is used to acknowledge the successful publication of data to the server.
KeyValueStatus
The KeyValueStatus class contains information about a Key Value Bucket.
ConsumerConfiguration
The ConsumerConfiguration class is responsible for specifying the configuration for creating a JetStream consumer on both the client and server. This class implements the JsonSerializable interface and provides options for configuring the consumer. Options can be set using a ConsumerConfiguration.Builder.
public String toJson() {
StringBuilder sb = beginJson();
JsonUtils.addField(sb, DESCRIPTION, description);
JsonUtils.addField(sb, DURABLE_NAME, durable);
JsonUtils.addField(sb, NAME, name);
JsonUtils.addField(sb, DELIVER_SUBJECT, deliverSubject);
JsonUtils.addField(sb, DELIVER_GROUP, deliverGroup);
JsonUtils.addField(sb, DELIVER_POLICY, GetOrDefault(deliverPolicy).toString());
JsonUtils.addFieldWhenGtZero(sb, OPT_START_SEQ, startSeq);
JsonUtils.addField(sb, OPT_START_TIME, startTime);
JsonUtils.addField(sb, ACK_POLICY, GetOrDefault(ackPolicy).toString());
JsonUtils.addFieldAsNanos(sb, ACK_WAIT, ackWait);
JsonUtils.addFieldWhenGtZero(sb, MAX_DELIVER, maxDeliver);
JsonUtils.addField(sb, MAX_ACK_PENDING, maxAckPending);
JsonUtils.addField(sb, FILTER_SUBJECT, filterSubject);
JsonUtils.addField(sb, REPLAY_POLICY, GetOrDefault(replayPolicy).toString());
JsonUtils.addField(sb, SAMPLE_FREQ, sampleFrequency);
JsonUtils.addFieldWhenGtZero(sb, RATE_LIMIT_BPS, rateLimit);
JsonUtils.addFieldAsNanos(sb, IDLE_HEARTBEAT, idleHeartbeat);
JsonUtils.addFldWhenTrue(sb, FLOW_CONTROL, flowControl);
JsonUtils.addField(sb, ApiConstants.MAX_WAITING, maxPullWaiting);
JsonUtils.addFldWhenTrue(sb, HEADERS_ONLY, headersOnly);
JsonUtils.addField(sb, MAX_BATCH, maxBatch);
JsonUtils.addField(sb, MAX_BYTES, maxBytes);
JsonUtils.addFieldAsNanos(sb, MAX_EXPIRES, maxExpires);
JsonUtils.addFieldAsNanos(sb, INACTIVE_THRESHOLD, inactiveThreshold);
JsonUtils.addDurations(sb, BACKOFF, backoff);
JsonUtils.addField(sb, NUM_REPLICAS, numReplicas);
JsonUtils.addField(sb, MEM_STORAGE, memStorage);
JsonUtils.addField(sb, METADATA, metadata);
return endJson(sb).toString();
}
protected static Integer normalize(Long l, int min) {
if (l == null) {
return null;
}
if (l < min) {
return INTEGER_UNSET;
}
if (l > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return l.intValue();
}The normalize method is defined in the class io.nats.client.api.ConsumerConfiguration and is used to convert a Long value into an Integer value based on certain conditions.
protected static Integer normalize(Long l, int min)-
l- ALongvalue to be normalized -
min- Anintvalue representing the minimum allowable value for normalization
- Returns an
Integervalue after normalization.
- If the
lvalue isnull, meaning that no value is provided, the method returnsnull. - If the
lvalue is less than the providedminvalue, the method returns a constant valueINTEGER_UNSET. - If the
lvalue is greater than the maximum allowedIntegervalue (Integer.MAX_VALUE), the method returns the maximumIntegervalue. - If none of the above conditions are met, the method converts the
lvalue into anIntegervalue using theintValue()method and returns it.
The normalize method in the ConsumerConfiguration class takes a Long value l and an integer min as parameters. It returns an Integer value.
The method checks if the l value is null. If it is, the method returns null. If the l value is less than the min value, the method returns a constant value INTEGER_UNSET.
If the l value is greater than Integer.MAX_VALUE, the method returns Integer.MAX_VALUE. Finally, if none of the above conditions are true, the method returns the l value as an Integer by calling the intValue method on it.

OrderedConsumerConfig
The OrderedConsumerConfig class is a public class used to configure ordered consumers. It provides methods and properties that can be used to define the behavior and settings of ordered consumers within a software application.
ConsumerInfo
The ConsumerInfo class represents a JetStream consumer and provides information about it. It is a subclass of the ApiResponse class, which is responsible for handling API responses.
SourceInfo
The SourceInfo class is a public class that extends the SourceInfoBase class. It provides information about a stream being sourced.
KeyValueEntry
The KeyValueEntry class represents a record in the Key Value history.
private static long calculateLength(byte[] value, Headers h) {
if (value == null) {
String hlen = h == null ? null : h.getFirst(MSG_SIZE_HDR);
return hlen == null ? 0 : Long.parseLong(hlen);
}
return value.length;
}The calculateLength method, defined in the io.nats.client.api.KeyValueEntry class, accepts two parameters: value, which is a byte array, and h, which is an object of the Headers class.
Here is a step-by-step description of what this method does:
-
Check if the
valueparameter isnull.- If
valueisnull, proceed to step 2. - If
valueis notnull, proceed to step 6.
- If
-
Check if the
hparameter is alsonull.- If
hisnull, assignnullto the variablehlen. - If
his notnull, proceed to step 3.
- If
-
Retrieve the value associated with the key
MSG_SIZE_HDRfrom thehheaders object.- Assign this value to the variable
hlen.
- Assign this value to the variable
-
Check if the
hlenvariable isnull.- If
hlenisnull, return0. - If
hlenis notnull, proceed to step 5.
- If
-
Parse the value of
hlenas alongand return it. -
If the
valueparameter is notnull, return the length of thevaluebyte array.
By following these steps, the calculateLength method calculates and returns the length of the value byte array, considering additional logic when the value is null and using the h headers object to retrieve the length if available.
The calculateLength method in the io.nats.client.api.KeyValueEntry class is used to determine the length of a byte array value with optional headers.
The method takes two parameters - value, which is a byte array, and h, which is an instance of the Headers class.
If the value is null, the method checks if the h is also null or if it contains the predefined header key MSG_SIZE_HDR. If the header exists, the method parses its value to a long and returns it as the calculated length. If the header is not found, the method returns 0.
If the value is not null, the method simply returns the length of the byte array.
Overall, the calculateLength method is used to determine the length of a byte array value with optional headers, either by directly returning the length of the byte array or by extracting it from a header.

PeerInfo
The PeerInfo class is a public class that represents information about a peer. It provides various methods and attributes to access and manipulate this information within a software program.
PurgeResponse
The PurgeResponse class is a subclass of ApiResponse that represents the response received after attempting to purge data. It provides additional functionality and information specific to purge requests.
SuccessApiResponse
The SuccessApiResponse class is a public class that extends the ApiResponse class. It represents a successful API response and is used for handling successful responses from an API.
Replica
The Replica class is a public class that extends the PeerInfo class. It represents a replica, which is a copy of the original object in a distributed system.
SourceInfoBase
SourceInfoBase is an abstract class that serves as a base for classes representing source code information. It provides common functionality and attributes that are necessary for source code analysis and manipulation. This class cannot be instantiated directly, but it is designed to be extended by concrete classes that provide specific source code information.
Placement
The Placement class is a public class that implements the JsonSerializable interface. It provides placement directives that need to be considered when placing replicas of a stream.
public String toJson() {
StringBuilder sb = beginJson();
addField(sb, CLUSTER, cluster);
addStrings(sb, TAGS, tags);
return endJson(sb).toString();
}The toJson method in the Placement class is used to convert the object fields into a JSON string representation. Below is a step-by-step description of what the method is doing based on its implementation:
-
Create a new
StringBuilderobject namedsb.StringBuilder sb = beginJson();
-
Invoke the
beginJsonmethod to initialize thesbobject with the necessary starting characters for JSON formatting. The exact implementation ofbeginJsonis not provided here, but it is assumed to add the opening brace{to thesbobject. -
Add the
clusterfield to thesbobject by invoking theaddFieldmethod.addField(sb, CLUSTER, cluster);
The
addFieldmethod adds a field to thesbobject in the format"fieldName" : "fieldValue". TheCLUSTERfield is the fieldName andclusteris the fieldValue. -
Add the
tagsfield to thesbobject by invoking theaddStringsmethod.addStrings(sb, TAGS, tags);
The
addStringsmethod adds fields that contain an array of strings. It adds theTAGSfield as the fieldName, andtagsas the fieldValue, which is an array of strings. -
Invoke the
endJsonmethod to finalize thesbobject with the necessary ending characters for JSON formatting. The exact implementation ofendJsonis not provided here, but it is assumed to add the closing brace}to thesbobject.return endJson(sb).toString();
-
Convert the
sbobject to aStringby invoking thetoStringmethod, and return the resulting JSON string.
The toJson method takes the fields cluster and tags from the Placement object and formats them into a JSON string representation.
The toJson method in the Placement class, located in the io.nats.client.api package, is used to convert a Placement object into a JSON representation.
This method first creates a StringBuilder object called sb to build the JSON string. It then appends the opening curly brace and initial properties to the sb object using the beginJson helper method.
The addField helper method is used to add the value of the cluster field to the sb object with the key "cluster". The addStrings helper method is used to add the values of the tags field to the sb object with the key "tags".
Finally, the JSON string is completed by appending the closing brace using the endJson helper method. The resulting JSON string is converted to a String and returned.
Overall, the toJson method allows for the serialization of a Placement object into a JSON representation.

KeyValuePurgeOptions
Key Value Purge Options is a public class that provides options for purging key-value pairs. It enables the customization of purging operations by specifying parameters such as the namespaces to be purged, the expiration time for the keys, and the maximum number of keys to purge. With this class, software engineers can easily implement key-value purging functionality in their applications.
ObjectMeta
The ObjectMeta class is a public class that implements JsonSerializable. It represents high level information about an object. Please note that the object store implementation is experimental and subject to change.
public String toJson()
@Override
public String toJson() {
StringBuilder sb = beginJson();
embedJson(sb);
return endJson(sb).toString();
}The toJson method, defined in the io.nats.client.api.ObjectMeta class, is responsible for generating a JSON representation of an object.
Here is a step-by-step description of what this method does based on its body:
- Create a new
StringBuilderobject namedsb. - Call the
beginJsonmethod to initialize theStringBuilderwith the initial JSON structure. - Call the
embedJsonmethod to add the object's data to theStringBuilder. - Call the
endJsonmethod to finalize the JSON structure of theStringBuilder. - Convert the
StringBuilderto aStringusing thetoStringmethod. - Return the JSON representation of the object as a
String.
The method toJson in the class io.nats.client.api.ObjectMeta converts the object of type ObjectMeta to a JSON string representation.
It starts by creating a StringBuilder named sb and calls beginJson to initialize the JSON string. Then, it invokes embedJson to append the relevant JSON properties and values to sb. Finally, it returns the completed JSON string by converting sb to a string with endJson.

void embedJson(StringBuilder sb) {
JsonUtils.addField(sb, NAME, objectName);
JsonUtils.addField(sb, DESCRIPTION, description);
JsonUtils.addField(sb, HEADERS, headers);
// avoid adding an empty child to the json because JsonUtils.addField
// only checks versus the object being null, which it is never
if (objectMetaOptions.hasData()) {
JsonUtils.addField(sb, OPTIONS, objectMetaOptions);
}
}The embedJson method, defined in the io.nats.client.api.ObjectMeta class, performs the following steps:
- Creates a
StringBuilderobjectsbas a parameter to build the JSON string. - Invokes
JsonUtils.addFieldmethod to add a field with the keyNAMEand the value ofobjectNameto theStringBuildersb. - Invokes
JsonUtils.addFieldmethod to add a field with the keyDESCRIPTIONand the value ofdescriptionto theStringBuildersb. - Invokes
JsonUtils.addFieldmethod to add a field with the keyHEADERSand the value ofheadersto theStringBuildersb. - Checks if the
objectMetaOptionsobject has data by calling thehasDatamethod. - If the
objectMetaOptionsobject has data, invokesJsonUtils.addFieldmethod to add a field with the keyOPTIONSand the value ofobjectMetaOptionsto theStringBuildersb. - The method is completed, and the resulting
StringBuildersbcontains the JSON representation of the embedded data.
The embedJson method in the ObjectMeta class is responsible for embedding the object's metadata into a JSON representation.
Here is a breakdown of what the method does:
- It takes a
StringBuilderparametersbas its input, which is used to build the JSON string. - It uses the
JsonUtils.addFieldmethod to add theobjectName,description, andheadersvalues to the JSON string. These values are added as fields with corresponding keys. - It checks if the
objectMetaOptionshas any data using thehasDatamethod. If it does, it adds theobjectMetaOptionsto the JSON string as well. - The method ensures that an empty child is not added to the JSON by checking if
objectMetaOptionshas data, asJsonUtils.addFieldonly checks if the object is null.
Overall, the embedJson method is responsible for creating a JSON representation of an object's metadata by adding the object's name, description, headers, and options (if any) to the JSON string.

StreamState
The StreamState class is a public class that represents the state of a stream. It provides functionality for managing the state of the stream.
ConsumerCreateRequest
The ConsumerCreateRequest class is a public class that implements the JsonSerializable interface. It is used as an object to make a request to create a consumer. This class is primarily used internally.
public String toJson()
@Override
public String toJson() {
StringBuilder sb = beginJson();
addField(sb, STREAM_NAME, streamName);
JsonUtils.addField(sb, CONFIG, config);
return endJson(sb).toString();
}The toJson method in the ConsumerCreateRequest class from the io.nats.client.api package is responsible for converting an instance of ConsumerCreateRequest to a JSON string representation.
Here is a step-by-step description of what the toJson method is doing based on its body:
-
Initialize a
StringBuilderobject namedsbby invoking thebeginJsonmethod. This method is not provided in the code snippet, but it is presumably responsible for initializing theStringBuilderand adding the initial JSON opening braces. -
Add a field to the
sbStringBuilder object using theaddFieldmethod. TheaddFieldmethod takes two parameters: thesbStringBuilder and theSTREAM_NAMEconstant as the field name, andstreamNameas the field value. ThestreamNameis an instance variable of theConsumerCreateRequestclass. -
Add a field to the
sbStringBuilder object using theJsonUtils.addFieldmethod. TheaddFieldmethod takes two parameters: thesbStringBuilder and theCONFIGconstant as the field name, andconfigas the field value. Theconfigis an instance variable of theConsumerCreateRequestclass. TheJsonUtilsclass contains various utility methods for JSON handling. -
Return the JSON string representation of the
sbStringBuilder object by invoking theendJsonmethod, passing in thesbStringBuilder. This method is not provided in the code snippet, but it is presumably responsible for adding the closing JSON braces and returning the final JSON string. -
Convert the
StringBuilderobject to a string representation by invoking thetoStringmethod on thesbStringBuilder.
In summary, the toJson method in the ConsumerCreateRequest class serializes the instance variables streamName and config of the ConsumerCreateRequest object to a JSON string representation.
The toJson method in the ConsumerCreateRequest class converts the consumer create request object to a JSON string representation.
It first initializes a StringBuilder object to start building the JSON string. Then, it adds the streamName field to the JSON string using the addField method. It also adds the config field to the JSON string using the JsonUtils.addField method.
Finally, it returns the JSON string representation of the consumer create request object by invoking the endJson method on the StringBuilder and converting it to a String using the toString method.

AccountStatistics
MessageGetRequest
The MessageGetRequest class is an object used to make requests for special message get requests. It implements the JsonSerializable interface.
public String toJson()
@Override
public String toJson() {
StringBuilder sb = beginJson();
addField(sb, SEQ, sequence);
addField(sb, LAST_BY_SUBJECT, lastBySubject);
addField(sb, NEXT_BY_SUBJECT, nextBySubject);
return endJson(sb).toString();
}The toJson method defined in the MessageGetRequest class in the io.nats.client.api package is used to convert an instance of MessageGetRequest into its JSON representation. Below is a step-by-step description of what this method is doing based on its body:
- Create a new
StringBuilderobject calledsbto build the JSON string. - Call the
beginJson()method to add the opening curly brace to the JSON. - Add the
sequencefield to the JSON by calling theaddField()method with thesequencefield name and value as parameters. This field represents the sequence number. - Add the
lastBySubjectfield to the JSON by calling theaddField()method with thelastBySubjectfield name and value as parameters. This field represents the last message by subject. - Add the
nextBySubjectfield to the JSON by calling theaddField()method with thenextBySubjectfield name and value as parameters. This field represents the next message by subject. - Call the
endJson()method to add the closing curly braces and comma to the JSON. - Convert the
StringBuilderobject to aStringby calling thetoString()method and return the result.
In summary, the toJson method serializes the MessageGetRequest object into a JSON string by constructing a StringBuilder and adding the necessary JSON tokens and fields based on the values of the sequence, lastBySubject, and nextBySubject fields.
The toJson() method in the io.nats.client.api.MessageGetRequest class is used to convert a MessageGetRequest object into a JSON format.
Here is a brief summary of what the method does based on its implementation:
- Initialize a
StringBuilderobject (namedsb) to build the JSON string. - Add the
sequencefield to the JSON string using theaddField(...)method. - Add the
lastBySubjectfield to the JSON string using theaddField(...)method. - Add the
nextBySubjectfield to the JSON string using theaddField(...)method. - Return the final JSON string by converting the
StringBuilderobject to a string using thetoString()method.
Overall, the toJson() method serializes the properties of a MessageGetRequest object into a JSON string representation.

MessageInfo
The MessageInfo class is a subclass of ApiResponse that provides information about a JetStream message.
SequenceInfo
The SequenceInfo class extends the SequencePair class and serves as a container for holding the sequence numbers associated with a consumer and a stream. It provides the necessary information for managing sequences in a software system.
ObjectLink
The ObjectLink class is a public class that implements the JsonSerializable interface. It is used to embed links to other objects. Please note that the implementation of this class in the object store is experimental and subject to change.
public String toJson()
@Override
public String toJson() {
StringBuilder sb = beginJson();
JsonUtils.addField(sb, BUCKET, bucket);
JsonUtils.addField(sb, NAME, objectName);
return endJson(sb).toString();
}This method is defined in the class io.nats.client.api.ObjectLink.
The toJson() method is used to convert the object link into a JSON string representation. It returns the JSON string.
- Create a new
StringBuilderobject namedsbby calling thebeginJson()method. - Add the "bucket" field to the JSON string representation using the
addField()method fromJsonUtilsclass with the value from thebucketfield. - Add the "name" field to the JSON string representation using the
addField()method fromJsonUtilsclass with the value from theobjectNamefield. - Call the
endJson()method with thesbStringBuilder object as an argument to complete the JSON string representation. - Convert the
sbStringBuilder object to a string by calling thetoString()method. - Return the JSON string representation.
ObjectLink objectLink = new ObjectLink();
objectLink.setBucket("myBucket");
objectLink.setObjectName("myObject");
String jsonString = objectLink.toJson();In this example, the toJson() method is called on an ObjectLink object with the "bucket" field set to "myBucket" and the "name" field set to "myObject". The toJson() method returns a JSON string representation of the object link.
The toJson method in the io.nats.client.api.ObjectLink class is used to convert an object link to its JSON representation.
The method starts by creating a StringBuilder to build the JSON string. It then adds the bucket and objectName fields to the JSON using the JsonUtils.addField method. Finally, it returns the JSON string representation by converting the StringBuilder to a String.

AccountTier
The AccountTier class represents the JetStream Account Tier.
AccountLimits
The AccountLimits class represents the JetStream Account Limits.
Source
The Source class is a subclass of SourceBase and provides source information.
SequencePair
This class represents a sequence pair and is used to store the sequence numbers associated with a consumer and stream.
ObjectStoreConfiguration
ObjectInfo
The ObjectInfo class is a Java class that implements the JsonSerializable interface. It represents an object's meta information along with its instance information. Please note that the object store implementation is currently experimental and may be subject to change.
public String toJson()
@Override
public String toJson() {
// never write MTIME (modified)
StringBuilder sb = beginJson();
// the go code embeds the objectMeta's fields instead of as a child object.
objectMeta.embedJson(sb);
JsonUtils.addField(sb, BUCKET, bucket);
JsonUtils.addField(sb, NUID, nuid);
JsonUtils.addField(sb, SIZE, size);
JsonUtils.addField(sb, CHUNKS, chunks);
JsonUtils.addField(sb, DIGEST, digest);
JsonUtils.addField(sb, DELETED, deleted);
return endJson(sb).toString();
}The toJson() method in the ObjectInfo class in the io.nats.client.api package is used to convert an object's information into a JSON string representation. Here is a step-by-step description of what the method does:
- Initialize a
StringBuilderobjectsbto store the JSON string. - Invoke the
beginJson()method to add the opening bracket[to thesbobject. - Invoke the
embedJson(sb)method on theobjectMetainstance variable to include theobjectMetafields in the JSON representation. This method is responsible for adding all the fields of theobjectMetaobject to thesbobject. - Invoke the
JsonUtils.addField(sb, BUCKET, bucket)method to add thebucketfield to the JSON string. This method takes thesbobject, the field name (BUCKET), and the value of thebucketfield, and adds it to the JSON string. - Repeat steps 4 to 7 for each of the following fields:
NUID,SIZE,CHUNKS,DIGEST, andDELETED. These fields are added to the JSON string using theJsonUtils.addField()method. - Invoke the
endJson(sb)method to add the closing bracket]to thesbobject. - Convert the
sbobject to aStringusing thetoString()method and return it.
The resulting string is a JSON representation of the object's information, excluding the MTIME field.
The toJson method in the ObjectInfo class is used to serialize the object's information into a JSON string representation.
The method starts by creating a StringBuilder object and initializing it with the beginning of a JSON string.
Next, it appends the JSON representation of the objectMeta fields, which are embedded directly into the JSON string instead of being represented as a child object.
Then, it adds additional fields such as BUCKET, NUID, SIZE, CHUNKS, DIGEST, and DELETED to the JSON string using a utility method called JsonUtils.addField().
Finally, it completes the JSON string by adding the end of the JSON string and returns it as a String.

FeatureConfiguration
The FeatureConfiguration class is an abstract class that provides a foundation for creating feature configurations. This class serves as a base for other classes that implement specific feature configurations.
Error
The Error class is a public class that implements the JsonSerializable interface. It represents an error that is returned from an API request.
public static Error convert(Status status) {
switch(status.getCode()) {
case 404:
return JsNoMessageFoundErr;
case 408:
return JsBadRequestErr;
}
return new Error(status.getCode(), NOT_SET, status.getMessage());
}The convert method in the Error class defined in io.nats.client.api is responsible for converting a given Status object into an Error object. Here is the step-by-step description of how the method works:
- The method takes a
Statusobject as a parameter. - It retrieves the status code from the
Statusobject using thegetCode()method. - It performs a
switchstatement on the status code to determine the appropriate error to return. - If the status code is
404, it returns theJsNoMessageFoundErrerror. - If the status code is
408, it returns theJsBadRequestErrerror. - If the method reaches this point, it means that the status code does not match any of the case statements. In this case, it creates a new
Errorobject with the status code, aNOT_SETvalue (presumably a constant value defined elsewhere), and the status message retrieved using thegetMessage()method from theStatusobject. - The method then returns the
Errorobject.
This method is useful for converting a Status object into an Error object based on the provided status code.
The convert method in the io.nats.client.api.Error class is used to convert an instance of Status into an Error.
Within the method, a switch statement is used to check the code of the given Status object. If the code is 404, JsNoMessageFoundErr is returned. If the code is 408, JsBadRequestErr is returned. If the code does not match any of these cases, a new Error object is created with the code, NOT_SET, and the message from the Status object.
Overall, this method takes a Status object and returns an Error object based on its code.

SourceBase
The SourceBase class is an abstract class that implements the JsonSerializable interface.
public String toJson() {
StringBuilder sb = beginJson();
JsonUtils.addField(sb, NAME, name);
if (startSeq > 0) {
JsonUtils.addField(sb, OPT_START_SEQ, startSeq);
}
JsonUtils.addField(sb, OPT_START_TIME, startTime);
JsonUtils.addField(sb, FILTER_SUBJECT, filterSubject);
JsonUtils.addField(sb, EXTERNAL, external);
return endJson(sb).toString();
}The toJson() method defined in the io.nats.client.api.SourceBase class is used to convert an instance of SourceBase to its JSON representation. Here is a step-by-step description of what the method is doing:
-
Create a
StringBuildercalledsbusing thebeginJson()method. This method initializes theStringBuilderwith an opening curly brace, which signifies the start of a JSON object. -
Add the
namefield to theStringBuilderusing theJsonUtils.addField()method. TheNAMEconstant is used as the key, and the value is thenamevariable of theSourceBaseinstance. -
Check if the
startSeqvariable is greater than 0. If it is, add thestartSeqfield to theStringBuilderusing theJsonUtils.addField()method. TheOPT_START_SEQconstant is used as the key, and the value is thestartSeqvariable. -
Add the
startTimefield to theStringBuilderusing theJsonUtils.addField()method. TheOPT_START_TIMEconstant is used as the key, and the value is thestartTimevariable. -
Add the
filterSubjectfield to theStringBuilderusing theJsonUtils.addField()method. TheFILTER_SUBJECTconstant is used as the key, and the value is thefilterSubjectvariable. -
Add the
externalfield to theStringBuilderusing theJsonUtils.addField()method. TheEXTERNALconstant is used as the key, and the value is theexternalvariable. -
Return the
StringBuilderafter calling theendJson()method, which appends a closing curly brace to signify the end of the JSON object. TheStringBuilderis converted to aString.
In summary, the toJson() method creates a JSON object representing an instance of SourceBase by adding its fields to a StringBuilder in the appropriate JSON format.
The toJson method in the SourceBase class is responsible for converting an instance of the SourceBase class into a JSON string representation.
It starts by creating a StringBuilder object to build the JSON string, and then adds various fields to the JSON using the JsonUtils.addField method.
The fields that are included in the JSON are name, startSeq, startTime, filterSubject, and external.
Finally, it completes the JSON string by calling the endJson method on the StringBuilder, and returns the JSON string as a String.

MessageDeleteRequest
The MessageDeleteRequest class is used to make a request for message delete requests.
public String toJson()
@Override
public String toJson() {
StringBuilder sb = beginJson();
addField(sb, SEQ, sequence);
if (isNoErase()) {
addField(sb, NO_ERASE, true);
}
return endJson(sb).toString();
}The toJson method in the MessageDeleteRequest class is responsible for converting the message delete request object into a JSON string representation.
Step-by-step description of the toJson method:
- Create a new
StringBuildercalledsbto store the JSON string representation. - Invoke the
beginJsonmethod to add the starting curly brace and other necessary JSON formatting to thesbstring. - Invoke the
addFieldmethod, passing thesbstring builder, the constant field nameSEQ, and the value of thesequencefield. This adds thesequencefield to the JSON string. - Check if the
isNoErasemethod returnstrue(indicating that the "no erase" flag is enabled).- If true, invoke the
addFieldmethod, passing thesbstring builder, the constant field nameNO_ERASE, and the valuetrue. This adds theNO_ERASEfield with the valuetrueto the JSON string.
- If true, invoke the
- Invoke the
endJsonmethod, passing thesbstring builder. This adds the closing curly brace to thesbstring. - Convert the
sbstring builder to aStringusing thetoStringmethod and return the result.
The toJson method essentially constructs a JSON string representation of the MessageDeleteRequest object based on its fields and their values. The resulting JSON string can be used for various purposes such as sending the request over a network or storing it in a file.
The toJson() method in the io.nats.client.api.MessageDeleteRequest class is used to convert the instance of MessageDeleteRequest to a JSON string representation.
Here's a breakdown of what the method does based on its body:
- It creates a
StringBuildernamedsbto build the JSON string. - It calls the
beginJson()method to add the initial opening "{" to thesb. - It adds the value of the
sequencefield to the JSON string by calling theaddField()method, using the constantSEQas the field name. - It checks if the
isNoErase()method returnstrue. If it does, it adds the field "noErase" with the valuetrueto the JSON string by calling theaddField()method, using the constantNO_ERASEas the field name. - It calls the
endJson()method to add the closing "}" to thesband convert it to aString. - It returns the final JSON string representation.
Overall, this method serializes the MessageDeleteRequest object into a JSON string by adding the sequence field and, optionally, the noErase field.

KeyValueConfiguration
The KeyValueConfiguration class is a subclass of FeatureConfiguration that defines the configuration for a Key Value bucket.