Skip to content

Commit 3b154b3

Browse files
authored
Merge pull request #47 from mongodb-developer/add-java-code
Add java code
2 parents a3c3318 + bde430c commit 3b154b3

File tree

13 files changed

+276
-132
lines changed

13 files changed

+276
-132
lines changed

docs/50-demo-app/2-start-app.mdx

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ Right now, you should see a big error message in the console, as we haven't conf
5858
```
5959
:::
6060

61+
<Tabs groupId="server">
62+
<TabItem value="node" label="🚀 NodeJS/Express">
6163

6264
### Expose the server port
6365

@@ -75,6 +77,24 @@ You'll see the text in the *Visibility* column change to `Public`.
7577

7678
That's it! You're now ready to move to the next section.
7779

80+
</TabItem>
81+
<TabItem value="java" label="☕️ Java Spring Boot">
82+
### Set the MongoDB connection
83+
To run the application in GitHub Codespaces, you now need to set the MongoDB connection string before starting the server.
84+
In the terminal of your Codespace, run:
85+
```Java
86+
export MONGODB_URI="<YOUR_CONNECTION_STRING>"
87+
```
88+
After setting the environment variable, start the application again with:
89+
```Java
90+
mvn spring-boot:run
91+
```
92+
<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/50-demo-app/2-start-app/5-set-environments.png" alt="The Port Visibility menu" />
93+
Once the command finishes, the application will be up and running on port 5000.
94+
<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/50-demo-app/2-start-app/6-app-started.png" alt="The Port Visibility menu" />
95+
96+
</TabItem>
97+
</Tabs>
7898
## 🦸 Option 2: Run locally
7999

80100
If you prefer to run the application locally, you can do so by following these steps. Keep in mind that the following steps of this lab will be using the codespace, so you might need to adapt some of the commands.
@@ -126,26 +146,33 @@ npm start
126146

127147
<TabItem value="java" label="☕️ Java Spring Boot">
128148

129-
You need to have a local JDK 17+ and Maven installed.
130-
131-
```bash
132-
cd client
133-
npm install
134-
```
135-
136-
Start the server application.
137-
138-
```bash
139-
cd java-server
140-
mvn spring-boot:start
149+
1. Before starting the backend, switch to the java-server project.
141150
```
142-
143-
And, in another terminal window, start the client application.
144-
145-
```bash
146-
cd client
147-
npm start
151+
git checkout java-server
148152
```
153+
This command moves you into the correct project folder that contains the Java backend code.
154+
155+
2. Set the MongoDB connection string as an environment variable:
156+
- On Linux / macOS:
157+
```bash
158+
export MONGODB_URI="<YOUR_CONNECTION_STRING>"
159+
````
160+
161+
- On Windows:
162+
```
163+
$env:MONGODB_URI="<YOUR_CONNECTION_STRING>"
164+
```
165+
166+
3. Run the Java server:
167+
```
168+
cd java-server
169+
mvn spring-boot:run
170+
```
171+
172+
4. Run the client:
173+
```bash
174+
(cd ../client && npm install && npm start)
175+
```
149176

150177
</TabItem>
151178
</Tabs>

docs/50-demo-app/3-configure.mdx

Lines changed: 2 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import TabItem from '@theme/TabItem';
55
# 👐 Configure the Application
66

77
Now that your environment is set up, you can configure the application.
8-
98
There should already be a file open in the IDE. If not, look in the file explorer on the left, and open the file below. This file contains the configuration for the application.
109

