Skip to content

Commit 14aff9e

Browse files
committed
DOCSP-33345: Java comments pt. 6 (#475)
* DOCSP-33345: Java comments pt. 6 * edits * more files * duplicate comments spreadsheet suggestions (cherry picked from commit 5762399)
1 parent 9b97fb5 commit 14aff9e

File tree

5 files changed

+85
-7
lines changed

5 files changed

+85
-7
lines changed

source/includes/fundamentals/code-snippets/GridFSOperations.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,14 @@ public final class GridFSOperations {
3131

3232
private static void createCustomBucket(MongoClient mongoClient) throws Exception {
3333
MongoDatabase database = mongoClient.getDatabase("mydb");
34+
// Creates a custom GridFS bucket named "myCustomBucket"
3435
// start createCustomGridFSBucket
3536
GridFSBucket gridFSBucket = GridFSBuckets.create(database, "myCustomBucket");
3637
// end createCustomGridFSBucket
3738
}
3839

3940
private static void uploadOptions() {
41+
// Defines options that specify configuration information for files uploaded to the bucket
4042
// start uploadOptions
4143
GridFSUploadOptions options = new GridFSUploadOptions()
4244
.chunkSizeBytes(1048576) // 1MB chunk size
@@ -48,37 +50,48 @@ private static void uploadFromInputStream(GridFSBucket gridFSBucket) throws Exce
4850
// start uploadFromInputStream
4951
String filePath = "/path/to/project.zip";
5052
try (InputStream streamToUploadFrom = new FileInputStream(filePath) ) {
53+
// Defines options that specify configuration information for files uploaded to the bucket
5154
GridFSUploadOptions options = new GridFSUploadOptions()
5255
.chunkSizeBytes(1048576)
5356
.metadata(new Document("type", "zip archive"));
5457

58+
// Uploads a file from an input stream to the GridFS bucket
5559
ObjectId fileId = gridFSBucket.uploadFromStream("myProject.zip", streamToUploadFrom, options);
5660

61+
// Prints the "_id" value of the uploaded file
5762
System.out.println("The file id of the uploaded file is: " + fileId.toHexString());
5863
}
5964
// end uploadFromInputStream
6065
}
6166

6267
private static void uploadFromOutputStream(GridFSBucket gridFSBucket) throws Exception {
68+
// Reads the file data from the specified path into memory
6369
// start uploadFromOutputStream
6470
Path filePath = Paths.get("/path/to/project.zip");
6571
byte[] data = Files.readAllBytes(filePath);
6672

73+
// Defines options that specify configuration information for files uploaded to the bucket
6774
GridFSUploadOptions options = new GridFSUploadOptions()
6875
.chunkSizeBytes(1048576)
6976
.metadata(new Document("type", "zip archive"));
7077

7178
try (GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("myProject.zip", options)) {
79+
// Writes file data to the GridFS upload stream
7280
uploadStream.write(data);
7381
uploadStream.flush();
82+
83+
// Prints the "_id" value of the uploaded file
7484
System.out.println("The file id of the uploaded file is: " + uploadStream.getObjectId().toHexString());
85+
86+
// Prints a message if any exceptions occur during the upload process
7587
} catch (Exception e) {
7688
System.err.println("The file upload failed: " + e);
7789
}
7890
// end uploadFromOutputStream
7991
}
8092

8193
private static void findAllFiles(GridFSBucket gridFSBucket) throws Exception {
94+
// Prints the details of each file in the GridFS bucket
8295
// start findAllFiles
8396
gridFSBucket.find().forEach(new Consumer<GridFSFile>() {
8497
@Override
@@ -89,9 +102,12 @@ public void accept(final GridFSFile gridFSFile) {
89102
// end findAllFiles
90103
}
91104
private static void findMatchingFiles(GridFSBucket gridFSBucket) throws Exception {
105+
// Creates a filter and sort document to match documents and sort them by ascending "filename" values
92106
// start findMatchingFiles
93107
Bson query = Filters.eq("metadata.type", "zip archive");
94108
Bson sort = Sorts.ascending("filename");
109+
110+
// Retrieves 5 documents in the bucket that match the filter and prints metadata
95111
gridFSBucket.find(query)
96112
.sort(sort)
97113
.limit(5)
@@ -105,9 +121,11 @@ public void accept(final GridFSFile gridFSFile) {
105121
}
106122

107123
private static void downloadToOutputStream(GridFSBucket gridFSBucket) throws Exception {
124+
// Defines options to select the first version of a bucket file
108125
// start downloadToStream
109126
GridFSDownloadOptions downloadOptions = new GridFSDownloadOptions().revision(0);
110127

128+
// Downloads a file to an output stream
111129
try (FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/myProject.zip")) {
112130
gridFSBucket.downloadToStream("myProject.zip", streamToDownloadTo, downloadOptions);
113131
streamToDownloadTo.flush();
@@ -118,10 +136,14 @@ private static void downloadToOutputStream(GridFSBucket gridFSBucket) throws Exc
118136
private static void downloadToMemory(GridFSBucket gridFSBucket) throws Exception {
119137
// start downloadToMemory
120138
ObjectId fileId = new ObjectId("60345d38ebfcf47030e81cc9");
139+
140+
// Opens an input stream to read a file containing a specified "_id" value and downloads the file
121141
try (GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId)) {
122142
int fileLength = (int) downloadStream.getGridFSFile().getLength();
123143
byte[] bytesToWriteTo = new byte[fileLength];
124144
downloadStream.read(bytesToWriteTo);
145+
146+
// Prints the downloaded file's contents as a string
125147
System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));
126148
}
127149
// end downloadToMemory
@@ -131,18 +153,23 @@ private static void downloadToMemory(GridFSBucket gridFSBucket) throws Exception
131153
private static void renameFile(GridFSBucket gridFSBucket) throws Exception {
132154
// start renameFile
133155
ObjectId fileId = new ObjectId("60345d38ebfcf47030e81cc9");
156+
157+
// Renames the file that has a specified "_id" value to "mongodbTutorial.zip"
134158
gridFSBucket.rename(fileId, "mongodbTutorial.zip");
135159
// end renameFile
136160
}
137161

138162
private static void deleteFile(GridFSBucket gridFSBucket) throws Exception {
139163
// start deleteFile
140164
ObjectId fileId = new ObjectId("60345d38ebfcf47030e81cc9");
165+
166+
// Deletes the file that has a specified "_id" value from the GridFS bucket
141167
gridFSBucket.delete(fileId);
142168
// end deleteFile
143169
}
144170

145171
private static void dropBucket(MongoClient mongoClient) throws Exception {
172+
// Deletes a database's default GridFS bucket
146173
// start dropBucket
147174
MongoDatabase database = mongoClient.getDatabase("mydb");
148175
GridFSBucket gridFSBucket = GridFSBuckets.create(database);
@@ -154,6 +181,7 @@ public static void main(final String[] args) throws Exception {
154181
String uri = "mongodb://localhost:27017";
155182

156183
try (MongoClient mongoClient = MongoClients.create(uri)) {
184+
// Creates a GridFS bucket on a database
157185
// start createGridFSBucket
158186
MongoDatabase database = mongoClient.getDatabase("mydb");
159187
GridFSBucket gridFSBucket = GridFSBuckets.create(database);

source/includes/fundamentals/code-snippets/IndexPage.java

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ private IndexPage() {
3737

3838
public static void main(String[] args) {
3939
IndexPage page = new IndexPage();
40+
4041
page.singleIndex();
4142
page.compoundIndex();
4243
page.wildCardIndex();
@@ -48,109 +49,136 @@ public static void main(String[] args) {
4849

4950
private void singleIndex() {
5051
System.out.println("single index");
52+
53+
// Creates an index on the "title" field in ascending order
5154
// begin single index
5255
String resultCreateIndex = collection.createIndex(Indexes.ascending("title"));
5356
System.out.println(String.format("Index created: %s", resultCreateIndex));
5457
// end single index
5558

59+
// Retrieves matching documents directly from the "title" index, applying a sort and projection
5660
// begin covered single query
5761
Bson filter = eq("title", "Batman");
5862
Bson sort = Sorts.ascending("title");
5963
Bson projection = fields(include("title"), excludeId());
6064
FindIterable<Document> cursor = collection.find(filter).sort(sort).projection(projection);
6165
// end covered single query
66+
67+
// Prints the results of the find operation
6268
cursor.forEach(doc -> System.out.println(doc));
6369

6470
}
6571

6672
private void compoundIndex() {
6773
System.out.println("compound index");
74+
75+
// Creates a compound index on the "type" and "rated" fields in ascending order
6876
// begin compound index
6977
String resultCreateIndex = collection.createIndex(Indexes.ascending("type", "rated"));
7078
System.out.println(String.format("Index created: %s", resultCreateIndex));
7179
// end compound index
7280

81+
// Retrieves matching documents directly from the compound index, applying a sort and projection
7382
// begin covered compound query
7483
Bson filter = and(eq("type", "movie"), eq("rated", "G"));
7584
Bson sort = Sorts.ascending("type", "rated");
7685
Bson projection = fields(include("type", "rated"), excludeId());
7786
FindIterable<Document> cursor = collection.find(filter).sort(sort).projection(projection);
7887
// end covered compound query
88+
89+
// Prints the results of the find operation
7990
cursor.forEach(doc -> System.out.println(doc));
8091
}
8192

8293
private void multiKeyIndex() {
8394
System.out.println("multikey index");
95+
// Creates a compound multikey index on the "rated", "genres", and "title" fields in ascending order
8496
// begin multikey index
8597
String resultCreateIndex = collection.createIndex(Indexes.ascending("rated", "genres", "title"));
8698
System.out.println(String.format("Index created: %s", resultCreateIndex));
8799
// end multikey index
88100

101+
// Retrieves matching documents directly from the multikey index, applying a sort and projection
89102
// begin covered multikey query
90103
Bson filter = and(eq("genres", "Animation"), eq("rated", "G"));
91104
Bson sort = Sorts.ascending("title");
92105
Bson projection = fields(include("title", "rated"), excludeId());
93106
FindIterable<Document> cursor = collection.find(filter).sort(sort).projection(projection);
94107
// end covered multikey query
108+
109+
// Prints the results of the find operation
95110
cursor.forEach(doc -> System.out.println(doc));
96111
}
97112

98113
private void textIndex() {
99114
System.out.println("text index");
115+
// Creates a text index on the "plot" field
100116
// begin text index
101-
// create a text index of the "plot" field in the "movies" collection
102-
// if a text index already exists with a different configuration, this will
103-
// error
104117
try {
105118
String resultCreateIndex = collection.createIndex(Indexes.text("plot"));
106119
System.out.println(String.format("Index created: %s", resultCreateIndex));
120+
121+
// Prints a message if a text index already exists with a different configuration
107122
} catch (MongoCommandException e) {
108123
if (e.getErrorCodeName().equals("IndexOptionsConflict"))
109124
System.out.println("there's an existing text index with different options");
110125
}
111126
// end text index
112127

128+
// Retrieves matching documents directly from the text index, applying a projection
113129
// begin text query
114130
Bson filter = text("java coffee shop");
115131
Bson projection = fields(include("fullplot"), excludeId());
116132
FindIterable<Document> cursor = collection.find(filter).projection(projection);
117133
// end text query
134+
135+
// Prints the results of the find operation
118136
cursor.forEach(doc -> System.out.println(doc));
119137
}
120138

121139
private void geoSpatialIndex() {
122140
System.out.println("geospatial index");
123141
collection = database.getCollection("theaters");
142+
143+
// Creates a geospatial index on the "location.geo" field
124144
// begin geospatial index
125-
// if an existing geo index exists, this will error
126145
try {
127146
String resultCreateIndex = collection.createIndex(Indexes.geo2dsphere("location.geo"));
128147
System.out.println(String.format("Index created: %s", resultCreateIndex));
148+
149+
// Prints a message if a geospatial index already exists with a different configuration
129150
} catch (MongoCommandException e) {
130151
if (e.getErrorCodeName().equals("IndexOptionsConflict"))
131-
System.out.println("there's an existing text index with different options");
152+
System.out.println("there's an existing geospatial index with different options");
132153
}
133154
// end geospatial index
134155

135156
// begin geospatial query
136-
// MongoDB Headquarters in NY, NY.
157+
// Stores the coordinates of the NY MongoDB headquarters
137158
Point refPoint = new Point(new Position(-73.98456, 40.7612));
159+
160+
// Retrieves documents that represent locations up to 1000 meters from the specified point directly from the geospatial index
161+
// Creates a filter to match a document
138162
Bson filter = near("location.geo", refPoint, 1000.0, 0.0);
139163
FindIterable<Document> cursor = collection.find(filter);
140164
// end geospatial query
165+
166+
// Prints the results of the find operation
141167
cursor.forEach(doc -> System.out.println(doc));
142168
}
143169

144170
private void uniqueIndex() {
145171
System.out.println("unique index");
146172
collection = database.getCollection("theaters");
147173

174+
// Creates a unique index on the "theaterID" field in descending order
148175
// begin unique index
149-
// this will fail if any duplicate values exist on the field you are indexing
150176
try {
151177
IndexOptions indexOptions = new IndexOptions().unique(true);
152178
String resultCreateIndex = collection.createIndex(Indexes.descending("theaterId"), indexOptions);
153179
System.out.println(String.format("Index created: %s", resultCreateIndex));
180+
181+
// Prints a message if the "theaterID" field contains duplicate values
154182
} catch (DuplicateKeyException e) {
155183
System.out.printf("duplicate field values encountered, couldn't create index: \t%s\n", e);
156184
}
@@ -160,6 +188,7 @@ private void wildcardIndex() {
160188
System.out.println("wildcard index");
161189
collection = database.getCollection("theaters");
162190

191+
// Creates a wildcard index on all values of the "location" field in ascending order
163192
// begin wildcard index
164193
String resultCreateIndex = collection.createIndex(Indexes.ascending("location.$**"));
165194
System.out.println(String.format("Index created: %s", resultCreateIndex));

source/includes/fundamentals/code-snippets/Insert.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ public static void main(String[] args) {
4747

4848
private void insertOneExample() {
4949
collection.drop();
50+
// Inserts a sample document and prints the document's ID
5051
// begin insertOneExample
5152
Document doc1 = new Document("color", "red").append("qty", 5);
5253

@@ -58,6 +59,7 @@ private void insertOneExample() {
5859

5960
private void insertManyExample() {
6061
collection.drop();
62+
// Inserts sample documents into a collection
6163
// begin insertManyExample
6264
List<Document> documents = new ArrayList<>();
6365

@@ -69,6 +71,7 @@ private void insertManyExample() {
6971

7072
InsertManyResult result = collection.insertMany(documents);
7173

74+
// Retrieves and prints the ID values of each inserted document
7275
List<ObjectId> insertedIds = new ArrayList<>();
7376
result.getInsertedIds().values()
7477
.forEach(doc -> insertedIds.add(doc.asObjectId().getValue()));
@@ -95,11 +98,15 @@ private void insertManyErrorExample() {
9598

9699
// begin insertManyErrorExample
97100
List<Integer> insertedIds = new ArrayList<>();
101+
102+
// Inserts sample documents and prints their "_id" values
98103
try {
99104
InsertManyResult result = collection.insertMany(documents);
100105
result.getInsertedIds().values()
101106
.forEach(doc -> insertedIds.add(doc.asInt32().getValue()));
102107
System.out.println("Inserted documents with the following ids: " + insertedIds);
108+
109+
// Prints a message if any exceptions occur during the operation and the "_id" values of inserted documents
103110
} catch(MongoBulkWriteException exception) {
104111
exception.getWriteResult().getInserts()
105112
.forEach(doc -> insertedIds.add(doc.getId().asInt32().getValue()));

source/includes/fundamentals/code-snippets/InsertUpdate.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ public static void main(String [] args){
4343
}
4444

4545
private void updateOneAttemptExample(){
46+
// Updates the "qty" value of the document that matches the filter
4647
// begin updateOneAttemptExample
4748
Bson filter = Filters.eq("color", "orange");
4849
Bson update = Updates.inc("qty", 10);
@@ -52,15 +53,20 @@ private void updateOneAttemptExample(){
5253

5354
private void updateOneExample(){
5455
// begin updateOneExample
56+
// Creates a filter and update document to increment the matching document's "qty" value
5557
Bson filter = Filters.eq("color", "orange");
5658
Bson update = Updates.inc("qty", 10);
59+
60+
// Updates the matching document or inserts a document if none match the query filter
5761
UpdateOptions options = new UpdateOptions().upsert(true);
5862
System.out.println(collection.updateOne(filter, update, options));
5963
// end updateOneExample
6064
}
6165

6266
private void preview(boolean drop){
6367
Bson filter = Filters.empty();
68+
69+
// Prints the JSON representation of each document in the collection
6470
collection.find(filter).forEach(doc -> System.out.println(doc.toJson()));
6571
if (drop){
6672
collection.drop();

source/includes/fundamentals/code-snippets/JMXMonitoring.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,23 @@ public class JMXMonitoring {
1212
public static void main(String[] args) throws InterruptedException {
1313
// start jmx-example
1414
JMXConnectionPoolListener connectionPoolListener = new JMXConnectionPoolListener();
15+
1516
MongoClientSettings settings =
1617
MongoClientSettings.builder()
1718
.applyConnectionString(URI)
1819
.applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(connectionPoolListener))
1920
.build();
21+
22+
// Creates a MongoClient instance that enables connection pool event monitoring with the JMX tool
2023
MongoClient mongoClient = MongoClients.create(settings);
24+
2125
try {
2226
System.out.println("Navigate to JConsole to see your connection pools...");
27+
28+
// Pauses the code execution so you can navigate to JConsole and inspect your connection pools
2329
Thread.sleep(Long.MAX_VALUE);
30+
31+
// Prints exception details if any exceptions occur during the code execution
2432
} catch (Exception e) {
2533
e.printStackTrace();
2634
}

0 commit comments

Comments
 (0)