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

BIN
RaceTimer/racetimer_endpoints/.DS_Store vendored Normal file

Binary file not shown.

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

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;'

View File

@ -0,0 +1 @@
# Semesterprojekt

View File

@ -12,7 +12,7 @@
</goals>
<properties>
<netbeans.deploy>true</netbeans.deploy>
<netbeans.deploy.clientUrlPart>index.jsp</netbeans.deploy.clientUrlPart>
<netbeans.deploy.clientUrlPart>/racetimers</netbeans.deploy.clientUrlPart>
</properties>
</action>
<action>
@ -28,7 +28,7 @@
<properties>
<netbeans.deploy.debugmode>true</netbeans.deploy.debugmode>
<netbeans.deploy>true</netbeans.deploy>
<netbeans.deploy.clientUrlPart>index.jsp</netbeans.deploy.clientUrlPart>
<netbeans.deploy.clientUrlPart>/racetimers</netbeans.deploy.clientUrlPart>
</properties>
</action>
<action>
@ -44,7 +44,7 @@
<properties>
<netbeans.deploy>true</netbeans.deploy>
<netbeans.deploy.profilemode>true</netbeans.deploy.profilemode>
<netbeans.deploy.clientUrlPart>index.jsp</netbeans.deploy.clientUrlPart>
<netbeans.deploy.clientUrlPart>/racetimers</netbeans.deploy.clientUrlPart>
</properties>
</action>
</actions>

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.

View File

@ -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;
}
}

View File

@ -3,25 +3,21 @@
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package FunctionLayer;
package DTO;
import entity.MapValues;
/**
*
* @author install1
*/
public class MapValues {
public class MapValuesDTO {
private int position;
private Users user;
private String playerSteamID;
private float time;
private int mapPoints;
public MapValues(int position, Users user, float time, int mapPoints) {
this.position = position;
this.user = user;
this.time = time;
this.mapPoints = mapPoints;
}
public int getPosition() {
return position;
}
@ -30,12 +26,12 @@ public class MapValues {
this.position = position;
}
public Users getUser() {
return user;
public String getPlayerSteamID() {
return playerSteamID;
}
public void setUser(Users user) {
this.user = user;
public void setPlayerSteamID(String playerSteamID) {
this.playerSteamID = playerSteamID;
}
public float getTime() {
@ -54,4 +50,14 @@ public class MapValues {
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();
}
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -3,28 +3,19 @@
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package FunctionLayer;
package DTO;
/**
*
* @author install1
*/
public class RecentTimes {
public class RecentTimesDTO {
private String MYSQLSteamID;
private String MYSQLStage;
private float MYSQLOldTime;
private Users user;
private PlayerDTO player;
private float improvedTime;
//in jsp use user object for displaying avatar, steam id, link to user site, improvedtime for showing improved time, stage for displaying what stage on what map
public RecentTimes(String MYSQLSteamID, String MYSQLStage, float MYSQLOldTime, Users user, float improvedTime) {
this.MYSQLSteamID = MYSQLSteamID;
this.MYSQLStage = MYSQLStage;
this.MYSQLOldTime = MYSQLOldTime;
this.user = user;
this.improvedTime = improvedTime;
}
public String getMYSQLSteamID() {
return MYSQLSteamID;
@ -50,12 +41,12 @@ public class RecentTimes {
this.MYSQLOldTime = MYSQLOldTime;
}
public Users getUser() {
return user;
public PlayerDTO getPlayer() {
return player;
}
public void setUser(Users user) {
this.user = user;
public void setPlayer(PlayerDTO player) {
this.player = player;
}
public float getImprovedTime() {
@ -66,4 +57,15 @@ public class RecentTimes {
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;
}
}

View File

@ -3,7 +3,7 @@
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DBAcess;
package DataMapper;
import java.sql.Connection;
import java.sql.SQLException;
@ -22,10 +22,9 @@ public class DBCPDataSource {
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.setUrl("jdbc:mysql://localhost:3306/unloze_racetimer_css?useLegacyDatetimeCode=false&serverTimezone=UTC");
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.setPassword("ahsdbahb/#¤FHdasd");
ds.setMaxTotal(-1);
ds.setMinIdle(5);
ds.setMaxIdle(-1);
@ -41,5 +40,4 @@ public class DBCPDataSource {
private DBCPDataSource() {
}
}

View File

@ -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;
}
}

View File

@ -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());
}
}
}

View File

@ -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");
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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 + " ]";
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,16 @@
package exceptions;
/**
*
* @author lam@cphbusiness.dk
*/
public class AuthenticationException extends Exception{
public AuthenticationException(String message) {
super(message);
}
public AuthenticationException() {
super("Could not be Authenticated");
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,16 @@
package exceptions;
/**
*
* @author lam@cphbusiness.dk
*/
public class NotFoundException extends Exception{
public NotFoundException(String message) {
super(message);
}
public NotFoundException() {
super("Requested item could not be found");
}
}

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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));
}
}

View File

@ -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");
}
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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>

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -1,2 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/mavenproject1"/>
<Context path="/Racetimer"/>

View File

@ -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>

View File

@ -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);
}
}
}

View File

@ -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 {
}
}

View File

@ -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);
}
*/
}

View File

@ -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());
}
*/
}

View File

@ -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');

View File

