Create Package (/packages)

This commit is contained in:
Georg Reisinger 2020-12-28 22:42:49 +01:00
parent 6953010bd3
commit cd9e0a45e0
13 changed files with 467 additions and 75 deletions

View File

@ -1,12 +1,19 @@
package at.reisinger; package at.reisinger;
import com.fasterxml.jackson.annotation.*;
/** /**
* Object einer at.reisinger.Card * Object einer at.reisinger.Card
*/ */
@JsonAutoDetect
public class Card { public class Card {
@JsonProperty
private String name; private String name;
@JsonProperty
private double damage; private double damage;
@JsonProperty
private ElementTyp elementTyp; private ElementTyp elementTyp;
@JsonProperty
private CardType cardType; private CardType cardType;
/** /**
@ -23,10 +30,82 @@ public class Card {
this.cardType = cardType; this.cardType = cardType;
} }
/**
* Erstellt eine neue Card mit, anhand des cardNamen werden der ElementType und der CardType automatisch bestimmt
* @param name Name der Card (ID)
* @param elementCardTyp ElementTyp und CardType in einem String. Beide Enums werden durch diesen String gewählt.
* Wird kein passender Typ gefunden, dann bleibt diese Eigenschaft auf null
* @param damage Damage der Card
*/
@JsonCreator
public Card(@JsonProperty("Id") String name, @JsonProperty("Name") String elementCardTyp, @JsonProperty("Damage") double damage){
ElementTyp tmpElement = stringToElementType(elementCardTyp);
if(tmpElement == null){
tmpElement = ElementTyp.UNDEF;
}
CardType tmpCard = stringToCardType(elementCardTyp);
if(tmpCard == null){
tmpCard = CardType.UNDEF;
}
this.name = name;
this.damage = damage;
this.elementTyp = tmpElement;
this.cardType = tmpCard;
}
/**
* Wenn ein String als ElementType vorhanden ist, dann gibt er den passenden ElementType zurück
* @param elementTypeString elementType als String
* @return Passender Element Type oder null falls nicht gefunden
*/
private ElementTyp stringToElementType(String elementTypeString){
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())) {
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 null;
}
/**
* Wenn ein String als cardType vorhanden ist, dann gibt er den passenden cardType zurück
* @param cardTypeString cardType als String
* @return Passender Card Type oder null falls nicht gefunden
*/
private CardType stringToCardType(String cardTypeString){
System.out.println("\n\n\n");
System.out.println("###CARD###, me.name() : cardTypeString\n");
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())) {
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 null;
}
/** /**
* Holt den Namen der at.reisinger.Card * Holt den Namen der at.reisinger.Card
* @return Name der at.reisinger.Card * @return Name der at.reisinger.Card
*/ */
@JsonGetter
public String getName() { public String getName() {
return this.name; return this.name;
} }
@ -35,6 +114,7 @@ public class Card {
* Holt den Damage der at.reisinger.Card * Holt den Damage der at.reisinger.Card
* @return Damage der at.reisinger.Card * @return Damage der at.reisinger.Card
*/ */
@JsonGetter
public double getDamage() { public double getDamage() {
return this.damage; return this.damage;
} }
@ -43,6 +123,7 @@ public class Card {
* Holt den ElementType der at.reisinger.Card * Holt den ElementType der at.reisinger.Card
* @return ElementType der at.reisinger.Card * @return ElementType der at.reisinger.Card
*/ */
@JsonGetter
public ElementTyp getElementTyp() { public ElementTyp getElementTyp() {
return this.elementTyp; return this.elementTyp;
} }
@ -51,6 +132,7 @@ public class Card {
* Holt den at.reisinger.CardType der at.reisinger.Card * Holt den at.reisinger.CardType der at.reisinger.Card
* @return at.reisinger.CardType der at.reisinger.Card * @return at.reisinger.CardType der at.reisinger.Card
*/ */
@JsonGetter
public CardType getCardType() { public CardType getCardType() {
return this.cardType; return this.cardType;
} }
@ -61,6 +143,7 @@ public class Card {
* @return Gibt die Wirksamkeit zurück * @return Gibt die Wirksamkeit zurück
* @throws InternalError Wenn die Effectifeness von den 2 at.reisinger.Cards nicht berechnet werden kann * @throws InternalError Wenn die Effectifeness von den 2 at.reisinger.Cards nicht berechnet werden kann
*/ */
@JsonGetter
public EffectivnessType getEffectivenessAgainst(Card toCeck) { public EffectivnessType getEffectivenessAgainst(Card toCeck) {
if(toCeck.getCardType() == CardType.MONSTER){ if(toCeck.getCardType() == CardType.MONSTER){
if(this.cardType == CardType.MONSTER){ if(this.cardType == CardType.MONSTER){
@ -84,6 +167,7 @@ public class Card {
* Setztden namen der at.reisinger.Card * Setztden namen der at.reisinger.Card
* @param neuerName Name der at.reisinger.Card * @param neuerName Name der at.reisinger.Card
*/ */
@JsonSetter
public void setName(String neuerName) { public void setName(String neuerName) {
this.name = neuerName; this.name = neuerName;
} }
@ -92,6 +176,7 @@ public class Card {
* Setzt den Damage der at.reisinger.Card * Setzt den Damage der at.reisinger.Card
* @param damage Der Damage * @param damage Der Damage
*/ */
@JsonSetter
public void setDamage(int damage) { public void setDamage(int damage) {
this.damage = damage; this.damage = damage;
} }
@ -100,6 +185,7 @@ public class Card {
* Setzt den ElementType der at.reisinger.Card * Setzt den ElementType der at.reisinger.Card
* @param elementTyp Der ElementType * @param elementTyp Der ElementType
*/ */
@JsonSetter
public void setElementType(ElementTyp elementTyp) { public void setElementType(ElementTyp elementTyp) {
this.elementTyp = elementTyp; this.elementTyp = elementTyp;
} }

View File

@ -1,5 +1,5 @@
package at.reisinger; package at.reisinger;
public enum CardType { public enum CardType {
MONSTER, SPELL MONSTER, SPELL, UNDEF, GOBLIN, TROLL, ELF, KNIGHT
} }

View File

@ -1,9 +1,6 @@
package at.reisinger; package at.reisinger;
import java.sql.Connection; import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
/** /**
@ -16,7 +13,7 @@ public class DBConnection {
private Connection c; private Connection c;
private Statement stmt; private Statement stmt;
private Connection con(){ private Connection con() {
this.c = null; this.c = null;
try { try {
Class.forName("org.postgresql.Driver"); Class.forName("org.postgresql.Driver");
@ -25,10 +22,9 @@ public class DBConnection {
"user", "user"); "user", "user");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
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("Opened database");
return c; return c;
} }
@ -36,56 +32,200 @@ public class DBConnection {
* Erstellt alle Beispieldaten und simuliert somit den * Erstellt alle Beispieldaten und simuliert somit den
* Verbindungsaufbau zu einer DB * Verbindungsaufbau zu einer DB
*/ */
public DBConnection(){ public DBConnection() {
this.c = con(); this.c = con();
System.out.println("Create Tables start");
try {
createTables();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
/*
Card c1 = new Card("Name", 10, ElementTyp.FIRE, CardType.MONSTER);
Card c2 = new Card("Name1", 12, ElementTyp.FIRE, CardType.SPELL);
Card c3 = new Card("Name2", 13, ElementTyp.WATER, CardType.MONSTER);
Card c4 = new Card("Name3", 14, ElementTyp.WATER, CardType.SPELL);
Card c5 = new Card("Name4", 15, ElementTyp.FIRE, CardType.MONSTER);
ArrayList<Card> deckArrList = new ArrayList<Card>();
ArrayList<Card> stackArrList = new ArrayList<Card>();
deckArrList.add(c1);
deckArrList.add(c2);
stackArrList.add(c3);
stackArrList.add(c4);
stackArrList.add(c5);
Cards deck = new Cards(deckArrList);
Cards stack = new Cards(stackArrList);
User user = new User(new Credentials("username", "passwort"), "Name", "Nachname", "Email", new Stack(stack, deck), new Coins(1000));
this.tradingDeals = new ArrayList<TradingDeal>();
this.packages = new ArrayList<Package>();
this.tradingDeals.add(new TradingDeal(user, c1, ElementTyp.FIRE, 10, CardType.MONSTER));
this.packages.add(new Package(stack, "Test at.reisinger.Package", 100));
*/
} }
private void createTables() throws SQLException { /**
* Erstellt alle Tabellen die für den Betrieb der Software bennötigt werden
*
* @throws SQLException
*/
public void init() {
this.c = con(); this.c = con();
try{ try {
stmt = this.c.createStatement(); stmt = this.c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS USERS " + String sql = "CREATE TABLE IF NOT EXISTS USERS " +
"(username TEXT PRIMARY KEY NOT NULL," + "(username TEXT PRIMARY KEY NOT NULL," +
" nachname TEXT NOT NULL, " + " nachname TEXT NOT NULL, " +
" email TEXT NOT NULL, " + " email TEXT NOT NULL, " +
" password TEXT NOT NULL)"; " password TEXT NOT NULL)";
stmt.executeUpdate(sql); stmt.executeUpdate(sql);
stmt.close(); stmt.close();
this.c.close(); this.c.close();
} catch ( Exception e ) { } catch (Exception e) {
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("User Table created"); System.out.println("User Table created");
this.c = con();
try {
stmt = this.c.createStatement();
String sql = "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\"));";
stmt.executeUpdate(sql);
stmt.close();
this.c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
this.c = con();
try {
stmt = this.c.createStatement();
String sql = "create unique index IF NOT EXISTS card_name_uindex on CARD (NAME);";
stmt.executeUpdate(sql);
stmt.close();
this.c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Card Table created");
this.c = con();
try {
stmt = this.c.createStatement();
String sql = "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" +
");";
stmt.executeUpdate(sql);
stmt.close();
this.c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Package Table created");
} }
/**
* Überprüft anhand des Namen der Karte, ob es schon eine solche Karte gibt
*
* @param name Name der zu prüfen ist
* @return True falls die Karte bereits existiert
*/
public boolean cardExists(String name) {
this.c = con();
int count = 0;
try {
stmt = this.c.createStatement();
ResultSet rs = stmt.executeQuery("select count(*) from card where name = \'" + name + "\';");
while (rs.next()) {
count = rs.getInt("count");
System.out.println("Count: ");
System.out.print(count);
}
rs.close();
stmt.close();
this.c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
if (count == 1) {
return true;
} else {
return false;
}
}
/**
* Fügt eine Karte der DB hinzu
* @param card Card die hinzugefügt werden soll
* @return true bei erfolg, false bei error
*/
public boolean addCard(Card card) {
this.c = con();
try{
stmt = this.c.createStatement();
String sql = "insert into card (NAME, DAMAGE, ELEMENTTYP, CARDTYPE) values (\'" + card.getName() +"\',\'" + card.getDamage() + "\',\'" + card.getElementTyp().name() + "\',\'" + card.getCardType().name() + "\')";
System.out.println(sql);
stmt.executeUpdate(sql);
stmt.close();
this.c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
return false;
}
System.out.println("Card added");
return true;
}
/**
* Ermittelt die nächste Package ID
* @return Die Nächste Package id, wenn 0, dann ist ein error
*/
public int nextPackageId(){
this.c = con();
String id = "";
try{
stmt = this.c.createStatement();
ResultSet rs = stmt.executeQuery( "select max(\"ID\") from package;");
while ( rs.next() ) {
id = rs.getString("max");
}
if (id == null){
id = "0";
}
rs.close();
stmt.close();
this.c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
return 0;
}
System.out.println("Package Next id is: ");
System.out.print(id);
return Integer.parseInt(id) + 1;
}
/**
* Fügt eine Package der DB hinzu,
* wenn eine Karte aus dem Package noch nicht in der Db ist,
* dann wird es automatisch hinzugefuegt
* @param pack Pack welches hinzugefügt werden soll
* @return True bei erfolg, false bei fehler
*/
public boolean addPackage(Package pack) {
for (Card ca : pack.getCards()) {
if (!cardExists(ca.getName())) {
if(!addCard(ca)){
return false;
}
}
this.c = con();
try {
stmt = this.c.createStatement();
String sql = "INSERT INTO package (\"ID\", \"name\") values (\'" + pack.getName() + "\',\'" + ca.getName() + "\');";
System.out.println(sql);
stmt.executeUpdate(sql);
stmt.close();
this.c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
return false;
}
System.out.println("Card zu Package hinzugefügt");
}
return true;
}
/**
* Fügt einen User der DB hinzu
* @param username Username des Users
* @param password Passwort des Users
* @param nachname nachname des Users
* @param email Email des Users
* @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){
this.c = con(); this.c = con();
try{ try{
@ -103,6 +243,40 @@ public class DBConnection {
return true; return true;
} }
/**
* Sucht einen User anhand des Usernamens.
* Gibt ein User Objekt zurück
* @param uname Username der zu suchen ist
* @return User als User Objekt
* @throws SQLException Fehler bei der Suche in der DB
*/
public User getUser(String uname) throws SQLException {
this.c = con();
String username="", password="", email ="", nachname = "";
try{
stmt = this.c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM users where username = \'" + uname + "\';" );
while ( rs.next() ) {
username = rs.getString("username");
nachname = rs.getString("nachname");
email = rs.getString("email");
password = rs.getString("password");
System.out.println( "username = " + username );
System.out.println( "nachname = " + nachname );
System.out.println( "email = " + email );
System.out.println( "password = " + password );
System.out.println();
}
rs.close();
stmt.close();
this.c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
return new User(new Credentials(username, password), username, username, email, new Coins(20));
}
/** /**
* Holt alle verfügbaren TradingDeals * Holt alle verfügbaren TradingDeals
* @return Alle Trading Deals * @return Alle Trading Deals

View File

@ -1,5 +1,5 @@
package at.reisinger; package at.reisinger;
public enum ElementTyp { public enum ElementTyp {
WATER, FIRE, NORMAL WATER, FIRE, NORMAL, UNDEF, REGULAR, GOBLIN, KNIGHT
} }

View File

@ -1,10 +1,15 @@
package at.reisinger; package at.reisinger;
import com.fasterxml.jackson.annotation.*;
/** /**
* at.reisinger.Package besteht aus 4 Karten. Ist eine Erweiterung der at.reisinger.Cards, zeigt für 4 at.reisinger.Cards den Preis und einen Packagenamen an * at.reisinger.Package besteht aus 4 Karten. Ist eine Erweiterung der at.reisinger.Cards, zeigt für 4 at.reisinger.Cards den Preis und einen Packagenamen an
*/ */
@JsonAutoDetect
public class Package extends Cards{ public class Package extends Cards{
@JsonProperty
private String name; private String name;
@JsonProperty
private int price; private int price;
/** /**
@ -13,7 +18,8 @@ public class Package extends Cards{
* @param name Name des Packages * @param name Name des Packages
* @param price Price des Packages * @param price Price des Packages
*/ */
public Package(Cards stack, String name, int price) { @JsonCreator
public Package(@JsonProperty Cards stack,@JsonProperty String name,@JsonProperty int price) {
super(stack.getCards()); super(stack.getCards());
this.name = name; this.name = name;
this.price = price; this.price = price;
@ -23,6 +29,7 @@ public class Package extends Cards{
* Holt den namen des Packages * Holt den namen des Packages
* @return Name des Packages * @return Name des Packages
*/ */
@JsonGetter
public String getName() { public String getName() {
return this.name; return this.name;
} }
@ -31,6 +38,7 @@ public class Package extends Cards{
* Holt den Preis des Packages * Holt den Preis des Packages
* @return Preis des Packages * @return Preis des Packages
*/ */
@JsonGetter
public int getPrice() { public int getPrice() {
return this.price; return this.price;
} }
@ -39,6 +47,7 @@ public class Package extends Cards{
* Setzt den Namen des Packages * Setzt den Namen des Packages
* @param neuName Neuer name des Packages * @param neuName Neuer name des Packages
*/ */
@JsonSetter
public void setName(String neuName) { public void setName(String neuName) {
this.name = neuName; this.name = neuName;
} }

View File

@ -3,7 +3,7 @@ package at.reisinger;
import java.util.ArrayList; import java.util.ArrayList;
public interface Store { public interface Store {
DBConnection db = new DBConnection(); //DBConnection db = new DBConnection();
void addTradingDeal(TradingDeal tradingDeal); void addTradingDeal(TradingDeal tradingDeal);

View File

@ -11,15 +11,17 @@ import java.util.ArrayList;
public class User implements Store{ public class User implements Store{
@JsonProperty @JsonProperty
private String name, nachname, email; private String name, nachname, email;
/*
@JsonProperty @JsonProperty
private Stack stack; private Stack stack;
*/
//private DBConnection db; //private DBConnection db;
@JsonProperty @JsonProperty
private Credentials credentials; private Credentials credentials;
@JsonProperty @JsonProperty
private Coins coins; private Coins coins;
/** /*
* Erstellt einen neuen at.reisinger.User * Erstellt einen neuen at.reisinger.User
* @param credentials Zugangsdaten des Users * @param credentials Zugangsdaten des Users
* @param name Name des Users * @param name Name des Users
@ -27,7 +29,7 @@ public class User implements Store{
* @param email Email des Users * @param email Email des Users
* @param stack Alle Karten des Users * @param stack Alle Karten des Users
* @param coins Alle Münzen des Users * @param coins Alle Münzen des Users
*/
@JsonCreator @JsonCreator
public User(@JsonProperty Credentials credentials,@JsonProperty String name,@JsonProperty String nachname,@JsonProperty String email,@JsonProperty Stack stack,@JsonProperty Coins coins) { public User(@JsonProperty Credentials credentials,@JsonProperty String name,@JsonProperty String nachname,@JsonProperty String email,@JsonProperty Stack stack,@JsonProperty Coins coins) {
this.credentials = credentials; this.credentials = credentials;
@ -38,14 +40,14 @@ public class User implements Store{
this.coins = coins; this.coins = coins;
//this.db = new at.reisinger.DBConnection(); //this.db = new at.reisinger.DBConnection();
} }
*/
@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) {
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.db = new at.reisinger.DBConnection(); //this.db = new at.reisinger.DBConnection();
} }
@ -53,7 +55,7 @@ public class User implements Store{
/** /**
* 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
*/
@JsonGetter @JsonGetter
public Stack getStack() { public Stack getStack() {
return stack; return stack;
@ -62,7 +64,7 @@ public class User implements Store{
/** /**
* Setzt den at.reisinger.Stack eines Users * Setzt den at.reisinger.Stack eines Users
* @param stack Der neue at.reisinger.Stack des Users * @param stack Der neue at.reisinger.Stack des Users
*/
@JsonSetter @JsonSetter
public void setStack(Stack stack) { public void setStack(Stack stack) {
this.stack = stack; this.stack = stack;
@ -210,12 +212,17 @@ public class User implements Store{
return new DBConnection().getAllTradingDeals(); return new DBConnection().getAllTradingDeals();
} }
@Override
public boolean doTrading(TradingDeal tradingDeal1, TradingDeal tradingDeal2) {
return false;
}
/** /**
* Startet ein Trading zw 2 TradingDeals * Startet ein Trading zw 2 TradingDeals
* @param myTradingDeal Wenn der Deal passt, wird diese Karte aus dem at.reisinger.Stack entfernt * @param myTradingDeal Wenn der Deal passt, wird diese Karte aus dem at.reisinger.Stack entfernt
* @param storeTradingDeal Wenn der Deal passt, wird diese Karte dem at.reisinger.Stack hinzugefügt * @param storeTradingDeal Wenn der Deal passt, wird diese Karte dem at.reisinger.Stack hinzugefügt
* @return True wenn erfolgreich, False wenn die Deals nicht zusammenpassen * @return True wenn erfolgreich, False wenn die Deals nicht zusammenpassen
*/
public boolean doTrading(TradingDeal myTradingDeal, TradingDeal storeTradingDeal) { public boolean doTrading(TradingDeal myTradingDeal, TradingDeal storeTradingDeal) {
if (storeTradingDeal.dealOk(myTradingDeal)){ if (storeTradingDeal.dealOk(myTradingDeal)){
stack.delCard(myTradingDeal.getCardToTrade()); stack.delCard(myTradingDeal.getCardToTrade());
@ -224,6 +231,7 @@ public class User implements Store{
} }
return false; return false;
} }
*/
/** /**
* Gibt alle Möglichen Trading Deals zurück * Gibt alle Möglichen Trading Deals zurück

View File

@ -1,5 +1,6 @@
package at.reisinger.server; package at.reisinger.server;
import at.reisinger.DBConnection;
import at.reisinger.server.msg.MsgHandler; import at.reisinger.server.msg.MsgHandler;
import at.reisinger.server.objects.Request; import at.reisinger.server.objects.Request;
import at.reisinger.server.objects.Response; import at.reisinger.server.objects.Response;
@ -23,8 +24,11 @@ public class Main {
* @param args Nicht Verwendet * @param args Nicht Verwendet
*/ */
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Starte Server auf Port 80"); System.out.println("DB init");
new DBConnection().init();
System.out.println("\n\nStarte Server auf Port " + port + "\n\n");
new Main(port); new Main(port);
} }
/** /**
@ -54,7 +58,7 @@ public class Main {
try{ try{
System.out.println("Socket von Client #" + this.id + " wurde gestartet!"); System.out.println("Socket von Client #" + this.id + " wurde gestartet!");
Request rq = new Request(this.socket, this.id); Request rq = new Request(this.socket, this.id);
Response rp = new Response(this.id, rq.getUrl(), rq.getCmd(), rq.getOut(), null, rq.getPayload()); Response rp = new Response(this.id, rq.getUrl(), rq.getCmd(), rq.getOut(), rq.getAuthString(), rq.getPayload());
//this.msgHandler = rp.getMsghandler(); //this.msgHandler = rp.getMsghandler();
this.socket.close(); this.socket.close();
System.out.println("Socket von Client #" + this.id + " wurde geschlossen!"); System.out.println("Socket von Client #" + this.id + " wurde geschlossen!");

View File

@ -21,6 +21,7 @@ public class Request {
private String url; private String url;
private final StringBuilder rqBuilder; private final StringBuilder rqBuilder;
private String payload; private String payload;
private String authString;
/** /**
* Get Request * Get Request
@ -64,12 +65,25 @@ public class Request {
headers.add(header); headers.add(header);
} }
int authIndex = headers.toString().indexOf("Authorization");
String authString = headers.toString().substring(authIndex + 21);
int authIndexEnd = authString.indexOf(',');
authString = authString.substring(0, authIndexEnd);
this.authString = authString;
String accessLog = String.format("Client %s, method %s, path %s, version %s, host %s, headers %s", String accessLog = String.format("Client %s, method %s, path %s, version %s, host %s, headers %s",
socket.toString(), method, path, version, host, headers.toString()); socket.toString(), method, path, version, host, headers.toString());
System.out.println(accessLog); System.out.println(accessLog);
} }
/**
* Auth Header
* @return get Auth Header
*/
public String getAuthString() {
return authString;
}
/** /**
* Get PrintStream --> Output * Get PrintStream --> Output

View File

@ -1,12 +1,18 @@
package at.reisinger.server.objects; package at.reisinger.server.objects;
import at.reisinger.*; import at.reisinger.*;
import at.reisinger.Package;
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;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.PrintStream; import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
@ -21,6 +27,7 @@ public class Response {
private String cmd; private String cmd;
private String url; private String url;
private String payload; private String payload;
private String authString;
private MsgHandler msgHandler; private MsgHandler msgHandler;
private StringBuilder rqBuilder; private StringBuilder rqBuilder;
@ -30,12 +37,12 @@ public class Response {
* @param url Request Url * @param url Request Url
* @param cmd Request CMD * @param cmd Request CMD
* @param out out Print Stream * @param out out Print Stream
* @param msgHandler Der MsgHandler * @param authString Der MsgHandler
* @param payload Payload des Requests * @param payload Payload des Requests
*/ */
public Response(int id, String url, String cmd, PrintStream out, MsgHandler msgHandler, String payload){ public Response(int id, String url, String cmd, PrintStream out, String authString, String payload){
this.id = id; this.id = id;
this.msgHandler = msgHandler; this.authString = authString;
this.url = url; this.url = url;
this.cmd = cmd; this.cmd = cmd;
this.out = out; this.out = out;
@ -80,6 +87,47 @@ public class Response {
} }
} }
/**
* Vergleicht das angegebene PW mit dem gespeicherten PW, True wenn richtig
* @param username User aus DB
* @param password PW zu User aus DB
* @param compareTo Base64 String von Basic Auth
* @return True if Login is correct, false if incorrect
*/
private boolean basicAuth(String username, String password, String compareTo){
String authStringEnc = basicAuthBase64(username, password);
if (compareTo.equals(authStringEnc)){
return true;
}
return false;
}
private String basicAuthBase64(String username, String password){
String authString = username + ":" + password;
//System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
String authStringEnc = new String(authEncBytes);
//System.out.println("Base64 encoded auth string: " + authStringEnc);
return authStringEnc;
}
private String basicAuthGetUsername(String authString) throws UnsupportedEncodingException {
String[] values;
if (authString != null) {
System.out.println("1");
byte[] credDecoded = Base64.getDecoder().decode(authString);
System.out.println("2");
String credentials = new String(credDecoded);
System.out.println("credentials: ");
System.out.println(credentials);
// credentials = username:password
values = credentials.split(":", 2);
}else{
values = null;
}
return values[0];
}
private void postMethodes() throws JsonProcessingException { private void postMethodes() throws JsonProcessingException {
if (this.url.startsWith("/users")) { if (this.url.startsWith("/users")) {
//payload to map //payload to map
@ -91,7 +139,7 @@ public class Response {
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(username, password, username, "not implemented")){
sendError("500"); sendError("409");
} }
//User to json //User to json
@ -103,12 +151,61 @@ public class Response {
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
userJson = "Error: JsonProcessingException -> " + e.getMessage(); userJson = "Error: JsonProcessingException -> " + e.getMessage();
} }
sendResponse(userJson, "200"); sendResponse(userJson, "201");
}else{ }else{
sendError("500"); sendError("500");
} }
}else if (this.url.startsWith("/sessions")) { }else if (this.url.startsWith("/sessions")) {
//payload to map
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.readValue(this.payload, new TypeReference<Map<String,Object>>(){});
String username = (String) map.get("Username");
String password = (String) map.get("Password");
User user = null;
DBConnection con = new DBConnection();
try {
user = con.getUser(username);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
String authString = basicAuthBase64(user.getCredentials().getUsername(), user.getCredentials().getPasswort());
if(basicAuth(username, password, authString)){
sendResponse(authString, "200");
}else{
sendError("401");
}
}else if (this.url.startsWith("/packages")) {
if(basicAuth("admin", "admin", this.authString)){
System.out.println("1");
ObjectMapper objectMapper = new ObjectMapper();
System.out.println("2");
ArrayList<Card> listCards = objectMapper.readValue(this.payload, new TypeReference<ArrayList<Card>>(){});
System.out.println("List cards");
System.out.println(listCards.toString());
Package packageCards = new Package(new Cards(listCards), new DBConnection().nextPackageId()+"", 5);
System.out.println("3");
if(!new DBConnection().addPackage(packageCards)){
sendError("500");
}else{
//Package to json
objectMapper = new ObjectMapper();
String packageJson = "";
if(packageCards != null) {
try {
packageJson += objectMapper.writeValueAsString(packageCards);
} catch (JsonProcessingException e) {
packageJson = "Error: JsonProcessingException -> " + e.getMessage();
}
sendResponse(packageJson, "201");
}else{
sendError("500");
}
}
}else{
sendError("401");
}
} }
} }

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", stack, coins); user = new User(credentials, "name", "nachname", "email", coins);
userNew = new User(credentials, "nameNew", "nachnameNew", "emailNew", stack, coins); userNew = new User(credentials, "nameNew", "nachnameNew", "emailNew", coins);
//Trading Deal //Trading Deal
Card cardToTrade = card; Card cardToTrade = card;
@ -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 Stack(stack, deck), new Coins(1000)); User user = new User(new Credentials("username", "passwort"), "Name", "Nachname", "Email", new Coins(1000));
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 Stack(stack, deck), new Coins(1000)); User user = new User(new Credentials("username", "passwort"), "Name", "Nachname", "Email", new Coins(1000));
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,7 +136,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);
TradingDeal vonDB = new TradingDeal(new User(new Credentials("username", "passwort"), "DerName", "Nachname", "Email", new Stack(stack, deck), 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)), 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());

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", stack, coins); user = new User(credentials, "name", "nachname", "email", coins);
userNew = new User(newCredentials, "nameNew", "nachnameNew", "emailNew", stack, coins); userNew = new User(newCredentials, "nameNew", "nachnameNew", "emailNew", coins);
//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", stack, coins); user = new User(credentials, "name", "nachname", "email", coins);
} }
@Test @Test
public void test_getName() { public void test_getName() {