1110
<Tabs groupId="server">
@@ -19,20 +18,6 @@ DATABASE_URI="mongodb+srv://user:password@serverurl"
1918
DATABASE_NAME="library"
2019
SECRET="secret"
2120
```
22-
</TabItem>
23-
24-
<TabItem value="java" label="☕️ Java Spring Boot">
25-
26-
File: `/java-server/src/main/resources/application.properties`
27-
28-
```
29-
spring.data.mongodb.uri=mongodb+srv://user:password@serverurl
30-
spring.data.mongodb.database=library
31-
```
32-
</TabItem>
33-
</Tabs>
34-
35-
3621

3722

3823
You'll need to change the `DATABASE_URI` parameter to match your connection string. That's the same one you used to import the data.
@@ -43,38 +28,23 @@ Don't remember how to get your connection string? Check out the [Import Data](/d
4328

4429
Copy and paste your connection string into the `DATABASE_URI` parameter.
4530

46-
<Tabs groupId="server">
47-
<TabItem value="node" label="🚀 NodeJS/Express">
4831
The file will automatically save, and the server will restart.
49-
</TabItem>
50-
51-
<TabItem value="java" label="☕️ Java Spring Boot">
52-
You need to start the server. Click on the terminal window and type:
5332

54-
```shell
55-
mvn spring-boot:run
56-
```
57-
58-
</TabItem>
59-
</Tabs>
6033

6134

6235
In the *Terminal* tab at the bottom, look for the `Server is running on port: 5000` line. If you see it, you're good to go!
6336

64-
<Tabs groupId="server">
65-
<TabItem value="node" label="🚀 NodeJS/Express">
66-
6737
<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/50-demo-app/3-configure/1-running.png" alt="The terminal panel" />
6838

6939
</TabItem>
7040

7141
<TabItem value="java" label="☕️ Java Spring Boot">
42+
Everything is set up correctly. You can proceed to the next step.
7243

7344
<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/50-demo-app/3-configure/1-running-java.png" alt="The terminal panel" />
74-
7545
</TabItem>
76-
</Tabs>
7746

47+
</Tabs>
7848

7949
## Reload the client
8050

docs/60-schema-validation/2-validate-users.mdx

Lines changed: 45 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import Screenshot from "@site/src/components/Screenshot";
12
import Tabs from '@theme/Tabs';
23
import TabItem from '@theme/TabItem';
34

@@ -60,7 +61,6 @@ The schema defines the following constraints:
6061

6162
## Explore the script to apply the schema
6263

63-
6464
<Tabs groupId="server">
6565
<TabItem value="node" label="🚀 NodeJS/Express">
6666

@@ -91,39 +91,36 @@ The function uses the `db.command()` method to apply the schema to the `users` c
9191
</TabItem>
9292

9393
<TabItem value="java" label="☕️ Java Spring Boot">
94+
In this step, we’ll review the code that applies schema validation to the users collection.
95+
It’s already implemented in `SchemaValidationConfig.java` no changes needed. We’ll look at two methods:
96+
```java title='src/main/java/com/mongodb/devrel/library/infrastructure/config/SchemaValidationConfig.java'
97+
@Configuration
98+
public class SchemaValidationConfig {
9499

95-
```java
96-
public void applySchemaValidation() {
97-
try (MongoClient mongoClient = MongoClients.create(mongoDBURI)) {
98-
MongoDatabase database = mongoClient.getDatabase("library");
99-
100-
Document userSchema = new Document("$jsonSchema", new Document()
101-
.append("bsonType", "object")
102-
.append("required", List.of("name", "isAdmin"))
103-
.append("properties", new Document()
104-
.append("name", new Document("bsonType", "string").append("minLength", 5)
105-
.append("description", "must be a string and is required"))
106-
.append("isAdmin", new Document("bsonType", "bool")
107-
.append("description", "must be a boolean and is required"))
108-
)
109-
);
110-
111-
Document command = new Document("collMod", "users")
112-
.append("validator", userSchema)
113-
.append("validationLevel", "strict")
114-
.append("validationAction", "error");
115-
116-
Document result = database.runCommand(command);
117-
118-
if (result.getDouble("ok") != 1.0) {
119-
System.err.println("Failed to enable schema validation!");
120-
System.exit(1);
121-
} else {
122-
System.out.println("Schema validation enabled!");
123-
}
100+
// fields ..
101+
102+
private void applyUserSchema(MongoDatabase db) {
103+
// implementation
104+
}
105+
106+
private void runCollMod(MongoDatabase db, String collection, Document schema) {
107+
// implementation
124108
}
109+
125110
}
126111
```
112+
- `applyUserSchema(MongoDatabase db)`
113+
- Ensures the users collection exists.
114+
- Builds a $jsonSchema requiring name (string, minLength: 5) and isAdmin (boolean).
115+
- Calls runCollMod(...) to attach the validator to the collection.
116+
117+
- `runCollMod(MongoDatabase db, String collection, Document schema)`
118+
- Executes collMod with validator, validationLevel=strict, and validationAction=error.
119+
120+
121+
122+
For readability, only the class structure is shown above.
123+
You can open the [SchemaValidationConfig](https://github.com/mongodb-developer/library-management-system/blob/java-server/java-server/src/main/java/com/mongodb/devrel/library/infrastructure/config/SchemaValidationConfig.java) in your project to review the complete implementation.
127124

128125
</TabItem>
129126
</Tabs>
@@ -164,24 +161,18 @@ You need to run the script to apply the schema to the `users` collection.
164161

165162
<TabItem value="java" label="☕️ Java Spring Boot">
166163

167-
1. Stop the running app.
168-
1. Locate the bottom panel and click on the `TERMINAL` tab.
169-
1. Press Ctrl+C to interrup the running app
170-
171-
1. Copy above code for `applySchemaValidation` as a method in the `LibraryApplication.java` class.
172-
1. Modify the `run` method to call `applySchemaValidation`
173-
```java
174-
@Override
175-
public void run(String... args) {
176-
log.info("🚀 App Started");
177-
applySchemaValidation();
178-
}
179-
```
180-
1. Restart the app typing in the Terminal:
164+
The `applyUserSchema` method is triggered by the [execute](https://github.com/mongodb-developer/library-management-system/blob/java-server/java-server/src/main/java/com/mongodb/devrel/library/infrastructure/config/SchemaValidationConfig.java#L44) method, which runs only if the property `lab.schema-mode` is set.
165+
To apply the schema, you must set this property to **apply**.
166+
167+
Stop the application if it’s running and restart it with:
168+
169+
```java
170+
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dlab.schema-mode=apply"
171+
```
172+
173+
When the application starts, you should see a message confirming that the validator was successfully applied to the users collection:
174+
<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/60-schema-validation/1-schema-applied.png" alt="The schema validation applied" />
181175

182-
```bash
183-
mvn spring-boot:start
184-
```
185176

186177
</TabItem>
187178
</Tabs>
@@ -214,17 +205,18 @@ Modify the script to insert a document again with the `name` and `isAdmin` field
214205
</TabItem>
215206

216207
<TabItem value="java" label="☕️ Java Spring Boot">
208+
In this step, the schema is already created, and it’s time to test it.
209+
The [validateUserSchema](https://github.com/mongodb-developer/library-management-system/blob/java-server/java-server/src/main/java/com/mongodb/devrel/library/infrastructure/config/SchemaValidationConfig.java#L97) method, already implemented, tries to insert a new user without the isAdmin field.
217210

218-
Now that the schema validation is enabled for the `users` collection, you can test it by inserting a document that does not match the schema, or you can check the Validation tab in Compass to check for the new validation rules.
219-
220-
You can also check it in the mongosh typing:
211+
To trigger it, stop the application if it’s running and start it again with the property set to **test**:
221212

222-
```
223-
db.getCollectionInfos({ name: "users" })
213+
```java
214+
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dlab.schema-mode=test"
224215
```
225216

226-
If schema validation is not enabled, the "validator" field will be missing or empty.
217+
In the logs, you should see an error indicating that the insert was rejected by the validator:
227218

219+
<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/60-schema-validation/2-schema-validated.png" alt="The schema validation applied" />
228220

229221
</TabItem>
230222
</Tabs>

docs/60-schema-validation/3-validate-authors.mdx

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
1+
import Tabs from '@theme/Tabs';
2+
import TabItem from '@theme/TabItem';
3+
14
# 🦸‍♀️ Enable Validation for the Authors Collection
25

36
In this exercise, you will define a JSON schema for the authors collection, apply the schema to the collection, and test the schema validation by inserting a document that does not match the schema.
47

58
This is an advanced exercise that requires you to write code. If you get stuck and you're doing this during a live workshop, you can flag down an instructor in the room for help.
69

10+
<Tabs groupId="server">
11+
<TabItem value="node" label="🚀 NodeJS/Express">
12+
713
1. Start by opening the `server/src/schema-validation/apply-schema.ts` file in your GitHub codespace and uncomment lines 41-61.
814
1. Complete the tasks marked with `// TODO` comments.
915
1. Execute the script again to apply the schema to the `authors` collection.
@@ -13,3 +19,35 @@ This is an advanced exercise that requires you to write code. If you get stuck a
1319

1420
```
1521
1. Finally, test the schema validation by modifying the `server/src/schema-validation/test-validation.ts` script. Inserting a document in the `authors` collection.
22+
</TabItem>
23+
24+
<TabItem value="java" label="☕️ Java Spring Boot">
25+
In this advanced exercise, you will extend the [SchemaValidationConfig](https://github.com/mongodb-developer/library-management-system/blob/java-server/java-server/src/main/java/com/mongodb/devrel/library/infrastructure/config/SchemaValidationConfig.java) class to support the authors collection.
26+
Two methods are already defined in the class, but both are left with `// TODO` markers for you to implement:
27+
```java title='src/main/java/com/mongodb/devrel/library/infrastructure/config/SchemaValidationConfig.java'
28+
private void applyAuthorSchema(MongoDatabase db) {
29+
// TODO: Implement the schema for authors ($jsonSchema with required 'name', 'bio', etc.)
30+
}
31+
32+
private void validateAuthorsSchema(MongoDatabase db) {
33+
// TODO: Insert an invalid document to assert rejection (e.g., missing or short 'name')
34+
}
35+
```
36+
37+
Once implemented, you can run the application with the right target and mode:
38+
39+
- Apply the schema to authors
40+
```java
41+
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dlab.schema-mode=apply -Dlab.schema-target=authors"
42+
```
43+
- Test the schema validation for authors
44+
```java
45+
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dlab.schema-mode=test -Dlab.schema-target=authors"
46+
```
47+
48+
When you run in apply mode, you should see logs confirming the schema was applied.
49+
When you run in test mode, the invalid insert should fail, proving the validation works.
50+
</TabItem>
51+
52+
53+
</Tabs>

0 commit comments

Comments
 (0)