@ -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 ('kurt_admin@somewhere.dk', 'test','Kurt_admins personal data');
INSERT INTO users (user_email, user_pass,users_data) VALUES ('peter_user@somewhere.dk', '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 ('kurt_admin@somewhere.dk', 'admin');
INSERT INTO user_roles (user_email, role_name) VALUES ('peter_user@somewhere.dk', 'user');

23
RaceTimer/racetimer_react/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br>
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br>
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br>
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br>
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

12812
RaceTimer/racetimer_react/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,33 @@
{
"name": "racetimer_react",
"version": "0.1.0",
"private": true,
"dependencies": {
"bootstrap": "^4.3.1",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-router-dom": "^5.0.1",
"react-scripts": "3.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,39 @@
import React, { Component } from 'react';
import { HashRouter as Router, Route } from "react-router-dom";
import Leaderboard from "./Leaderboard/Leaderboard";
import Player from "./Player/Player";
import Maps from "./Maps/Maps";
class App extends Component {
constructor(props) {
super(props);
this.state = {
players: []
};
}
setLeaderboard = (players) => {
this.setState({ players })
}
render() {
return (
<React.Fragment>
<Router>
<Route path={`/leaderboard`} render={(props) => {
return (<Leaderboard setLeaderboard={this.setLeaderboard} />)
}} />
<Route path={`/player/:steamid`} render={(props) => {
return (<Player {...props} />)
}} />
<Route path={`/map/:mapname/:stage`} render={(props) => {
return (<Maps {...props} />)
}} />
</Router>
</React.Fragment>
)
}
}
export default App;

View File

@ -0,0 +1,43 @@
const URLleaderboard = "http://localhost:8080/racetimer_endpoints-1.0/api/timers/leaderboard";
const URLPlayer = "http://localhost:8080/racetimer_endpoints-1.0/api/timers/player/";
const URLPlayerMaps = "http://localhost:8080/racetimer_endpoints-1.0/api/timers/player/maps/";
const URLMaps = "http://localhost:8080/racetimer_endpoints-1.0/api/timers/map/";
function makeOptions(method, body) {
var opts = {
method: method,
headers: {
"Content-type": "application/json"
}
};
if (body) {
opts.body = JSON.stringify(body);
}
return opts;
}
function handleHttpErrors(res) {
if (!res.ok) {
return Promise.reject({ status: res.status, fullError: res.json() });
}
return res.json();
}
class DataFacade {
getLeaderBoard = () => {
return fetch(URLleaderboard).then(handleHttpErrors);
};
getPlayer = steamID => {
return fetch(URLPlayer + steamID).then(handleHttpErrors);
}
getPlayerTimes = steamID => {
return fetch(URLPlayerMaps + steamID).then(handleHttpErrors);
}
getMapTimes = (mapname, stage) => {
return fetch(URLMaps + mapname + "/" + stage).then(handleHttpErrors);
}
}
export default new DataFacade();

View File

@ -0,0 +1,48 @@
import React from 'react';
import Facade from '../Datafacade/datafacade';
import { NavLink } from 'react-router-dom'
class Leaderboard extends React.Component {
constructor(props) {
super(props)
this.state = {
players: []
};
}
componentDidMount = async () => {
const players = await Facade.getLeaderBoard();
this.setState({ players });
this.props.setLeaderboard(players);
};
render() {
return (
<React.Fragment>
<div className="container mm" style={{ marginTop: "85px" }}>
<div style={{
position: 'absolute', left: '50%', top: '30%'
}}>
{this.state.players.map(e => (
<div>
<NavLink to={'/player/' + e.steamID}>
<strong class="col-lg-1 col-centered" /> {e.steamID}<br />
<strong class="col-lg-1 col-centered" />{e.name}<br />
<img src={e.Avatar} /> <br />
<strong class="col-lg-1 col-centered" />Rank: {e.Rank}<br />
<strong class="col-lg-1 col-centered" />Points: {e.PlayerPoints}<br />
<strong class="col-lg-1 col-centered" />Times: {e.Times}<br />
<br />
<br />
</NavLink>
</div>
))}
</div>
</div>
</React.Fragment>
);
}
}
export default Leaderboard;

View File

@ -0,0 +1,55 @@
import React from 'react';
import Facade from '../Datafacade/datafacade';
class Maps extends React.Component {
constructor(props) {
super(props)
this.state = {
mapTimes: [],
mapName: '',
};
}
componentWillMount = async () => {
const mapname = this.props.match.params.mapname;
const stage = this.props.match.params.stage;
const mapTimes = await Facade.getMapTimes(mapname, stage);
this.setState({ mapTimes });
this.setState({ mapName: mapname })
};
render() {
return (
<React.Fragment>
<div className="container mm" style={{ marginTop: "85px" }}>
<div style={{
position: 'absolute', left: '50%', top: '30%'
}}>
<div>
<strong class="col-lg-1 col-centered" />{this.state.mapName}<br />
<br />
<br />
{this.state.mapTimes.map(e => (
<div>
<strong class="col-lg-1 col-centered" /> Position: {e.position}<br />
<strong class="col-lg-1 col-centered" /> SteamID: {e.steamID}<br />
<strong class="col-lg-1 col-centered" /> Name: {e.name}<br />
<strong class="col-lg-1 col-centered" /> Mappoints: {e.mapPoint}<br />
<strong class="col-lg-1 col-centered" /> Time: 0{e.mapTimeMinutes}:{e.mapTimeSeconds}<br />
<br />
<br />
</div>
))}
</div>
</div>
</div>
</React.Fragment>
)
}
}
export default Maps;

View File

@ -0,0 +1,62 @@
import React from 'react';
import Facade from '../Datafacade/datafacade';
import { NavLink } from 'react-router-dom'
class Player extends React.Component {
constructor(props) {
super(props)
this.state = {
player: {},
mapTimes: []
};
}
componentWillMount = async () => {
const steamid = this.props.match.params.steamid;
const player = await Facade.getPlayer(steamid);
const mapTimes = await Facade.getPlayerTimes(steamid);
this.setState({ player });
this.setState({ mapTimes });
};
render() {
return (
<React.Fragment>
<div className="container mm" style={{ marginTop: "85px" }}>
<div style={{
position: 'absolute', left: '50%', top: '30%'
}}>
<div>
<a href={"http://steamcommunity.com/profiles/" + this.state.player.steamID64}>
<strong class="col-lg-1 col-centered" /> {this.state.player.steamID}<br />
<strong class="col-lg-1 col-centered" />{this.state.player.name}<br />
<img src={this.state.player.Avatar} /> <br />
<strong class="col-lg-1 col-centered" />Rank: {this.state.player.Rank}<br />
<strong class="col-lg-1 col-centered" />Points: {this.state.player.PlayerPoints}<br />
<strong class="col-lg-1 col-centered" />Times: {this.state.player.Times}<br />
<br />
<br />
</a>
{this.state.mapTimes.map(e => (
<div>
<NavLink to={'/map/' + e.mapname + "/" + e.mapstage}>
<strong class="col-lg-1 col-centered" /> Map: {e.mapname}<br />
<strong class="col-lg-1 col-centered" /> Stage: {e.mapstage}<br />
<strong class="col-lg-1 col-centered" /> Position: {e.position}<br />
<strong class="col-lg-1 col-centered" /> Time: 0{e.mapTimeMinutes}:{e.mapTimeSeconds}<br />
<strong class="col-lg-1 col-centered" /> MapPoints: {e.mapPoint}<br />
<br />
<br />
</NavLink>
</div>
))}
</div>
</div>
</div>
</React.Fragment>
);
}
}
export default Player;

View File

@ -0,0 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.css';
import { HashRouter } from 'react-router-dom';
ReactDOM.render(<HashRouter><App /></HashRouter>, document.getElementById('root'));

View File

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_j2eeVersion>1.7-web</org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_j2eeVersion>
<org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_deploy_2e_server>Tomcat</org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_deploy_2e_server>
</properties>
</project-shared-configuration>

View File

@ -1,123 +0,0 @@
<?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>com.mycompany</groupId>
<artifactId>racetimer_web</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>racetimer_web</name>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>com.github.go-ive</groupId>
<artifactId>steam-api</artifactId>
<version>5.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20170516</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
<classifier>adapters</classifier>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>26.0-jre</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<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>
</plugins>
</build>
</project>

View File

@ -1,43 +0,0 @@
/*
* 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 DBAcess;
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 DBCPDataSource2 {
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_stats?useLegacyDatetimeCode=false&serverTimezone=UTC");
ds.setUrl("jdbc:mysql://localhost:3306/unloze_stats?useLegacyDatetimeCode=false&serverTimezone=UTC");
ds.setUsername("unloze_stats");
ds.setPassword("R8J8E9Fzmcc7ZfDAGAk7");
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 DBCPDataSource2() {
}
}

View File

@ -1,42 +0,0 @@
/*
* 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 DBAcess;
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 DBCPDataSource3 {
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/xenforo?useLegacyDatetimeCode=false&serverTimezone=UTC");
ds.setUrl("jdbc:mysql://localhost:3306/xenforo?useLegacyDatetimeCode=false&serverTimezone=UTC");
ds.setUsername("XenforoWebTimer");
ds.setPassword("FNF#)(EFHFSNj23n4nfdsfbFE");
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 DBCPDataSource3() {
}
}

View File

@ -1,548 +0,0 @@
/*
* 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 DBAcess;
import FunctionLayer.ErrorMessageDisplay;
import FunctionLayer.MapBoard;
import FunctionLayer.MapValues;
import FunctionLayer.RecentTimes;
import FunctionLayer.UserBanners;
import FunctionLayer.Users;
import com.google.common.base.Stopwatch;
import com.google.common.collect.HashBiMap;
import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author install1
*/
public class DataMapper {
private static String DefaultAvatar = "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_full.jpg";
public static List<MapBoard> GetAllMapColoumns() throws SQLException, ErrorMessageDisplay, IOException, PropertyVetoException {
List<MapBoard> AllMapColoumns = new ArrayList();
List<MapValues> mv = new ArrayList();
int prefixSkip = 3;
MapBoard mapboardnames = null;
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
try {
l_cCon = DBCPDataSource.getConnection();
String l_sSQL = "SELECT * FROM `zetimer_table` LIMIT 1;";
l_pStatement = l_cCon.prepareStatement(l_sSQL);
l_rsSearch = l_pStatement.executeQuery();
ResultSetMetaData metaData = l_rsSearch.getMetaData();
for (int i = prefixSkip; i <= metaData.getColumnCount(); i++) {
mapboardnames = new MapBoard(metaData.getColumnLabel(i), mv);
AllMapColoumns.add(mapboardnames);
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper 1 " + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
Collections.sort(AllMapColoumns,
(d1, d2) -> d1.getMapName().compareTo(d2.getMapName()));
return AllMapColoumns;
}
public static List<Users> getAllUsersNameSteamIdInitialization() throws SQLException, ErrorMessageDisplay, IOException, PropertyVetoException {
List<Users> userlist = new ArrayList();
Users user = null;
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
try {
l_cCon = DBCPDataSource.getConnection();
String l_sSQL = "SELECT steam_auth, name FROM `zetimer_table`";
l_pStatement = l_cCon.prepareStatement(l_sSQL);
l_rsSearch = l_pStatement.executeQuery();
while (l_rsSearch.next()) {
user = new Users(l_rsSearch.getString(1), l_rsSearch.getString(2), "", 0, 0, 0);
userlist.add(user);
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper 2 " + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return userlist;
}
public static LinkedHashMap<Users, Float> GetMapTimes(String mapindexes, List<Users> LeaderBoard, LinkedHashMap<String, Users> Usermap) throws ErrorMessageDisplay {
String l_sSQL = "SELECT steam_auth, "
+ mapindexes + " FROM `zetimer_table` WHERE "
+ mapindexes + " > 0.00 ORDER BY "
+ mapindexes + " ASC;";
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
LinkedHashMap<Users, Float> usertimes = new LinkedHashMap();
Users user;
try {
l_cCon = DBCPDataSource.getConnection();
l_pStatement = l_cCon.prepareStatement(l_sSQL);
l_rsSearch = l_pStatement.executeQuery();
while (l_rsSearch.next()) {
user = Usermap.get(l_rsSearch.getString(1));
usertimes.put(user, l_rsSearch.getFloat(2));
}
l_cCon.close();
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper GetMapTimes sql: " + l_sSQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return usertimes;
}
public static List<Users> SetUsersAvatars(List<Users> userAvatarLinks) throws IOException, ErrorMessageDisplay, SQLException {
String l_SQL = "SELECT * FROM `userStrings`";
HashBiMap<String, String> strList = HashBiMap.create();
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
try {
l_cCon = DBCPDataSource.getConnection();
l_pStatement = l_cCon.prepareStatement(l_SQL);
l_rsSearch = l_pStatement.executeQuery();
while (l_rsSearch.next()) {
strList.put(l_rsSearch.getString(1), l_rsSearch.getString(2));
}
for (int i = 0; i < userAvatarLinks.size(); i++) {
String str = strList.inverse().get(userAvatarLinks.get(i).getSteamID());
if (str != null) {
userAvatarLinks.get(i).setAvatar(str);
} else {
userAvatarLinks.get(i).setAvatar(DefaultAvatar);
}
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("Datamapper sql: " + l_SQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return userAvatarLinks;
}
public synchronized static void UpdatePlayerAvatarsToDB(List<Users> userAvatars, List<String> ConvertedID, int start, int end) throws ErrorMessageDisplay, MalformedURLException, IOException {
List<String> arr = new ArrayList();
String Avatar = "";
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
String l_sSQL = "CREATE TABLE IF NOT EXISTS `userStrings` (`strings` VARCHAR(254) NOT NULL, `steam_auth` VARCHAR(65) NOT NULL, PRIMARY KEY (`steam_auth`));";
try {
l_cCon = DBCPDataSource.getConnection();
l_pStatement = l_cCon.prepareStatement(l_sSQL);
l_pStatement.executeUpdate();
for (int i = start; i < end; i++) {
StringBuilder sb = new StringBuilder();
URL url = new URL("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=262F3F0C6B83E0F263C272C3762002F1&steamids="
+ ConvertedID.get(i));
try (InputStream is = url.openStream();
InputStreamReader in = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(in)) {
String word;
while ((word = reader.readLine()) != null) {
sb.append(word);
}
}
arr.add(sb.toString());
}
for (int i = start; i < end; i++) {
if (arr.get(i).contains("avatarfull\":")) {
Avatar = arr.get(i).substring(arr.get(i).indexOf("avatarfull\":") + 13, arr.get(i).indexOf("\",\"personastate"));
l_sSQL = "INSERT INTO `userStrings` (`steam_auth`, `strings`) VALUES ('" + userAvatars.get(i).getSteamID()
+ "', '" + Avatar + "') ON DUPLICATE KEY UPDATE `strings` = '" + Avatar + "'";
l_pStatement.addBatch(l_sSQL);
}
}
l_pStatement.executeBatch();
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper 5 sql: " + l_sSQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
}
/**
* @deprecated @param PlayerIndexSteamID
* @return
* @throws ErrorMessageDisplay
* @throws SQLException
* @throws IOException
* @throws PropertyVetoException
*/
public static List<Float> GetSpecificPlayerTimes(String PlayerIndexSteamID) throws ErrorMessageDisplay, SQLException, IOException, PropertyVetoException {
List<Float> PlayerTimes = new ArrayList();
List<MapBoard> AllMaps = GetAllMapColoumns();
String l_sSQL = "";
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
try {
l_cCon = DBCPDataSource.getConnection();
for (int i = 0; i < AllMaps.size(); i++) {
l_sSQL = "SELECT " + AllMaps.get(i).getMapName() + " FROM `zetimer_table` WHERE steam_auth = '" + PlayerIndexSteamID + "'"
+ " AND " + AllMaps.get(i).getMapName() + " > 0.00";
l_pStatement = l_cCon.prepareStatement(l_sSQL);
l_rsSearch = l_pStatement.executeQuery();
if (l_rsSearch.next()) {
PlayerTimes.add(l_rsSearch.getFloat(1));
}
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper sql: " + l_sSQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return PlayerTimes;
}
public static List<MapBoard> GetPlayerRelatedMaps(String PlayerIndexSteamID) throws ErrorMessageDisplay, SQLException, IOException, PropertyVetoException {
List<MapBoard> AllPlayerRelatedMaps = new ArrayList();
List<MapValues> mv = new ArrayList();
List<MapBoard> AllMaps = GetAllMapColoumns();
MapBoard map = null;
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
String l_SQL = "";
try {
l_cCon = DBCPDataSource.getConnection();
for (int i = 0; i < AllMaps.size(); i++) {
l_SQL = "SELECT " + AllMaps.get(i).getMapName() + " FROM `zetimer_table` WHERE steam_auth = '" + PlayerIndexSteamID + "'";
l_pStatement = l_cCon.prepareStatement(l_SQL);
l_rsSearch = l_pStatement.executeQuery();
if (l_rsSearch.next()) {
if (l_rsSearch.getFloat(1) > 0.0) {
map = new MapBoard(AllMaps.get(i).getMapName(), mv);
AllPlayerRelatedMaps.add(map);
}
}
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper sql: " + l_SQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return AllPlayerRelatedMaps;
}
public static int GetAdmin(String name, String psw) throws ErrorMessageDisplay {
String l_SQL = "";
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
try {
l_cCon = DBCPDataSource.getConnection();
l_SQL = "CREATE TABLE IF NOT EXISTS `Admins` (`username` VARCHAR(64) NOT NULL, `password` VARCHAR(65) NOT NULL, `role` VARCHAR(65) NOT NULL, PRIMARY KEY (`username`));";
l_pStatement = l_cCon.prepareStatement(l_SQL);
l_pStatement.executeUpdate();
l_SQL = "SELECT role FROM `Admins` WHERE username = '" + name + "' AND password = '" + psw + "'";
l_pStatement = l_cCon.prepareStatement(l_SQL);
l_rsSearch = l_pStatement.executeQuery();
if (l_rsSearch.next()) {
switch (l_rsSearch.getString(1)) {
case "Tech": {
return 3;
}
case "Global Admin": {
return 2;
}
case "Admin": {
return 1;
}
}
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper sql: " + l_SQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return 0;
}
public static void DeleteMapEntry(String map, String steamID) throws ErrorMessageDisplay {
String l_SQL = "";
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
try {
l_cCon = DBCPDataSource.getConnection();
l_SQL = "UPDATE `zetimer_table` SET `" + map + "` = 0.000 WHERE `steam_auth` = '" + steamID + "';";
l_pStatement = l_cCon.prepareStatement(l_SQL);
l_pStatement.executeUpdate();
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper sql: " + l_SQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
}
public static MapBoard getCurrentMap() throws IOException, ErrorMessageDisplay {
String GetCurrentmap = "https://api.steampowered.com/IGameServersService/GetServerList/v1/?key=262F3F0C6B83E0F263C272C3762002F1&filter=addr\\151.80.230.149:27015&limit=1";
JSONObject json = readJsonFromUrl(GetCurrentmap);
String sjson = json.toString();
List<MapValues> mv = new ArrayList();
MapBoard map = new MapBoard(sjson.substring(sjson.indexOf("map\":\"") + 6, sjson.indexOf("\",\"specport\"")), mv);
return map;
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
}
public static List<String> getHlstatsxIngamePlayerSteamID() throws ErrorMessageDisplay {
List<String> ingamePlayersSteamID = new ArrayList();
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
String l_SQL = "";
try {
l_cCon = DBCPDataSource2.getConnection();
l_SQL = "SELECT steam_id FROM `hlstats_Livestats` WHERE server_id = 1";
l_pStatement = l_cCon.prepareStatement(l_SQL);
l_rsSearch = l_pStatement.executeQuery();
while (l_rsSearch.next()) {
ingamePlayersSteamID.add(l_rsSearch.getString(1));
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper sql: " + l_SQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return ingamePlayersSteamID;
}
public static List<MapBoard> getCurrentMapLevels(MapBoard map) throws SQLException, ErrorMessageDisplay, IOException, PropertyVetoException {
List<MapBoard> allColoumns = GetAllMapColoumns();
List<MapBoard> currentLvls = new ArrayList();
for (int i = 0; i < allColoumns.size(); i++) {
if (allColoumns.get(i).getMapName().contains(map.getMapName())) {
currentLvls.add(allColoumns.get(i));
}
}
return currentLvls;
}
public static Map<String, String> getAllAdmins() throws ErrorMessageDisplay {
Map<String, String> HM = new HashMap();
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
String l_SQL = "SELECT username, role FROM `Admins`";
try {
l_cCon = DBCPDataSource.getConnection();
l_pStatement = l_cCon.prepareStatement(l_SQL);
l_rsSearch = l_pStatement.executeQuery();
while (l_rsSearch.next()) {
HM.put(l_rsSearch.getString(1), l_rsSearch.getString(2));
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper sql: " + l_SQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return HM;
}
public static void createAdmin(String name, String password, String role) throws ErrorMessageDisplay {
String l_SQL = "INSERT INTO `Admins` (`username`,`password`,`role`) VALUES (?, ?, ?)";
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
try {
l_cCon = DBCPDataSource.getConnection();
l_pStatement = l_cCon.prepareStatement(l_SQL);
l_pStatement.setString(1, name);
l_pStatement.setString(2, password);
l_pStatement.setString(3, role);
l_pStatement.executeUpdate();
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper sql: " + l_SQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
}
public static LinkedHashMap<Users, Float> GetMapRelatedTimes(MapBoard mapname, List<Users> LeaderBoardInfo, Map<String, Users> UserMap) throws ErrorMessageDisplay {
LinkedHashMap<Users, Float> LHM = new LinkedHashMap();
int index = 0;
int counter = 0;
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
String l_SQL = "SELECT steam_auth, "
+ mapname.getMapName() + " FROM `zetimer_table` WHERE "
+ mapname.getMapName() + " > 0.00 ORDER BY "
+ mapname.getMapName() + " ASC;";
try {
l_cCon = DBCPDataSource.getConnection();
l_pStatement = l_cCon.prepareStatement(l_SQL);
l_rsSearch = l_pStatement.executeQuery();
while (l_rsSearch.next()) {
counter++;
Users user = UserMap.get(l_rsSearch.getString(1));
index = LeaderBoardInfo.indexOf(user);
LHM.put(LeaderBoardInfo.get(index), l_rsSearch.getFloat(2));
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper GetMapRelatedTimes sql: " + l_SQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return LHM;
}
public static List<UserBanners> getUserbanners(List<Users> PlayerLeaderBoard, List<String> ConvertedID) throws ErrorMessageDisplay {
List<UserBanners> UBList = new ArrayList();
UserBanners ub;
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
List<Integer> user_id = new ArrayList();
List<Long> Provider_key = new ArrayList();
List<Integer> user_group_id = new ArrayList();
String l_SQL = "SELECT t2.user_id, t2.provider_key, t1.user_group_id FROM `xf_user_group_relation` t1, `xf_user_external_auth` t2 WHERE t1.user_id = t2.user_id AND t2.provider = \"steam\"";
try {
l_cCon = DBCPDataSource3.getConnection();
l_pStatement = l_cCon.prepareStatement(l_SQL);
l_rsSearch = l_pStatement.executeQuery();
while (l_rsSearch.next()) {
user_id.add(l_rsSearch.getInt(1));
Provider_key.add(l_rsSearch.getLong(2));
user_group_id.add(l_rsSearch.getInt(3));
}
int indexIDs = 0;
int counter = 0;
while (indexIDs < user_id.size()) {
List<Integer> Iarr = new ArrayList();
while (indexIDs < user_id.size() && Provider_key.get(indexIDs).intValue() == Provider_key.get(counter).intValue()) {
//2 = user, 6 = mapper, 7 = admin, 8 = technical staff, 10 = leader, 12 = vip, 15 = event winner, 19 = discord manager, 20 NSFW, 25 = event manager
// 11 = GA
int groupID = user_group_id.get(indexIDs);
if (groupID == 6 || groupID == 7 || groupID == 8 || groupID == 10 || groupID == 11 || groupID == 12 || groupID == 15 || groupID == 19
|| groupID == 25) {
Iarr.add(groupID);
}
indexIDs++;
}
counter = indexIDs;
boolean end = false;
if (indexIDs >= user_id.size()) {
indexIDs = user_id.size() - 1;
end = true;
}
int index = ConvertedID.indexOf(String.valueOf(Provider_key.get(indexIDs - 1)));
if (index != -1) {
ub = new UserBanners(Iarr, PlayerLeaderBoard.get(index));
UBList.add(ub);
}
if (end) {
break;
}
/*
if (Objects.equals(Provider_key.get(indexIDs - 1), Long.valueOf("76561198343747394"))) {
throw new ErrorMessageDisplay("UBList kaka size: " + UBList.get(UBList.size() - 1).getUrlBanners().size()
+ " name: " + UBList.get(UBList.size() - 1).getUser().getName());
}
*/
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper getUserbanners sql: " + l_SQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return UBList;
}
public static List<RecentTimes> getRecentTimes() throws ErrorMessageDisplay {
List<RecentTimes> RTlist = new ArrayList();
Connection l_cCon = null;
PreparedStatement l_pStatement = null;
ResultSet l_rsSearch = null;
String SQL = "SELECT * FROM `recenttimes_table`";
try {
l_cCon = DBCPDataSource.getConnection();
l_pStatement = l_cCon.prepareStatement(SQL);
l_rsSearch = l_pStatement.executeQuery();
while (l_rsSearch.next() && RTlist.size() < 500) {
RecentTimes RT = new RecentTimes(l_rsSearch.getString(2), l_rsSearch.getString(3), l_rsSearch.getFloat(4), null, 0);
RTlist.add(RT);
}
} catch (SQLException ex) {
throw new ErrorMessageDisplay("failed in DataMapper getRecentTimes sql: " + SQL + ex.getMessage());
} finally {
CloseConnections(l_pStatement, l_rsSearch, l_cCon);
}
return RTlist;
}
public static void CloseConnections(PreparedStatement ps, ResultSet rs, Connection con) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(DataMapper.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException ex) {
Logger.getLogger(DataMapper.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(DataMapper.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}

View File

@ -1,220 +0,0 @@
/*
* 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 FunctionLayer.Caching;
import FunctionLayer.ErrorMessageDisplay;
import FunctionLayer.LogicFacade;
import FunctionLayer.MapBoard;
import FunctionLayer.RecentTimes;
import FunctionLayer.UserBanners;
import FunctionLayer.Users;
import com.google.common.base.Stopwatch;
import com.google.common.collect.MapMaker;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author install1
*/
//https://stackoverflow.com/questions/15357953/cached-map-with-data-initialization-and-whole-data-refreshed-periodically-in-jav
public class GACaching {
//change to 3 hours again
public static final long EXPIRE_TIME_IN_SECONDS = TimeUnit.SECONDS.convert(3, TimeUnit.HOURS);
public static int UPDATE_AVATARS_CYCLE = 2;
public static int AVATAR_INDEXES = 0;
public static GACaching instance = new GACaching();
private final ConcurrentMap<Integer, Users> UsersCache;
private final ConcurrentMap<Integer, Users> UsersCachePoints;
private final ConcurrentMap<Integer, MapBoard> MapCache;
private final ConcurrentMap<Integer, MapBoard> MapCacheValues;
private final ConcurrentMap<Integer, UserBanners> UserBannerCache;
private final ConcurrentMap<Integer, Users> UserCacheTimeAmount;
private final ConcurrentMap<Integer, RecentTimes> UserCacheRecentTimes;
private final Stopwatch stopwatch;
public GACaching() {
this.stopwatch = Stopwatch.createUnstarted();
this.UsersCache = new MapMaker().concurrencyLevel(2).makeMap();
this.MapCache = new MapMaker().concurrencyLevel(2).makeMap();
this.UsersCachePoints = new MapMaker().concurrencyLevel(2).makeMap();
this.MapCacheValues = new MapMaker().concurrencyLevel(2).makeMap();
this.UserBannerCache = new MapMaker().concurrencyLevel(2).makeMap();
this.UserCacheTimeAmount = new MapMaker().concurrencyLevel(2).makeMap();
this.UserCacheRecentTimes = new MapMaker().concurrencyLevel(2).makeMap();
}
public synchronized void Initialization() throws ErrorMessageDisplay {
// if the map is not initialized, initialize it with the data
try {
if (!stopwatch.isRunning()) {
putAllConcurrentMaps();
stopwatch.start();
}
if (stopwatch.elapsed(TimeUnit.MINUTES) >= UPDATE_AVATARS_CYCLE && AVATAR_INDEXES < UserCacheTimeAmount.values().size()) {
UPDATE_AVATARS_CYCLE = (int) (stopwatch.elapsed().toMinutes() + 2);
updateAvatars(AVATAR_INDEXES);
}
// if the map is expired, refresh all the data in the map
if (stopwatch.elapsed(TimeUnit.SECONDS) >= EXPIRE_TIME_IN_SECONDS) {
UPDATE_AVATARS_CYCLE = 2;
if (AVATAR_INDEXES >= UserCacheTimeAmount.values().size()) {
AVATAR_INDEXES = 0;
}
clearConcurrentMaps();
putAllConcurrentMaps();
stopwatch.reset();
}
} catch (SQLException | IOException | PropertyVetoException ex) {
throw new ErrorMessageDisplay("Initialization failed: " + ex);
}
}
public synchronized void UpdateDeletedEntries() throws SQLException, ErrorMessageDisplay, IOException, PropertyVetoException {
clearConcurrentMaps();
putAllConcurrentMaps();
stopwatch.reset();
}
public synchronized void updateAvatars(int AVATAR_INDEXES1) throws ErrorMessageDisplay {
new Thread(() -> {
try {
LogicFacade.UpdatePlayerAvatarsToDB((new ArrayList(UserCacheTimeAmount.values())), AVATAR_INDEXES1);
} catch (IOException | ErrorMessageDisplay ex) {
Logger.getLogger(GACaching.class.getName()).log(Level.SEVERE, null, ex);
}
}).start();
//each itereation handle 200 updates
AVATAR_INDEXES += 200;
}
private Map<Integer, RecentTimes> getUserRecentTimesCache(ConcurrentMap<Integer, Users> UserCacheTimeAmount1, ConcurrentMap<Integer, MapBoard> mpb) throws ErrorMessageDisplay {
LinkedHashMap<Integer, RecentTimes> LHM = LogicFacade.getRecentTimes(UserCacheTimeAmount1, mpb);
return LHM;
}
private Map<Integer, Users> getUserCacheContent() throws SQLException, ErrorMessageDisplay, IOException, PropertyVetoException {
List<Users> Users;
Users = LogicFacade.getAllUsersNameSteamIdInitialization();
LinkedHashMap<Integer, Users> LHM = new LinkedHashMap();
for (int i = 0; i < Users.size(); i++) {
LHM.put(i, Users.get(i));
}
return LHM;
}
private Map<Integer, MapBoard> getMapBoardCacheContent() throws ErrorMessageDisplay, SQLException, IOException, PropertyVetoException {
List<MapBoard> MB;
MB = LogicFacade.GetAllMapColoumns();
LinkedHashMap<Integer, MapBoard> LHM = new LinkedHashMap();
for (int i = 0; i < MB.size(); i++) {
LHM.put(i, MB.get(i));
}
return LHM;
}
private Map<Integer, Users> getUserPointCacheContent(List<Users> PlayerLeaderBoard, List<MapBoard> mapBoard) throws ErrorMessageDisplay, SQLException, IOException, PropertyVetoException {
List<Users> Users;
Users = LogicFacade.getPlayerPointsAndRankInitialization(PlayerLeaderBoard, mapBoard);
LinkedHashMap<Integer, Users> LHM = new LinkedHashMap();
for (int i = 0; i < Users.size(); i++) {
LHM.put(i, Users.get(i));
}
return LHM;
}
private Map<Integer, MapBoard> getMapBoardCacheValues(List<MapBoard> mapBoard, List<Users> PlayerLeaderBoard) throws ErrorMessageDisplay {
List<MapBoard> MB;
MB = LogicFacade.getAllMapValues(mapBoard, PlayerLeaderBoard);
LinkedHashMap<Integer, MapBoard> LHM = new LinkedHashMap();
for (int i = 0; i < MB.size(); i++) {
LHM.put(i, MB.get(i));
}
return LHM;
}
private Map<Integer, UserBanners> getUserBannerCacheContent(List<Users> PlayerLeaderBoard) throws ErrorMessageDisplay {
List<UserBanners> UB;
UB = LogicFacade.getUserBanners(PlayerLeaderBoard);
LinkedHashMap<Integer, UserBanners> LHM = new LinkedHashMap();
for (int i = 0; i < UB.size(); i++) {
LHM.put(i, UB.get(i));
}
return LHM;
}
private Map<Integer, Users> getUserTimeCache(List<Users> PlayerLeaderBoard, List<MapBoard> mapBoard) {
List<Users> Users;
Users = LogicFacade.getPlayertimeAmount(PlayerLeaderBoard, mapBoard);
LinkedHashMap<Integer, Users> LHM = new LinkedHashMap();
for (int i = 0; i < Users.size(); i++) {
LHM.put(i, Users.get(i));
}
return LHM;
}
public List<MapBoard> getAllMapValues() {
List<MapBoard> MapColoumns = new ArrayList(MapCacheValues.values());
return MapColoumns;
}
public List<UserBanners> getUserBanners() {
List<UserBanners> UB = new ArrayList(UserBannerCache.values());
return UB;
}
public List<Users> getAllPlayerValues() {
List<Users> Users = new ArrayList(UserCacheTimeAmount.values());
return Users;
}
public List<RecentTimes> getAllRecentTimes() {
List<RecentTimes> RT = new ArrayList(UserCacheRecentTimes.values());
return RT;
}
public int getAvatatindexTest() {
return AVATAR_INDEXES;
}
public int getUPDATE_AVATARS_CYCLE() {
return UPDATE_AVATARS_CYCLE;
}
public int getStopWatchMinutes() {
return (int) stopwatch.elapsed(TimeUnit.MINUTES);
}
private void clearConcurrentMaps() {
UsersCache.clear();
MapCache.clear();
UsersCachePoints.clear();
MapCacheValues.clear();
UserBannerCache.clear();
UserCacheTimeAmount.clear();
UserCacheRecentTimes.clear();
}
private void putAllConcurrentMaps() throws SQLException, ErrorMessageDisplay, IOException, PropertyVetoException {
UsersCache.putAll(getUserCacheContent());
MapCache.putAll(getMapBoardCacheContent());
UsersCachePoints.putAll(getUserPointCacheContent(new ArrayList(UsersCache.values()), new ArrayList(MapCache.values())));
MapCacheValues.putAll(getMapBoardCacheValues(new ArrayList(MapCache.values()), new ArrayList(UsersCachePoints.values())));
UserBannerCache.putAll(getUserBannerCacheContent(new ArrayList(UsersCachePoints.values())));
UserCacheTimeAmount.putAll(getUserTimeCache(new ArrayList(UsersCachePoints.values()), new ArrayList(MapCacheValues.values())));
UserCacheRecentTimes.putAll(getUserRecentTimesCache(UserCacheTimeAmount, MapCacheValues));
}
}

View File

@ -1,121 +0,0 @@
/*
* 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 FunctionLayer.Caching;
import FunctionLayer.ErrorMessageDisplay;
import FunctionLayer.LogicFacade;
import FunctionLayer.MapBoard;
import FunctionLayer.Users;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author install1
*/
public class Guava {
//https://www.tutorialspoint.com/guava/guava_caching_utilities.htm
//https://stackoverflow.com/questions/31576136/how-should-i-implement-guava-cache-when-i-plan-to-cache-multiple-values-efficien
/**
* @deprecated @return the same list with Values for Usernames, steam ids
* and avatars on initializing being set
* @throws ErrorMessageDisplay
*/
public List<Users> getAllUsersNameSteamIdInitialization() throws ErrorMessageDisplay {
Supplier<List<Users>> fulllist = Suppliers.memoize(() -> {
List<Users> users = new ArrayList();
try {
users = LogicFacade.getAllUsersNameSteamIdInitialization();
} catch (SQLException | ErrorMessageDisplay | IOException | PropertyVetoException ex) {
Logger.getLogger(Guava.class.getName()).log(Level.SEVERE, null, ex);
}
return users;
});
return fulllist.get();
}
/**
* @deprecated
* @return
*/
public List<MapBoard> GetAllMapColoumns() {
Supplier<List<MapBoard>> fulllist = Suppliers.memoize(() -> {
List<MapBoard> MapColoumns = new ArrayList();
try {
MapColoumns = LogicFacade.GetAllMapColoumns();
} catch (SQLException | ErrorMessageDisplay | IOException | PropertyVetoException ex) {
Logger.getLogger(Guava.class.getName()).log(Level.SEVERE, null, ex);
}
return MapColoumns;
});
return fulllist.get();
}
/*
/**
* @deprecated @param PlayerLeaderBoard
* @return
public List<Users> getAllUsersNameSteamIdUpdates(List<Users> PlayerLeaderBoard) {
Supplier<List<Users>> fulllist = Suppliers.memoize(() -> {
List<Users> users = new ArrayList();
try {
users = LogicFacade.getAllUsersNameSteamIdUpdates(PlayerLeaderBoard);
} catch (SQLException | ErrorMessageDisplay | IOException | PropertyVetoException ex) {
Logger.getLogger(Guava.class.getName()).log(Level.SEVERE, null, ex);
}
return users;
});
return fulllist.get();
}*/
/**
* @deprecated
* @param PlayerLeaderBoard
* @param mapBoard
* @return
*/
public List<Users> getPlayerPointsAndRankInitialization(List<Users> PlayerLeaderBoard, List<MapBoard> mapBoard) {
Supplier<List<Users>> fulllist = Suppliers.memoize(() -> {
List<Users> users = new ArrayList();
try {
users = LogicFacade.getPlayerPointsAndRankInitialization(PlayerLeaderBoard, mapBoard);
} catch (SQLException | ErrorMessageDisplay | IOException | PropertyVetoException ex) {
Logger.getLogger(Guava.class.getName()).log(Level.SEVERE, null, ex);
}
return users;
});
return fulllist.get();
}
/**
* @deprecated
* @param PlayerLeaderBoard
* @param mapBoard
* @return
*/
public List<Users> getPlayerPointsAndRankUpdates(List<Users> PlayerLeaderBoard, List<MapBoard> mapBoard) {
Supplier<List<Users>> fulllist = Suppliers.memoize(() -> {
List<Users> users = new ArrayList();
try {
users = LogicFacade.getPlayerPointsAndRankUpdates(PlayerLeaderBoard, mapBoard);
} catch (SQLException | ErrorMessageDisplay | IOException | PropertyVetoException ex) {
Logger.getLogger(Guava.class.getName()).log(Level.SEVERE, null, ex);
}
return users;
});
return fulllist.get();
}
}

View File

@ -1,17 +0,0 @@
/*
* 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 FunctionLayer;
/**
*
* @author install1
*/
public class ErrorMessageDisplay extends Exception {
public ErrorMessageDisplay(String msg) {
super(msg);
}
}

View File

@ -1,424 +0,0 @@
/*
* 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 FunctionLayer;
import DBAcess.DataMapper;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
/**
*
* @author install1
*/
public class LogicFacade {
public static List<MapBoard> GetAllMapColoumns() throws ErrorMessageDisplay, SQLException, IOException, PropertyVetoException {
List<MapBoard> AllMapColoumns = DataMapper.GetAllMapColoumns();
AllMapColoumns = MapNameUpdate(AllMapColoumns);
return AllMapColoumns;
}
public static List<Users> getAllUsersNameSteamIdInitialization() throws SQLException, ErrorMessageDisplay, IOException, PropertyVetoException {
List<Users> users = DataMapper.getAllUsersNameSteamIdInitialization();
users = DataMapper.SetUsersAvatars(users);
return users;
}
private static List<MapBoard> MapNameUpdate(List<MapBoard> AllMapColoumns) {
int l_iLength = 0;
StringBuilder sb;
for (int i = 0; i < AllMapColoumns.size(); i++) {
l_iLength = AllMapColoumns.get(i).getMapName().length() - 1;
while (Character.isDigit(AllMapColoumns.get(i).getMapName().charAt(l_iLength))) {
l_iLength--;
}
if (AllMapColoumns.get(i).getMapName().charAt(l_iLength) == 'S') {
sb = new StringBuilder();
sb = sb.append(AllMapColoumns.get(i).getMapName().substring(0, l_iLength));
AllMapColoumns.get(i).setMapName(sb.toString() + " Stage: "
+ AllMapColoumns.get(i).getMapName().substring(l_iLength + 1, AllMapColoumns.get(i).getMapName().length()));
}
}
return AllMapColoumns;
}
private static List<RecentTimes> MapNameUpdateRecentTimes(List<RecentTimes> AllRecentTimes) {
int l_iLength = 0;
StringBuilder sb;
for (int i = 0; i < AllRecentTimes.size(); i++) {
l_iLength = AllRecentTimes.get(i).getMYSQLStage().length() - 1;
while (Character.isDigit(AllRecentTimes.get(i).getMYSQLStage().charAt(l_iLength))) {
l_iLength--;
}
if (AllRecentTimes.get(i).getMYSQLStage().charAt(l_iLength) == 'S') {
sb = new StringBuilder();
sb = sb.append(AllRecentTimes.get(i).getMYSQLStage().substring(0, l_iLength));
AllRecentTimes.get(i).setMYSQLStage(sb.toString() + " Stage: "
+ AllRecentTimes.get(i).getMYSQLStage().substring(l_iLength + 1, AllRecentTimes.get(i).getMYSQLStage().length()));
}
}
return AllRecentTimes;
}
public synchronized static void UpdatePlayerAvatarsToDB(List<Users> userAvatarLinks, int AVATAR_INDEXES1) throws IOException, ErrorMessageDisplay {
List<String> ConvertedID = new ArrayList();
int indexRange = AVATAR_INDEXES1;
if (AVATAR_INDEXES1 + 200 >= userAvatarLinks.size()) {
indexRange = userAvatarLinks.size();
} else {
indexRange += 200;
}
for (int i = AVATAR_INDEXES1; i < indexRange; i++) {
ConvertedID.add(Long.toString(convertSteamIdToCommunityId(userAvatarLinks.get(i).getSteamID())));
}
DataMapper.UpdatePlayerAvatarsToDB(userAvatarLinks, ConvertedID, AVATAR_INDEXES1, indexRange);
}
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;
}
public static Users getUser(String PlayerIndexSteamID, List<Users> users, List<MapBoard> mapBoard) throws ErrorMessageDisplay {
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getSteamID().equals(PlayerIndexSteamID)) {
Users user = users.get(i);
return user;
}
}
return null;
}
public static List<Users> getPlayerPointsAndRankInitialization(List<Users> LeaderBoard, List<MapBoard> AllMapColoumns) throws ErrorMessageDisplay, SQLException, IOException, PropertyVetoException {
LinkedHashMap<Users, Float> usertimes;
int Points = 0;
int index = 0;
LinkedHashMap<String, Users> HM = new LinkedHashMap();
List<Users> tempusers;
/*
AllMapColoumns roughly 58 itterations currently
LeaderBoard around 1500(?) right now
*/
for (int i = 0; i < LeaderBoard.size(); i++) {
HM.put(LeaderBoard.get(i).getSteamID(), LeaderBoard.get(i));
}
for (int i = 0; i < AllMapColoumns.size(); i++) {
usertimes = DataMapper.GetMapTimes(ConvertPageNameToDBName(AllMapColoumns.get(i).getMapName()), LeaderBoard, HM);
tempusers = new ArrayList(usertimes.keySet());
for (int j = 0; j < tempusers.size(); j++) {
Points = ConvertPositionToPoints(j, tempusers.size(), Points);
Users user = HM.get(tempusers.get(j).getSteamID());
if (user != null) {
index = LeaderBoard.indexOf(user);
LeaderBoard.get(index).setPlayerPoints(LeaderBoard.get(index).getPlayerPoints() + Points);
}
}
}
LeaderBoard.sort(Comparator.comparing(Users::getPlayerPoints).reversed());
for (int i = 0; i < LeaderBoard.size(); i++) {
LeaderBoard.get(i).setRank(i + 1);
}
return LeaderBoard;
}
/**
* @deprecated @param LeaderBoard
* @param AllMapColoumns
* @return
* @throws ErrorMessageDisplay
* @throws SQLException
* @throws IOException
* @throws PropertyVetoException
*/
public static List<Users> getPlayerPointsAndRankUpdates(List<Users> LeaderBoard, List<MapBoard> AllMapColoumns) throws ErrorMessageDisplay, SQLException, IOException, PropertyVetoException {
LinkedHashMap<Users, Float> usertimes;
int Points = 0;
int index = 0;
LinkedHashMap<String, Users> HM = new LinkedHashMap();
List<Users> tempusers;
for (int i = 0; i < LeaderBoard.size(); i++) {
HM.put(LeaderBoard.get(i).getSteamID(), LeaderBoard.get(i));
}
//grab ingame players and currently played map, only update those
//this means max 64 players can get updated and only stages on one map
MapBoard map = DataMapper.getCurrentMap();
List<MapBoard> MapLvls = DataMapper.getCurrentMapLevels(map);
List<String> IngamePlayersSteamID = DataMapper.getHlstatsxIngamePlayerSteamID();
List<Users> IngamePlayers = ConvertSteam3ToSteam2(IngamePlayersSteamID, HM);
for (int i = 0; i < MapLvls.size(); i++) {
usertimes = DataMapper.GetMapTimes(ConvertPageNameToDBName(MapLvls.get(i).getMapName()), IngamePlayers, HM);
tempusers = new ArrayList(usertimes.keySet());
for (int j = 0; j < tempusers.size(); j++) {
Points = ConvertPositionToPoints(j, tempusers.size(), Points);
Users user = HM.get(tempusers.get(j).getSteamID());
if (user != null) {
index = LeaderBoard.indexOf(user);
LeaderBoard.get(index).setPlayerPoints(LeaderBoard.get(index).getPlayerPoints() + Points);
}
}
}
LeaderBoard.sort(Comparator.comparing(Users::getPlayerPoints).reversed());
for (int i = 0; i < LeaderBoard.size(); i++) {
LeaderBoard.get(i).setRank(i + 1);
}
return LeaderBoard;
}
public static int GetAdmin(String name, String psw) throws ErrorMessageDisplay {
return DataMapper.GetAdmin(name, psw);
}
public static void DeleteMapEntry(String map, String SteamID) throws ErrorMessageDisplay {
map = ConvertPageNameToDBName(map);
//throw new ErrorMessageDisplay("failed in logicfacade. map: " + map + " steam: " + SteamID);
DataMapper.DeleteMapEntry(map, SteamID);
}
private static String ConvertPageNameToDBName(String map) throws ErrorMessageDisplay {
StringBuilder sb;
int Stage = 0;
int l_iLength = map.length() - 1; //maybe -1
if (Character.isDigit(map.charAt(l_iLength)) && map.contains("Stage:")) {
while (Character.isDigit(map.charAt(l_iLength))) {
l_iLength--;
}
l_iLength++;
if (l_iLength < map.length()) {
Stage = Integer.valueOf(map.substring(l_iLength, map.length()));
}
l_iLength -= 8;
sb = new StringBuilder();
sb = sb.append(map.substring(0, l_iLength)).append("S").append(Stage);
map = sb.toString();
}
//throw new ErrorMessageDisplay("failed in logicfacade. ConvertPageNameToDBName: " + map);
return map;
}
private static List<Users> ConvertSteam3ToSteam2(List<String> IngamePlayersSteamID, Map<String, Users> HM) {
List<Users> IngamePlayers = new ArrayList();
String Convert3To64To2 = "";
for (int i = 0; i < IngamePlayersSteamID.size(); i++) {
if (IngamePlayersSteamID.get(i).contains("U")) {
Convert3To64To2 = convertCommunityIdToSteamId(convertSteamIdToCommunityId(IngamePlayersSteamID.get(i)));
} else {
Convert3To64To2 = IngamePlayersSteamID.get(i);
}
Users user = HM.get(Convert3To64To2);
if (user != null) {
IngamePlayers.add(user);
}
}
return IngamePlayers;
}
public static String convertCommunityIdToSteamId(long communityId) {
long steamId1 = communityId % 2;
long steamId2 = communityId - 76561197960265728L;
steamId2 = (steamId2 - steamId1) / 2;
return "STEAM_0:" + steamId1 + ":" + steamId2;
}
public static Map<String, String> getAllAdmins() throws ErrorMessageDisplay {
Map<String, String> HM = DataMapper.getAllAdmins();
return HM;
}
public static void createAdmin(String name, String password, String role) throws ErrorMessageDisplay {
DataMapper.createAdmin(name, password, role);
}
public static List<MapBoard> getAllMapValues(List<MapBoard> AllMapColoumns, List<Users> LeaderBoard) throws ErrorMessageDisplay {
List<MapBoard> AllMapColoumnsToDB = new ArrayList();
List<MapValues> mvListnull = new ArrayList();
MapBoard maps;
Map<String, Users> HM = new HashMap();
List<MapBoard> allMapBoards = new ArrayList();
LinkedHashMap<Users, Float> MapRelatedHashMap;
List<Users> HashmaprelatedUsers;
List<Float> HashmaprelatedFloats;
int MapPoints = 0;
for (int i = 0; i < AllMapColoumns.size(); i++) {
maps = new MapBoard(ConvertPageNameToDBName(AllMapColoumns.get(i).getMapName()), mvListnull);
AllMapColoumnsToDB.add(maps);
}
for (int i = 0; i < LeaderBoard.size(); i++) {
HM.put(LeaderBoard.get(i).getSteamID(), LeaderBoard.get(i));
}
// something goes wrong here as in retrieving maps
for (int i = 0; i < AllMapColoumns.size(); i++) {
List<MapValues> mvList = new ArrayList();
MapRelatedHashMap = new LinkedHashMap(DataMapper.GetMapRelatedTimes(AllMapColoumnsToDB.get(i), LeaderBoard, HM));
HashmaprelatedUsers = new ArrayList(MapRelatedHashMap.keySet());
HashmaprelatedFloats = new ArrayList(MapRelatedHashMap.values());
for (int j = 0; j < MapRelatedHashMap.size(); j++) {
MapPoints = ConvertPositionToPoints(j, HashmaprelatedUsers.size(), MapPoints);
MapValues mv1 = new MapValues(j, HashmaprelatedUsers.get(j), HashmaprelatedFloats.get(j), MapPoints);
mvList.add(mv1);
}
maps = new MapBoard(AllMapColoumns.get(i).getMapName(), mvList);
allMapBoards.add(maps);
/*
if (i > 45) {
throw new ErrorMessageDisplay("map: " + allMapBoards.get(i).getMapName()
+ " time: " + allMapBoards.get(i).getMapvalues().get(0).getTime() + " allMapBoards size: " + allMapBoards.size()
+ " allMapBoards mapvalues size: " + allMapBoards.get(i).getMapvalues().size() + " allMapBoards.get(i).getMapvalues().get(0).getUser().getName(): " + allMapBoards.get(i).getMapvalues().get(0).getUser().getName()); //getMapvalues().get(0) is trobuel
}
*/
}
return allMapBoards;
}
public static List<MapBoard> getPlayerRelatedMapBoard(List<MapBoard> mapBoard, Users user) throws ErrorMessageDisplay {
List<MapBoard> newMapBoard = new ArrayList();
int index = 0;
for (int j = 0; j < mapBoard.size(); j++) {
for (int i = 0; i < mapBoard.get(j).getMapvalues().size(); i++) {
if (mapBoard.get(j).getMapvalues().get(i).getUser().equals(user)) {
newMapBoard.add(mapBoard.get(j));
}
}
}
//throw new ErrorMessageDisplay("newMapBoard size: " + newMapBoard.size() + " mapBoard size: " + mapBoard.size());
return newMapBoard;
}
public static List<Integer> getPlayerPositions(List<MapBoard> PlayerRelatedMapBoard, Users user) {
List<Integer> PlayerPositions = new ArrayList();
int index = 0;
for (int i = 0; i < PlayerRelatedMapBoard.size(); i++) {
for (int j = 0; j < PlayerRelatedMapBoard.get(i).getMapvalues().size(); j++) {
if (PlayerRelatedMapBoard.get(i).getMapvalues().get(j).getUser().equals(user)) {
PlayerPositions.add(PlayerRelatedMapBoard.get(i).getMapvalues().get(j).getPosition());
break;
}
}
}
return PlayerPositions;
}
public static int getMapIndex(List<MapBoard> mapBoard, String map) throws ErrorMessageDisplay {
int index = 0;
for (int i = 0; i < mapBoard.size(); i++) {
if (mapBoard.get(i).getMapName().equals(map)) {
index = i;
break;
}
}
//throw new ErrorMessageDisplay("getMapIndex: " + index + " map: " + map + " mapBoard.get(i).getMapName(): " + mapBoard.get(0).getMapName());
return index;
}
public static List<UserBanners> getUserBanners(List<Users> PlayerLeaderBoard) throws ErrorMessageDisplay {
List<String> ConvertedID = new ArrayList();
for (int i = 0; i < PlayerLeaderBoard.size(); i++) {
ConvertedID.add(Long.toString(convertSteamIdToCommunityId(PlayerLeaderBoard.get(i).getSteamID())));
}
List<UserBanners> UBList = DataMapper.getUserbanners(PlayerLeaderBoard, ConvertedID);
Collections.sort(UBList, (o1, o2) -> o1.getUser().getRank() - o2.getUser().getRank());
/*
throw new ErrorMessageDisplay("UBList 0: " + UBList.get(0).getUser().getName()
+ " UBlist 1: " + UBList.get(1).getUser().getName() + " PlayerLeaderBoard 0: " + PlayerLeaderBoard.get(0).getName() + " PlayerLeaderBoard 1: "
+ PlayerLeaderBoard.get(1).getName() + " UBlist size: " + UBList.size() + " PlayerLeaderBoard size: " + PlayerLeaderBoard.size());
*/
return UBList;
}
public static List<Users> getPlayertimeAmount(List<Users> PlayerLeaderBoard, List<MapBoard> mapBoard) {
boolean test = false;
for (int i = 0; i < 100; i++) {
if (PlayerLeaderBoard.get(i).getTimes() > 0) {
test = true;
break;
}
}
if (!test) {
for (int i = 0; i < mapBoard.size(); i++) {
for (int j = 0; j < mapBoard.get(i).getMapvalues().size(); j++) {
int index = PlayerLeaderBoard.indexOf(mapBoard.get(i).getMapvalues().get(j).getUser());
PlayerLeaderBoard.get(index).setTimes(PlayerLeaderBoard.get(index).getTimes() + 1);
}
}
}
return PlayerLeaderBoard;
}
public static LinkedHashMap<Integer, RecentTimes> getRecentTimes(ConcurrentMap<Integer, Users> UserCacheTimeAmount1, ConcurrentMap<Integer, MapBoard> mpb) throws ErrorMessageDisplay {
List<RecentTimes> RT = DataMapper.getRecentTimes();
RT = MapNameUpdateRecentTimes(RT);
List<Users> userlist = new ArrayList(UserCacheTimeAmount1.values());
List<MapBoard> mpblist = new ArrayList(mpb.values());
LinkedHashMap<Integer, RecentTimes> LHM = new LinkedHashMap();
for (int i = 0; i < RT.size(); i++) {
String RTSteamID = RT.get(i).getMYSQLSteamID();
int index = userlist.indexOf(UserCacheTimeAmount1.entrySet().stream().filter(e -> e.getValue().getSteamID().equals(RTSteamID)).findFirst().get().getValue());
Users user = userlist.get(index);
RT.get(i).setUser(user);
String mapname = RT.get(i).getMYSQLStage();
index = mpblist.indexOf(mpb.entrySet().stream().filter(e -> e.getValue().getMapName().equals(mapname)).findFirst().get().getValue());
int index2 = -1;
if (mpblist.get(index).getMapvalues().stream().filter(e -> e.getUser().getSteamID()
.equals(user.getSteamID())).findFirst().isPresent()) {
index2 = mpblist.get(index).getMapvalues().indexOf(mpblist.get(index)
.getMapvalues().stream().filter(e -> e.getUser().getSteamID().equals(user.getSteamID())).findFirst().get());
}
if (index2 != -1) {
if (mpblist.get(index).getMapvalues().get(index2).getUser() == null) {
throw new ErrorMessageDisplay("user is also null!");
}
float test = mpblist.get(index).getMapvalues().get(index2).getTime();
float newtime = test;
try {
int minutesval = (((int) RT.get(i).getMYSQLOldTime()) * 60);
float secondsval = (RT.get(i).getMYSQLOldTime() - (int) RT.get(i).getMYSQLOldTime()) * 100;
int newminutesval = (((int) newtime) * 60);
float newsecondsval = (newtime - (int) newtime) * 100;
float improvedTime = (minutesval + secondsval) - (newminutesval + newsecondsval);
minutesval = (int) improvedTime / 60;
secondsval = (improvedTime - (minutesval * 60));
secondsval *= 0.01;
improvedTime = minutesval + secondsval;
//174,999 - 50,1 = 124.899 / 60 = 2 * 60 = 120. 124.899 - 120 = 4.899 * 0.01 = 0.04899 + 2 = 2.04899.
// 2 minutes and 4 seconds, 8.99 milliseconds
RT.get(i).setImprovedTime(improvedTime);
} catch (Exception ex) {
throw new ErrorMessageDisplay("getRecentTimes: " + ex.getMessage() + " mapname: " + mapname + " user: " + user.getName() + " index: " + index);
}
}
}
for (int i = 0; i < RT.size(); i++) {
LHM.put(i, RT.get(i));
}
return LHM;
}
public boolean containsSteamID(final List<Users> list, final String name) {
return list.stream().map(Users::getSteamID).filter(name::equals).findFirst().isPresent();
}
public static int ConvertPositionToPoints(int Position, int PlayerCount, int Points) {
float li = 0;
li = PlayerCount - Position;
Points = (int) Math.floor((li / PlayerCount) * 100);
return Points;
}
}

View File

@ -1,39 +0,0 @@
/*
* 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 FunctionLayer;
import java.util.List;
/**
*
* @author install1
*/
public class MapBoard {
private String mapName;
private List<MapValues> mapvalues;
public String getMapName() {
return mapName;
}
public void setMapName(String mapName) {
this.mapName = mapName;
}
public List<MapValues> getMapvalues() {
return mapvalues;
}
public void setMapvalues(List<MapValues> mapvalues) {
this.mapvalues = mapvalues;
}
public MapBoard(String mapName, List<MapValues> mapvalues) {
this.mapName = mapName;
this.mapvalues = mapvalues;
}
}

View File

@ -1,40 +0,0 @@
/*
* 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 FunctionLayer;
import java.io.Serializable;
/**
*
* @author install1
*/
public class Maps {
private String name;
private int Points;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPoints() {
return Points;
}
public void setPoints(int Points) {
this.Points = Points;
}
public Maps(String name, int Points) {
this.name = name;
this.Points = Points;
}
}

View File

@ -1,50 +0,0 @@
/*
* 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 FunctionLayer;
import java.util.List;
/**
*
* @author install1
*/
public class UserBanners {
private List<Integer> UrlBanners;
private Users user;
public UserBanners(List<Integer> UrlBanners, Users user) {
this.UrlBanners = UrlBanners;
this.user = user;
}
public List<Integer> getUrlBanners() {
return UrlBanners;
}
public void setUrlBanners(List<Integer> UrlBanners) {
this.UrlBanners = UrlBanners;
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
@Override
public boolean equals(Object o) {
if (o instanceof UserBanners) {
UserBanners p = (UserBanners) o;
return this.user.equals(p.getUser());
} else {
return false;
}
}
}

View File

@ -1,76 +0,0 @@
/*
* 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 FunctionLayer;
/**
*
* @author install1
*/
public class Users {
private String steamID;
private String name;
private String Avatar;
private int Rank;
private int PlayerPoints;
private int Times;
public Users(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 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 int getTimes() {
return Times;
}
public void setTimes(int Times) {
this.Times = Times;
}
}

View File

@ -1,22 +0,0 @@
/*
* 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 Presentation;
import FunctionLayer.ErrorMessageDisplay;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author install1
*/
public class AdminLogin extends Command {
@Override
String execute(HttpServletRequest request, HttpServletResponse response) throws ErrorMessageDisplay {
return "AdminLogin";
}
}

View File

@ -1,42 +0,0 @@
/*
* 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 Presentation;
import FunctionLayer.ErrorMessageDisplay;
import FunctionLayer.LogicFacade;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author install1
*/
public class Authenticatelogin extends Command {
@Override
String execute(HttpServletRequest request, HttpServletResponse response) throws ErrorMessageDisplay {
String name = request.getParameter("uname");
String psw = request.getParameter("psw");
int VerifyAdmin = LogicFacade.GetAdmin(name, psw);
if (VerifyAdmin > 0) {
HttpSession session = request.getSession();
session.setAttribute("VerifyAdmin", VerifyAdmin);
session.setAttribute("AdminName", name);
if (VerifyAdmin < 2) {
return "Content";
} else {
Map <String, String> HM = LogicFacade.getAllAdmins();
session.setAttribute("adminMap", HM);
return "AdminPage";
}
}
return "Content";
}
}

View File

@ -1,43 +0,0 @@
/*
* 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 Presentation;
import FunctionLayer.ErrorMessageDisplay;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author install1
*/
abstract class Command {
private static HashMap<String, Command> commands;
private static void initCommands() {
commands = new HashMap();
commands.put("SessionAttributeHandler", new SessionAttributeHandler());
commands.put("mapfnfo", new MapInfo());
commands.put("playerinfo", new PlayerInfo());
commands.put("adminLogin", new AdminLogin());
commands.put("Authenticatelogin", new Authenticatelogin());
commands.put("DeleteEntry", new DeleteIndex());
commands.put("CreateAdmin", new CreateAdmin());
//add methods here for the controller
}
static Command from(HttpServletRequest request) throws ErrorMessageDisplay {
String commandName = request.getParameter("command");
if (commands == null) {
initCommands();
}
return commands.getOrDefault(commandName, new SessionAttributeHandler());
}
abstract String execute(HttpServletRequest request, HttpServletResponse response)
throws ErrorMessageDisplay;
}

View File

@ -1,33 +0,0 @@
/*
* 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 Presentation;
import FunctionLayer.ErrorMessageDisplay;
import FunctionLayer.LogicFacade;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author install1
*/
public class CreateAdmin extends Command {
@Override
String execute(HttpServletRequest request, HttpServletResponse response) throws ErrorMessageDisplay {
HttpSession session = request.getSession();
String name = request.getParameter("name");
String password = request.getParameter("psw1");
String role = request.getParameter("Role");
LogicFacade.createAdmin(name, password, role);
Map<String, String> HM = LogicFacade.getAllAdmins();
session.setAttribute("adminMap", HM);
return "AdminPage";
}
}

View File

@ -1,54 +0,0 @@
/*
* 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 Presentation;
import FunctionLayer.Caching.GACaching;
import FunctionLayer.ErrorMessageDisplay;
import FunctionLayer.LogicFacade;
import FunctionLayer.MapBoard;
import FunctionLayer.RecentTimes;
import FunctionLayer.UserBanners;
import FunctionLayer.Users;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author install1
*/
public class DeleteIndex extends Command {
@Override
String execute(HttpServletRequest request, HttpServletResponse response) throws ErrorMessageDisplay {
//throw new ErrorMessageDisplay("reached delete indes");
HttpSession session = request.getSession();
String playermap = (String) request.getParameter("PlayerRelatedMap");
String SteamId = request.getParameter("DeleteIndexSteamID");
LogicFacade.DeleteMapEntry(playermap, SteamId);
try {
GACaching.instance.UpdateDeletedEntries();
} catch (SQLException | IOException | PropertyVetoException ex) {
Logger.getLogger(DeleteIndex.class.getName()).log(Level.SEVERE, null, ex);
}
List<MapBoard> mapBoard = GACaching.instance.getAllMapValues();
List<RecentTimes> recentTimes = GACaching.instance.getAllRecentTimes();
List<UserBanners> UB = GACaching.instance.getUserBanners();
List<Users> PlayerLeaderBoard = GACaching.instance.getAllPlayerValues();
session.setAttribute("LeaderBoard", PlayerLeaderBoard);
session.setAttribute("MapBoard", mapBoard);
session.setAttribute("UserBanners", UB);
session.setAttribute("RecentTimes", recentTimes);
return "Content";
}
}

View File

@ -1,75 +0,0 @@
/*
* 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 Presentation;
import FunctionLayer.MapBoard;
import FunctionLayer.ErrorMessageDisplay;
import FunctionLayer.LogicFacade;
import FunctionLayer.UserBanners;
import FunctionLayer.Users;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author install1
*/
public class DisplayContent extends Command {
@Override
String execute(HttpServletRequest request, HttpServletResponse response) throws ErrorMessageDisplay {
try {
HttpSession session = request.getSession();
List<Users> PlayerLeaderBoard = (List<Users>) session.getAttribute("LeaderBoard");
List<MapBoard> mapBoard = (List<MapBoard>) session.getAttribute("MapBoard");
boolean firsttime = session.getAttribute("first") != null;
PlayerLeaderBoard = LogicFacade.GetAllUsersNameSteamIdAvatar(PlayerLeaderBoard);
List<Users> UpdateDBAvatars = PlayerLeaderBoard;
List<UserBanners> UB = (List<UserBanners>) session.getAttribute("UserBanners");;
if (mapBoard == null) {
mapBoard = LogicFacade.GetAllMapColoumns();
}
PlayerLeaderBoard = LogicFacade.getPlayerPointsAndRank(PlayerLeaderBoard, mapBoard, firsttime);
mapBoard = LogicFacade.getAllMapValues(mapBoard, PlayerLeaderBoard);
if (UB == null) {
UB = LogicFacade.getUserBanners(PlayerLeaderBoard);
}
PlayerLeaderBoard = LogicFacade.getPlayertimeAmount(PlayerLeaderBoard, mapBoard);
if (mapBoard.size() < 1) {
throw new ErrorMessageDisplay("No maps available, call jenz mapBoard size: " + mapBoard.size() + " other: " + mapBoard.get(0).getMapvalues().size());
}
session.setAttribute("first", firsttime);
session.setAttribute("LeaderBoard", PlayerLeaderBoard);
session.setAttribute("MapBoard", mapBoard);
session.setAttribute("UserBanners", UB);
Thread t = new Thread() {
@Override
public void run() {
while (true) {
try {
LogicFacade.UpdatePlayerAvatarsToDB(UpdateDBAvatars);
Thread.sleep(1000 * 60 * 180);
} catch (IOException | InterruptedException | ErrorMessageDisplay ex) {
Logger.getLogger(DisplayContent.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
t.start();
} catch (SQLException | IOException | PropertyVetoException ex) {
Logger.getLogger(DisplayContent.class.getName()).log(Level.SEVERE, null, ex);
}
return "Content";
}
}

View File

@ -1,89 +0,0 @@
/*
* 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 Presentation;
import FunctionLayer.ErrorMessageDisplay;
import java.io.IOException;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author install1
*/
/**
*
* @webServlet should be initiated once on beginning, FrontController is the URL, when applied on tomcat having URL wrong breaks session objects
*/
@WebServlet(name = "FrontController", urlPatterns = {"/FrontController"})
public class FrontController extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Command action = Command.from(request);
String view = action.execute(request, response);
request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);
} catch (ErrorMessageDisplay ex) {
request.setAttribute("error", ex.getMessage());
request.getRequestDispatcher("/WEB-INF/test.jsp").forward(request, response);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

View File

@ -1,36 +0,0 @@
/*
* 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 Presentation;
import FunctionLayer.ErrorMessageDisplay;
import FunctionLayer.LogicFacade;
import FunctionLayer.MapBoard;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author install1
*/
public class MapInfo extends Command {
@Override
String execute(HttpServletRequest request, HttpServletResponse response) throws ErrorMessageDisplay {
HttpSession session = request.getSession(false);
if (session != null) {
List<MapBoard> mapBoard = (List<MapBoard>) session.getAttribute("MapBoard");
String map = (String) request.getParameter("mapname");
int index = LogicFacade.getMapIndex(mapBoard, map);
request.setAttribute("SpecificMapIndex", index);
return "MapInfo";
} else {
return "SessionTimeoutRedirect";
}
}
}

View File

@ -1,45 +0,0 @@
/*
* 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 Presentation;
import FunctionLayer.ErrorMessageDisplay;
import FunctionLayer.LogicFacade;
import FunctionLayer.MapBoard;
import FunctionLayer.Users;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author install1
*/
public class PlayerInfo extends Command {
@Override
String execute(HttpServletRequest request, HttpServletResponse response) throws ErrorMessageDisplay {
HttpSession session = request.getSession();
if (session != null) {
String PlayerIndexSteamID = request.getParameter("player");
List<Users> users = (List<Users>) session.getAttribute("LeaderBoard");
List<MapBoard> mapBoard = (List<MapBoard>) session.getAttribute("MapBoard");
Users user = LogicFacade.getUser(PlayerIndexSteamID, users, mapBoard);
List<MapBoard> PlayerRelatedMapBoard = LogicFacade.getPlayerRelatedMapBoard(mapBoard, user);
String SteamID64 = Long.toString(LogicFacade.convertSteamIdToCommunityId(user.getSteamID()));
List<Integer> PlayerPositions = LogicFacade.getPlayerPositions(PlayerRelatedMapBoard, user);
request.setAttribute("CommunityID", SteamID64);
request.setAttribute("user", user);
request.setAttribute("PlayerRelatedMapBoard", PlayerRelatedMapBoard);
request.setAttribute("positions", PlayerPositions);
//throw new ErrorMessageDisplay("PlayerRelatedMapBoard size: " + PlayerRelatedMapBoard.size());
return "PlayerInfo";
} else {
return "SessionTimeoutRedirect";
}
}
}

View File

@ -1,51 +0,0 @@
/*
* 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 Presentation;
import FunctionLayer.RecentTimes;
import FunctionLayer.Caching.GACaching;
import FunctionLayer.ErrorMessageDisplay;
import FunctionLayer.MapBoard;
import FunctionLayer.UserBanners;
import FunctionLayer.Users;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author install1
*/
public class SessionAttributeHandler extends Command {
/**
* SessionAttributeHandler redirects all required calls to clients
*
* @param request
* @param response
* @return
* @throws ErrorMessageDisplay
*/
@Override
String execute(HttpServletRequest request, HttpServletResponse response) throws ErrorMessageDisplay {
HttpSession session = request.getSession();
GACaching.instance.Initialization();
List<MapBoard> mapBoard = GACaching.instance.getAllMapValues();
List<RecentTimes> recentTimes = GACaching.instance.getAllRecentTimes();
List<UserBanners> UB = GACaching.instance.getUserBanners();
List<Users> PlayerLeaderBoard = GACaching.instance.getAllPlayerValues();
if (mapBoard.size() < 1) {
throw new ErrorMessageDisplay("No maps available, call jenz");
}
session.setAttribute("LeaderBoard", PlayerLeaderBoard);
session.setAttribute("MapBoard", mapBoard);
session.setAttribute("UserBanners", UB);
session.setAttribute("RecentTimes", recentTimes);
return "Content";
}
}

View File

@ -1,15 +0,0 @@
# DEFAULT CACHE REGION
jcs.default=DC
jcs.default.cacheattributes=org.apache.commons.jcs.engine.CompositeCacheAttributes
jcs.default.cacheattributes.MaxObjects=1000
jcs.default.cacheattributes.MemoryCacheName=org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache
jcs.default.cacheattributes.UseMemoryShrinker=false
jcs.default.cacheattributes.MaxMemoryIdleTime=3600
jcs.default.cacheattributes.ShrinkerInterval=60
jcs.default.elementattributes=org.apache.commons.jcs.engine.ElementAttributes
jcs.default.elementattributes.IsEternal=false
jcs.default.elementattributes.MaxLife=21600
jcs.default.elementattributes.IdleTime=1800
jcs.default.elementattributes.IsSpool=true
jcs.default.elementattributes.IsRemote=true
jcs.default.elementattributes.IsLateral=true

View File

@ -1,49 +0,0 @@
<%--
Document : AdminLogin
Created on : 08-11-2018, 21:08:22
Author : install1
--%>
<%@page contentType="text/html" pageEncoding="windows-1252"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Admin Login</title>
</head>
<body>
<div class="text-center">
<button type="button" class="btn btn-info" onclick="GetFrontPage()">Overview</button>
<br>
<br>
<form id="1112" name="Authenticatelogin" action="FrontController" method="POST">
<input type="hidden" name="command" value="Authenticatelogin">
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button class="btn btn-primary" onclick="AuthenticateLogin()" >Login</button>
</div>
</form>
</div>
<SCRIPT LANGUAGE="JavaScript">
function GetFrontPage()
{
document.getElementById('1111').submit();
}
function AuthenticateLogin()
{
document.getElementById('1112').submit();
}
</SCRIPT>
<form id="1111" name="SessionAttributeHandler" action="FrontController" method="POST">
<input type="hidden" name="command" value="SessionAttributeHandler">
</form>
</body>
</html>

View File

@ -1,95 +0,0 @@
<%--
Document : AdminPage
Created on : 13-11-2018, 22:35:37
Author : install1
--%>
<%@page import="java.util.List"%>
<%@page import="java.util.Map"%>
<%@page contentType="text/html" pageEncoding="windows-1252"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<title>Administration Page</title>
</head>
<body>
<div class="text-center">
<button type="button" class="btn btn-info" onclick="GetFrontPage();">Overview</button>
<br>
<br>
</div>
<div align="center">
<button class="btn btn-primary" onclick="CreateAdminFunc();" >Create Admin</button>
</div>
<form id="1111" name="CreateAdmin" action="FrontController" method="POST">
<input type="hidden" name="command" value="CreateAdmin">
<div class="container">
<label for="name"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" required>
<label for="psw1"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw1" required>
<label for="role"><b>Role</b></label>
<select name="Role" form="1111">
<option value="Tech">Tech</option>
<option value="Global Admin">Global Admin</option>
<option value="Admin">Admin</option>
</select>
<br>
</div>
</form>
<div class="container">
<div class="row">
<div class="col-sm">
<%
Map<String, String> map = (Map) session.getAttribute("adminMap");
for (Map.Entry<String, String> entry : map.entrySet()) {
%>
<div align="center">
<span href="#" class="fake-link" >
<div>
<%
out.println(entry.getKey());
%>
</div>
<div>
<% out.println(entry.getValue());
%>
</div>
</span>
</div>
<br>
<%
}
%>
</div>
</div>
</div>
<style>
.fake-link {
color: #007bff;
text-decoration: underline;
cursor: pointer;
}
</style>
<SCRIPT LANGUAGE="JavaScript">
function CreateAdminFunc()
{
document.getElementById('1111').submit();
}
function GetFrontPage()
{
document.getElementById('1112').submit();
}
</SCRIPT>
<form id="1112" name="SessionAttributeHandler" action="FrontController" method="POST">
<input type="hidden" name="command" value="SessionAttributeHandler">
</form>
</body>
</html>

View File

@ -1,259 +0,0 @@
<%--
Document : index
Created on : 21-10-2018, 14:28:06
Author : install1
--%>
<%@page import="java.text.DecimalFormat"%>
<%@page import="FunctionLayer.RecentTimes"%>
<%@page import="java.util.Collections"%>
<%@page import="FunctionLayer.UserBanners"%>
<%@page import="FunctionLayer.MapBoard"%>
<%@page import="FunctionLayer.Users"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Maptimers</title>
</head>
<body>
<% String AdminName = (String) session.getAttribute("AdminName");
if (AdminName != null) {
%>
<h1>You are logged in as: <%=AdminName%> </h1>
<%
}
%>
<button type="button" class="btn btn-warning" onclick="AdminLogin()">Admin login</button>
<div class="row">
<div class="col-sm-12">
<div class="text-center">
<button type="button" class="btn btn-primary" onclick="DisplayMaps()">Maps</button>
<button type="button" class="btn btn-success" onclick="DisplayPlayers()">Players</button>
<button type="button" class="btn btn-secondary" onclick="RecentTimes()">Recent Times</button>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="text-center">
<div id="MapDiv">
<%
List<MapBoard> AllMapColoumns = (List<MapBoard>) session.getAttribute("MapBoard");
if (AllMapColoumns != null) {
for (int i = 0; i < AllMapColoumns.size(); i++) {
%>
<button id="<%=AllMapColoumns.get(i).getMapName()%>" class="list-group-item list-group-item-action" onclick="GetMapPage(this.id);" style="border: none" > <span href="#" class="fake-link" ><%out.print(AllMapColoumns.get(i).getMapName());%></span>
</button>
<%
}
} else { %>
<li class="list-group-item disabled">No map Entries, call jenz!</li>
<% } %>
</div>
<div id="RecentDiv">
<%
List<RecentTimes> recentTimes = (List<RecentTimes>) session.getAttribute("RecentTimes");
if (recentTimes != null) {
for (int i = 0; i < recentTimes.size(); i++) {
%>
<button class="list-group-item list-group-item-action" id="<%=recentTimes.get(i).getUser().getSteamID()%>" style="border: none" onclick="GetplayerPage(this.id);">
<span href="#" class="fake-link" >
<div>
<%out.print(recentTimes.get(i).getUser().getSteamID());%>
</div>
<div>
<%out.print(recentTimes.get(i).getUser().getName());%>
</div>
<div>
<img src="<%out.println(recentTimes.get(i).getUser().getAvatar()); %>">
</div>
<div>
<%out.print(recentTimes.get(i).getMYSQLStage());%>
</div>
<div>
<%
float fdefault = recentTimes.get(i).getImprovedTime();
int MinuteAdjusterImproved = (int) fdefault;
float secondsAdjusterImproved = Float.valueOf(String.format("%.2f", (fdefault - MinuteAdjusterImproved) * 100));
out.print("\nImproved by: 0" + MinuteAdjusterImproved + ":"
+ secondsAdjusterImproved);
%>
</div>
<div>
<%
//00:56.4
float newAdjustedTime = (((int) recentTimes.get(i).getMYSQLOldTime()) * 60
+ ((recentTimes.get(i).getMYSQLOldTime() - (int) recentTimes.get(i).getMYSQLOldTime()) * 100))
- (MinuteAdjusterImproved * 60 + secondsAdjusterImproved);
int newMinuteTime = (int) newAdjustedTime / 60;
float SecondsAdjusterNewTime = Float.valueOf(String.format("%.2f", newAdjustedTime - (newMinuteTime * 60)));
out.print("New Time: 0" + newMinuteTime + ":" + SecondsAdjusterNewTime);
%>
</div>
</span>
</button>
<% }
}
%>
</div>
</div>
</div>
</div>
<div id="PlayerDiv">
<% List<UserBanners> UB = (List<UserBanners>) session.getAttribute("UserBanners");
List<Users> PlayerLeaderBoard = (List<Users>) session.getAttribute("LeaderBoard");
int UBIndex = 0;
if (PlayerLeaderBoard != null && UB != null) {
// out.println("UB size: " + UB.size());
for (int j = 0; j < PlayerLeaderBoard.size(); j++) {
%>
<button class="list-group-item list-group-item-action" id="<%=PlayerLeaderBoard.get(j).getSteamID()%>" style="border: none" onclick="GetplayerPage(this.id);"><span href="#" class="fake-link" >
<div class="container" id="Players">
<div class="row d-flex justify-content-between">
<div>
<%out.print(PlayerLeaderBoard.get(j).getSteamID());%>
</div>
<div>
<%out.print(PlayerLeaderBoard.get(j).getName());%>
</div>
<div>
<%out.print("Rank: " + PlayerLeaderBoard.get(j).getRank());%>
</div>
<div>
<%out.print("Points: " + PlayerLeaderBoard.get(j).getPlayerPoints());%>
</div>
<div>
<%out.print("Times: " + PlayerLeaderBoard.get(j).getTimes());%>
</div>
</div>
<div class="row d-flex justify-content-between">
<div>
<div class="d-flex justify-content-between" id="Players">
<%
String img = "";
if (UBIndex < UB.size() && UB.get(UBIndex).getUser().equals(PlayerLeaderBoard.get(j))) {
for (int i = 0; i < UB.get(UBIndex).getUrlBanners().size(); i++) {
switch (UB.get(UBIndex).getUrlBanners().get(i)) {
case 25: {
img = "https://unloze.com/images/badges/Event-Manager.png";
break;
}
case 19: {
img = "https://unloze.com/images/badges/Discord-Manager.png";
break;
}
case 15: {
img = "https://unloze.com/images/badges/Event-Winner.png";
break;
}
case 12: {
img = "https://unloze.com/images/badges/VIP.png";
break;
}
case 11: {
img = "https://unloze.com/images/badges/Global-Admin.png";
break;
}
case 10: {
img = "https://unloze.com/images/badges/Leader.png";
break;
}
case 8: {
img = "https://unloze.com/images/badges/Tech-Staff.png";
break;
}
case 7: {
img = "https://unloze.com/images/badges/Admin.png";
break;
}
case 6: {
img = "https://unloze.com/images/badges/Mapper.png";
break;
}
}
%>
<div >
<img src="<%out.println(img); %>">
</div>
<%
}
UBIndex++;
}
%>
</div>
</div>
<div class="float-right" >
<img src="<%out.println(PlayerLeaderBoard.get(j).getAvatar()); %>">
</div>
</div>
</div>
</span> </button>
<% }
} else {
%>
<li class="list-group-item disabled">No Player Entries</li>
<% }%>
</div>
<SCRIPT LANGUAGE="JavaScript">
function GetMapPage(count)
{
document.getElementById("mapindexes").value = count;
document.getElementById('1111').submit();
}
function GetplayerPage(count)
{
document.getElementById("playerindex").value = count;
document.getElementById('1112').submit();
}
function AdminLogin()
{
document.getElementById('1113').submit();
}
$('#PlayerDiv').hide();
function DisplayMaps() {
$('#PlayerDiv').hide();
$('#RecentDiv').hide();
$('#MapDiv').show();
}
function DisplayPlayers()
{
$('#PlayerDiv').show();
$('#MapDiv').hide();
$('#RecentDiv').hide();
}
function RecentTimes()
{
$('#PlayerDiv').hide();
$('#MapDiv').hide();
$('#RecentDiv').show();
}
</SCRIPT>
<form id="1111" name="mapfnfo" action="FrontController" method="POST">
<input type="hidden" name="command" value="mapfnfo">
<input type="hidden" name="mapname" id='mapindexes' value=''>
</form>
<form id="1112" name="playerinfo" action="FrontController" method="POST">
<input type="hidden" name="command" value="playerinfo">
<input type="hidden" name="player" id='playerindex' value=''>
</form>
<form id="1113" name="adminLogin" action="FrontController" method="POST">
<input type="hidden" name="command" value="adminLogin">
</form>
<style>
.fake-link {
color: #007bff;
text-decoration: underline;
cursor: pointer;
}
</style>
</body>
</html>

View File

@ -1,205 +0,0 @@
<%--
Document : Mapdetails
Created on : 23-10-2018, 14:12:31
Author : install1
--%>
<%@page import="FunctionLayer.UserBanners"%>
<%@page import="FunctionLayer.MapBoard"%>
<%@page import="java.text.DecimalFormat"%>
<%@page import="java.math.BigDecimal"%>
<%@page import="java.util.List"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.Map"%>
<%@page import="FunctionLayer.Users"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LeaderBoards</title>
</head>
<body>
<% String AdminName = (String) request.getSession().getAttribute("AdminName");
if (AdminName != null) {
%>
<h1>You are logged in as: <%=AdminName%> </h1>
<%
}
%>
<div class="container">
<div class="row">
<div class="col-sm">
<div align="center">
<button type="button" class="btn btn-info" onclick="GetFrontPage()">Overview</button>
</div>
<br>
<br>
<%
List<UserBanners> UB = (List<UserBanners>) session.getAttribute("UserBanners");
List<MapBoard> mapBoard = (List<MapBoard>) session.getAttribute("MapBoard");
//might not find mapname as parameter
int index = (Integer) request.getAttribute("SpecificMapIndex");
String map = (String) request.getParameter("mapname");
String VerifyAdmins = session.getAttribute("VerifyAdmin") == null ? "0" : String.valueOf(session.getAttribute("VerifyAdmin"));
int VerifyAdmin = Integer.valueOf(VerifyAdmins);
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(1);
out.println("<H2 align=\"center\">" + map + "</h2>");
if (mapBoard != null) {
for (int i = 0; i < mapBoard.get(index).getMapvalues().size(); i++) {
%>
<button id="<%=mapBoard.get(index).getMapvalues().get(i).getUser().getSteamID()%>" style="border: none" onclick="GetplayerPage(this.id);"
class="list-group-item list-group-item-action" >
<span href="#" class="fake-link" >
<div class="row d-flex justify-content-between">
<div> <%out.println(mapBoard.get(index).getMapvalues().get(i).getUser().getSteamID());%></div>
<div> <%out.println(mapBoard.get(index).getMapvalues().get(i).getUser().getName());%></div>
<div><%out.println("Rank: " + mapBoard.get(index).getMapvalues().get(i).getUser().getRank());%></div>
<div>
<%out.println("Points: " + mapBoard.get(index).getMapvalues().get(i).getUser().getPlayerPoints());%>
</div>
<div>
<%out.println("Times: " + mapBoard.get(index).getMapvalues().get(i).getUser().getTimes());%>
</div>
<div>
<%out.println("Map Position: " + (i + 1)); %>
</div>
<div> <%out.println("Time: " + "0" + (long) (mapBoard.get(index).getMapvalues().get(i).getTime())
+ ":" + (df.format((mapBoard.get(index).getMapvalues().get(i).getTime() - (long) (mapBoard.get(index).getMapvalues().get(i).getTime())) * 100)));%>
</div>
<div>
<%out.println("Map Points: " + mapBoard.get(index).getMapvalues().get(i).getMapPoints() + "/100");%>
</div>
</div>
<div align="center">
<img src="<%out.println(mapBoard.get(index).getMapvalues().get(i).getUser().getAvatar()); %>">
</div>
<%
String img = ""; //userlist.indexOf(UserCacheTimeAmount1.entrySet().stream().filter(e -> e.getValue().getSteamID().equals(RTSteamID)).findFirst().get().getValue());
Users user = mapBoard.get(index).getMapvalues().get(i).getUser();
int mbIndex = -1;
for (int j = 0; j < UB.size(); j++) {
if (UB.get(j).getUser().equals(user)) {
mbIndex = j;
break;
}
}
if (mbIndex > 0) {
for (int j = 0; j < UB.get(mbIndex).getUrlBanners().size(); j++) {
switch (UB.get(mbIndex).getUrlBanners().get(j)) {
case 25: {
img = "https://unloze.com/images/badges/Event-Manager.png";
break;
}
case 19: {
img = "https://unloze.com/images/badges/Discord-Manager.png";
break;
}
case 15: {
img = "https://unloze.com/images/badges/Event-Winner.png";
break;
}
case 12: {
img = "https://unloze.com/images/badges/VIP.png";
break;
}
case 11: {
img = "https://unloze.com/images/badges/Global-Admin.png";
break;
}
case 10: {
img = "https://unloze.com/images/badges/Leader.png";
break;
}
case 8: {
img = "https://unloze.com/images/badges/Tech-Staff.png";
break;
}
case 7: {
img = "https://unloze.com/images/badges/Admin.png";
break;
}
case 6: {
img = "https://unloze.com/images/badges/Mapper.png";
break;
}
}
%>
<div align="center">
<div >
<img src="<%out.println(img);%>">
</div>
</div>
<% }
}
%>
</span> </button>
<%
if (VerifyAdmin > 0) {
%>
<div align="center">
<button value="<%out.print(mapBoard.get(index).getMapName());%>" id="<%=mapBoard.get(index).getMapvalues().get(i).getUser().getSteamID()%>" style="border: none" onclick="removeentry(this.id, this.value);" >
<span href="#" class="fake-link" >
<div class="d-flex justify-content-between">
<div>
<%out.println("Delete Entry");%>
</div>
</div>
</span> </button>
</div>
<%
}
%>
<br>
<br>
<% }
}
%>
</div>
</div>
</div>
<style>
.fake-link {
color: #007bff;
text-decoration: underline;
cursor: pointer;
}
</style>
<SCRIPT LANGUAGE="JavaScript">
function GetplayerPage(count)
{
document.getElementById("playerindex").value = count;
document.getElementById('1111').submit();
}
function GetFrontPage()
{
document.getElementById('1112').submit();
}
function removeentry(steamID, map)
{
document.getElementById("PlayerRelatedMap").value = map;
document.getElementById("SteamID").value = steamID;
document.getElementById('1113').submit();
}
</SCRIPT>
<form id="1111" name="playerinfo" action="FrontController" method="POST">
<input type="hidden" name="command" value="playerinfo">
<input type="hidden" name="player" id='playerindex' value=''>
</form>
<form id="1112" name="SessionAttributeHandler" action="FrontController" method="POST">
<input type="hidden" name="command" value="SessionAttributeHandler">
</form>
<form id="1113" name="DeleteEntry" action="FrontController" method="POST">
<input type="hidden" name="command" value="DeleteEntry">
<input type="hidden" name="DeleteIndexSteamID" id='SteamID' value=''>
<input type="hidden" name="PlayerRelatedMap" id='PlayerRelatedMap' value=''>
</form>
</body>
</html>

View File

@ -1,329 +0,0 @@
<%--
Document : PlayerInfo
Created on : 04-11-2018, 20:57:35
Author : install1
--%>
<%@page import="java.util.ArrayList"%>
<%@page import="FunctionLayer.RecentTimes"%>
<%@page import="FunctionLayer.UserBanners"%>
<%@page import="FunctionLayer.MapBoard"%>
<%@page import="java.text.DecimalFormat"%>
<%@page import="java.util.List"%>
<%@page import="FunctionLayer.Users"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Player Stats</title>
</head>
<body>
<div align="center">
<div id="overview" class="btn btn-info overviewclass" >Overview</div>
</div>
<%
DecimalFormat df = new DecimalFormat();
List<RecentTimes> recentTimes = (List<RecentTimes>) session.getAttribute("RecentTimes");
List<UserBanners> UB = (List<UserBanners>) session.getAttribute("UserBanners");
List<MapBoard> DifferentiateMapBoard = (List<MapBoard>) session.getAttribute("MapBoard");
String VerifyAdmins = session.getAttribute("VerifyAdmin") == null ? "0" : String.valueOf(session.getAttribute("VerifyAdmin"));
int VerifyAdmin = Integer.valueOf(VerifyAdmins);
StringBuilder sb = new StringBuilder();
String SteamID64 = (String) request.getAttribute("CommunityID");
if (SteamID64 != null) {
sb.append("https://steamcommunity.com/profiles/").append(SteamID64);
} else {
sb.append("https://steamcommunity.com/profiles/");
}
List<Integer> PlayerPositions = (List<Integer>) request.getAttribute("positions");
Users user = (Users) request.getAttribute("user");
List<MapBoard> PlayerRelatedMapBoard = (List<MapBoard>) request.getAttribute("PlayerRelatedMapBoard");
df.setMaximumFractionDigits(1);
if (user != null && recentTimes != null) {
%>
<div class="container">
<div class="row">
<div class="col-sm">
<div align="center" class="fake-2">
<br>
<br>
<a target="_blank" href="<%out.println(sb.toString());%>">
<button style="border: none"
class="list-group-item list-group-item-action" >
<span class="fake-link" >
<div> <%out.println(user.getName());%></div>
<div> <%out.println(user.getSteamID());%></div>
<div>
<img src="<%out.println(user.getAvatar()); %>">
</div>
<div>
<% out.print("Rank: " + user.getRank()); %>
</div>
<div>
<% out.print("Points: " + user.getPlayerPoints()); %>
</div>
<div>
<% out.print("Times: " + user.getTimes()); %>
</div>
<%
String img = "";
int UBIndex = 0;
while (UB.size() > UBIndex) {
if (UB.get(UBIndex).getUser().equals(user)) {
break;
}
UBIndex++;
}
if (UBIndex < UB.size()) {
for (int i = 0; i < UB.get(UBIndex).getUrlBanners().size(); i++) {
switch (UB.get(UBIndex).getUrlBanners().get(i)) {
case 25: {
img = "https://unloze.com/images/badges/Event-Manager.png";
break;
}
case 19: {
img = "https://unloze.com/images/badges/Discord-Manager.png";
break;
}
case 15: {
img = "https://unloze.com/images/badges/Event-Winner.png";
break;
}
case 12: {
img = "https://unloze.com/images/badges/VIP.png";
break;
}
case 11: {
img = "https://unloze.com/images/badges/Global-Admin.png";
break;
}
case 10: {
img = "https://unloze.com/images/badges/Leader.png";
break;
}
case 8: {
img = "https://unloze.com/images/badges/Tech-Staff.png";
break;
}
case 7: {
img = "https://unloze.com/images/badges/Admin.png";
break;
}
case 6: {
img = "https://unloze.com/images/badges/Mapper.png";
break;
}
}
%>
<div>
<img src="<%out.println(img);%>">
</div>
<% }
}
%>
</span> </button>
</a>
</div>
<%
for (int i = 0; i < PlayerRelatedMapBoard.size(); i++) {
%>
<div align="center" class="group">
<div class="element" data-id="<%=PlayerRelatedMapBoard.get(i).getMapName()%>" >
<span href="#" class="fake-link" >
<%out.println(" Map " + PlayerRelatedMapBoard.get(i).getMapName());%>
</span>
</div>
</div>
<span class="fake-2" >
<div align="center">
<%out.println("Map Position: " + (PlayerRelatedMapBoard.get(i).getMapvalues().get(PlayerPositions.get(i)).getPosition() + 1)); %>
</div>
<div align="center"> <%out.println("Time: 0" + (int) Math.floor(PlayerRelatedMapBoard.get(i).getMapvalues().get(PlayerPositions.get(i)).getTime())
+ ":" + (df.format((PlayerRelatedMapBoard.get(i).getMapvalues().get(PlayerPositions.get(i)).getTime() - Math.floor(PlayerRelatedMapBoard.get(i).getMapvalues().get(PlayerPositions.get(i)).getTime())) * 100)));%></div>
<div align="center"> <%out.println("Map Points: " + PlayerRelatedMapBoard.get(i).getMapvalues().get(PlayerPositions.get(i)).getMapPoints() + "/100"); %></div>
</span>
<%
if (VerifyAdmin > 0) {
%>
<div align="center">
<button value="<%out.print(user.getSteamID());%>" id="<%out.print(PlayerRelatedMapBoard.get(i).getMapName());%>" onclick="DeleteEntryFunc(this.value, this.id)" >
<span href="#" class="fake-link" >
<%out.println("Delete Entry");%>
</span>
</button>
</div>
<%
}
%>
<br>
<br>
<%
}
}
%>
</div>
</div>
</div>
<div class="header">
<div class="leftH" id="leftHDiv" >
<div id="lefth1">
<% String AdminName = (String) request.getSession().getAttribute("AdminName");
if (AdminName != null) {
%>
<h1>You are logged in as: <%=AdminName%> </h1>
<%
} %>
<h1>Recently improved times: </h1>
</div>
<%
for (int i = 0; i < recentTimes.size(); i++) {
if (recentTimes.get(i).getUser().equals(user)) {
%>
<div>
<%out.print("\n" + recentTimes.get(i).getMYSQLStage()); %>
</div>
<div>
<%
float fdefault = recentTimes.get(i).getImprovedTime();
int MinuteAdjusterImproved = (int) fdefault;
float secondsAdjusterImproved = Float.valueOf(String.format("%.2f", (fdefault - MinuteAdjusterImproved) * 100));
out.print("\nImproved by: 0" + MinuteAdjusterImproved + ":"
+ secondsAdjusterImproved);
%>
</div>
<br>
<%
}
}
%>
</div>
</div>
<div class="header">
<div class="rightH group1" id="rightHDiv" >
<div id="righth1">
<h1>Maps with no time yet:</h1>
</div>
<%
List<MapBoard> feex = new ArrayList(PlayerRelatedMapBoard);
List<MapBoard> feex1 = new ArrayList(DifferentiateMapBoard);
feex1.removeAll(feex);
for (int i = 0; i < feex1.size(); i++) {
%>
<div class="element1" id="<%=feex1.get(i).getMapName()%>" >
<span href="#" class="fake-link2" >
<%out.print("\n" + feex1.get(i).getMapName()); %>
</span>
</div>
<br>
<%
}
%>
</div>
</div>
<style>
.fake-link {
color: #007bff;
text-decoration: underline;
cursor: pointer;
position: relative;
z-index: 3;
}
.fake-link2 {
color: #007bff;
text-decoration: underline;
cursor: pointer;
position: relative;
z-index: 3;
}
.fake-2{
position: relative;
z-index: 3;
}
.fake-2 a{
display:inline-block;
width: 300px;
}
.overviewclass{
position: relative;
z-index: 3;
}
.header {
display: inline-block;
width: 100%;
position: absolute;
z-index: 1;
top: 0px;
}
.leftH {
position: absolute;
z-index: 2;
float: left;
top: 0px;
}
.rightH {
position: absolute;
z-index: 2;
float: right;
top: 0px;
}
</style>
<script type="text/javascript">
</script>
<script>
$("#overview").click(function () {
document.getElementById('1112').submit();
});
$('.group1 .element1').click(function () {
id1 = $(this).attr('id');
document.getElementById("mapindexes1").value = id1;
document.getElementById('1114').submit();
});
$('.group .element').click(function () {
id = $(this).attr('data-id');
document.getElementById("mapindexes").value = id;
document.getElementById('1111').submit();
});
function DeleteEntryFunc(steamID, map)
{
document.getElementById("PlayerRelatedMap").value = map;
document.getElementById("SteamID").value = steamID;
document.getElementById('1113').submit();
}
$("#leftHDiv").css({
position: 'relative',
right: '-150px'
});
$("#lefth1").css({
position: 'relative',
right: '125px'
});
$("#rightHDiv").css({
position: 'relative',
});
$("#righth1").css({
position: 'relative',
});
</script>
<form id="1111" name="mapfnfo" action="FrontController" method="POST">
<input type="hidden" name="command" value="mapfnfo">
<input type="hidden" name="mapname" id='mapindexes' value=''>
</form>
<form id="1112" name="SessionAttributeHandler" action="FrontController" method="POST">
<input type="hidden" name="command" value="SessionAttributeHandler">
</form>
<form id="1113" name="DeleteEntry" action="FrontController" method="POST">
<input type="hidden" name="command" value="DeleteEntry">
<input type="hidden" name="DeleteIndexSteamID" id='SteamID' value=''>
<input type="hidden" name="PlayerRelatedMap" id='PlayerRelatedMap' value=''>
</form>
<form id="1114" name="mapfnfo" action="FrontController" method="POST">
<input type="hidden" name="command" value="mapfnfo">
<input type="hidden" name="mapname" id='mapindexes1' value=''>
</form>
</body>
</html>

View File

@ -1,21 +0,0 @@
<%--
Document : SessionTimeoutRedirect
Created on : 08-11-2018, 17:49:13
Author : install1
--%>
<%@page contentType="text/html" pageEncoding="windows-1252"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>TimeoutHandling</title>
</head>
<body>
<form name="DisplayContent" action="FrontController" method="POST">
<input type="hidden" name="command" value="SessionAttributeHandler">
Loading Avatars, please wait 20-30 seconds...
</form>
<SCRIPT LANGUAGE="JavaScript">document.forms[0].submit();</SCRIPT>
</body>
</html>

View File

@ -1,31 +0,0 @@
<%--
Document : test
Created on : 25-10-2018, 15:39:27
Author : install1
--%>
<%@page contentType="text/html" pageEncoding="windows-1252"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>JSP Page</title>
</head>
<body>
<h1>Backup nothingness</h1>
<% String error = (String) request.getAttribute("error");
if (error != null) {
out.println("<H2>Error!!</h2>");
out.println(error);
} else {
%>
<form name="DisplayContent" action="FrontController" method="POST">
<input type="hidden" name="command" value="SessionAttributeHandler">
<input type="submit" />
</form>
<SCRIPT LANGUAGE="JavaScript">document.forms[0].submit();</SCRIPT>
</body>
<% }
%>
</body>
</html>

View File

@ -1,22 +0,0 @@
<%--
Document : dummy
Created on : 21-10-2018, 17:07:46
Author : install1
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="refresh" action="1;FrontController">
<title>StartPoint</title>
</head>
<body>
<form name="SessionAttributeHandler" action="FrontController" method="POST">
<input type="hidden" name="command" value="SessionAttributeHandler">
Loading Avatars, please wait 20-30 seconds...
</form>
<SCRIPT LANGUAGE="JavaScript">document.forms[0].submit();</SCRIPT>
</body>
</html>

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More