-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathItemCardAdd.java
More file actions
74 lines (58 loc) · 2.24 KB
/
ItemCardAdd.java
File metadata and controls
74 lines (58 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.queststore.Services;
import com.queststore.DAO.CardDAO;
import com.queststore.DAO.CardDAOSql;
import com.queststore.DAO.DaoException;
import com.queststore.Model.Card;
import com.queststore.Model.CardTypes;
import com.queststore.Model.Categories;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class ItemCardAdd implements HttpHandler {
private CardDAO cardDAO;
ItemCardAdd(CardDAO cardDAO) {
this.cardDAO = cardDAO;
}
public ItemCardAdd() {
this.cardDAO = new CardDAOSql();
}
@Override
public void handle(HttpExchange httpExchange) throws IOException {
JSONparser jsonParser = new JSONparser();
String method = httpExchange.getRequestMethod();
List<String> items = new ArrayList<>();
List<Card> cardList = new ArrayList<>();
if(method.equals("POST")) {
items = jsonParser.parseJSONlistToArray(jsonParser.convertJSONtoString(httpExchange));
}
try {
cardList = addCardToDB(items);
} catch (DaoException e) {
e.printStackTrace();
}
JtwigTemplate template = JtwigTemplate.classpathTemplate("templates/mentor-items.twig");
JtwigModel model = JtwigModel.newModel();
model.with("cardsList", cardList);
// render a template to a string
String response = template.render(model);
// send the results to a the client
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
public List<Card> addCardToDB(List<String> items) throws DaoException {
List<Card> cardList = new ArrayList<>();
int artifactTypeId = 2;
Card newCard = new Card(4, items.get(0), items.get(2), new Categories(1, "easy"), null,
Integer.parseInt((String) items.get(1)), new CardTypes(artifactTypeId, "artifact"), true);
cardDAO.add(newCard);
cardList.add(newCard);
return cardList;
}
}