Login Bugfix + put&get /users/{username} + get /cards

This commit is contained in:
Georg Reisinger 2020-12-29 20:09:26 +01:00
parent e9fcbb36dc
commit 0b1d3ad677
10 changed files with 288 additions and 122 deletions

View File

@ -60,15 +60,7 @@ public class Card {
*/ */
private ElementTyp stringToElementType(String elementTypeString){ private ElementTyp stringToElementType(String elementTypeString){
for (ElementTyp e : ElementTyp.values()) { for (ElementTyp e : ElementTyp.values()) {
System.out.println(e.toString().toLowerCase());
System.out.println(elementTypeString.toLowerCase().contains(e.name().toLowerCase()));
if (elementTypeString.toLowerCase().contains(e.name().toLowerCase())) { if (elementTypeString.toLowerCase().contains(e.name().toLowerCase())) {
System.out.println("\n\n\n");
System.out.println("####Element####, me.name() : elementTypeString");
System.out.println(e.name().toLowerCase());
System.out.print(" : ");
System.out.println(elementTypeString.toLowerCase());
System.out.println("\n\n\n");
return e; return e;
} }
} }
@ -81,20 +73,8 @@ public class Card {
* @return Passender Card Type oder null falls nicht gefunden * @return Passender Card Type oder null falls nicht gefunden
*/ */
private CardType stringToCardType(String cardTypeString){ private CardType stringToCardType(String cardTypeString){
System.out.println("\n\n\n");
System.out.println("###CARD###, me.name() : cardTypeString\n");
for (CardType me : CardType.values()) { for (CardType me : CardType.values()) {
System.out.println("\n\n\n");
System.out.print(me.name().toLowerCase());
System.out.print(" : ");
System.out.println(cardTypeString.toLowerCase());
System.out.println("\n\n\n");
if (cardTypeString.toLowerCase().contains(me.toString().toLowerCase())) { if (cardTypeString.toLowerCase().contains(me.toString().toLowerCase())) {
System.out.println("\n\n\n");
System.out.print(me.name().toLowerCase());
System.out.print(" : ");
System.out.println(cardTypeString.toLowerCase());
System.out.println("\n\n\n");
return me; return me;
} }
} }

View File

@ -1,19 +1,25 @@
package at.reisinger; package at.reisinger;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
/** /**
* Verwaltet eine Liste vo at.reisinger.Cards * Verwaltet eine Liste vo at.reisinger.Cards
*/ */
@JsonAutoDetect
public class Cards { public class Cards {
@JsonDeserialize(as = ArrayList.class, contentAs = Card.class)
private ArrayList<Card> cards; private ArrayList<Card> cards;
/** /**
* Erstellt ein nues obj mit gegebenen Karten * Erstellt ein nues obj mit gegebenen Karten
* @param cardsArrayList Die at.reisinger.Cards zum erstellen des Obj * @param cardsArrayList Die at.reisinger.Cards zum erstellen des Obj
*/ */
public Cards(ArrayList<Card> cardsArrayList) { @JsonCreator
public Cards(@JsonProperty("cards") ArrayList<Card> cardsArrayList) {
this.cards = cardsArrayList; this.cards = cardsArrayList;
} }
@ -23,6 +29,7 @@ public class Cards {
* Fügt eine neue at.reisinger.Card hinzu * Fügt eine neue at.reisinger.Card hinzu
* @param newCard neue at.reisinger.Card * @param newCard neue at.reisinger.Card
*/ */
@JsonSetter
public void addCard(Card newCard) { public void addCard(Card newCard) {
this.cards.add(newCard); this.cards.add(newCard);
} }
@ -31,6 +38,7 @@ public class Cards {
* Holt alle at.reisinger.Cards * Holt alle at.reisinger.Cards
* @return Alle at.reisinger.Cards * @return Alle at.reisinger.Cards
*/ */
@JsonGetter
public ArrayList<Card> getCards() { public ArrayList<Card> getCards() {
return this.cards; return this.cards;
} }

View File

@ -10,8 +10,8 @@ import java.util.ArrayList;
* Die "Datenbank" sind hier nur beispieldaten. * Die "Datenbank" sind hier nur beispieldaten.
*/ */
public class DBConnection { public class DBConnection {
private ArrayList<TradingDeal> tradingDeals; //private ArrayList<TradingDeal> tradingDeals;
private ArrayList<Package> packages; //private ArrayList<Package> packages;
private Connection c; private Connection c;
private Statement stmt; private Statement stmt;
@ -28,7 +28,7 @@ public class DBConnection {
* Erstellt alle Tabellen die für den Betrieb der Software bennötigt werden * Erstellt alle Tabellen die für den Betrieb der Software bennötigt werden
*/ */
public void init() { public void init() {
PostgresHelper.executeUpdateMessage("CREATE TABLE IF NOT EXISTS USERS (username TEXT PRIMARY KEY NOT NULL, nachname TEXT NOT NULL, email TEXT NOT NULL, password TEXT NOT NULL)", "User Table created"); PostgresHelper.executeUpdateMessage("CREATE TABLE IF NOT EXISTS USERS (username TEXT PRIMARY KEY NOT NULL, nachname TEXT NOT NULL, email TEXT NOT NULL, password TEXT NOT NULL, bio TEXT, image TEXT, coins integer default 20 not null)", "User Table created");
PostgresHelper.executeUpdate("CREATE TABLE IF NOT EXISTS CARD(NAME TEXT not null,DAMAGE FLOAT not null,ELEMENTTYP TEXT not null,CARDTYPE TEXT not null, PRIMARY KEY (\"name\"));"); PostgresHelper.executeUpdate("CREATE TABLE IF NOT EXISTS CARD(NAME TEXT not null,DAMAGE FLOAT not null,ELEMENTTYP TEXT not null,CARDTYPE TEXT not null, PRIMARY KEY (\"name\"));");
PostgresHelper.executeUpdateMessage("create unique index IF NOT EXISTS card_name_uindex on CARD (NAME);", "Card Table created"); PostgresHelper.executeUpdateMessage("create unique index IF NOT EXISTS card_name_uindex on CARD (NAME);", "Card Table created");
PostgresHelper.executeUpdateMessage("create table IF NOT EXISTS package(\"ID\" varchar(255) not null,name varchar(255) not null constraint name references card, i serial not null constraint package_i primary key );", "Package Table created"); PostgresHelper.executeUpdateMessage("create table IF NOT EXISTS package(\"ID\" varchar(255) not null,name varchar(255) not null constraint name references card, i serial not null constraint package_i primary key );", "Package Table created");
@ -42,13 +42,11 @@ public class DBConnection {
* @return Das Package aus dem Shop, null falls ein Fehler auftritt * @return Das Package aus dem Shop, null falls ein Fehler auftritt
*/ */
public Package userAcquirePackage(String username) { public Package userAcquirePackage(String username) {
System.out.println("Vor den coins");
int coins = checkCoins(username); int coins = checkCoins(username);
if (!(coins - 5 >= 0)) { if (!(coins - 5 >= 0)) {
return null; return null;
} }
updateCoins(coins - 5, username); updateCoins(coins - 5, username);
System.out.println("nach den soins");
this.c = PostgresHelper.con(); this.c = PostgresHelper.con();
String id = ""; String id = "";
@ -57,8 +55,6 @@ public class DBConnection {
ResultSet rs = stmt.executeQuery("select \"ID\" as id from package LIMIT 1;"); ResultSet rs = stmt.executeQuery("select \"ID\" as id from package LIMIT 1;");
while (rs.next()) { while (rs.next()) {
id = rs.getString("id"); id = rs.getString("id");
System.out.println("id = " + id);
System.out.println();
} }
rs.close(); rs.close();
stmt.close(); stmt.close();
@ -87,12 +83,10 @@ public class DBConnection {
damage = rs.getInt("damage"); damage = rs.getInt("damage");
Card newCard = new Card(cardname, elementtyp + cardtype, damage); Card newCard = new Card(cardname, elementtyp + cardtype, damage);
cards.addCard(newCard); cards.addCard(newCard);
System.out.println();
Connection b = PostgresHelper.con(); Connection b = PostgresHelper.con();
try { try {
stmt = b.createStatement(); stmt = b.createStatement();
String sql = "INSERT INTO public.user_cards (username, name, gesperrt) VALUES ( \'" + username + "\',\'" + newCard.getName() + "\', \'false\');"; String sql = "INSERT INTO public.user_cards (username, name, gesperrt) VALUES ( \'" + username + "\',\'" + newCard.getName() + "\', \'false\');";
System.out.println(sql);
stmt.executeUpdate(sql); stmt.executeUpdate(sql);
stmt.close(); stmt.close();
b.close(); b.close();
@ -154,8 +148,6 @@ public class DBConnection {
ResultSet rs = stmt.executeQuery("Select coins from users where username = \'" + username + "\';"); ResultSet rs = stmt.executeQuery("Select coins from users where username = \'" + username + "\';");
while (rs.next()) { while (rs.next()) {
coins = rs.getInt("coins"); coins = rs.getInt("coins");
System.out.println("Count: ");
System.out.print(coins);
} }
rs.close(); rs.close();
stmt.close(); stmt.close();
@ -183,8 +175,6 @@ public class DBConnection {
ResultSet rs = stmt.executeQuery("select count(*) from card where name = \'" + name + "\';"); ResultSet rs = stmt.executeQuery("select count(*) from card where name = \'" + name + "\';");
while (rs.next()) { while (rs.next()) {
count = rs.getInt("count"); count = rs.getInt("count");
System.out.println("Count: ");
System.out.print(count);
} }
rs.close(); rs.close();
stmt.close(); stmt.close();
@ -234,8 +224,6 @@ public class DBConnection {
System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.err.println(e.getClass().getName() + ": " + e.getMessage());
return 0; return 0;
} }
System.out.println("Package Next id is: ");
System.out.print(id);
return Integer.parseInt(id) + 1; return Integer.parseInt(id) + 1;
} }
@ -270,8 +258,25 @@ public class DBConnection {
* @param email Email des Users * @param email Email des Users
* @return True wenn alles erfolgreich war, false wenn es nicht erfolgreich war * @return True wenn alles erfolgreich war, false wenn es nicht erfolgreich war
*/ */
public boolean addUser(String username, String password, String nachname, String email) { public boolean addUser(String username, String password, String nachname, String email, String bio, String image) {
return PostgresHelper.executeUpdateMessage("INSERT INTO users (username, nachname, email, password) values (\'" + username + "\',\'" + nachname + "\',\'" + email + "\',\'" + password + "\')", "User added"); return PostgresHelper.executeUpdateMessage("INSERT INTO users (username, nachname, email, password, bio, image) values (\'" + username + "\',\'" + nachname + "\',\'" + email + "\',\'" + password + "\',\'" + bio + "\',\'" + image + "\')", "User added");
}
/**
* Updated den Nachnamen, Bio und das Image eines Users mit gegebenen usernamen
* @param username User der geändert werden soll
* @param bio Neue BIO
* @param image Neues Image
* @param name Neuer Nachname
* @return True bei erfolg, sonst false
*/
public boolean updateUser(String username, String bio, String image, String name){
System.out.println("UPDATE public.users SET nachname = \'"+ name+"\', bio = \'"+bio+"\', image = \'"+image+"\' WHERE username LIKE \'"+username+"\' ESCAPE \'#\'");
return PostgresHelper.executeUpdate("UPDATE public.users SET nachname = \'"+ name+"\', bio = \'"+bio+"\', image = \'"+image+"\' WHERE username LIKE \'"+username+"\' ESCAPE \'#\'");
}
/**
private boolean updateUser(String username, String name, String bio, String image){
return PostgresHelper.executeUpdate("UPDATE public.users SET nachname = \'"+ name +"\', bio = \'"+bio+"\', image = \'"+image+"\' WHERE username LIKE \'"+username+"\' ESCAPE \'#\'");
} }
/** /**
@ -279,12 +284,12 @@ public class DBConnection {
* Gibt ein User Objekt zurück * Gibt ein User Objekt zurück
* *
* @param uname Username der zu suchen ist * @param uname Username der zu suchen ist
* @return User als User Objekt * @return User als User Objekt, null bei fehler
* @throws SQLException Fehler bei der Suche in der DB * @throws SQLException Fehler bei der Suche in der DB
*/ */
public User getUser(String uname) throws SQLException { public User getUser(String uname) throws SQLException {
this.c = PostgresHelper.con(); this.c = PostgresHelper.con();
String username = "", password = "", email = "", nachname = ""; String username = "", password = "", email = "", nachname = "", bio="", image="";
try { try {
stmt = this.c.createStatement(); stmt = this.c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users where username = \'" + uname + "\';"); ResultSet rs = stmt.executeQuery("SELECT * FROM users where username = \'" + uname + "\';");
@ -293,11 +298,37 @@ public class DBConnection {
nachname = rs.getString("nachname"); nachname = rs.getString("nachname");
email = rs.getString("email"); email = rs.getString("email");
password = rs.getString("password"); password = rs.getString("password");
System.out.println("username = " + username); bio = rs.getString("bio");
System.out.println("nachname = " + nachname); image = rs.getString("image");
System.out.println("email = " + email); }
System.out.println("password = " + password); rs.close();
System.out.println(); stmt.close();
this.c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
return null;
}
System.out.println("User pulled successfully");
return new User(new Credentials(username, password), username, username, email, new Coins(20), bio, image);
}
/**
* Holt alle Karten eines Users
* @param username Username des Users
* @return Cards Object, falls es null ist, war ein fehler
*/
public Cards getCards(String username){
this.c = PostgresHelper.con();
String cardname = "";
Cards allCards = new Cards(new ArrayList<Card>());
ArrayList<String> cardnamenarray = new ArrayList<String>();
try {
stmt = this.c.createStatement();
ResultSet rs = stmt.executeQuery("select * from user_cards where username = \'" + username + "\';");
while (rs.next()) {
cardname = rs.getString("name");
cardnamenarray.add(cardname);
System.out.println("cardname = " + cardname);
} }
rs.close(); rs.close();
stmt.close(); stmt.close();
@ -306,15 +337,40 @@ public class DBConnection {
System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0); System.exit(0);
} }
System.out.println("Operation done successfully"); System.out.println("Card Namen pulled successfully");
return new User(new Credentials(username, password), username, username, email, new Coins(20)); for (String st : cardnamenarray) {
Connection b = PostgresHelper.con();
try {
stmt = b.createStatement();
ResultSet rs = stmt.executeQuery("select * from card where NAME = \'" + st + "\';");
while (rs.next()) {
int damage =rs.getInt("damage");
String elementtyp =rs.getString("elementtyp");
String cardtype=rs.getString("cardtype");
System.out.println("damage = " + damage);
System.out.println("elementtyp = " + elementtyp);
System.out.println("cardtype = " + cardtype);
System.out.println();
allCards.addCard(new Card(st, elementtyp+cardtype, damage));
}
rs.close();
stmt.close();
b.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Card pulled successfully");
}
return allCards;
} }
/** /**
* Holt alle verfügbaren TradingDeals * Holt alle verfügbaren TradingDeals
* *
* @return Alle Trading Deals * @return Alle Trading Deals
*/
public ArrayList<TradingDeal> getAllTradingDeals() { public ArrayList<TradingDeal> getAllTradingDeals() {
return this.tradingDeals; return this.tradingDeals;
} }
@ -323,9 +379,9 @@ public class DBConnection {
* Fügt einen neuen Tradingdeal zum at.reisinger.Store hinzu * Fügt einen neuen Tradingdeal zum at.reisinger.Store hinzu
* *
* @param tradingDeal Der neue Deal * @param tradingDeal Der neue Deal
*/
public void addTradingDeal(TradingDeal tradingDeal) { public void addTradingDeal(TradingDeal tradingDeal) {
this.tradingDeals.add(tradingDeal); this.tradingDeals.add(tradingDeal);
} }
*/
} }

View File

@ -8,9 +8,9 @@ import java.util.ArrayList;
* at.reisinger.User & at.reisinger.Store Logik * at.reisinger.User & at.reisinger.Store Logik
*/ */
@JsonAutoDetect @JsonAutoDetect
public class User implements Store{ public class User{
@JsonProperty @JsonProperty
private String name, nachname, email; private String name, nachname, email, bio, image;
/* /*
@JsonProperty @JsonProperty
private Stack stack; private Stack stack;
@ -42,16 +42,54 @@ public class User implements Store{
} }
*/ */
@JsonCreator @JsonCreator
public User(@JsonProperty Credentials credentials,@JsonProperty String name,@JsonProperty String nachname,@JsonProperty String email,@JsonProperty Coins coins) { public User(@JsonProperty Credentials credentials,@JsonProperty String name,@JsonProperty String nachname,@JsonProperty String email,@JsonProperty Coins coins, @JsonProperty String bio, @JsonProperty String image) {
this.credentials = credentials; this.credentials = credentials;
this.name = name; this.name = name;
this.nachname = nachname; this.nachname = nachname;
this.email = email; this.email = email;
//this.stack = null; //this.stack = null;
this.coins = coins; this.coins = coins;
this.bio = bio;
this.image = image;
//this.db = new at.reisinger.DBConnection(); //this.db = new at.reisinger.DBConnection();
} }
/**
* Holt die Bio vom User
* @return Bio des Users
*/
@JsonGetter
public String getBio() {
return bio;
}
/**
* Setzt die Bio vom User
* @param bio Bio des Users
*/
@JsonSetter
public void setBio(String bio) {
this.bio = bio;
}
/**
* Holt das image vom user
* @return Image vom user
*/
@JsonGetter
public String getImage() {
return image;
}
/**
* Setzt das image vom user
* @param image Image vom user
*/
@JsonSetter
public void setImage(String image) {
this.image = image;
}
/** /**
* Holt den at.reisinger.Stack des Users * Holt den at.reisinger.Stack des Users
* @return at.reisinger.Stack des Users * @return at.reisinger.Stack des Users
@ -199,15 +237,16 @@ public class User implements Store{
/** /**
* Fügt dem at.reisinger.Store einen neuen Tradingdeal hinzu * Fügt dem at.reisinger.Store einen neuen Tradingdeal hinzu
* @param tradingDeal Der neue Tradingdeal * @param tradingDeal Der neue Tradingdeal
*/ *
public void addTradingDeal(TradingDeal tradingDeal) { public void addTradingDeal(TradingDeal tradingDeal) {
new DBConnection().addTradingDeal(tradingDeal); new DBConnection().addTradingDeal(tradingDeal);
} }
/** /**
* Holt alle verfügbaren Tradingdeals * Holt alle verfügbaren Tradingdeals
* @return Alle verfügbaren Deals * @return Alle verfügbaren Deals
*/ *
public ArrayList<TradingDeal> getTradingDeals() { public ArrayList<TradingDeal> getTradingDeals() {
return new DBConnection().getAllTradingDeals(); return new DBConnection().getAllTradingDeals();
} }
@ -237,7 +276,7 @@ public class User implements Store{
* Gibt alle Möglichen Trading Deals zurück * Gibt alle Möglichen Trading Deals zurück
* @param toTrade Prüft nach diesem Deal * @param toTrade Prüft nach diesem Deal
* @return * @return
*/ *
@Override @Override
public ArrayList<TradingDeal> getPossibleTradingDeals(Card toTrade) { public ArrayList<TradingDeal> getPossibleTradingDeals(Card toTrade) {
ArrayList<TradingDeal> storeList = new DBConnection().getAllTradingDeals(); ArrayList<TradingDeal> storeList = new DBConnection().getAllTradingDeals();
@ -251,6 +290,7 @@ public class User implements Store{
return possible; return possible;
} }
*/
/** /**
* Checkt ob es sich um den selben at.reisinger.User handelt * Checkt ob es sich um den selben at.reisinger.User handelt
* @param toCheck Mit diesem at.reisinger.User wird verglichen * @param toCheck Mit diesem at.reisinger.User wird verglichen

View File

@ -3,6 +3,7 @@ package at.reisinger.server.helper;
import at.reisinger.Card; import at.reisinger.Card;
import at.reisinger.Cards; import at.reisinger.Cards;
import at.reisinger.Package; import at.reisinger.Package;
import at.reisinger.User;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@ -23,21 +24,21 @@ public class JsonHelper {
*/ */
public static String packageListToJson(ArrayList<Card> listCards, String name){ public static String packageListToJson(ArrayList<Card> listCards, String name){
Package packageCards = new Package(new Cards(listCards),name, 5); Package packageCards = new Package(new Cards(listCards),name, 5);
return packageToJson(packageCards); return objToJson(packageCards);
} }
/** /**
* Wandelt ein Package Objekt in ein Json um * Wandelt ein Package Objekt in ein Json um
* @param packageCards Package Objekt das in ein Json umgewandelt werden soll * @param obj Objekt das in ein Json umgewandelt werden soll
* @return Json String des Packages * @return Json String des Packages
*/ */
public static String packageToJson(Package packageCards){ public static String objToJson(Object obj){
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
objectMapper = new ObjectMapper(); objectMapper = new ObjectMapper();
String packageJson = ""; String packageJson = "";
if(packageCards != null) { if(obj != null) {
try { try {
packageJson += objectMapper.writeValueAsString(packageCards); packageJson += objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
packageJson = "Error: JsonProcessingException -> " + e.getMessage(); packageJson = "Error: JsonProcessingException -> " + e.getMessage();
} }
@ -47,7 +48,7 @@ public class JsonHelper {
} }
} }
public static Map<String, Object> jsonPayload2ToMap(String payload){ public static Map<String, Object> jsonPayloadToMap(String payload){
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
try { try {
return objectMapper.readValue(payload, new TypeReference<Map<String,Object>>(){}); return objectMapper.readValue(payload, new TypeReference<Map<String,Object>>(){});
@ -57,4 +58,21 @@ public class JsonHelper {
} }
} }
public static String userToJson(User user){
//User to json
ObjectMapper objectMapper = new ObjectMapper();
objectMapper = new ObjectMapper();
String userJson = "";
if(user != null) {
try {
userJson += objectMapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
userJson = "Error: JsonProcessingException -> " + e.getMessage();
}
return userJson;
}else{
return null;
}
}
} }

View File

@ -34,9 +34,8 @@ public class PostgresHelper {
* @return True bei erfolg, sonst false * @return True bei erfolg, sonst false
*/ */
public static boolean executeUpdateMessage(String sql, String message){ public static boolean executeUpdateMessage(String sql, String message){
boolean tmp = executeUpdate(sql);
System.out.println(message); System.out.println(message);
return tmp; return executeUpdate(sql);
} }
/** /**

View File

@ -3,6 +3,7 @@ package at.reisinger.server.objects;
import at.reisinger.*; import at.reisinger.*;
import at.reisinger.Package; import at.reisinger.Package;
import at.reisinger.server.helper.JsonHelper; import at.reisinger.server.helper.JsonHelper;
import at.reisinger.server.helper.PostgresHelper;
import at.reisinger.server.msg.MsgHandler; import at.reisinger.server.msg.MsgHandler;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
@ -47,10 +48,13 @@ public class Response {
this.cmd = cmd; this.cmd = cmd;
this.out = out; this.out = out;
this.payload = payload; this.payload = payload;
System.out.println(cmd);
if (this.url != null) { if (this.url != null) {
if (this.cmd.equals("GET")) { if (this.cmd.equals("GET")) {
getMethodes(); if(login()) {
getMethodes();
}else{
sendError("401");
}
}else if (this.cmd.equals("POST")){ }else if (this.cmd.equals("POST")){
try { try {
postMethodes(); postMethodes();
@ -58,18 +62,55 @@ public class Response {
e.printStackTrace(); e.printStackTrace();
} }
}else if (this.cmd.equals("PUT")){ }else if (this.cmd.equals("PUT")){
putMethodes(); if(login()) {
putMethodes();
}else{
sendError("401");
}
}else if (this.cmd.equals("DELETE")){ }else if (this.cmd.equals("DELETE")){
deleteMethodes(); if(login()) {
deleteMethodes();
}else{
sendError("401");
}
}else{ }else{
sendError("405"); sendError("405");
} }
} }
} }
/**
* Alle Get Methoden
* Nur für angemeldete user erreichbar
*/
private void getMethodes(){ private void getMethodes(){
if (this.url.startsWith("/messages")) { if (this.url.startsWith("/users")) {
} else if (this.url.startsWith("/")) { String username = this.url.substring(this.url.lastIndexOf('/') + 1);
System.out.println("Username in /users/{username}: " + username);
User user = null;
try {
user = new DBConnection().getUser(username);
} catch (SQLException throwables) {
throwables.printStackTrace();
sendError("401");
}
if (user != null){
String userJson = JsonHelper.userToJson(user);
if(userJson != null && !userJson.isEmpty()){
sendResponse(userJson, "200");
}
}else{
sendError("500");
}
} else if (this.url.startsWith("/cards")) {
String username = basicAuthGetUsername(this.authString);
Cards allCards = new DBConnection().getCards(username);
String jsonCards = JsonHelper.objToJson(allCards);
if (jsonCards != null && !jsonCards.isEmpty()){
sendResponse(jsonCards, "200");
}else{
sendError("500");
}
} }
} }
@ -96,10 +137,8 @@ public class Response {
*/ */
private String basicAuthBase64(String username, String password){ private String basicAuthBase64(String username, String password){
String authString = username + ":" + password; String authString = username + ":" + password;
//System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes()); byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
String authStringEnc = new String(authEncBytes); String authStringEnc = new String(authEncBytes);
//System.out.println("Base64 encoded auth string: " + authStringEnc);
return authStringEnc; return authStringEnc;
} }
@ -110,13 +149,10 @@ public class Response {
*/ */
private String basicAuthGetUsername(String authString) { private String basicAuthGetUsername(String authString) {
String[] values; String[] values;
System.out.println("auth To username");
if (authString != null) { if (authString != null) {
byte[] credDecoded = Base64.getDecoder().decode(authString); byte[] credDecoded = Base64.getDecoder().decode(authString);
String credentials = new String(credDecoded); String credentials = new String(credDecoded);
values = credentials.split(":", 2); values = credentials.split(":", 2);
System.out.println("credentials: ");
System.out.println(values[0]);
}else{ }else{
values = null; values = null;
} }
@ -125,36 +161,30 @@ public class Response {
/** /**
* Alle Post Methoden, siehe API beschreibung für genauere details * Alle Post Methoden, siehe API beschreibung für genauere details
*
* Kann auch von nicht angemeldeten usern erreicht werden.
* login() wird hier verwendet
* @throws JsonProcessingException Fehler beim de-/serialisieren * @throws JsonProcessingException Fehler beim de-/serialisieren
*/ */
private void postMethodes() throws JsonProcessingException { private void postMethodes() throws JsonProcessingException {
if (this.url.startsWith("/users")) { if (this.url.startsWith("/users")) {
Map<String, Object> map = JsonHelper.jsonPayload2ToMap(this.payload); Map<String, Object> map = JsonHelper.jsonPayloadToMap(this.payload);
String username = (String) map.get("Username"); String username = (String) map.get("Username");
String password = (String) map.get("Password"); String password = (String) map.get("Password");
User newUser = new User(new Credentials(username, password), username, username, "not implemented", new Coins(20)); User newUser = new User(new Credentials(username, password), username, username, "not implemented", new Coins(20), "BIO", "IMAGE");
System.out.println("CON DB"); System.out.println("CON DB");
DBConnection con = new DBConnection(); DBConnection con = new DBConnection();
if(!con.addUser(username, password, username, "not implemented")){ if(!con.addUser(newUser.getCredentials().getUsername(), newUser.getCredentials().getPasswort(), newUser.getCredentials().getUsername(), newUser.getEmail(), newUser.getBio(), newUser.getImage())){
sendError("409"); sendError("409");
} }
String userJson = JsonHelper.userToJson(newUser);;
//User to json if(userJson != null) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper = new ObjectMapper();
String userJson = "";
if(newUser != null) {
try {
userJson += objectMapper.writeValueAsString(newUser);
} catch (JsonProcessingException e) {
userJson = "Error: JsonProcessingException -> " + e.getMessage();
}
sendResponse(userJson, "201"); sendResponse(userJson, "201");
}else{ }else{
sendError("500"); sendError("500");
} }
}else if (this.url.startsWith("/sessions")) { }else if (this.url.startsWith("/sessions")) {
Map<String, Object> map = JsonHelper.jsonPayload2ToMap(this.payload); Map<String, Object> map = JsonHelper.jsonPayloadToMap(this.payload);
String username = (String) map.get("Username"); String username = (String) map.get("Username");
String password = (String) map.get("Password"); String password = (String) map.get("Password");
User user = null; User user = null;
@ -173,39 +203,40 @@ public class Response {
sendError("401"); sendError("401");
} }
}else if (this.url.startsWith("/packages")) { }else if (this.url.startsWith("/packages")) {
if(basicAuth("admin", "admin", this.authString)){ if(login()) {
ObjectMapper objectMapper = new ObjectMapper(); if (basicAuth("admin", "admin", this.authString)) {
ArrayList<Card> listCards = objectMapper.readValue(this.payload, new TypeReference<ArrayList<Card>>(){}); ObjectMapper objectMapper = new ObjectMapper();
Package packageCards = new Package(new Cards(listCards), new DBConnection().nextPackageId()+"", 5); ArrayList<Card> listCards = objectMapper.readValue(this.payload, new TypeReference<ArrayList<Card>>() {
if(!new DBConnection().addPackage(packageCards)){ });
sendError("500"); Package packageCards = new Package(new Cards(listCards), new DBConnection().nextPackageId() + "", 5);
}else{ if (!new DBConnection().addPackage(packageCards)) {
String packageJson = JsonHelper.packageToJson(packageCards);
if(packageJson != null) {
sendResponse(packageJson, "201");
}else{
sendError("500"); sendError("500");
} else {
String packageJson = JsonHelper.objToJson(packageCards);
if (packageJson != null) {
sendResponse(packageJson, "201");
} else {
sendError("500");
}
} }
} else {
sendError("401");
} }
}else{
sendError("401");
} }
}else if (this.url.startsWith("/transactions/packages")) { }else if (this.url.startsWith("/transactions/packages")) {
if(login()){ if (login()) {
DBConnection db = new DBConnection(); DBConnection db = new DBConnection();
Package newPackage = db.userAcquirePackage(basicAuthGetUsername(this.authString)); Package newPackage = db.userAcquirePackage(basicAuthGetUsername(this.authString));
if (newPackage == null){ if (newPackage == null) {
sendError("500"); sendError("500");
}else{ } else {
String packageJson = JsonHelper.packageToJson(newPackage); String packageJson = JsonHelper.objToJson(newPackage);
if(packageJson == null){ if (packageJson == null) {
sendError("500"); sendError("500");
}else { } else {
sendResponse(packageJson, "200"); sendResponse(packageJson, "200");
} }
} }
}else{
sendError("401");
} }
} }
} }
@ -232,20 +263,52 @@ public class Response {
} }
/** /**
* Alle Put Methoden, siehe API beschreibung für genauere details * Alle Put Methoden
* Nur für angemeldete user erreichbar
* @throws JsonProcessingException Fehler beim de-/serialisieren * @throws JsonProcessingException Fehler beim de-/serialisieren
*/ */
private void putMethodes(){ private void putMethodes(){
if (this.url.startsWith("/messages")) { if (this.url.startsWith("/users")) {
String username = this.url.substring(this.url.lastIndexOf('/') + 1);
System.out.println("Username in /users/{username}: " + username);
User user = null;
try {
user = new DBConnection().getUser(username);
} catch (SQLException throwables) {
throwables.printStackTrace();
sendError("401");
}
if(user != null) {
Map<String, Object> map = JsonHelper.jsonPayloadToMap(this.payload);
String bio = (String) map.get("Bio");
String image = (String) map.get("Image");
String name = (String) map.get("Name");
System.out.println("Request /users:");
System.out.println("Bio: " + bio + "\nImage: " + image + "\nName: " + name);
user.setBio(bio);
user.setImage(image);
user.setNachname(name);
if (new DBConnection().updateUser(username, user.getBio(), user.getImage(), user.getNachname())) {
sendResponse(JsonHelper.userToJson(user), "200");
} else {
sendError("500");
}
}else{
sendError("500");
}
} }
} }
/** /**
* Alle Delete Methoden, siehe API beschreibung für genauere details * Alle Delete Methoden, siehe API beschreibung für genauere details
* Nur für angemeldete user erreichbar
* @throws JsonProcessingException Fehler beim de-/serialisieren * @throws JsonProcessingException Fehler beim de-/serialisieren
*/ */
private void deleteMethodes(){ private void deleteMethodes(){
if (this.url.startsWith("/messages")) { if (this.url.startsWith("/messages")) {
} }
} }

View File

@ -36,8 +36,8 @@ public class StoreTest {
Coins coins = new Coins(10); Coins coins = new Coins(10);
//at.reisinger.User //at.reisinger.User
Credentials credentials = new Credentials("username", "passwort"); Credentials credentials = new Credentials("username", "passwort");
user = new User(credentials, "name", "nachname", "email", coins); user = new User(credentials, "name", "nachname", "email", coins, "BIO", "IMAGE");
userNew = new User(credentials, "nameNew", "nachnameNew", "emailNew", coins); userNew = new User(credentials, "nameNew", "nachnameNew", "emailNew", coins, "BIO", "IMAGE");
//Trading Deal //Trading Deal
Card cardToTrade = card; Card cardToTrade = card;
@ -47,7 +47,7 @@ public class StoreTest {
tradingDeal = new TradingDeal(user, cardToTrade, requiredElementType, requiredMinDamage, requiredCardType); tradingDeal = new TradingDeal(user, cardToTrade, requiredElementType, requiredMinDamage, requiredCardType);
} }
/*
@Test @Test
void test_addTradingDeal() { void test_addTradingDeal() {
@ -66,7 +66,7 @@ public class StoreTest {
stackArrList.add(c5); stackArrList.add(c5);
Cards deck = new Cards(deckArrList); Cards deck = new Cards(deckArrList);
Cards stack = new Cards(stackArrList); Cards stack = new Cards(stackArrList);
User user = new User(new Credentials("username", "passwort"), "Name", "Nachname", "Email", new Coins(1000)); User user = new User(new Credentials("username", "passwort"), "Name", "Nachname", "Email", new Coins(1000), "BIO", "IMAGE");
ArrayList<TradingDeal> tradingDeals = new ArrayList<TradingDeal>(); ArrayList<TradingDeal> tradingDeals = new ArrayList<TradingDeal>();
ArrayList<Package> packages = new ArrayList<at.reisinger.Package>(); ArrayList<Package> packages = new ArrayList<at.reisinger.Package>();
tradingDeals.add(new TradingDeal(user, c1, ElementTyp.FIRE, 10, CardType.MONSTER)); tradingDeals.add(new TradingDeal(user, c1, ElementTyp.FIRE, 10, CardType.MONSTER));
@ -108,7 +108,7 @@ public class StoreTest {
stackArrList.add(c5); stackArrList.add(c5);
Cards deck = new Cards(deckArrList); Cards deck = new Cards(deckArrList);
Cards stack = new Cards(stackArrList); Cards stack = new Cards(stackArrList);
User user = new User(new Credentials("username", "passwort"), "Name", "Nachname", "Email", new Coins(1000)); User user = new User(new Credentials("username", "passwort"), "Name", "Nachname", "Email", new Coins(1000), "BIO", "IMAGE");
ArrayList<TradingDeal> tradingDeals = new ArrayList<TradingDeal>(); ArrayList<TradingDeal> tradingDeals = new ArrayList<TradingDeal>();
ArrayList<at.reisinger.Package> packages = new ArrayList<at.reisinger.Package>(); ArrayList<at.reisinger.Package> packages = new ArrayList<at.reisinger.Package>();
tradingDeals.add(new TradingDeal(user, c1, ElementTyp.FIRE, 10, CardType.MONSTER)); tradingDeals.add(new TradingDeal(user, c1, ElementTyp.FIRE, 10, CardType.MONSTER));
@ -136,10 +136,12 @@ public class StoreTest {
stackArrList.add(c5); stackArrList.add(c5);
Cards deck = new Cards(deckArrList); Cards deck = new Cards(deckArrList);
Cards stack = new Cards(stackArrList); Cards stack = new Cards(stackArrList);
TradingDeal vonDB = new TradingDeal(new User(new Credentials("username", "passwort"), "DerName", "Nachname", "Email", new Coins(1000)), c1, ElementTyp.FIRE, 10, CardType.SPELL); TradingDeal vonDB = new TradingDeal(new User(new Credentials("username", "passwort"), "DerName", "Nachname", "Email", new Coins(1000), "BIO", "IMAGE"), c1, ElementTyp.FIRE, 10, CardType.SPELL);
expected.add(vonDB); expected.add(vonDB);
System.out.println(result.get(0).getCardToTrade().getName()); System.out.println(result.get(0).getCardToTrade().getName());
System.out.println(expected.get(0).getCardToTrade().getName()); System.out.println(expected.get(0).getCardToTrade().getName());
assertTrue(result.get(0).getCardToTrade().equals(expected.get(0).getCardToTrade())); assertTrue(result.get(0).getCardToTrade().equals(expected.get(0).getCardToTrade()));
} }
*/
} }

View File

@ -36,8 +36,8 @@ public class TradingDealTest {
//at.reisinger.User //at.reisinger.User
Credentials credentials = new Credentials("username", "passwort"); Credentials credentials = new Credentials("username", "passwort");
Credentials newCredentials = new Credentials("usernamenew", "passwortnew"); Credentials newCredentials = new Credentials("usernamenew", "passwortnew");
user = new User(credentials, "name", "nachname", "email", coins); user = new User(credentials, "name", "nachname", "email", coins, "BIO", "IMAGE");
userNew = new User(newCredentials, "nameNew", "nachnameNew", "emailNew", coins); userNew = new User(newCredentials, "nameNew", "nachnameNew", "emailNew", coins, "BIO", "IMAGE");
//Trading Deal //Trading Deal
Card cardToTrade = card; Card cardToTrade = card;

View File

@ -38,7 +38,7 @@ public class UserTest {
Coins coins = new Coins(10); Coins coins = new Coins(10);
//at.reisinger.User //at.reisinger.User
Credentials credentials = new Credentials("username", "pw"); Credentials credentials = new Credentials("username", "pw");
user = new User(credentials, "name", "nachname", "email", coins); user = new User(credentials, "name", "nachname", "email", coins, "BIO", "IMAGE");
} }
@Test @Test
public void test_getName() { public void test_getName() {