JsonHelper + PostgresHelper + acquire package (/transactions/packages)
This commit is contained in:
parent
cd9e0a45e0
commit
e9fcbb36dc
@ -1,5 +1,7 @@
|
||||
package at.reisinger;
|
||||
|
||||
import at.reisinger.server.helper.PostgresHelper;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
|
||||
@ -13,97 +15,158 @@ public class DBConnection {
|
||||
private Connection c;
|
||||
private Statement stmt;
|
||||
|
||||
private Connection con() {
|
||||
this.c = null;
|
||||
try {
|
||||
Class.forName("org.postgresql.Driver");
|
||||
this.c = DriverManager
|
||||
.getConnection("jdbc:postgresql://postgres.dergeorg.at:5432/mtcg",
|
||||
"user", "user");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.err.println(e.getClass().getName() + ": " + e.getMessage());
|
||||
System.exit(0);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Erstellt alle Beispieldaten und simuliert somit den
|
||||
* Verbindungsaufbau zu einer DB
|
||||
*/
|
||||
public DBConnection() {
|
||||
this.c = con();
|
||||
this.c = PostgresHelper.con();
|
||||
}
|
||||
|
||||
/**
|
||||
* Erstellt alle Tabellen die für den Betrieb der Software bennötigt werden
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void init() {
|
||||
this.c = con();
|
||||
try {
|
||||
stmt = this.c.createStatement();
|
||||
String sql = "CREATE TABLE IF NOT EXISTS USERS " +
|
||||
"(username TEXT PRIMARY KEY NOT NULL," +
|
||||
" nachname TEXT NOT NULL, " +
|
||||
" email TEXT NOT NULL, " +
|
||||
" password TEXT NOT NULL)";
|
||||
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("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)", "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.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 user_cards(username TEXT not null constraint user_cards_users_username_fk references users,name text not null, gesperrt boolean not null);", "UserCards 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);
|
||||
/**
|
||||
* Holt ein Random package aus dem Shop
|
||||
*
|
||||
* @param username User der das Package haben möchte
|
||||
* @return Das Package aus dem Shop, null falls ein Fehler auftritt
|
||||
*/
|
||||
public Package userAcquirePackage(String username) {
|
||||
System.out.println("Vor den coins");
|
||||
int coins = checkCoins(username);
|
||||
if (!(coins - 5 >= 0)) {
|
||||
return null;
|
||||
}
|
||||
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");
|
||||
updateCoins(coins - 5, username);
|
||||
System.out.println("nach den soins");
|
||||
|
||||
this.c = con();
|
||||
this.c = PostgresHelper.con();
|
||||
String id = "";
|
||||
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);
|
||||
ResultSet rs = stmt.executeQuery("select \"ID\" as id from package LIMIT 1;");
|
||||
while (rs.next()) {
|
||||
id = rs.getString("id");
|
||||
System.out.println("id = " + id);
|
||||
System.out.println();
|
||||
}
|
||||
rs.close();
|
||||
stmt.close();
|
||||
this.c.close();
|
||||
} catch (Exception e) {
|
||||
System.err.println(e.getClass().getName() + ": " + e.getMessage());
|
||||
System.exit(0);
|
||||
return null;
|
||||
}
|
||||
System.out.println("Package Table created");
|
||||
System.out.println("Package selected successfully");
|
||||
this.c = PostgresHelper.con();
|
||||
String packagename = "", cardname = "", elementtyp = "", cardtype = "";
|
||||
int zeilennummer = 0, damage = 0;
|
||||
Cards cards = new Cards(new ArrayList<Card>());
|
||||
try {
|
||||
stmt = this.c.createStatement();
|
||||
ResultSet rs = stmt.executeQuery("select i as zeilennummer, package.\"ID\" as id, package.name as packagename, c.name as cardname, c.DAMAGE as damage, c.ELEMENTTYP as elementtyp, c.CARDTYPE as cardtype from package join card c on c.name = package.name where \"ID\" = \'" + id + "\';");
|
||||
int count = 0;
|
||||
while (rs.next()) {
|
||||
System.out.println(count++);
|
||||
zeilennummer = rs.getInt("zeilennummer");
|
||||
id = rs.getString("id");
|
||||
packagename = rs.getString("packagename");
|
||||
cardname = rs.getString("cardname");
|
||||
elementtyp = rs.getString("elementtyp");
|
||||
cardtype = rs.getString("cardtype");
|
||||
damage = rs.getInt("damage");
|
||||
Card newCard = new Card(cardname, elementtyp + cardtype, damage);
|
||||
cards.addCard(newCard);
|
||||
System.out.println();
|
||||
Connection b = PostgresHelper.con();
|
||||
try {
|
||||
stmt = b.createStatement();
|
||||
String sql = "INSERT INTO public.user_cards (username, name, gesperrt) VALUES ( \'" + username + "\',\'" + newCard.getName() + "\', \'false\');";
|
||||
System.out.println(sql);
|
||||
stmt.executeUpdate(sql);
|
||||
stmt.close();
|
||||
b.close();
|
||||
} catch (Exception e) {
|
||||
System.err.println(e.getClass().getName() + ": " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
System.out.println("User got Card successfully");
|
||||
}
|
||||
rs.close();
|
||||
stmt.close();
|
||||
this.c.close();
|
||||
} catch (Exception e) {
|
||||
System.err.println(e.getClass().getName() + ": " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
System.out.println("Package pulled successfully");
|
||||
deletePackage(id);
|
||||
|
||||
if (cards.getCards().size() != 0 && cards != null) {
|
||||
return new Package(cards, packagename, 5);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Löscht ein Package anhand des Namens
|
||||
*
|
||||
* @param name Name des Packages das gelöscht werden soll
|
||||
* @return True bei erfolg, sonst false
|
||||
*/
|
||||
public boolean deletePackage(String name) {
|
||||
return PostgresHelper.executeUpdateMessage("DELETE FROM package WHERE \"ID\" = \'" + name + "\';", "Package deleted successfully");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Coins setzten
|
||||
*
|
||||
* @param coins Anzahl die zu setzten ist
|
||||
* @return True bei erfolg, sonst false
|
||||
*/
|
||||
public boolean updateCoins(int coins, String username) {
|
||||
return PostgresHelper.executeUpdateMessage("UPDATE users SET coins = " + coins + " WHERE username = \'" + username + "\';", "Coins Updated");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt die Anzahl an verfügbaren coins zurück
|
||||
*
|
||||
* @return Anzahl der Coins, -1 ist error
|
||||
*/
|
||||
public int checkCoins(String username) {
|
||||
System.out.println("Check coin start");
|
||||
this.c = PostgresHelper.con();
|
||||
int coins = 0;
|
||||
try {
|
||||
stmt = this.c.createStatement();
|
||||
ResultSet rs = stmt.executeQuery("Select coins from users where username = \'" + username + "\';");
|
||||
while (rs.next()) {
|
||||
coins = rs.getInt("coins");
|
||||
System.out.println("Count: ");
|
||||
System.out.print(coins);
|
||||
}
|
||||
rs.close();
|
||||
stmt.close();
|
||||
this.c.close();
|
||||
} catch (Exception e) {
|
||||
System.out.println("check soin error");
|
||||
System.err.println(e.getClass().getName() + ": " + e.getMessage());
|
||||
return -1;
|
||||
}
|
||||
System.out.println("\nCoins: " + coins);
|
||||
return coins;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -113,7 +176,7 @@ public class DBConnection {
|
||||
* @return True falls die Karte bereits existiert
|
||||
*/
|
||||
public boolean cardExists(String name) {
|
||||
this.c = con();
|
||||
this.c = PostgresHelper.con();
|
||||
int count = 0;
|
||||
try {
|
||||
stmt = this.c.createStatement();
|
||||
@ -139,47 +202,36 @@ public class DBConnection {
|
||||
|
||||
/**
|
||||
* 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;
|
||||
return PostgresHelper.executeUpdateMessage("insert into card (NAME, DAMAGE, ELEMENTTYP, CARDTYPE) values (\'" + card.getName() + "\',\'" + card.getDamage() + "\',\'" + card.getElementTyp().name() + "\',\'" + card.getCardType().name() + "\')", "Card added");
|
||||
}
|
||||
|
||||
/**
|
||||
* Ermittelt die nächste Package ID
|
||||
*
|
||||
* @return Die Nächste Package id, wenn 0, dann ist ein error
|
||||
*/
|
||||
public int nextPackageId(){
|
||||
this.c = con();
|
||||
public int nextPackageId() {
|
||||
this.c = PostgresHelper.con();
|
||||
String id = "";
|
||||
try{
|
||||
try {
|
||||
stmt = this.c.createStatement();
|
||||
ResultSet rs = stmt.executeQuery( "select max(\"ID\") from package;");
|
||||
while ( rs.next() ) {
|
||||
ResultSet rs = stmt.executeQuery("select max(\"ID\") from package;");
|
||||
while (rs.next()) {
|
||||
id = rs.getString("max");
|
||||
}
|
||||
if (id == null){
|
||||
if (id == null) {
|
||||
id = "0";
|
||||
}
|
||||
rs.close();
|
||||
stmt.close();
|
||||
this.c.close();
|
||||
} catch ( Exception e ) {
|
||||
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
|
||||
} catch (Exception e) {
|
||||
System.err.println(e.getClass().getName() + ": " + e.getMessage());
|
||||
return 0;
|
||||
}
|
||||
System.out.println("Package Next id is: ");
|
||||
@ -191,121 +243,89 @@ public class DBConnection {
|
||||
* 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)){
|
||||
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());
|
||||
if(!PostgresHelper.executeUpdateMessage("INSERT INTO package (\"ID\", \"name\") values (\'" + pack.getName() + "\',\'" + ca.getName() + "\');", "Card zu Package hinzugefügt")){
|
||||
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
|
||||
* @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){
|
||||
this.c = con();
|
||||
try{
|
||||
stmt = this.c.createStatement();
|
||||
String sql = "INSERT INTO users (username, nachname, email, password) values (\'" + username +"\',\'" + nachname + "\',\'" + email + "\',\'" + password + "\')";
|
||||
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("User added");
|
||||
return true;
|
||||
public boolean addUser(String username, String password, String nachname, String email) {
|
||||
return PostgresHelper.executeUpdateMessage("INSERT INTO users (username, nachname, email, password) values (\'" + username + "\',\'" + nachname + "\',\'" + email + "\',\'" + password + "\')", "User added");
|
||||
}
|
||||
|
||||
/**
|
||||
* 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() );
|
||||
this.c = PostgresHelper.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");
|
||||
System.out.println("Operation done successfully");
|
||||
return new User(new Credentials(username, password), username, username, email, new Coins(20));
|
||||
}
|
||||
|
||||
/**
|
||||
* Holt alle verfügbaren TradingDeals
|
||||
*
|
||||
* @return Alle Trading Deals
|
||||
*/
|
||||
public ArrayList<TradingDeal> getAllTradingDeals(){
|
||||
public ArrayList<TradingDeal> getAllTradingDeals() {
|
||||
return this.tradingDeals;
|
||||
}
|
||||
|
||||
/**
|
||||
* Holt alle verfügbaren Packages
|
||||
* @return Alle Packages
|
||||
*/
|
||||
public ArrayList<Package> getAllPackages(){
|
||||
return this.packages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fügt einen neuen Tradingdeal zum at.reisinger.Store hinzu
|
||||
*
|
||||
* @param tradingDeal Der neue Deal
|
||||
*/
|
||||
public void addTradingDeal(TradingDeal tradingDeal){
|
||||
public void addTradingDeal(TradingDeal tradingDeal) {
|
||||
this.tradingDeals.add(tradingDeal);
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Fügt ein neues at.reisinger.Package zu dem at.reisinger.Store hinzu
|
||||
// * @param packageDeal Das neue at.reisinger.Package
|
||||
// */
|
||||
// public void addPackage(at.reisinger.Package packageDeal){
|
||||
// this.packages.add(packageDeal);
|
||||
// }
|
||||
}
|
||||
|
@ -1,7 +1,60 @@
|
||||
package at.reisinger.server.helper;
|
||||
|
||||
import at.reisinger.Card;
|
||||
import at.reisinger.Cards;
|
||||
import at.reisinger.Package;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Hilfsfunktionen für Jackson Json
|
||||
*/
|
||||
public class JsonHelper {
|
||||
|
||||
/**
|
||||
* Wandelt ein Package in form einer ArrayList<Card> om ein Json um
|
||||
* @param listCards Cards die in dem Json stehen sollen
|
||||
* @param name Name des Packages
|
||||
* @return Json String des Packages
|
||||
*/
|
||||
public static String packageListToJson(ArrayList<Card> listCards, String name){
|
||||
Package packageCards = new Package(new Cards(listCards),name, 5);
|
||||
return packageToJson(packageCards);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wandelt ein Package Objekt in ein Json um
|
||||
* @param packageCards Package Objekt das in ein Json umgewandelt werden soll
|
||||
* @return Json String des Packages
|
||||
*/
|
||||
public static String packageToJson(Package packageCards){
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper = new ObjectMapper();
|
||||
String packageJson = "";
|
||||
if(packageCards != null) {
|
||||
try {
|
||||
packageJson += objectMapper.writeValueAsString(packageCards);
|
||||
} catch (JsonProcessingException e) {
|
||||
packageJson = "Error: JsonProcessingException -> " + e.getMessage();
|
||||
}
|
||||
return packageJson;
|
||||
}else{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<String, Object> jsonPayload2ToMap(String payload){
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
try {
|
||||
return objectMapper.readValue(payload, new TypeReference<Map<String,Object>>(){});
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
61
src/main/java/at/reisinger/server/helper/PostgresHelper.java
Normal file
61
src/main/java/at/reisinger/server/helper/PostgresHelper.java
Normal file
@ -0,0 +1,61 @@
|
||||
package at.reisinger.server.helper;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.Statement;
|
||||
|
||||
/**
|
||||
* Hilfsfunktionen für die verwendung der Postgres DB
|
||||
*/
|
||||
public class PostgresHelper {
|
||||
|
||||
/**
|
||||
* Verbindet mit der Datenbank
|
||||
* @return Das Connection Objekt
|
||||
*/
|
||||
public static Connection con() {
|
||||
Connection c = null;
|
||||
try {
|
||||
Class.forName("org.postgresql.Driver");
|
||||
c = DriverManager
|
||||
.getConnection("jdbc:postgresql://postgres.dergeorg.at:5432/mtcg",
|
||||
"user", "user");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.err.println(e.getClass().getName() + ": " + e.getMessage());
|
||||
System.exit(0);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Führt ein Sql statement ohne rückgabe aus, mit message nachricht
|
||||
* @param sql Sql command
|
||||
* @return True bei erfolg, sonst false
|
||||
*/
|
||||
public static boolean executeUpdateMessage(String sql, String message){
|
||||
boolean tmp = executeUpdate(sql);
|
||||
System.out.println(message);
|
||||
return tmp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Führt ein Sql statement ohne rückgabe aus
|
||||
* @param sql Sql command
|
||||
* @return True bei erfolg, sonst false
|
||||
*/
|
||||
public static boolean executeUpdate(String sql){
|
||||
Connection c = con();
|
||||
Statement stmt;
|
||||
try {
|
||||
stmt = c.createStatement();
|
||||
stmt.executeUpdate(sql);
|
||||
stmt.close();
|
||||
c.close();
|
||||
} catch (Exception e) {
|
||||
System.err.println(e.getClass().getName() + ": " + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
@ -2,10 +2,12 @@ package at.reisinger.server.objects;
|
||||
|
||||
import at.reisinger.*;
|
||||
import at.reisinger.Package;
|
||||
import at.reisinger.server.helper.JsonHelper;
|
||||
import at.reisinger.server.msg.MsgHandler;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.postgresql.shaded.com.ongres.scram.common.bouncycastle.pbkdf2.Pack;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
@ -28,8 +30,6 @@ public class Response {
|
||||
private String url;
|
||||
private String payload;
|
||||
private String authString;
|
||||
private MsgHandler msgHandler;
|
||||
private StringBuilder rqBuilder;
|
||||
|
||||
/**
|
||||
* Nimmt die Daten des requests und generiert eine Response
|
||||
@ -47,7 +47,6 @@ public class Response {
|
||||
this.cmd = cmd;
|
||||
this.out = out;
|
||||
this.payload = payload;
|
||||
this.rqBuilder = new StringBuilder();
|
||||
System.out.println(cmd);
|
||||
if (this.url != null) {
|
||||
if (this.cmd.equals("GET")) {
|
||||
@ -70,20 +69,7 @@ public class Response {
|
||||
|
||||
private void getMethodes(){
|
||||
if (this.url.startsWith("/messages")) {
|
||||
String lastBit = this.url.substring(this.url.lastIndexOf('/') + 1);
|
||||
System.out.println("Last Bit: " + lastBit);
|
||||
if(lastBit.equals("messages")){
|
||||
listAllMsg();
|
||||
}else{
|
||||
String message = msgHandler.getMsg(Integer.parseInt(lastBit)).getMsg();
|
||||
if(message == null){
|
||||
sendError("404");
|
||||
}else {
|
||||
sendResponse(message, "200");
|
||||
}
|
||||
}
|
||||
} else if (this.url.startsWith("/")) {
|
||||
startseite();
|
||||
}
|
||||
}
|
||||
|
||||
@ -102,6 +88,12 @@ public class Response {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Erstellt den basicAuth Base64 Token aus Username und Passwort
|
||||
* @param username Username für den Token
|
||||
* @param password Passwort für den Token
|
||||
* @return Der Base64 BasicAtuth String
|
||||
*/
|
||||
private String basicAuthBase64(String username, String password){
|
||||
String authString = username + ":" + password;
|
||||
//System.out.println("auth string: " + authString);
|
||||
@ -111,28 +103,33 @@ public class Response {
|
||||
return authStringEnc;
|
||||
}
|
||||
|
||||
private String basicAuthGetUsername(String authString) throws UnsupportedEncodingException {
|
||||
/**
|
||||
* Aus dem Base64 BasicAuth String wird der Username extrahiert
|
||||
* @param authString Base64 BasicAuth String aus dem der Username ausgelesen werden soll
|
||||
* @return Der Username der in dem Base64 BasicAuth String ist
|
||||
*/
|
||||
private String basicAuthGetUsername(String authString) {
|
||||
String[] values;
|
||||
System.out.println("auth To username");
|
||||
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);
|
||||
System.out.println("credentials: ");
|
||||
System.out.println(values[0]);
|
||||
}else{
|
||||
values = null;
|
||||
}
|
||||
return values[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Post Methoden, siehe API beschreibung für genauere details
|
||||
* @throws JsonProcessingException Fehler beim de-/serialisieren
|
||||
*/
|
||||
private void postMethodes() throws JsonProcessingException {
|
||||
if (this.url.startsWith("/users")) {
|
||||
//payload to map
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
Map<String, Object> map = objectMapper.readValue(this.payload, new TypeReference<Map<String,Object>>(){});
|
||||
Map<String, Object> map = JsonHelper.jsonPayload2ToMap(this.payload);
|
||||
String username = (String) map.get("Username");
|
||||
String password = (String) map.get("Password");
|
||||
User newUser = new User(new Credentials(username, password), username, username, "not implemented", new Coins(20));
|
||||
@ -143,6 +140,7 @@ public class Response {
|
||||
}
|
||||
|
||||
//User to json
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper = new ObjectMapper();
|
||||
String userJson = "";
|
||||
if(newUser != null) {
|
||||
@ -156,9 +154,7 @@ public class Response {
|
||||
sendError("500");
|
||||
}
|
||||
}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>>(){});
|
||||
Map<String, Object> map = JsonHelper.jsonPayload2ToMap(this.payload);
|
||||
String username = (String) map.get("Username");
|
||||
String password = (String) map.get("Password");
|
||||
User user = null;
|
||||
@ -178,26 +174,14 @@ public class Response {
|
||||
}
|
||||
}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();
|
||||
}
|
||||
String packageJson = JsonHelper.packageToJson(packageCards);
|
||||
if(packageJson != null) {
|
||||
sendResponse(packageJson, "201");
|
||||
}else{
|
||||
sendError("500");
|
||||
@ -206,32 +190,62 @@ public class Response {
|
||||
}else{
|
||||
sendError("401");
|
||||
}
|
||||
}else if (this.url.startsWith("/transactions/packages")) {
|
||||
if(login()){
|
||||
DBConnection db = new DBConnection();
|
||||
Package newPackage = db.userAcquirePackage(basicAuthGetUsername(this.authString));
|
||||
if (newPackage == null){
|
||||
sendError("500");
|
||||
}else{
|
||||
String packageJson = JsonHelper.packageToJson(newPackage);
|
||||
if(packageJson == null){
|
||||
sendError("500");
|
||||
}else {
|
||||
sendResponse(packageJson, "200");
|
||||
}
|
||||
}
|
||||
}else{
|
||||
sendError("401");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft den Login, anhand des BasicAuth Base64 String
|
||||
* @return True wenn login daten korrekt, sonst false
|
||||
*/
|
||||
private boolean login(){
|
||||
String username = basicAuthGetUsername(this.authString);
|
||||
User user = null;
|
||||
DBConnection con = new DBConnection();
|
||||
try {
|
||||
user = con.getUser(username);
|
||||
} catch (SQLException throwables) {
|
||||
throwables.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
if (basicAuth(user.getCredentials().getUsername(), user.getCredentials().getPasswort(), this.authString)){
|
||||
return true;
|
||||
}else{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Put Methoden, siehe API beschreibung für genauere details
|
||||
* @throws JsonProcessingException Fehler beim de-/serialisieren
|
||||
*/
|
||||
private void putMethodes(){
|
||||
if (this.url.startsWith("/messages")) {
|
||||
String lastBit = this.url.substring(this.url.lastIndexOf('/') + 1);
|
||||
System.out.println("Last Bit: " + lastBit);
|
||||
System.out.println("Payload" + this.payload);
|
||||
String message = msgHandler.editMsg(Integer.parseInt(lastBit), this.payload);
|
||||
if(message == null){
|
||||
sendError("404");
|
||||
}else {
|
||||
sendResponse("","200");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Delete Methoden, siehe API beschreibung für genauere details
|
||||
* @throws JsonProcessingException Fehler beim de-/serialisieren
|
||||
*/
|
||||
private void deleteMethodes(){
|
||||
if (this.url.startsWith("/messages")) {
|
||||
String lastBit = this.url.substring(this.url.lastIndexOf('/') + 1);
|
||||
String message = msgHandler.delMsg(Integer.parseInt(lastBit));
|
||||
if(message == null){
|
||||
sendError("404");
|
||||
}else {
|
||||
sendResponse("", "200");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -249,6 +263,9 @@ public class Response {
|
||||
//out.print(responseText);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sendet eine Startseite, mit allen befehlen und wie man diese verwendet
|
||||
|
||||
private void startseite() {
|
||||
sendResponse("lists all messages: GET /messages<br>" +
|
||||
"add message: POST /messages (Payload: the message; Response an id like1)<br>" +
|
||||
@ -257,11 +274,7 @@ public class Response {
|
||||
"update first message: PUT /messages/1 (Payload: the message)<br>" +
|
||||
"remove first message: DELETE /messages/1<br>", "200");
|
||||
}
|
||||
|
||||
private void listAllMsg() {
|
||||
sendResponse(msgHandler.getAllMsg(), "200");
|
||||
//sendResponse("Test");
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Sendet eine Response
|
||||
@ -276,14 +289,4 @@ public class Response {
|
||||
out.print("\r\n");
|
||||
out.print(responseText);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Msg Handler
|
||||
*
|
||||
* @return msgHandler Handler der Nachrichten
|
||||
*/
|
||||
public MsgHandler getMsghandler() {
|
||||
return this.msgHandler;
|
||||
}
|
||||
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user