Chat CRUD - Editing an OCS Message
Create, read, update and delete a chat message the way OCS does, then fix the update method that edits one.
1. Reference Guide (On your own)
| Term | Definition / Example | Requirement |
|---|---|---|
| CRUD | The four things a program does with stored data: Create, Read, Update, Delete. A chat does all four to its messages. | OCS chat. In an ArrayList they are add, get, set and remove (4.08 ArrayList Methods) |
| Endpoint | A URL plus a verb that a program can call: PATCH /api/dm/conversations/{id}/messages/{messageId} |
OCS DirectMessageApiController |
| HTTP verb | POST creates, GET reads, PUT replaces a whole item, PATCH changes part of an item, DELETE removes. |
OCS edits a message with PATCH |
| Status code | The number the server answers with: 200 OK, 204 No Content, 400 Bad Request, 401 Unauthorized (not logged in), 403 Forbidden, 404 Not Found, 405 Method Not Allowed, 409 Conflict |
HTTP. OCS chat answers all of these except 405, which Hack 3 uses |
| JSON | Text that carries data between programs: {"body":"Hello team"} |
OCS request and response bodies |
| Object and field | An object holds data in fields: Message m = new Message(1, "Ada", "Hello team"); |
MiraCosta CS 111 (object-oriented programming); 1.12 Classes & Objects |
| Method | Code that belongs to an object and can change its fields: m.update("Hello everyone"); |
1.9 Method Signatures |
this and shadowing |
Inside a method, this means the object being changed. A parameter with the same name as a field hides the field, so you must write this. to reach the field. |
AP CSA FRQ 2, Class Writing and Design: 2015 Q2 HiddenWord |
| Reference (alias) | A variable holds a reference to an object, not the object. Message b = a; makes two names for one message, not a copy. |
1.13 Object Creation and Storage |
| Exception | A way to stop a method and report bad input: throw new IllegalArgumentException("age must be positive"); |
MiraCosta CS 111 (language basics) |
| Mutation | Changing a field of an object that already exists. Everyone who holds a reference to it sees the change. | MiraCosta CS 111 (object-oriented programming) |
| Soft delete | Keep the message, mark it deleted, clear its text. OCS deletes this way. |
Linked List History Deletion (CS113) |
- MiraCosta’s catalog says CS 111, Introduction to Computer Science I: Java, “introduces object-oriented programming” and covers language basics such as control structures and data types.
- Writing a class with a constructor and methods is what AP CSA FRQ 2 asks. See 2015 Q2 (a constructor and a hint method) and 2019 Q2 (
StepTracker).
2. Real-Life Application (In-Class)
Chat CRUD in OCS
Open /dm in OCS. Open your browser’s developer tools, choose the Network tab, and filter by Fetch/XHR. Open a chat, send a message, then edit it. Each action sends one main request. You may also see rows named OPTIONS (the browser asking permission first) and read (marking the chat as read). Ignore those two. Click a request to see its Method, its Status, and the Payload and Response tabs. If you have no chat yet, start one with a classmate.
| What you do | Request in the Network tab | What the server answers |
|---|---|---|
| Open a chat | GET /api/dm/conversations/{id}/messages |
200 and a JSON list of messages |
| Send “Hello team” | POST /api/dm/conversations/{id}/messages with {"body":"Hello team"} |
200 and the new message as JSON (id, senderName, body, sentAt, …) |
| Edit your message | PATCH /api/dm/conversations/{id}/messages/{messageId} with {"body":"Hello everyone"} |
200 and the changed message, with edited set to true |
| Edit a message that does not exist | the same PATCH |
404 Not Found |
| Edit someone else’s message | the same PATCH |
403 Forbidden |
| Edit with blank text | the same PATCH |
400 Bad Request |
| Edit a deleted message | the same PATCH |
409 Conflict |
| Delete your message | DELETE /api/dm/conversations/{id}/messages/{messageId} |
204 No Content (a soft delete, as in the CS113 lesson) |
In class, try the first three rows and one blank edit. The rest of the table is for reading.
Two things to notice:
- The
messageIdin the URL is the message’s id, not its position in the list. The server finds the message by that id. - OCS edits with
PATCH, notPUT.PUTreplaces a whole item.PATCHchanges part of it, and an edit only changes the body. Many other APIs usePUTfor updates. The CRUD idea is the same.
The other people in the chat see your edit because the server also sends an edited event over a WebSocket.
The takeaway: CRUD is the idea, the HTTP verb is how it travels, and a method on an object is how the server code changes the data.
Source: DirectMessageApiController (getMessages, postMessage, editMessage, deleteMessage) and DirectMessageService.editMessage in the OCS spring backend, and messages-api.js in the Messages page.
3. Tech Talk (In-Class)
Learning Objective: Change an object by editing its fields in the right method, and say what each CRUD request does to a chat message.
Success Criteria: You can name the verb and status code for each CRUD operation, explain why a parameter with the same name as a field changes nothing, handle an id that does not exist, and tell an alias from a copy.
A chat message is an object. Its fields hold the data:
| Field | Meaning | Example |
|---|---|---|
id |
The number the server gave the message | 1 |
sender |
Who wrote it (OCS calls it senderName) |
"Ada" |
body |
The text | "Hello team" |
edited |
Has the text been changed? | false |
Each CRUD operation lines up with a request and with Java:
| CRUD | HTTP verb | In Java |
|---|---|---|
| Create | POST |
new Message(...), then add to a list |
| Read | GET |
show(), or get from a list |
| Update | PUT or PATCH |
a method such as update(...) that changes fields |
| Delete | DELETE |
set deleted, or remove from a list |
Here is the starter update method. It has a bug. You will find it in the Popcorn Hack.
// Starter code: edit this message
void update(String body) {
body = body;
edited = true;
}
Code Examples (On your own)
A. A Message object. The MessageBasics class has fields, a constructor and show, and no update
The constructor fills in the fields. show turns the message into one line of text. There is no update yet.
Terminology:
this.id = id; copies the parameter id into the field id. The this. is how you reach the field when the parameter has the same name.
Code Runner Challenge
Run it, then add a second Message and predict what show() prints
View IPYNB Source
// CODE_RUNNER: Run it, then add a second Message and predict what show() prints
// A chat message as an object: the fields hold its data and the constructor fills them in.
public class MessageBasics {
static class Message {
int id;
String sender;
String body;
boolean edited;
Message(int id, String sender, String body) {
this.id = id;
this.sender = sender;
this.body = body;
this.edited = false;
}
// Turn the message into one line of text.
String show() {
return "#" + id + " " + sender + ": " + body + (edited ? " (edited)" : "");
}
}
public static void main(String[] args) {
Message first = new Message(1, "Ada", "Hello team");
System.out.println(first.show());
// Try it: remove the // marks, but predict the second line before you run.
// Message second = new Message(2, "Alan", "Ready for the demo?");
// System.out.println(second.show());
}
}
MessageBasics.main(null);
Popcorn Hack (In-Class)
2-minute challenge: trace the starter update before you run it.
- On paper, write
Message m = new Message(1, "Ada", "Hello team");. Tracem.update("Hello everyone");through the starter from the Tech Talk, one line at a time. - Answer both questions in the Popcorn checker under the runner before you run.
- Run the starter runner below and compare its output with your prediction.
- When the checker finishes, copy its line into your submission notes.
Do not fix the starter here. Fixing it is Homework Hack 1.
Code Runner Challenge
Run the starter update and compare its output with your prediction
View IPYNB Source
// CODE_RUNNER: Run the starter update and compare its output with your prediction
// The starter update has a bug. Do not fix it here: this runner only shows what it does.
public class StarterUpdate {
static class Message {
int id;
String sender;
String body;
boolean edited;
Message(int id, String sender, String body) {
this.id = id;
this.sender = sender;
this.body = body;
this.edited = false;
}
// Starter code: edit this message
void update(String body) {
body = body;
edited = true;
}
String show() {
return "#" + id + " " + sender + ": " + body + (edited ? " (edited)" : "");
}
}
public static void main(String[] args) {
Message m = new Message(1, "Ada", "Hello team");
System.out.println("Before: " + m.show());
m.update("Hello everyone");
System.out.println("After update: " + m.show());
}
}
StarterUpdate.main(null);
Before you press Run, predict this output.
4. MCQ Check (In-Class)
4 questions, one at a time. Answer, check, then go to the next one. At the end, copy the score line into your submission notes.
5. Homework Hacks (On your own)
Task: Work up from one message to a whole chat API. Fix the starter update, find a message by its id, then answer requests with status codes. Each starter compiles before you edit it, so you can run the initial version and read its FAIL lines. Change only what the TODO asks for, and keep going until the last line reads ---- N / N passed ----.
Copy these lines into your submission notes as you finish each part:
Lesson: CS111 Chat CRUD
MCQ Chat CRUD: <paste the copied score line, such as 2/4 | answers: A,A,A,A>
Popcorn: <paste the Popcorn checker line>
Homework Hack 1: ---- <N> / 7 passed ----
Homework Hack 2: ---- <N> / 6 passed ----
Homework Hack 3: ---- <N> / 11 passed ----
Submission Safety Rules (Read First)
- Each runner is a complete program ending with
ClassName.main(null);. Run it and leave the output showing. - Do not change the tests below the
Testsline. - Save each runner with its 💾 button before you submit.
Hack 1: Fix update (10 minutes)
Object variable mutation. The starter update from the Tech Talk is in the runner below, with 7 tests. Fix it so the message really changes. You start this hack with your teacher in class and finish it on your own. A fresh Message(1, "Ada", "Hello team") is used for each test.
| Call | Expected |
|---|---|
update("Hello everyone") |
The text changes and the message shows (edited) |
update("First"), then update("Second") |
The last edit wins |
update(" Hello again ") |
The spaces at the ends are removed |
update(" ") or update(null) |
IllegalArgumentException; the message stays as it was and is not marked edited |
Message b = a; b.update("Hi all"); |
a shows the change too |
x.update("Bye") on one message |
A different message y is not touched |
Code Runner Challenge
Fix update until every check prints PASS
View IPYNB Source
// CODE_RUNNER: Fix update until every check prints PASS
// update has a bug. Run the tests, read the FAIL lines, then fix update until you see 7 / 7 passed.
import java.util.function.Supplier;
public class MessageUpdate {
static class Message {
int id;
String sender;
String body;
boolean edited;
Message(int id, String sender, String body) {
this.id = id;
this.sender = sender;
this.body = body;
this.edited = false;
}
// TODO: fix this method. A real edit must:
// - throw IllegalArgumentException if the new text is null or blank (OCS answers 400),
// - store the new text without spaces at the start or end,
// - mark the message as edited.
// A rejected edit must leave the message exactly as it was, and not edited.
void update(String body) {
body = body;
edited = true;
}
String show() {
return "#" + id + " " + sender + ": " + body + (edited ? " (edited)" : "");
}
}
// ---- Tests: do not change below this line ----
static Message fresh() {
return new Message(1, "Ada", "Hello team");
}
static String tryUpdate(Message m, String text) {
try {
m.update(text);
} catch (IllegalArgumentException e) {
return "rejected " + m.show();
} catch (RuntimeException e) {
return "crash: " + e.getClass().getSimpleName();
}
return m.show();
}
public static void main(String[] args) {
Check.that("edit changes the text", "#1 Ada: Hello everyone (edited)",
() -> tryUpdate(fresh(), "Hello everyone"));
Check.that("the last edit wins", "#1 Ada: Second (edited)", () -> {
Message m = fresh();
m.update("First");
return tryUpdate(m, "Second");
});
Check.that("spaces at the ends are trimmed", "#1 Ada: Hello again (edited)",
() -> tryUpdate(fresh(), " Hello again "));
Check.that("blank text is rejected", "rejected #1 Ada: Hello team",
() -> tryUpdate(fresh(), " "));
Check.that("null text is rejected", "rejected #1 Ada: Hello team",
() -> tryUpdate(fresh(), null));
Check.that("two names, one message", "#1 Ada: Hi all (edited)", () -> {
Message a = fresh();
Message b = a;
b.update("Hi all");
return a.show();
});
Check.that("other messages are not touched", "x=#1 Ada: Bye (edited) | y=#2 Alan: Hello team", () -> {
Message x = fresh();
Message y = new Message(2, "Alan", "Hello team");
x.update("Bye");
return "x=" + x.show() + " | y=" + y.show();
});
Check.summary();
}
}
// ---- Test helper (do not edit) ----
class Check {
private static int passed = 0;
private static int total = 0;
// An exception counts as a FAIL so one unfinished method does not stop the other checks.
static void that(String label, String expected, Supplier<String> actual) {
total++;
try {
String got = actual.get();
if (expected.equals(got)) { passed++; System.out.println("PASS " + label); }
else System.out.println("FAIL " + label + ": expected " + expected + ", got " + got);
} catch (Exception e) {
System.out.println("FAIL " + label + " (" + e + ")");
}
}
static void summary() { System.out.println("---- " + passed + " / " + total + " passed ----"); }
}
MessageUpdate.main(null);
Hack 2: Edit a message by its id (10 minutes)
Lookup by id. OCS edits a message by its id, not its position. Write update(int id, String newBody) so it finds the message with this id and replaces its body. Return true if it changed a message, or false if no message has that id, and in that case leave the log unchanged. This runner has a ChatLog built on an ArrayList, as in 4.08. The ids are 10, 20 and 30, so an id is never the same as a position. The runner has no edit method on Message, so write the change yourself. This update(int, String) is a different method, in a different class, from the update in Hack 1.
| Chat log ids 10, 20, 30 | Expected |
|---|---|
update(20, "Ready now") |
true, only message 20 changes |
update(10, "Hi") and update(30, "See you") |
true, only that message changes |
update(99, "x") |
false, the log is unchanged |
update(2, "x") |
false: 2 is a position, not an id |
update(1, "x") on an empty log |
false |
Code Runner Challenge
Write update(id, newBody) until every check prints PASS
View IPYNB Source
// CODE_RUNNER: Write update(id, newBody) until every check prints PASS
// OCS edits a message by its ID, not by its position. Write the same idea for this chat log.
import java.util.ArrayList;
import java.util.function.Supplier;
public class ChatLogUpdate {
static class Message {
int id;
String sender;
String body;
Message(int id, String sender, String body) {
this.id = id;
this.sender = sender;
this.body = body;
}
}
static class ChatLog {
ArrayList<Message> messages = new ArrayList<>();
void add(Message m) {
messages.add(m);
}
// TODO: find the message whose id equals id and replace its body with newBody.
// Return true if you changed a message, or false if no message has that id.
// When nothing is found the log must stay unchanged. The id is NOT the position in the list.
boolean update(int id, String newBody) {
throw new UnsupportedOperationException("update is not written yet");
}
String show() {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < messages.size(); i++) {
Message m = messages.get(i);
if (i > 0) sb.append(" | ");
sb.append("#").append(m.id).append(" ").append(m.sender).append(": ").append(m.body);
}
return sb.append("]").toString();
}
}
// ---- Tests: do not change below this line ----
static ChatLog fresh() {
ChatLog log = new ChatLog();
log.add(new Message(10, "Ada", "Hello"));
log.add(new Message(20, "Alan", "Ready?"));
log.add(new Message(30, "Ada", "Bye"));
return log;
}
static String edit(ChatLog log, int id, String text) {
boolean changed = log.update(id, text);
return changed + " " + log.show();
}
public static void main(String[] args) {
Check.that("edit the middle message", "true [#10 Ada: Hello | #20 Alan: Ready now | #30 Ada: Bye]",
() -> edit(fresh(), 20, "Ready now"));
Check.that("edit the first message", "true [#10 Ada: Hi | #20 Alan: Ready? | #30 Ada: Bye]",
() -> edit(fresh(), 10, "Hi"));
Check.that("edit the last message", "true [#10 Ada: Hello | #20 Alan: Ready? | #30 Ada: See you]",
() -> edit(fresh(), 30, "See you"));
Check.that("a missing id changes nothing", "false [#10 Ada: Hello | #20 Alan: Ready? | #30 Ada: Bye]",
() -> edit(fresh(), 99, "x"));
Check.that("the id is not the position", "false [#10 Ada: Hello | #20 Alan: Ready? | #30 Ada: Bye]",
() -> edit(fresh(), 2, "x"));
Check.that("an empty log has no id to find", "false []",
() -> edit(new ChatLog(), 1, "x"));
Check.summary();
}
}
// ---- Test helper (do not edit) ----
class Check {
private static int passed = 0;
private static int total = 0;
// An exception counts as a FAIL so one unfinished method does not stop the other checks.
static void that(String label, String expected, Supplier<String> actual) {
total++;
try {
String got = actual.get();
if (expected.equals(got)) { passed++; System.out.println("PASS " + label); }
else System.out.println("FAIL " + label + ": expected " + expected + ", got " + got);
} catch (Exception e) {
System.out.println("FAIL " + label + " (" + e + ")");
}
}
static void summary() { System.out.println("---- " + passed + " / " + total + " passed ----"); }
}
ChatLogUpdate.main(null);
Hack 3: Answer requests with status codes (10 minutes)
REST verbs. A server answers every request with a status code. Write handle(String verb, int id, String body) for a tiny server that stores one message. The checks run in order on one server, so each check starts from what the one before left behind. If every check fails, fix POST first. This runner is separate from the other hacks, so write handle yourself. Compare verbs with equals, not ==.
| Verb | What handle does |
Status |
|---|---|---|
POST |
Store a new message with this id and body | 200 |
GET |
Is a message with this id stored? | 200 if yes, 404 if not |
PUT or PATCH |
Edit the body of the stored message | 400 if the body is blank or null, 404 if no message has this id, 409 if the message was deleted, otherwise change the body and 200 |
DELETE |
Soft delete: set the body to "" and deleted to true |
204 if the id is stored, 404 if not |
| anything else | Nothing changes | 405 |
This tiny server is simpler than OCS. It accepts both PUT and PATCH (the OCS chat accepts only PATCH), the caller picks the id (in OCS the server does), and a blank POST is not rejected (OCS answers 400).
Code Runner Challenge
Write handle(verb, id, body) until every check prints PASS
View IPYNB Source
// CODE_RUNNER: Write handle(verb, id, body) until every check prints PASS
// An API answers every request with a status code. Write a tiny version for one chat message.
import java.util.function.Supplier;
public class ChatApi {
static class Message {
int id;
String body;
boolean deleted;
Message(int id, String body) {
this.id = id;
this.body = body;
}
}
// The one message this tiny server stores. null means nothing is stored yet.
Message current;
// TODO: write handle. It receives one request and returns the status code:
// POST store a new message with this id and body, return 200
// GET return 200 if a message with this id is stored, otherwise 404
// PUT or PATCH edit the body of the stored message:
// 400 if body is null or blank; 404 if no message has this id;
// 409 if the message was deleted; otherwise change the body and return 200
// DELETE soft delete: 404 if no message has this id; otherwise set the body to ""
// (an empty String), set deleted to true and return 204
// any other verb return 405
int handle(String verb, int id, String body) {
throw new UnsupportedOperationException("handle is not written yet");
}
// ---- Tests: do not change below this line ----
String state() {
if (current == null) return "none";
if (!current.deleted) return current.body;
return current.body.isEmpty() ? "(deleted)" : "(deleted, text kept: " + current.body + ")";
}
static String send(ChatApi api, String verb, int id, String body) {
// A fresh String each time, so comparing verbs with == would fail here. Use equals.
int status = api.handle(new String(verb), id, body);
return status + " " + api.state();
}
public static void main(String[] args) {
// One server for all checks, in order: each check starts from what the one before left behind.
ChatApi api = new ChatApi();
Check.that("POST stores a message", "200 Hello", () -> send(api, "POST", 1, "Hello"));
Check.that("GET finds it", "200 Hello", () -> send(api, "GET", 1, null));
Check.that("GET with another id is 404", "404 Hello", () -> send(api, "GET", 2, null));
Check.that("PATCH edits the body", "200 Hello again", () -> send(api, "PATCH", 1, "Hello again"));
Check.that("PUT edits the body too", "200 Replaced", () -> send(api, "PUT", 1, "Replaced"));
Check.that("blank text is 400", "400 Replaced", () -> send(api, "PATCH", 1, " "));
Check.that("editing a missing id is 404", "404 Replaced", () -> send(api, "PATCH", 7, "x"));
Check.that("deleting a missing id is 404", "404 Replaced", () -> send(api, "DELETE", 7, null));
Check.that("DELETE is a soft delete", "204 (deleted)", () -> send(api, "DELETE", 1, null));
Check.that("editing a deleted message is 409", "409 (deleted)", () -> send(api, "PATCH", 1, "x"));
Check.that("an unknown verb is 405", "405 (deleted)", () -> send(api, "TRACE", 1, null));
Check.summary();
}
}
// ---- Test helper (do not edit) ----
class Check {
private static int passed = 0;
private static int total = 0;
// An exception counts as a FAIL so one unfinished method does not stop the other checks.
static void that(String label, String expected, Supplier<String> actual) {
total++;
try {
String got = actual.get();
if (expected.equals(got)) { passed++; System.out.println("PASS " + label); }
else System.out.println("FAIL " + label + ": expected " + expected + ", got " + got);
} catch (Exception e) {
System.out.println("FAIL " + label + " (" + e + ")");
}
}
static void summary() { System.out.println("---- " + passed + " / " + total + " passed ----"); }
}
ChatApi.main(null);
Grading Plan (1 Point Total)
| Part | Points | What earns the points |
|---|---|---|
| Popcorn | 0.2 | Both predictions for the starter update written before running, the run compared with them, and the checker line in the notes. |
| MCQ | 0.2 | 4 correct. 0.15 for 2 or 3, 0.1 if every question was answered. |
| Homework Hack 1 | 0.2 | update fixed, 7 / 7 passed. |
| Homework Hack 2 | 0.15 | update(id, newBody) finds the message by id, 6 / 6 passed. |
| Homework Hack 3 | 0.25 | handle returns the right status codes, 11 / 11 passed. |
| Total | 1.0 |
Quick Validation Checklist
- Each runner ends with
ClassName.main(null);and shows output. - The popcorn checker line and the MCQ score are in the notes.
- Every hack runner prints
N / N passed. - Each runner was saved with 💾 before submitting, as the code submission form asks.
- While the assignment is open, you can read the AI feedback, fix your code and submit again.
6. Lesson Revisions
Revision Made: First version. Its facts were checked against the OCS chat source code, and an independent review tightened the Hack 3 tests. It has not been peer-tested yet.
7. Feedback Evidence
No learner feedback has been recorded for this version yet. After a peer does the popcorn and the hacks without help, record what confused them here and revise the lesson.
8. LxD Cycle Process
Empathize: Students see “(edited)” and assume the message changed. They do not see that a parameter with the same name as a field hides the field, so the object never changed. They also treat two variables as two objects, and a message id as a position.
Define:
- POV: CS 111 students need to see that an edit finds one object and changes its fields, because a wrong name or a wrong lookup changes nothing, or the wrong message.
- Learning Goal: Name the verb and status code for each CRUD request, fix an
updatemethod that does not change the object, find a message by id, and explain a404.
Ideate:
- HMW Question: How might we make students trace a field and a parameter that share a name?
- HMW Question: How might we show that an id is not a position?
Prototype:
- Real OCS requests in the Network tab, a popcorn prediction, an MCQ, three self-checking hacks and a grading plan.
Test:
- Ask a peer to do the popcorn and the hacks without help, then revise anything that confused them.
9. References/Citations
Open Coding Society. spring backend (Open-Coding-Society/spring), src/main/java/com/open/spring/mvc/directmessages/:
DirectMessageApiController.java:getMessages,postMessage,editMessage(PATCH) anddeleteMessage.DirectMessageService.java:editMessageanddeleteMessage.
Open Coding Society. pages, Messages page: _projects/systems/messages/js/messages-api.js (the verbs the page sends).
MiraCosta College. Computer Science, course descriptions: CS 111, Introduction to Computer Science I: Java.
Open Coding Society. Lessons used above: 1.9 Method Signatures, 1.12 Classes & Objects, 1.13 Object Creation and Storage, 4.08 ArrayList Methods, Linked List History Deletion (CS113), and AP CSA FRQ 2 Class Writing and Design: 2015 Q2, 2019 Q2.
Submit Assignment
Rate the lesson during class in the 💬 Microblog panel's Ratings tab. Anything you skipped there is finished here.
Need to update a submission later? Open the submissions dashboard.