initial commit for having a backup

This commit is contained in:
jenzur
2019-06-13 22:08:08 +02:00
parent f54c447eb6
commit 6e89398bee
189 changed files with 15766 additions and 4367 deletions
Binary file not shown.
+28
View File
@@ -0,0 +1,28 @@
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# Avoid ignoring Maven wrapper jar file (.jar files are usually ignored)
!/.mvn/wrapper/maven-wrapper.jar
# NetBeans
nb-configuration
# Derby Test Database
derby.log
# DATABASE
persistence.xml
# Local development Database
pu.properties
# Local test database
pu_integration_test.properties
/nbproject/
nb-configuration.xml
+18
View File
@@ -0,0 +1,18 @@
language: java
jdk: oraclejdk8
cache:
directories:
- $HOME/.m2
script:
- mvn -DPU_NAME=pu_travis_integration_test verify
- mvn -Dremote.user=tomcat -Dremote.password=1324test tomcat7:deploy
# Verify that we have a deployed project
- mvn verify -PACCEPT_TEST
services:
- mysql
before_install:
- mysql -e 'CREATE DATABASE travis_test;'
+1
View File
@@ -0,0 +1 @@
# Semesterprojekt
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<actions>
<action>
<actionName>run</actionName>
<packagings>
<packaging>war</packaging>
<packaging>ear</packaging>
<packaging>ejb</packaging>
</packagings>
<goals>
<goal>package</goal>
</goals>
<properties>
<netbeans.deploy>true</netbeans.deploy>
<netbeans.deploy.clientUrlPart>/racetimers</netbeans.deploy.clientUrlPart>
</properties>
</action>
<action>
<actionName>debug</actionName>
<packagings>
<packaging>war</packaging>
<packaging>ear</packaging>
<packaging>ejb</packaging>
</packagings>
<goals>
<goal>package</goal>
</goals>
<properties>
<netbeans.deploy.debugmode>true</netbeans.deploy.debugmode>
<netbeans.deploy>true</netbeans.deploy>
<netbeans.deploy.clientUrlPart>/racetimers</netbeans.deploy.clientUrlPart>
</properties>
</action>
<action>
<actionName>profile</actionName>
<packagings>
<packaging>ejb</packaging>
<packaging>ear</packaging>
<packaging>war</packaging>
</packagings>
<goals>
<goal>package</goal>
</goals>
<properties>
<netbeans.deploy>true</netbeans.deploy>
<netbeans.deploy.profilemode>true</netbeans.deploy.profilemode>
<netbeans.deploy.clientUrlPart>/racetimers</netbeans.deploy.clientUrlPart>
</properties>
</action>
</actions>
+430
View File
@@ -0,0 +1,430 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>webracetimer</groupId>
<artifactId>racetimer_endpoints</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>racetimer_endpoints</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<remote.server>http://racetimerweb.unloze.com/manager/text</remote.server>
<!--<tomcat.version>7.0.93</tomcat.version>-->
<tomcat.version>8.5.40</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>commons-digester</groupId>
<artifactId>commons-digester</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.5.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.5.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.28</version>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.28</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.28</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.github.wnameless</groupId>
<artifactId>json-flattener</artifactId>
<version>0.6.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20170516</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.nimbusds/nimbus-jose-jwt -->
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<!--<version>7.2.0</version>-->
<version>6.2</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.3.0</version>
<scope>test</scope>
</dependency>
<!-- Database used for UnitTests -->
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.14.2.0</version>
<scope>test</scope>
</dependency>
<!-- Embedded Tomcat for Integrations Testing -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>${tomcat.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>${tomcat.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper-el</artifactId>
<version>${tomcat.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>${tomcat.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
<scope>test</scope>
<!-- End of Embedded Tomcat for Integrations Testing -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<includes>
<include>**/integrationtests/*</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.1</version>
<configuration>
<excludes>
<exclude>**/integrationtests/*</exclude>
</excludes>
</configuration>
</plugin>
<!--This is used to deploy to your "Production" Tomcat using maven -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<server>TomcatServer</server>
<url>${remote.server}</url>
<username>${remote.user}</username>
<password>${remote.password}</password>
<!-- <username>${env.TOMCAT_USER} </username>-->
<!-- <password>${env.TOMCAT_PASSWORD}</password>-->
<update>true</update>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-util</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-coyote</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-api</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper-el</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-el-api</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-tribes</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina-ha</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-annotations-api</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-juli</artifactId>
<version>${tomcat.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<!-- Build with -P<profileName> to activate the profiles-->
<profiles>
<profile>
<id>ACCEPT_TEST</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<includes>
<include>**/accepttests/*</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.1</version>
<configuration>
<excludes>
<exclude>**/accepttests/*</exclude>
<exclude>**/integrationtests/*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
Binary file not shown.
@@ -0,0 +1,83 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import entity.MapValues;
/**
*
* @author install1
*/
public class MapBoardDTO {
private String steamID;
private String name;
private int mapPoint;
private int mapTimeMinutes;
private float mapTimeSeconds;
private int position;
public MapBoardDTO() {
}
public MapBoardDTO(MapValues mapvalue, String name) {
this.steamID = mapvalue.getPlayerSteamID();
this.name = name;
this.mapPoint = mapvalue.getMapPoints();
this.mapTimeMinutes = (int) Math.floor(mapvalue.getTime());
this.mapTimeSeconds = (float) (mapvalue.getTime() - Math.floor(mapvalue.getTime())) * 100;
this.position = mapvalue.getPosition();
}
public String getSteamID() {
return steamID;
}
public void setSteamID(String steamID) {
this.steamID = steamID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMapPoint() {
return mapPoint;
}
public void setMapPoint(int mapPoint) {
this.mapPoint = mapPoint;
}
public int getMapTimeMinutes() {
return mapTimeMinutes;
}
public void setMapTimeMinutes(int mapTimeMinutes) {
this.mapTimeMinutes = mapTimeMinutes;
}
public float getMapTimeSeconds() {
return mapTimeSeconds;
}
public void setMapTimeSeconds(float mapTimeSeconds) {
this.mapTimeSeconds = mapTimeSeconds;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
}
@@ -0,0 +1,63 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import entity.MapValues;
/**
*
* @author install1
*/
public class MapValuesDTO {
private int position;
private String playerSteamID;
private float time;
private int mapPoints;
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getPlayerSteamID() {
return playerSteamID;
}
public void setPlayerSteamID(String playerSteamID) {
this.playerSteamID = playerSteamID;
}
public float getTime() {
return time;
}
public void setTime(float time) {
this.time = time;
}
public int getMapPoints() {
return mapPoints;
}
public void setMapPoints(int mapPoints) {
this.mapPoints = mapPoints;
}
public MapValuesDTO() {
}
public MapValuesDTO(MapValues mapvalue){
this.position = mapvalue.getPosition();
this.playerSteamID = mapvalue.getPlayerSteamID();
this.time = mapvalue.getTime();
this.mapPoints = mapvalue.getMapPoints();
}
}
@@ -0,0 +1,49 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import entity.Player;
import static facade.Facade.convertSteamIdToCommunityId;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author install1
*/
public class PlayerDTO {
private String steamID64;
private String steamID;
private String name;
private String Avatar;
private int Rank;
private int PlayerPoints;
private int Times;
private List<Integer> UrlBanners = new ArrayList();
public PlayerDTO(String steamID, String name, String Avatar, int Rank, int PlayerPoints, int Times) {
this.steamID = steamID;
this.name = name;
this.Avatar = Avatar;
this.Rank = Rank;
this.PlayerPoints = PlayerPoints;
this.Times = Times;
}
public PlayerDTO() {
}
public PlayerDTO(Player player) {
this.steamID = player.getSteamID();
this.steamID64 = String.valueOf(convertSteamIdToCommunityId(player.getSteamID()));
this.name = player.getName();
this.Avatar = player.getAvatar();
this.Rank = player.getRank();
this.PlayerPoints = player.getPlayerPoints();
this.Times = player.getTimesCount();
}
}
@@ -0,0 +1,57 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import entity.MapBoard;
import entity.MapValues;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author install1
*/
public class PlayerMapBoardDTO {
private String steamID;
private String mapname;
private int mapstage;
private int mapPoint;
private int mapTimeMinutes;
private float mapTimeSeconds;
private int position;
public PlayerMapBoardDTO() {
}
public PlayerMapBoardDTO(String steamID) {
this.steamID = steamID;
}
public void addMapValues(MapValues mapvalue, String mapName) {
Pattern pattern = Pattern.compile("S(\\d+)");
Matcher matcher = pattern.matcher(mapName);
String map = "";
int stage = 1; //0
if (matcher.find()) {
String group = matcher.group();
map = mapName.substring(0, mapName.indexOf(group));
stage = Integer.valueOf(group.substring(1));
} else {
map = mapName;
}
this.steamID = mapvalue.getPlayerSteamID();
this.mapPoint = mapvalue.getMapPoints();
this.mapTimeMinutes = (int) Math.floor(mapvalue.getTime());
this.mapTimeSeconds = (float) (mapvalue.getTime() - Math.floor(mapvalue.getTime())) * 100;
this.position = mapvalue.getPosition();
this.mapname = map;
this.mapstage = stage;
}
}
@@ -0,0 +1,71 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
/**
*
* @author install1
*/
public class RecentTimesDTO {
private String MYSQLSteamID;
private String MYSQLStage;
private float MYSQLOldTime;
private PlayerDTO player;
private float improvedTime;
public String getMYSQLSteamID() {
return MYSQLSteamID;
}
public void setMYSQLSteamID(String MYSQLSteamID) {
this.MYSQLSteamID = MYSQLSteamID;
}
public String getMYSQLStage() {
return MYSQLStage;
}
public void setMYSQLStage(String MYSQLStage) {
this.MYSQLStage = MYSQLStage;
}
public float getMYSQLOldTime() {
return MYSQLOldTime;
}
public void setMYSQLOldTime(float MYSQLOldTime) {
this.MYSQLOldTime = MYSQLOldTime;
}
public PlayerDTO getPlayer() {
return player;
}
public void setPlayer(PlayerDTO player) {
this.player = player;
}
public float getImprovedTime() {
return improvedTime;
}
public void setImprovedTime(float improvedTime) {
this.improvedTime = improvedTime;
}
public RecentTimesDTO() {
}
public RecentTimesDTO(String MYSQLSteamID, String MYSQLStage, float MYSQLOldTime, PlayerDTO player, float improvedTime) {
this.MYSQLSteamID = MYSQLSteamID;
this.MYSQLStage = MYSQLStage;
this.MYSQLOldTime = MYSQLOldTime;
this.player = player;
this.improvedTime = improvedTime;
}
}
@@ -0,0 +1,43 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DataMapper;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.dbcp2.BasicDataSource;
/**
*
* @author install1
*/
public class DBCPDataSource {
private static BasicDataSource ds = new BasicDataSource();
static {
try {
ds.setDriver(new com.mysql.cj.jdbc.Driver());
ds.setUrl("jdbc:mysql://151.80.230.149:3306/unloze_racetimer_css?useLegacyDatetimeCode=false&serverTimezone=UTC");
ds.setUsername("unloze_racetimer_css");
ds.setPassword("ahsdbahb/#¤FHdasd");
ds.setMaxTotal(-1);
ds.setMinIdle(5);
ds.setMaxIdle(-1);
ds.setMaxOpenPreparedStatements(100);
} catch (SQLException ex) {
Logger.getLogger(DBCPDataSource.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
private DBCPDataSource() {
}
}
@@ -0,0 +1,70 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DataMapper;
import com.google.common.collect.MapMaker;
import entity.MapBoard;
import entity.MapValues;
import entity.Player;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
/**
*
* @author install1
*/
public class DataMapperCalls {
public static Map.Entry<Collection<Player>, Collection<MapBoard>> getAllValues() {
Collection<Player> allPlayers = new ArrayList();
//add mapvalues
ConcurrentMap<String, MapBoard> allMapBoards = new MapMaker().concurrencyLevel(4).makeMap();
String sqlQuery = "SELECT * FROM `zetimer_table`";
int limitfetch = 0;
try (Connection con = DBCPDataSource.getConnection()) {
try (PreparedStatement ps = con.prepareStatement(sqlQuery)) {
try (ResultSet result = ps.executeQuery()) {
int fetchSize = result.getMetaData().getColumnCount();
while (result.next() && limitfetch < 25) {
int timesCounter = 0;
Player player = new Player(result.getString(1), result.getString(2));
int i = 3;
while (i < fetchSize) {
String columnLabel = result.getMetaData().getColumnLabel(i);
if (!allMapBoards.keySet().contains(columnLabel)) {
allMapBoards.put(columnLabel, new MapBoard(columnLabel));
}
double specificDouble = result.getDouble(i);
if (specificDouble > 0.000) {
timesCounter++;
MapValues mapValue = new MapValues();
mapValue.setPlayerSteamID(player);
mapValue.setTime((float) specificDouble);
allMapBoards.get(columnLabel).getMapvalues().add(mapValue);
}
i++;
}
player.setTimesCount(timesCounter);
allPlayers.add(player);
limitfetch++;
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
Map.Entry<Collection<Player>, Collection<MapBoard>> entry = new AbstractMap.SimpleEntry(allPlayers, allMapBoards.values());
return entry;
}
}
@@ -0,0 +1,26 @@
package cors;
import java.io.IOException;
import java.util.logging.Logger;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
//Comment out these two annotations below to disable CORS-handling
@Provider //This will ensure that the filter is used "automatically"
@PreMatching
public class CorsRequestFilter implements ContainerRequestFilter {
private final static Logger log = Logger.getLogger(CorsRequestFilter.class.getName());
@Override
public void filter(ContainerRequestContext requestCtx) throws IOException {
// When HttpMethod comes as OPTIONS, just acknowledge that it accepts...
if (requestCtx.getRequest().getMethod().equals("OPTIONS")) {
// log.info("HTTP Method (OPTIONS) - Detected!");
// Just send a OK response back to the browser.
// The response goes through the chain of applicable response filters.
requestCtx.abortWith(Response.status(Response.Status.OK).build());
}
}
}
@@ -0,0 +1,25 @@
package cors;
import java.io.IOException;
import java.util.logging.Logger;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.ext.Provider;
//Comment out the two annotations below to disable CORS-handling
@Provider
@PreMatching
public class CorsResponseFilter implements ContainerResponseFilter {
private final static Logger LOG = Logger.getLogger(CorsResponseFilter.class.getName());
@Override
public void filter( ContainerRequestContext requestCtx, ContainerResponseContext res )
throws IOException {
// LOG.info( "Executing REST response filter" );
res.getHeaders().add("Access-Control-Allow-Origin", "*" );
res.getHeaders().add("Access-Control-Allow-Credentials", "true" );
res.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT" );
res.getHeaders().add("Access-Control-Allow-Headers", "Origin, Accept, Content-Type, Authorization,x-access-token");
}
}
@@ -0,0 +1,61 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.persistence.Id;
import javax.persistence.Table;
import org.mindrot.jbcrypt.BCrypt;
/**
*
* @author install1
*/
@Entity
public class AdminEditor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
private String adminName;
@Basic(optional = false)
@NotNull
private String adminPass;
public AdminEditor() {
}
public boolean verifyPassword(String pw) {
return (BCrypt.checkpw(pw, adminPass));
}
public AdminEditor(String adminName, String adminPass) {
this.adminName = adminName;
this.adminPass = BCrypt.hashpw(adminPass, BCrypt.gensalt());
}
public String getUserName() {
return adminName;
}
public void setUserName(String adminName) {
this.adminName = adminName;
}
public String getUserPass() {
return this.adminPass;
}
public void setUserPass(String adminPass) {
this.adminPass = adminPass;
}
}
@@ -0,0 +1,63 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
/**
*
* @author install1
*/
@Entity
@Table(name = "mapboard")
public class MapBoard implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
private String mapName;
public MapBoard() {
}
@OneToMany(cascade = CascadeType.PERSIST)
private List<MapValues> mapvalues = new ArrayList();
public List<MapValues> getMapvalues() {
return mapvalues;
}
public void setMapName(String mapName) {
this.mapName = mapName;
}
public void addMapvalues(MapValues mapvalue){
this.mapvalues.add(mapvalue);
}
public void setMapvalues(List<MapValues> mapvalues) {
this.mapvalues = mapvalues;
}
public MapBoard(String mapName) {
this.mapName = mapName;
}
public String getMapName() {
return mapName;
}
}
@@ -0,0 +1,127 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
/**
*
* @author install1
*/
@Entity
public class MapValues implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Basic(optional = false)
@NotNull
private Integer id;
@Basic(optional = false)
@NotNull
private int position;
@Basic(optional = false)
@NotNull
private String playerSteamID;
@Basic(optional = false)
@NotNull
private float time;
@Basic(optional = false)
@NotNull
private int mapPoints;
@ManyToOne()
@JoinTable(name = "mapboard_mapvalues")
private MapBoard mapboards;
public MapBoard getMapBoards() {
return mapboards;
}
public void setMapBoards(MapBoard mapBoards) {
this.mapboards = mapBoards;
}
public MapValues() {
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getPlayerSteamID() {
return playerSteamID;
}
public void setPlayerSteamID(Player player) {
this.playerSteamID = player.getSteamID();
}
public float getTime() {
return time;
}
public void setTime(float time) {
this.time = time;
}
public int getMapPoints() {
return mapPoints;
}
public void setMapPoints(int mapPoints) {
this.mapPoints = mapPoints;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof MapValues)) {
return false;
}
MapValues other = (MapValues) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.MapValues[ id=" + id + " ]";
}
}
@@ -0,0 +1,112 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
/**
*
* @author install1
*/
@Entity
public class Player implements Serializable {
public Player(String steamID, String name) {
this.steamID = steamID;
this.name = name;
}
public Player() {
}
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
private String steamID;
@Basic(optional = false)
@NotNull
private String name;
@Basic(optional = false)
@NotNull
private String avatar;
private int rank = 0;
private int playerPoints = 0;
private int timesCount = 0;
@ManyToMany(mappedBy = "players", cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private List<UrlBanners> urlBanners = new ArrayList();
public String getSteamID() {
return steamID;
}
public void setSteamID(String steamID) {
this.steamID = steamID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String Avatar) {
this.avatar = Avatar;
}
public int getRank() {
return rank;
}
public void setRank(int Rank) {
this.rank = Rank;
}
public int getPlayerPoints() {
return playerPoints;
}
public void setPlayerPoints(int PlayerPoints) {
this.playerPoints = PlayerPoints;
}
public void addPlayerPoints(int points) {
this.playerPoints += points;
}
public int getTimesCount() {
return timesCount;
}
public void setTimesCount(int timesCount) {
this.timesCount = timesCount;
}
public Collection<UrlBanners> getUrlBanners() {
return urlBanners;
}
public void setUrlBanners(List<UrlBanners> urlBanners) {
this.urlBanners = urlBanners;
}
}
@@ -0,0 +1,54 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;
/**
*
* @author install1
*/
@Entity
public class UrlBanners implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
private String name;
private String badgeUrl;
@ManyToMany
private List<Player> players = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBadgeUrl() {
return badgeUrl;
}
public void setBadgeUrl(String badgeUrl) {
this.badgeUrl = badgeUrl;
}
}
@@ -0,0 +1,16 @@
package exceptions;
/**
*
* @author [email protected]
*/
public class AuthenticationException extends Exception{
public AuthenticationException(String message) {
super(message);
}
public AuthenticationException() {
super("Could not be Authenticated");
}
}
@@ -0,0 +1,96 @@
package exceptions;
import com.google.gson.Gson;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
/*
Utility class to map errors into JSON
*/
class Error {
private int statusCode;
private String statusDescription;
private String errorMessage;
public Error(int statusCode, String statusDescription, String errorMessage) {
this.statusCode = statusCode;
this.statusDescription = statusDescription;
this.errorMessage = errorMessage;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getStatusDescription() {
return statusDescription;
}
public void setStatusDescription(String statusDescription) {
this.statusDescription = statusDescription;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
static private final Gson gson = new Gson();
@Override
public Response toResponse(Throwable ex) {
Response.StatusType type = getStatusType(ex);
Logger.getLogger(GenericExceptionMapper.class.getName()).log(Level.SEVERE, null, ex);
Error error = new Error(
type.getStatusCode(),
type.getReasonPhrase(),
ex.getLocalizedMessage());
String errJson = gson.toJson(error);
return Response.status(error.getStatusCode())
.entity(errJson)
.type(MediaType.APPLICATION_JSON)
.build();
}
private Response.StatusType getStatusType(Throwable ex) {
if (ex instanceof WebApplicationException) {
return((WebApplicationException)ex).getResponse().getStatusInfo();
}
if(ex instanceof AuthenticationException){
return Response.Status.FORBIDDEN;
} else {
return Response.Status.INTERNAL_SERVER_ERROR;
}
}
//Small hack, to provide json-error response in the filter
public static Response makeErrRes(String msg,int status){
Error error = new Error(
status,
msg,
msg);
String errJson =gson.toJson(error);
return Response.status(error.getStatusCode())
.entity(errJson)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
@@ -0,0 +1,16 @@
package exceptions;
/**
*
* @author [email protected]
*/
public class NotFoundException extends Exception{
public NotFoundException(String message) {
super(message);
}
public NotFoundException() {
super("Requested item could not be found");
}
}
@@ -0,0 +1,290 @@
package facade;
import DTO.MapBoardDTO;
import DTO.PlayerMapBoardDTO;
import DTO.PlayerDTO;
import DataMapper.DataMapperCalls;
import com.google.common.collect.MapMaker;
import entity.MapBoard;
import entity.MapValues;
import entity.Player;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import utils.PuSelector;
public class Facade {
private ConcurrentMap<String, Player> playerCache = new MapMaker().concurrencyLevel(4).makeMap();
private ConcurrentMap<String, MapBoard> mapBoardCache = new MapMaker().concurrencyLevel(4).makeMap();
private ConcurrentMap<String, ConcurrentMap<String, MapValues>> playerRelatedMapValuesCache = new MapMaker().concurrencyLevel(6).makeMap();
private final long EXPIRE_TIME_IN_SECONDS = TimeUnit.SECONDS.convert(30, TimeUnit.MINUTES);
private Instant elapsedTime;
private int initSetup = 0;
public Facade() {
elapsedTime = Instant.now();
initSetup = 1;
}
public List<MapBoardDTO> getSpecificMap(String mapname, int stage) {
List<MapBoardDTO> returnlist = new ArrayList();
String mapRetrieved = mapname + "S" + stage;
MapBoard mapBoard = mapBoardCache.getOrDefault(mapRetrieved, null);
if (mapBoard == null){
mapRetrieved = mapname;
mapBoard = mapBoardCache.get(mapRetrieved);
}
List<MapValues> mapvalues = mapBoard.getMapvalues();
for (MapValues mapvalue : mapvalues) {
returnlist.add(new MapBoardDTO(mapvalue, playerCache.get(mapvalue.getPlayerSteamID()).getName()));
}
return returnlist;
}
public List<PlayerMapBoardDTO> getPlayerMaps(String steamid) {
try {
ConcurrentMap<String, MapValues> playerMaps = playerRelatedMapValuesCache.get(steamid);
List<PlayerMapBoardDTO> playerMapBoardDtos = new ArrayList();
for (Entry<String, MapValues> entries : playerMaps.entrySet()) {
PlayerMapBoardDTO mapBoardDto = new PlayerMapBoardDTO(steamid);
mapBoardDto.addMapValues(entries.getValue(), entries.getKey());
playerMapBoardDtos.add(mapBoardDto);
}
return playerMapBoardDtos;
} catch (Exception ex) {
return null;
}
}
public PlayerDTO getPlayer(String steamid) {
EntityManager em = PuSelector.getEntityManagerFactory("pu").createEntityManager();
try {
Query query = em.createQuery("SELECT a FROM Player AS a WHERE a.steamID LIKE :steamID")
.setParameter("steamID", steamid);
Player player = (Player) query.getSingleResult();
return new PlayerDTO(player);
} finally {
em.close();
}
}
public Collection<PlayerDTO> getleaderBoard() {
EntityManager em = PuSelector.getEntityManagerFactory("pu").createEntityManager();
try {
Query query = em.createQuery("SELECT a FROM Player AS a ORDER BY A.rank ASC ");
List<Player> players = (List<Player>) query.getResultList();
Collection<PlayerDTO> playersDTO = new ArrayList();
for (Player player : players) {
playersDTO.add(new PlayerDTO(player));
}
return playersDTO;
} finally {
em.close();
}
}
private void addNewPlayerValuesToCache(Collection<Player> keyCollection) {
for (Player player : keyCollection) {
playerCache.put(player.getSteamID(), player);
}
}
private String convertCommunityIdToSteamId(long communityId) {
long steamId1 = communityId % 2;
long steamId2 = communityId - 76561197960265728L;
steamId2 = (steamId2 - steamId1) / 2;
return "STEAM_0:" + steamId1 + ":" + steamId2;
}
private void retrieveAvatarFull(String avatarurl) {
//https://steamcommunity.com/profiles/76561198517905428 some nosteamers have no information available on steams rest-endpoints
try {
URL url = new URL(avatarurl);
//System.out.println("avatarurl: " + avatarurl + "\n");
JSONTokener tokener = new JSONTokener(url.openStream());
JSONObject root = new JSONObject(tokener);
JSONObject jsonObject = root.getJSONObject("response");
JSONArray jsonArray = jsonObject.getJSONArray("players");
int incrementer = 0;
for (; incrementer < jsonArray.length();) {
System.out.println("incrementer: " + incrementer + "\n");
try {
String steamID64 = jsonArray.getJSONObject(incrementer).getString("steamid");
String avatar = jsonArray.getJSONObject(incrementer).getString("avatarfull");
String steamID = convertCommunityIdToSteamId(Long.valueOf(steamID64));
playerCache.get(steamID).setAvatar(avatar);
} catch (Exception ex) {
System.out.println("ex: " + ex.getLocalizedMessage() + "\n");
}
incrementer++;
}
} catch (MalformedURLException ex) {
Logger.getLogger(Facade.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Facade.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void updateAvatarsToCache() {
//http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=262F3F0C6B83E0F263C272C3762002F1&steamids=76561198029832363,76561198003907342
StringBuilder avatarURL = new StringBuilder();
avatarURL.append("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=262F3F0C6B83E0F263C272C3762002F1&steamids=");
int incrementer = 0;
for (Player player : playerCache.values()) {
if (incrementer > 0) {
avatarURL.append(",");
}
incrementer++;
avatarURL.append(Long.toString(convertSteamIdToCommunityId(player.getSteamID())));
//550 is too large size for url.openStream(), fetch limit is probably about 100 players best
if (incrementer >= 100 || incrementer >= playerCache.size()) {
retrieveAvatarFull(avatarURL.toString());
avatarURL = new StringBuilder();
avatarURL.append("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=262F3F0C6B83E0F263C272C3762002F1&steamids=");
incrementer = 0;
}
}
}
private void setNonExistingAvatarOnPlayers() {
for (Player player : playerCache.values()) {
String avatar = player.getAvatar();
if (avatar == null) {
player.setAvatar("https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_full.jpg");
}
}
}
public static long convertSteamIdToCommunityId(String steamId) {
if (steamId.matches("^STEAM_[0-1]:[0-1]:[0-9]+$")) {
String[] tmpId = steamId.substring(8).split(":");
return Long.valueOf(tmpId[0]) + Long.valueOf(tmpId[1]) * 2 + 76561197960265728L; //76561197960265728L
} else if (steamId.matches("^\\[U:[0-1]:[0-9]+\\]+$")) {
String[] tmpId = steamId.substring(3, steamId.length() - 1).split(":");
return Long.valueOf(tmpId[0]) + Long.valueOf(tmpId[1]) + 76561197960265728L; //76561197960265727L
}
return 0;
}
private void addNewMapBoardValuesToCache(Collection<MapBoard> value) {
for (MapBoard mapboard : value) {
mapBoardCache.put(mapboard.getMapName(), mapboard);
}
}
private void orderingMapBoardValuesByTime() {
Collection<MapBoard> mapboards = mapBoardCache.values();
for (MapBoard mapboard : mapboards) {
List<MapValues> mapvalues = new ArrayList(mapboard.getMapvalues());
mapvalues.sort(Comparator.comparing(MapValues::getTime));
mapBoardCache.get(mapboard.getMapName()).setMapvalues(mapvalues);
}
}
private void setPositionAndMapPoints() {
for (MapBoard mapboard : mapBoardCache.values()) {
List<MapValues> mapvalues = mapboard.getMapvalues();
int playerCount = mapvalues.size();
int position = 1;
for (MapValues mapvalue : mapvalues) {
mapvalue.setPosition(position);
float percentageSpreader = 0;
percentageSpreader = playerCount - position;
mapvalue.setMapPoints((int) Math.floor((percentageSpreader / playerCount) * 100));
position++;
}
}
}
private void setPlayerPoints() {
for (MapBoard mapboard : mapBoardCache.values()) {
List<MapValues> mapvalues = mapboard.getMapvalues();
for (MapValues mapvalue : mapvalues) {
String steamID = mapvalue.getPlayerSteamID();
int mapPoints = mapvalue.getMapPoints();
System.out.println("\nmapPoints: " + mapPoints + "\n");
playerCache.get(steamID).addPlayerPoints(mapPoints);
}
}
}
private void updatePlayerRanks() {
List<Player> playerList = new ArrayList(playerCache.values());
playerList.sort(Comparator.comparing(Player::getPlayerPoints).reversed());
int rank = 1;
for (Player player : playerList) {
playerCache.get(player.getSteamID()).setRank(rank);
rank++;
}
}
public void setTimesAsociatedToPeople() {
Collection<MapBoard> mapboards = mapBoardCache.values();
for (MapBoard mapboard : mapboards) {
List<MapValues> mapvalues = mapboard.getMapvalues();
for (MapValues mapvalue : mapvalues) {
ConcurrentMap<String, MapValues> playerMapValueCache = playerRelatedMapValuesCache.getOrDefault(mapvalue.getPlayerSteamID(), null);
if (playerMapValueCache == null) {
ConcurrentMap<String, MapValues> localMap = new MapMaker().concurrencyLevel(4).makeMap();
localMap.put(mapboard.getMapName(), mapvalue);
playerRelatedMapValuesCache.put(mapvalue.getPlayerSteamID(), localMap);
} else {
playerMapValueCache.put(mapboard.getMapName(), mapvalue);
playerRelatedMapValuesCache.put(mapvalue.getPlayerSteamID(), playerMapValueCache);
}
}
}
}
public void checkTimeElapse() {
Instant current = Instant.now();
long timeElapsed = Duration.between(elapsedTime, current).toMillis();
System.out.println("timeElapsed: " + timeElapsed + "\n");
if (timeElapsed >= EXPIRE_TIME_IN_SECONDS || initSetup > 0) {
initSetup = 0;
elapsedTime = Instant.now();
Entry<Collection<Player>, Collection<MapBoard>> playersMapBoards = DataMapperCalls.getAllValues();
Collection<MapBoard> mapBoardCollection = playersMapBoards.getValue();
playerCache.clear();
mapBoardCache.clear();
playerRelatedMapValuesCache.clear();
addNewMapBoardValuesToCache(mapBoardCollection);
addNewPlayerValuesToCache(playersMapBoards.getKey());
updateAvatarsToCache();
setNonExistingAvatarOnPlayers();
orderingMapBoardValuesByTime();
setPositionAndMapPoints();
setPlayerPoints();
updatePlayerRanks();
setTimesAsociatedToPeople();
}
}
public List<Player> getAllPlayersFromCache() {
checkTimeElapse();
return new ArrayList(playerCache.values());
}
public Collection<MapBoard> getAllMapBoardsFromCache() {
checkTimeElapse();
return mapBoardCache.values();
}
}
@@ -0,0 +1,33 @@
package rest;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
@javax.ws.rs.ApplicationPath("api")
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
resources.add(RolesAllowedDynamicFeature.class);
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method. It is automatically
* populated with all resources defined in the project. If required, comment
* out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(cors.CorsRequestFilter.class);
resources.add(cors.CorsResponseFilter.class);
resources.add(exceptions.GenericExceptionMapper.class);
resources.add(org.glassfish.jersey.server.wadl.internal.WadlResource.class);
resources.add(rest.TimerResource.class);
resources.add(security.JWTAuthenticationFilter.class);
resources.add(security.LoginEndpoint.class);
}
}
@@ -0,0 +1,56 @@
package rest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import facade.Facade;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
@Path("timers")
public class TimerResource {
Facade facade = new Facade();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
@Context
private UriInfo context;
@Context
SecurityContext securityContext;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("leaderboard")
public String retrieveLeaderBoard() {
return gson.toJson(facade.getleaderBoard());
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("player/{steamid}")
public String retrievePlayer(@PathParam("steamid") String steamid) {
return gson.toJson(facade.getPlayer(steamid));
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("player/maps/{steamid}")
public String retrievePlayerMaps(@PathParam("steamid") String steamid) {
facade.checkTimeElapse();
return gson.toJson(facade.getPlayerMaps(steamid));
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("map/{mapname}/{number}")
public String retrieveSpecificMapStages(@PathParam("mapname") String mapname, @PathParam("number") int stage) {
facade.checkTimeElapse();
return gson.toJson(facade.getSpecificMap(mapname, stage));
}
}
@@ -0,0 +1,87 @@
package security;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
import exceptions.AuthenticationException;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Priority;
import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
@Provider
@Priority(Priorities.AUTHENTICATION)
public class JWTAuthenticationFilter implements ContainerRequestFilter {
private static final List<Class<? extends Annotation>> securityAnnotations
= Arrays.asList(DenyAll.class, PermitAll.class, RolesAllowed.class);
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext request) throws IOException {
if (isSecuredResource()) {
String token = request.getHeaderString("x-access-token");//
if (token == null) {
request.abortWith(exceptions.GenericExceptionMapper.makeErrRes(token, 403));
return;
}
try {
UserPrincipal user = getUserPrincipalFromTokenIfValid(token);
//What if the client had logged out????
request.setSecurityContext(new JWTSecurityContext(user, request));
} catch (AuthenticationException | ParseException | JOSEException ex) {
Logger.getLogger(JWTAuthenticationFilter.class.getName()).log(Level.SEVERE, null, ex);
request.abortWith(exceptions.GenericExceptionMapper.makeErrRes("Token not valid (timed out?)", 403));
}
}
}
private boolean isSecuredResource() {
for (Class<? extends Annotation> securityClass : securityAnnotations) {
if (resourceInfo.getResourceMethod().isAnnotationPresent(securityClass)) {
return true;
}
}
for (Class<? extends Annotation> securityClass : securityAnnotations) {
if (resourceInfo.getResourceClass().isAnnotationPresent(securityClass)) {
return true;
}
}
return false;
}
private UserPrincipal getUserPrincipalFromTokenIfValid(String token)
throws ParseException, JOSEException, AuthenticationException {
SignedJWT signedJWT = SignedJWT.parse(token);
//Is it a valid token (generated with our shared key)
JWSVerifier verifier = new MACVerifier(SharedSecret.getSharedKey());
if (signedJWT.verify(verifier)) {
if (new Date().getTime() > signedJWT.getJWTClaimsSet().getExpirationTime().getTime()) {
throw new AuthenticationException("Your Token is no longer valid");
}
String username = signedJWT.getJWTClaimsSet().getClaim("username").toString();
return new UserPrincipal(username);
} else {
throw new JOSEException("User could not be extracted from token");
}
}
}
@@ -0,0 +1,34 @@
package security;
import java.security.Principal;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.SecurityContext;
public class JWTSecurityContext implements SecurityContext {
UserPrincipal user;
ContainerRequestContext request;
public JWTSecurityContext(UserPrincipal user,ContainerRequestContext request) {
this.user = user;
this.request = request;
}
@Override
public boolean isSecure() {
return request.getUriInfo().getBaseUri().getScheme().equals("https");
}
@Override
public Principal getUserPrincipal() {
return user;
}
@Override
public String getAuthenticationScheme() {
return "JWT"; //Only for INFO
}
@Override
public boolean isUserInRole(String role) {
//no roles, only admins have a user, to delete times
return true;
}
}
@@ -0,0 +1,57 @@
package security;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import utils.UserFacade;
import java.util.Date;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import utils.PuSelector;
@Path("login")
public class LoginEndpoint {
public static final int TOKEN_EXPIRE_TIME = 1000 * 60 * 30; //30 min
public static final UserFacade userFacade = UserFacade.getInstance(PuSelector.getEntityManagerFactory("pu"));
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
private String createToken(String userName, List<String> roles) throws JOSEException {
StringBuilder res = new StringBuilder();
for (String string : roles) {
res.append(string);
res.append(",");
}
String rolesAsString = res.length() > 0 ? res.substring(0, res.length() - 1) : "";
String issuer = "semesterdemo_security_course";
JWSSigner signer = new MACSigner(SharedSecret.getSharedKey());
Date date = new Date();
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject(userName)
.claim("username", userName)
.claim("roles", rolesAsString)
.claim("issuer", issuer)
.issueTime(date)
.expirationTime(new Date(date.getTime() + TOKEN_EXPIRE_TIME))
.build();
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
signedJWT.sign(signer);
return signedJWT.serialize();
}
}
@@ -0,0 +1,19 @@
package security;
import java.security.SecureRandom;
/* This generates a secure random per execution of the server
* A server restart, will generate a new key, making all existing tokens invalid
* For production (and if a load-balancer is used) come up with a persistent key strategy */
public class SharedSecret {
private static byte[] secret;
public static byte[] getSharedKey() {
if (secret == null) { //Or better read as an environment variable set on production server
secret = new byte[32];
new SecureRandom().nextBytes(secret);
}
return secret;
}
}
@@ -0,0 +1,37 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package security;
import entity.AdminEditor;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author install1
*/
public class UserPrincipal implements Principal {
private String username;
/* Create a UserPrincipal, given the Entity class User*/
public UserPrincipal(AdminEditor admin) {
this.username = admin.getUserName();
}
public UserPrincipal(String username) {
super();
this.username = username;
}
@Override
public String getName() {
return username;
}
}
@@ -0,0 +1,50 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package utils;
import entity.AdminEditor;
import entity.MapBoard;
import entity.Player;
import facade.Facade;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* @author install1
*/
public class Initialization {
public static void main(String[] args) {
setupDBTablesWithPresentValues();
}
private static void setupDBTablesWithPresentValues() {
Facade facade = new Facade();
List<Player> getAllPlayers = facade.getAllPlayersFromCache();
Collection<MapBoard> getAllMapBoards = facade.getAllMapBoardsFromCache();
AdminEditor admin = new AdminEditor("jenz", "1234");
EntityManager em = PuSelector.getEntityManagerFactory("pu").createEntityManager();
//simply cant persist collections/list
em.getTransaction().begin();
em.createQuery("delete from AdminEditor").executeUpdate();
em.createQuery("delete from MapBoard").executeUpdate();
em.createQuery("delete from MapValues").executeUpdate();
em.createQuery("delete from Player").executeUpdate();
em.createQuery("delete from UrlBanners").executeUpdate();
for (Player player : getAllPlayers) {
System.out.println("player: " + player.getName());
em.persist(player);
}
for (MapBoard mapboard : getAllMapBoards) {
System.out.println("mapboard: " + mapboard.getMapName());
em.persist(mapboard);
}
em.persist(admin);
em.getTransaction().commit();
}
}
@@ -0,0 +1,81 @@
package utils;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.eclipse.persistence.config.PersistenceUnitProperties;
// Returns an EntityManagerFactory using the provided PU_NAME)
// DO NOT CHANGE THIS FILE, UNLESS YOU REALLY KNOW WHAT YOU DO
public class PuSelector {
private static String PU_NAME;
private static EntityManagerFactory emf;
public static final String FILE_EXTENSION = ".properties";
public static Properties loadProperties(String propertyFile) {
Properties props = new Properties();
String propertyFileName = propertyFile + FILE_EXTENSION;
try {
props.load(PuSelector.class.getResourceAsStream("/META-INF/" + propertyFileName));
for (Object key : props.keySet()) {
props.setProperty((String) key, props.getProperty((String) key).trim());
}
} catch (Exception ex) {
throw new RuntimeException("Could not load properies for :" + propertyFileName);
}
return props;
}
public static EntityManagerFactory getEntityManagerFactory(String persistenceUnitName) {
//This ensures that only ONE factory will ever be used. If a test has set to a test-db, this will be used also for example from the login end-point
if (emf != null) {
System.out.println("Returned an EntityManagerFactory for --> " + emf.getProperties().get("javax.persistence.jdbc.url"));
return emf;
}
PU_NAME = persistenceUnitName;
//You can override the given PU_NAME from maven like this for integration tests: mvn -DPU_NAME=pu-test-on-travis verify
String puVal = System.getProperty("PU_NAME");
if (puVal != null) {
PU_NAME = puVal;
}
Properties props = null;
/*
If you set the following environment variables on your production server, the production persistence unit will use them.
export SERVER="PRODUCTION"
export USER="YOUR_DATABASE_USER"
export PASSWORD="YOUR PASSWORD FOR THE PRODUCTION DB"
MUST BE SET in this file on Digital Ocean (if file don't exist, create it): /usr/share/tomcat8/bin/setenv.sh
*/
System.out.println("SERVER -->" + System.getenv("SERVER"));
boolean isDeployed = (System.getenv("SERVER") != null);
if (isDeployed) {
if (System.getenv("SERVER").equals("PRODUCTION")) { //You could also setup a Test server where you set SERVER="TEST"
PU_NAME = "pu_production";
System.out.println("PU_NAME: " + PU_NAME);
props = loadProperties(PU_NAME);
String user = System.getenv("USER") != null ? System.getenv("USER") : "";
String password = System.getenv("PASSWORD") != null ? System.getenv("PASSWORD") : "";
props.setProperty("javax.persistence.jdbc.user", user);
props.setProperty("javax.persistence.jdbc.password", password);
}
}
//If NOT deployed
if (props == null) {
props = loadProperties(PU_NAME);
}
//Only reason to give persistence file another name is that it must NOT be git-ignored, which is what we usually do with persistence.xml
props.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
"META-INF/persistence-for-all.xml");
emf = Persistence.createEntityManagerFactory("DO_NOT_RENAME_ME", props);
return emf;
}
}
@@ -0,0 +1,29 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package utils;
import javax.persistence.EntityManagerFactory;
/**
*
* @author install1
*/
public class UserFacade {
private static EntityManagerFactory emf;
private static UserFacade instance;
private UserFacade() {
}
public static UserFacade getInstance(EntityManagerFactory factory) {
if (instance == null) {
emf = factory;
instance = new UserFacade();
}
return instance;
}
}
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DO_NOT_RENAME_ME" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- This is the template usd for all databases (persistence units) used by this project -->
<!-- Remember to add your Entity Classes below -->
<class>entity.AdminEditor</class>
<class>entity.MapBoard</class>
<class>entity.MapValues</class>
<class>entity.Player</class>
<class>entity.UrlBanners</class>
<!-- maybe remove this again? <exclude-unlisted-classes>false</exclude-unlisted-classes> -->
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<!-- DONT ADD ANYTHING HERE
This part will come from one of the pu_xxxx.properties files -->
</properties>
</persistence-unit>
</persistence>
@@ -0,0 +1,18 @@
# THIS REPRESENTS YOUR "PRODUCTION" DATABASE WHICH YOU MUST CREATE REMOTELY ON YOUR DROPLET
# The properties below will be merged in to your persistence unit, when the PuSelector class detects it is running on Digital Ocean
# For this to work you must set the following environment variables on Digital Ocean in this file (if file don't exist, create it):
# /usr/share/tomcat8/bin/setenv.sh
# Add these three lines to the file:
# export SERVER="PRODUCTION"
# export USER="YOUR_DATABASE_USER"
# export PASSWORD="YOUR PASSWORD FOR THE PRODUCTION DB"
# Observe no username and password below:
javax.persistence.jdbc.driver=com.mysql.jdbc.Driver
javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/unloze_racetimer_css?zeroDateTimeBehavior=convertToNull&serverTimezone=UTC
javax.persistence.schema-generation.database.action=create
@@ -0,0 +1,12 @@
# THIS REPRESENTS A LOCAL DATABASE (USED FOR INTEGRATION TESTS) WHICH YOU MUST CREATE
# The properties below will be merged in to your persistence unit, when your tests are activated by travis like this (see .travis.yml):
# mvn -DPU_NAME=pu_travis_integration_test verify
# DO NOT change this file, it's use by Travis (see .travis.yml) and is ready for use
javax.persistence.jdbc.url=jdbc:mysql://127.0.0.1:3306/travis_test?zeroDateTimeBehavior=convertToNull&serverTimezone=UTC
javax.persistence.jdbc.user=root
javax.persistence.jdbc.driver=com.mysql.jdbc.Driver
# Password not required for the Travis Database
javax.persistence.schema-generation.database.action=drop-and-create
@@ -0,0 +1,11 @@
# THIS REPRESENTS AN IN-MEMORY-DATABASE USED TO "MOCK AWAY" THE EXTERNAL DATABASE FOR UNIT-TESTS
# The properties below will be merged in to your persistence unit, when persistence unit name "pu_unit_test_mock" is given to the PuSelector
# DO NOT CHANGE THIS FILE. ITS READY TO USE BOTH LOCALLY, AND FOR TEST'S RUNNING ON TRAVIS
javax.persistence.jdbc.url=jdbc:derby:memory:myTestDB;create=true
javax.persistence.jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver
eclipselink.logging.level=WARNING
eclipselink.canonicalmodel.subpackage=test
javax.persistence.schema-generation.database.action=create
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/Racetimer"/>
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
@@ -0,0 +1,60 @@
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Set;
import javax.servlet.ServletException;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.scan.StandardJarScanner;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
public class EmbeddedTomcat {
private final static String TMP_DIR = System.getProperty("java.io.tmpdir")+"/EmbeddedTomcat";
Tomcat tomcat;
public void start(int port,String appContext) throws ServletException,
MalformedURLException,
LifecycleException {
String webAppLocation = "src/main/webapp/";
tomcat = new Tomcat();
tomcat.setBaseDir(TMP_DIR);
tomcat.setPort(port);
// Define a web application context.
Context context = tomcat.addWebapp(appContext, new File(webAppLocation).getAbsolutePath());
((StandardJarScanner) context.getJarScanner()).setScanManifest(false);
// Add servlet that will register Jersey REST resources
Tomcat.addServlet(context, "jersey-container-servlet", resourceConfig());
context.addServletMappingDecoded("/api/*", "jersey-container-servlet");
tomcat.start();
//Don't comment the line below in unless you know what you do. It will block here, waiting for the server to stop.
//This can be usefull for testing the embedded server from a browser or postman
//tomcat.getServer().await();
}
private ServletContainer resourceConfig() {
//Load the Wizard-generated rest.ApplicationConfig - class
Set<Class<?>> resources = new rest.ApplicationConfig().getClasses();
System.out.println("Loaded Classes Count: "+resources.size());
return new ServletContainer(new ResourceConfig(resources));
}
public void stop() {
try {
tomcat.stop();
tomcat.destroy();
//Delete our embedded Tomcat's temp
FileUtils.deleteDirectory(new File(TMP_DIR));
}
catch (IOException | LifecycleException ex) {
throw new RuntimeException(ex);
}
}
}
@@ -0,0 +1,38 @@
package accepttests;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.given;
import io.restassured.parsing.Parser;
import java.net.MalformedURLException;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import org.apache.catalina.LifecycleException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class AcceptTestDemo {
private static final String APP_CONTEXT = "/jwtbackend"; //IMPORTANT--> this should reflect the value in META-INF/context.xml
private static EntityManagerFactory emf;
@Test
public void serverIsRunning() {
System.out.println("TESTING IF SERVER IS RUNNING");
given().when().get().then().statusCode(200);
}
@BeforeClass
public static void setUpBeforeAll() throws LifecycleException, ServletException, MalformedURLException {
RestAssured.baseURI = "https://deploy.mydemos.dk/";
//RestAssured.port = 80;
//RestAssured.basePath = APP_CONTEXT;
RestAssured.defaultParser = Parser.JSON;
}
@AfterClass
public static void tearDownAfterAll() throws LifecycleException {
}
}
@@ -0,0 +1,131 @@
package integrationtests;
import org.junit.BeforeClass;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import io.restassured.http.ContentType;
import io.restassured.parsing.Parser;
import java.net.MalformedURLException;
import javax.servlet.ServletException;
import org.apache.catalina.LifecycleException;
import static org.hamcrest.Matchers.*;
import org.junit.AfterClass;
import org.junit.Test;
import utils.PuSelector;
public class IntegrationTest {
/*
protected static int SERVER_PORT;
protected static String APP_CONTEXT;
protected static String SERVER_URL;
public IntegrationTest() {
}
private static EmbeddedTomcat tomcat;
@BeforeClass
public static void setUpBeforeAll() throws ServletException, MalformedURLException, LifecycleException {
System.out.println("INTEGRATION TEST");
TestUtils.setupTestUsers(PuSelector.getEntityManagerFactory("pu_integration_test"));
SERVER_PORT = 7777;
APP_CONTEXT = "/restbackend";
SERVER_URL = "http://localhost";
//Setup and start Embedded Tomcat for testing
tomcat = new EmbeddedTomcat();
tomcat.start(SERVER_PORT, APP_CONTEXT);
//Setup RestAssured
RestAssured.baseURI = SERVER_URL;
RestAssured.port = SERVER_PORT;
RestAssured.basePath = APP_CONTEXT;
RestAssured.defaultParser = Parser.JSON;
}
@AfterClass
public static void tearDownAfterAll() {
tomcat.stop();
}
//This is how we hold on to the token after login, similar to that a client must store the token somewhere
private static String securityToken;
//Utility method to login and set the returned securityToken
private static void login(String role, String password) {
String json = String.format("{username: \"%s\", password: \"%s\"}", role, password);
securityToken = given()
.contentType("application/json")
.body(json)
.when().post("/api/login")
.then()
.extract().path("token");
}
private void logOut() {
securityToken = null;
}
@Test
public void serverIsRunning() {
System.out.println("Testing is server UP");
given().when().get("/").then().statusCode(200);
}
@Test
public void testRestNoAuthenticationRequired() {
given()
.contentType("application/json")
.when()
.get("/api/info").then()
.statusCode(200)
.body("msg", equalTo("Hello anonymous"));
}
@Test
public void testRestForAdmin() {
login("admin", "test");
given()
.contentType("application/json")
.accept(ContentType.JSON)
.header("x-access-token", securityToken)
.when()
.get("/api/info/admin").then()
.statusCode(200)
.body("msg", equalTo("Hello to (admin) User: admin"));
}
@Test
public void testRestForUser() {
login("user", "test");
given()
.contentType("application/json")
.header("x-access-token", securityToken)
.when()
.get("/api/info/user").then()
.statusCode(200)
.body("msg", equalTo("Hello to User: user"));
}
@Test
public void userNotAuthenticated() {
logOut();
given()
.contentType("application/json")
.when()
.get("/api/info/user").then()
.statusCode(403);
}
@Test
public void adminNotAuthenticated() {
logOut();
given()
.contentType("application/json")
.when()
.get("/api/info/user").then()
.statusCode(403);
}
*/
}
@@ -0,0 +1,39 @@
package unittest;
import exceptions.AuthenticationException;
import javax.persistence.EntityManagerFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import utils.PuSelector;
public class TestUsers {
/*
private static UserFacade facade;
@BeforeClass
public static void setUpClass() {
EntityManagerFactory emf = PuSelector.getEntityManagerFactory("pu_unit_test_mock");
facade = UserFacade.getInstance(emf);
TestUtils.setupTestUsers(emf);
}
@AfterClass
public static void tearDownClass() {
}
@Test
public void getUserValid() throws AuthenticationException {
User u = facade.getVeryfiedUser("user", "test");
assertEquals("user", u.getUserName());
}
@Test(expected = AuthenticationException.class)
public void getUserInValid() throws AuthenticationException {
User u = facade.getVeryfiedUser("user", "testxxxx");
assertEquals("user", u.getUserName());
}
*/
}
@@ -0,0 +1,6 @@
INSERT INTO users (user_name, user_pass) VALUES ('user', 'test');
INSERT INTO users (user_name, user_pass) VALUES ('admin', 'test');
INSERT INTO roles (role_name) VALUES ('user');
INSERT INTO roles (role_name) VALUES ('admin');
INSERT INTO user_roles (user_name, role_name) VALUES ('user', 'admin');
INSERT INTO user_roles (user_name, role_name) VALUES ('admin', 'admin');
@@ -0,0 +1,29 @@
-- use NAME OF YOUR DB;
create table users
(
user_email varchar(45) primary key,
user_pass varchar(255) not null,
users_data varchar(255)
);
create table roles
(
role_name varchar(15) primary key
);
create table user_roles
(
user_email varchar(45) not null,
role_name varchar(15) not null,
foreign key (user_email) references users (user_email),
foreign key (role_name) references roles (role_name),
primary key( user_email, role_name )
);
INSERT INTO users (user_email, user_pass,users_data) VALUES ('[email protected]', 'test','Kurt_admins personal data');
INSERT INTO users (user_email, user_pass,users_data) VALUES ('[email protected]', 'test','Peter_users personal data');
INSERT INTO roles (role_name) VALUES ('user');
INSERT INTO roles (role_name) VALUES ('admin');
INSERT INTO user_roles (user_email, role_name) VALUES ('[email protected]', 'admin');
INSERT INTO user_roles (user_email, role_name) VALUES ('[email protected]', 'user');