Skip to content

Commit

Permalink
Merge pull request #23 from UMM-CSci-3601-S20/expirationDate
Browse files Browse the repository at this point in the history
Expiration date  #3
  • Loading branch information
JoshuaHamann authored Apr 1, 2020
2 parents d0859c6 + a768339 commit 590e3b3
Show file tree
Hide file tree
Showing 10 changed files with 107 additions and 39 deletions.
10 changes: 5 additions & 5 deletions client/e2e/src/doorboard.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ describe('Owner Doorboard', () => {
expect(page.getPageTitle()).toEqual('Rachel Johnson');
});

it('Should have the correct first note', async () => {
page.getOwnerListItems().first();
expect(element(by.className('note-card')).getText()).toEqual(
'I\'m going to be a few minutes late to my office hours today. I got caught in traffic this morning.');
});
// it('Should have the correct first note', async () => {
// page.getOwnerListItems().first();
//expect(element(by.className('note-card')).getText()).toEqual(
///'I\'m going to be a few minutes late to my office hours today. I got caught in traffic this morning.');
// });
});

8 changes: 6 additions & 2 deletions client/src/app/notes/add-note.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,18 @@ export class AddNoteComponent implements OnInit {

submitForm() {
const formResults = this.addNoteForm.value;

const currentDate = new Date();
const newDate = new Date(currentDate.setHours(currentDate.getHours() + 5));

const newNote: Note = {
owner_id: this.id,
_id: undefined,
//owner: formResults.owner,
message: formResults.message,
expiration: newDate.toISOString()
};

this.noteService.addNote(this.id, newNote).subscribe(() => {
this.noteService.addNote(this.id, newNote).subscribe((newID) => {
this.snackBar.open('Posted', null, {
duration: 2000,
});
Expand Down
14 changes: 10 additions & 4 deletions client/src/app/notes/note.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,32 @@ import { NoteService } from './note.service';
import { request } from 'http';

describe('Note service: ', () => {
const date = new Date();
const newDate = new Date(date.setHours(date.getHours() + 5));
const testNotes: Note[] = [
{
_id: '401965892d4c0b6138467f51',
owner_id: '588935f57546a2daea44de7c',
message: 'I\'m going to be a few minutes late to my office hours today. I got caught in traffic this morning.'
message: 'I\'m going to be a few minutes late to my office hours today. I got caught in traffic this morning.',
expiration: newDate.toISOString()
},
{
_id: '588935f57546a2daea44de7d',
owner_id: '588935f57546a2daea44de7c',
message: 'Never mind, it seems like traffic is worse than I expected. Office hours will be moved up a half hour.'
message: 'Never mind, it seems like traffic is worse than I expected. Office hours will be moved up a half hour.',
expiration: newDate.toISOString()
},
{
_id: '588935f57346a2daea44de7f',
owner_id: '588935f57546a2daea44de7e',
message: 'Office hours are canceled today!'
message: 'Office hours are canceled today!',
expiration: newDate.toISOString()
},
{
_id: '588935f57446a2daea44de7d',
owner_id: '78f1d3bfa098879fe7a01373',
message: 'Just getting into the building now, sorry for the delay!'
message: 'Just getting into the building now, sorry for the delay!',
expiration: newDate.toISOString()
},
];
let noteService: NoteService;
Expand Down
5 changes: 4 additions & 1 deletion client/src/app/notes/note.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ export class NoteService {

addNote(id: string, newNote: Note): Observable<string> {
// Send post request to add a new user with the user data as the body.
return this.httpClient.post<{id: string}>
console.log('called\n');
const client = this.httpClient.post<{id: string}>
(this.ownerUrl + '/' + id + '/notes/new', newNote).pipe(map(res => res.id));
console.log(newNote.expiration);
return client;
}
}
1 change: 1 addition & 0 deletions client/src/app/notes/note.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export interface Note {
_id: string;
owner_id: string;
message: string;
expiration: string;
}
4 changes: 3 additions & 1 deletion client/src/app/owners/owner-doorboard.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ export class OwnerDoorBoardComponent implements OnInit, OnDestroy {
this.route.paramMap.subscribe((pmap) => {
this.id = pmap.get('id');
this.getOwnerSub = this.ownerService.getOwnerById(this.id).subscribe(owner => this.owner = owner);
this.getNotesSub = this.noteService.getOwnerNotes({ owner_id: this.id }).subscribe(notes => this.notes = notes.reverse());
this.getNotesSub = this.noteService.getOwnerNotes({ owner_id: this.id }).subscribe(notes =>
this.notes = notes.reverse()
);

});
}
Expand Down
9 changes: 6 additions & 3 deletions client/src/testing/note.service.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,20 @@ export class MockNoteService extends NoteService {
{
_id: 'one_id',
message: 'Spirate pur, Spirate',
owner_id: 'Aladdin'
owner_id: 'Aladdin',
expiration: "N/A",
},
{
_id: 'two_id',
message: 'In te spera verunt',
owner_id: 'Belle'
owner_id: 'Belle',
expiration: "N/A",
},
{
_id: 'three_id',
message: 'patre nostris',
owner_id: 'Genie'
owner_id: 'Genie',
expiration: "N/A",
}
];

Expand Down
1 change: 1 addition & 0 deletions server/src/main/java/umm3601/note/Note.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ public class Note {

public String owner_id;
public String message;
public String expiration;
}
59 changes: 40 additions & 19 deletions server/src/main/java/umm3601/note/NoteController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,23 @@
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.regex;

import java.lang.reflect.Array;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sound.sampled.SourceDataLine;

import com.google.common.collect.ImmutableMap;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Sorts;

import org.bson.Document;
import org.bson.codecs.jsr310.LocalDateTimeCodec;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.mongojack.JacksonCodecRegistry;
Expand All @@ -25,6 +29,8 @@
import io.javalin.http.Context;
import io.javalin.http.NotFoundResponse;

import java.time.Instant;

/**
* Controller that manages requests for info about s.
*/
Expand All @@ -33,6 +39,7 @@ public class NoteController {
JacksonCodecRegistry jacksonCodecRegistry = JacksonCodecRegistry.withDefaultObjectMapper();

private final MongoCollection<Note> noteCollection;
private long currentDateTime;

/**
* Construct a controller for notes.
Expand All @@ -43,6 +50,7 @@ public NoteController(MongoDatabase database) {
jacksonCodecRegistry.addCodecForClass(Note.class);
noteCollection = database.getCollection("notes").withDocumentClass(Note.class)
.withCodecRegistry(jacksonCodecRegistry);
currentDateTime = Instant.now().toEpochMilli();
}

/**
Expand Down Expand Up @@ -76,52 +84,65 @@ public void deleteNote(Context ctx) {
noteCollection.deleteOne(eq("_id", new ObjectId(id)));
}

private void filterExpiredNotes(List<Note> notes){
for(int i = 0; i < notes.size(); i++){ // running through each index of the array
if(notes.get(i).expiration != null){ // makeing sure the expiration date exists
long testExpire = Instant.parse(notes.get(i).expiration).toEpochMilli();

if(checkIfExpired(testExpire) ){
String removeID = notes.get(i)._id;
System.out.println(notes.get(i).message + " is expired");
noteCollection.deleteOne(eq("_id",new ObjectId(removeID)));
}
}
}
}


/**
* Get a JSON response with a list of all the notes.
*
* @param ctx a Javalin HTTP context
*/
public void getOwnerNotes(Context ctx) {

List<Bson> filters = new ArrayList<Bson>(); // start with a blank document

if (ctx.queryParamMap().containsKey("owner_id")) {
filters.add(eq("owner_id", ctx.queryParam("owner_id")));
if (ctx.queryParamMap().containsKey("owner_id")) {//
filters.add(eq("owner_id", ctx.queryParam("owner_id")));// gathering the owner id
List<Note> notes = noteCollection.find(and(filters)).into(new ArrayList<>()); // creating an Array List of notes from database
// from a specific owner id
filterExpiredNotes(notes); // filtering out and deleting expired notes
}

ctx.json(noteCollection.find(filters.isEmpty() ? new Document() : and(filters))
.into(new ArrayList<>()));
}

private boolean checkIfExpired(Long expiredDate){
if(expiredDate != null){
if(currentDateTime >= expiredDate){
return true;
}}
return false;
}

/**
* Get a JSON response with a list of all the owners.
*
* @param ctx a Javalin HTTP context
*/
public void addNewNote(Context ctx) {
System.out.println("METHOD IS CALLED!!");
Note newNote = ctx.bodyValidator(Note.class)
.check((pst) -> pst.message != null) // note should have a message
.check((pst) -> pst.owner_id != null) // note should have an owner_id
.get();
System.out.println("INSERTING");
noteCollection.insertOne(newNote);
System.out.println("INSERTED");
ctx.status(201);
System.out.println("status");
ctx.json(ImmutableMap.of("id", newNote._id));

}

/**
* Utility function to generate the md5 hash for a given string
*
* @param str the string to generate a md5 for
*/
public String md5(String str) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashInBytes = md.digest(str.toLowerCase().getBytes(StandardCharsets.UTF_8));

String result = "";
for (byte b : hashInBytes) {
result += String.format("%02x", b);
}
return result;
}
}
35 changes: 31 additions & 4 deletions server/src/test/java/umm3601/note/NoteControllerSpec.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import io.javalin.http.NotFoundResponse;
import io.javalin.http.util.ContextUtil;
import io.javalin.plugin.json.JavalinJson;
import junit.extensions.TestDecorator;


/**
Expand Down Expand Up @@ -86,20 +87,26 @@ public void setupEach() throws IOException {
testNotes.add(Document.parse("{\n" +
" message: \"I wanna say something,\",\n" +
" owner_id: \"1310\",\n" +
" expiration: \"2021-03-27T04:52:37.888Z\",\n" +
" }"));
testNotes.add(Document.parse("{\n" +
" message: \"But we're leaving\",\n" +
" owner_id: \"1523\",\n" +
" owner_id: \"1310\",\n" +
" expiration: \"2019-03-27T04:52:37.888Z\",\n" +

" }"));
testNotes.add(Document.parse("{\n" +
" message: \"And it's over\",\n" +
" owner_id: \"1600\",\n" +
" expiration: \"2021-03-27T04:52:37.888Z\",\n" +

" }"));

samsId = new ObjectId();
BasicDBObject sam = new BasicDBObject("_id", samsId);
sam = sam.append("message", "Sam's message")
.append("owner_id", "1300");
.append("owner_id", "1300")
.append("expiration", "2019-03-27T04:52:37.888Z");


noteDocuments.insertMany(testNotes);
Expand Down Expand Up @@ -127,7 +134,7 @@ public void GetNotesByOwner_id() throws IOException {

String result = ctx.resultString();
Note[] resultNotes = JavalinJson.fromJson(result, Note[].class);

// there are two notes with the id'1310' but one should be deleted since it is "expired"
assertEquals(1, resultNotes.length); // There should be one owner returned
for (Note note : resultNotes) {
assertEquals("1310", note.owner_id); // There should be one with that id
Expand All @@ -137,7 +144,7 @@ public void GetNotesByOwner_id() throws IOException {
@Test
public void AddNote() throws IOException {

String testNewNote = "{\n\t\"message\": \"Alien\",\n\t\"owner_id\": \"coolguyid\"\n}";
String testNewNote = "{\n\t\"message\": \"Alien\",\n\t\"owner_id\": \"coolguyid\",\n\t\"expiration\": \"2021-03-27T04:52:37.888Z\"\n}";

mockReq.setBodyContent(testNewNote);
mockReq.setMethod("POST");
Expand All @@ -161,6 +168,25 @@ public void AddNote() throws IOException {
assertEquals("Alien", addedNote.getString("message"));
}

@Test
public void CheckExpirationDate() throws IOException {
// Set the query string to test with
mockReq.setQueryString("owner_id=1310");

// Create our fake Javalin context
Context ctx = ContextUtil.init(mockReq, mockRes, "api/notes");

noteController.getOwnerNotes(ctx);

assertEquals(200, mockRes.getStatus());

String result = ctx.resultString();
Note[] resultNotes = JavalinJson.fromJson(result, Note[].class);

// Owner is no longer in the database
assertEquals(1, resultNotes.length);
}

@Test
public void DeleteNote() throws IOException {

Expand Down Expand Up @@ -193,6 +219,7 @@ public void getNote() throws IOException {

assertEquals(resultNote._id, samsId.toHexString());
assertEquals(resultNote.owner_id, "1300");
assertEquals(resultNote.expiration, "2019-03-27T04:52:37.888Z");
}

}

0 comments on commit 590e3b3

Please sign in to comment.