Merge pull request 'turs' (#31) from turs into master

Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/31
This commit is contained in:
Marcin Woźniak 2020-12-14 15:50:35 +01:00
commit ca440a3fd5
15 changed files with 679 additions and 117 deletions

View File

@ -46,10 +46,7 @@ W paczce dla proda w protpertiesach poufne dane odczytywane są ze zmiennych śr
Zeby spakowac apke do `jara` wystarcza dwie komendy zaczynajac z glownego katalogu projektu Zeby spakowac apke do `jara` wystarcza dwie komendy zaczynajac z glownego katalogu projektu
``` ```
mvn clean mvn clean; mvn install; cd restservice; mvn clean package spring-boot:repackage
mvn install
cd restservice
mvn clean package spring-boot:repackage
``` ```
Utworzony zostanie jar w `restservice/target/restservice-1.0-SNAPSHOT.jar`. Oczywiscie zeby jar zadzialal kontenery dockerowe musza byc odpalone (lub baza danych na serwerze jesli zmienialismy propertisy z localhost) Utworzony zostanie jar w `restservice/target/restservice-1.0-SNAPSHOT.jar`. Oczywiscie zeby jar zadzialal kontenery dockerowe musza byc odpalone (lub baza danych na serwerze jesli zmienialismy propertisy z localhost)

View File

@ -0,0 +1,118 @@
package com.plannaplan.entities;
import java.sql.Date;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.plannaplan.models.TourData;
import com.plannaplan.types.AppState;
/**
* entity that keeps app configurations
*/
@Entity
public class AppConfig {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Date firstTourStart;
private Date firstTourEnd;
private Date secondTourStart;
private Date secondTourEnd;
private Timestamp configDate;
/**
* no parameter construcotor
*/
public AppConfig() {
}
/**
* constructor
*
* @param firstTour first TourData instacne
* @param scondTour second TourData instacne
*/
public AppConfig(TourData firstTour, TourData scondTour) {
this.firstTourStart = firstTour.getStart();
this.firstTourEnd = firstTour.getEnd();
this.secondTourStart = scondTour.getStart();
this.secondTourEnd = scondTour.getEnd();
this.configDate = new Timestamp(System.currentTimeMillis());
}
/**
*
* second tour end getter
*
* @return Date inforamtion when second tour ends
*/
public Date getSecondTourEnd() {
return secondTourEnd;
}
/**
* first second start getter
*
* @return Date inforamtion when second tour start
*/
public Date getSecondTourStart() {
return secondTourStart;
}
/**
* first tour end getter
*
* @return Date inforamtion when first tour end
*/
public Date getFirstTourEnd() {
return firstTourEnd;
}
/**
* first tour start getter
*
* @return Date inforamtion when first tour start
*/
public Date getFirstTourStart() {
return firstTourStart;
}
/**
* config date getter
*
* @return Timestamp when configuration took place
*/
public Timestamp getConfigDate() {
return configDate;
}
/**
* current state getter
*
* @return AppState of app at the moment of calling method
*/
public AppState getCurrentState() {
final Date now = new Date(System.currentTimeMillis());
if (this.secondTourEnd.before(now)) {
return AppState.NO_TOUR;
}
if (this.secondTourStart.before(now)) {
return AppState.SECOND_TOUR;
}
if (this.firstTourEnd.before(now)) {
return AppState.NO_TOUR;
}
if (this.firstTourStart.before(now)) {
return AppState.FIRST_TOUR;
}
return AppState.NO_TOUR;
}
}

View File

@ -11,7 +11,8 @@ import javax.persistence.Id;
import com.plannaplan.types.UserRoles; import com.plannaplan.types.UserRoles;
/** /**
* Entity of User grouping of state ssociated about id,name,surname,email,role,token,tokenCreatedDate * Entity of User grouping of state ssociated about
* id,name,surname,email,role,token,tokenCreatedDate
*/ */
@Entity @Entity
@ -28,18 +29,16 @@ public class User {
private UserRoles role; private UserRoles role;
private String token; private String token;
private Timestamp tokenUsageDate; private Timestamp tokenUsageDate;
public User() { public User() {
} }
/* /**
* User *
* * @param name name given to the user
* @param name name given to the user
* @param surname surname given to the user * @param surname surname given to the user
* @param email mail given to the user * @param mail mail given to the user
* @param role role given to the user * @param role
*/ */
public User(String name, String surname, String mail, UserRoles role) { public User(String name, String surname, String mail, UserRoles role) {
this.name = name; this.name = name;
@ -48,136 +47,144 @@ public class User {
this.role = role; this.role = role;
} }
/* /**
* User *
* * @param name name given to the user
* @param name name given to the user
* @param surname surname given to the user * @param surname surname given to the user
* @param email mail given to the user * @param mail mail given to the user
* @param usosId id in the USOS system * @param usosId id in the USOS system
* @param role role given to the user * @param role
*/ */
public User(String name, String surname, String mail, String usosId, UserRoles role){ public User(String name, String surname, String mail, String usosId, UserRoles role) {
this(name,surname,mail,role); this(name, surname, mail, role);
this.usosId = usosId; this.usosId = usosId;
} }
/* /**
* getusosId * usos id getter
* *
* @return usosId * @return usosid
*/ */
public String getUsosId() { public String getUsosId() {
return usosId; return usosId;
} }
/* /**
* getEmail * email getter
* *
* @return email * @return mailof user
*/ */
public String getEmail() { public String getEmail() {
return email; return email;
} }
/* /**
* setEmail * email setter
* *
* @param email set email to the user * @param email user email
*/ */
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
/* /**
* getTokenUsageDate * token usage getter
* *
* @return tokenUsageDate * @return Timestamp when token was used
*/ */
public Timestamp getTokenUsageDate() { public Timestamp getTokenUsageDate() {
return tokenUsageDate; return tokenUsageDate;
} }
/* /**
* getToken * token getter
* *
* @return token * @return user token
*/ */
public String getToken() { public String getToken() {
return token; return token;
} }
/* /**
* setToken * token seter. Sets token and automaticly set time when was set
* *
* @param token set token to the entity * @param token token to set
*/ */
public void setToken(String token) { public void setToken(String token) {
this.tokenUsageDate = new Timestamp(System.currentTimeMillis()); this.tokenUsageDate = new Timestamp(System.currentTimeMillis());
this.token = token; this.token = token;
} }
/* getName /**
* * name setter
* @return name *
* @return String user name
*/ */
public String getName() { public String getName() {
return name; return name;
} }
/* getRole /**
* * user rolse getter
* @return role *
* @return UserRoles of user
*/ */
public UserRoles getRole() { public UserRoles getRole() {
return role; return role;
} }
/* setRole /**
* * user role setter
* @param role set role to the entity *
* @param role to be set
*/ */
public void setRole(UserRoles role) { public void setRole(UserRoles role) {
this.role = role; this.role = role;
} }
/* /**
* getSurname * surname getter
* @return surname *
* @return string surname
*/ */
public String getSurname() { public String getSurname() {
return surname; return surname;
} }
/* /**
* setSurname * surname setter
* @param surname set surname into entity user *
* @param surname string to be set as surnames
*/ */
public void setSurname(String surname) { public void setSurname(String surname) {
this.surname = surname; this.surname = surname;
} }
/* /**
* setName * name stter
* @param name set name into entity user *
* @param name stirng to be set as name
*/ */
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/* /**
* getId * id getter
* @return id *
* @return id in database
*/ */
public Long getId() { public Long getId() {
return this.id; return this.id;
} }
/* /**
* isCredentialsNonExpired * it checks if given ammount of time passed since last token usage. If not
* Returns TRUE if is Credentials Non Expired in the otherwise it returns false * retunr true and reset time otherwise return false and token won work anymore
*
* @return boolena if credentials (token) is expired or not
*/ */
public boolean isCredentialsNonExpired() { public boolean isCredentialsNonExpired() {
final long diffInMilliseconds = Math final long diffInMilliseconds = Math
.abs(this.tokenUsageDate.getTime() - new Timestamp(System.currentTimeMillis()).getTime()); .abs(this.tokenUsageDate.getTime() - new Timestamp(System.currentTimeMillis()).getTime());
final long minutes = TimeUnit.MILLISECONDS.toMinutes(diffInMilliseconds); final long minutes = TimeUnit.MILLISECONDS.toMinutes(diffInMilliseconds);

View File

@ -1,51 +1,50 @@
package com.plannaplan.models; package com.plannaplan.models;
import java.util.Date;
import java.io.InputStream; import java.io.InputStream;
public class ConfigData { public class ConfigData {
private Date start; private TourData firstTour;
private Date end; private TourData secondTour;
private InputStream filestream; private InputStream filestream;
/* /**
* ConfigData * constructor
* *
* @param start when the configdata begins * @param firstTour date of first tours
* @param end when the configdata ends * @param secondTour date of second tours
* @param filestream where the filestream is * @param filestream filestram with data to import
*/ */
public ConfigData(Date start, Date end, InputStream filestream) { public ConfigData(TourData firstTour, TourData secondTour, InputStream filestream) {
this.start = start; this.firstTour = firstTour;
this.end = end; this.secondTour = secondTour;
this.filestream = filestream; this.filestream = filestream;
} }
/* /**
* getFilestream * second tour getter
* *
* @return filestream * @return TourData second tour
*/
public TourData getSecondTour() {
return secondTour;
}
/**
* first tour getter
*
* @return TourData first tour
*/
public TourData getFirstTour() {
return firstTour;
}
/**
* filestream getter
*
* @return InputStream with data to import
*/ */
public InputStream getFilestream() { public InputStream getFilestream() {
return filestream; return filestream;
} }
/*
* getEnd
*
* @return end
*/
public Date getEnd() {
return end;
}
/*
* getStart
*
* @return start
*/
public Date getStart() {
return start;
}
} }

View File

@ -0,0 +1,49 @@
package com.plannaplan.models;
import java.sql.Date;
public class TourData {
private Date start;
private Date end;
/**
* construcotr for java.sql.Date
*
* @param start Date when tour start
* @param end Date when tour end
*/
public TourData(Date start, Date end) {
this.start = start;
this.end = end;
}
/**
* constructor construcotr for java.util.Date
*
* @param start Date when tour start
* @param end Date when tour end
*/
public TourData(java.util.Date start, java.util.Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
}
/**
* tour end getter
*
* @return Date end of tour
*/
public Date getEnd() {
return end;
}
/**
* tour start getter
*
* @return Date beginning of tour
*/
public Date getStart() {
return start;
}
}

View File

@ -0,0 +1,8 @@
package com.plannaplan.repositories;
import com.plannaplan.entities.AppConfig;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AppConfigRepository extends JpaRepository<AppConfig, Long> {
}

View File

@ -2,28 +2,64 @@ package com.plannaplan.services;
import com.plannaplan.models.ConfigData; import com.plannaplan.models.ConfigData;
import com.plannaplan.models.FileData; import com.plannaplan.models.FileData;
import com.plannaplan.repositories.AppConfigRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.plannaplan.configutils.*; import com.plannaplan.configutils.*;
import com.plannaplan.entities.AppConfig;
/** /**
* FileReader is used for reading xls file from input stream. * FileReader is used for reading xls file from input stream.
*/ */
@Component @Component
public class ConfiguratorService { public class ConfiguratorService {
@Autowired @Autowired
private FileToDatabaseMigrator migrator; private FileToDatabaseMigrator migrator;
@Autowired
private AppConfigRepository configRepo;
public ConfiguratorService() { public ConfiguratorService() {
} }
/**
* methoid to config system
*
* @param data ConfigData containng system configs
*/
public void config(ConfigData data) { public void config(ConfigData data) {
FileReader reader = new FileReader(data.getFilestream()); FileReader reader = new FileReader(data.getFilestream());
FileData coursesData = reader.read(); FileData coursesData = reader.read();
this.configRepo.save(new AppConfig(data.getFirstTour(), data.getSecondTour()));
migrator.migrate(coursesData); migrator.migrate(coursesData);
} }
/**
* current config getter
*
* @return AppConfig with newest config_date
*/
public AppConfig getCurrentConfig() {
final List<AppConfig> repsonse = this.configRepo.findAll().stream().sorted(new Comparator<AppConfig>() {
@Override
public int compare(AppConfig i1, AppConfig i2) {
if (i1.getConfigDate().after(i2.getConfigDate())) {
return -1;
}
if (i1.getConfigDate().before(i2.getConfigDate())) {
return 1;
}
return 0;
}
}).collect(Collectors.toList());
return repsonse.get(0);
}
} }

View File

@ -0,0 +1,5 @@
package com.plannaplan.types;
public enum AppState {
FIRST_TOUR, SECOND_TOUR, NO_TOUR
}

View File

@ -0,0 +1,141 @@
package com.plannaplan.entities;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.sql.Date;
import com.plannaplan.models.TourData;
import com.plannaplan.types.AppState;
import org.junit.Test;
public class AppConfigTest {
private static long ONE_DAY = 86400000;
@Test
public void shouldReturnNoTourDueToTooEarly() {
final Date firtstTourStart = new Date(System.currentTimeMillis() + ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() + 2 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() + 3 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getCurrentState() == AppState.NO_TOUR);
}
@Test
public void shouldReturnFirstTourDueToStart() throws InterruptedException {
final Date firtstTourStart = new Date(System.currentTimeMillis());
final Date firtstTourEnd = new Date(System.currentTimeMillis() + 2 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() + 3 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
Thread.sleep(1000);
assertTrue(config.getCurrentState() == AppState.FIRST_TOUR);
}
@Test
public void shouldReturnFirstTourDueToInBetween() {
final Date firtstTourStart = new Date(System.currentTimeMillis() - ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() + 2 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() + 3 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getCurrentState() == AppState.FIRST_TOUR);
}
@Test
public void shouldReturnNoTourInLastDay() throws InterruptedException {
final Date firtstTourStart = new Date(System.currentTimeMillis() - ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis());
final Date secondTourStart = new Date(System.currentTimeMillis() + 3 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
Thread.sleep(1000);
assertTrue(config.getCurrentState() == AppState.NO_TOUR);
}
@Test
public void shouldReturnNoTourInBetween() {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 2 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() - ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() + 3 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getCurrentState() == AppState.NO_TOUR);
}
@Test
public void shouldReturnSecondTourInStart() throws InterruptedException {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 2 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() - ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis());
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
Thread.sleep(1000);
assertTrue(config.getCurrentState() == AppState.SECOND_TOUR);
}
@Test
public void shouldReturnSecondTourInBetween() {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 3 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() - 2 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() - ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getCurrentState() == AppState.SECOND_TOUR);
}
@Test
public void shouldReturnNoTourDueToEndSecond() throws InterruptedException {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 3 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() - 2 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() - ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis());
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
Thread.sleep(1000);
assertTrue(config.getCurrentState() == AppState.NO_TOUR);
}
@Test
public void shouldReturnNoTourAfterSecondEnd() {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 4 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() - 3 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() - 2 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() - ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getCurrentState() == AppState.NO_TOUR);
}
@Test
public void shouldReturnSecondTourWhereThereIsABrake() throws InterruptedException {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 4 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis());
final Date secondTourStart = new Date(System.currentTimeMillis());
final Date secondTourEnd = new Date(System.currentTimeMillis() + ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
Thread.sleep(1000);
assertTrue(config.getCurrentState() == AppState.SECOND_TOUR);
}
}

View File

@ -8,9 +8,13 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.io.InputStream; import java.io.InputStream;
import java.sql.Date;
import com.plannaplan.TestApplication; import com.plannaplan.TestApplication;
import com.plannaplan.entities.AppConfig;
import com.plannaplan.models.ConfigData; import com.plannaplan.models.ConfigData;
import com.plannaplan.models.TourData;
import com.plannaplan.repositories.AppConfigRepository;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -32,11 +36,18 @@ public class ConfiguratorServiceTest {
@Autowired @Autowired
private LecturerService lecturerService; private LecturerService lecturerService;
@Autowired
private AppConfigRepository appConfigRepo;
@Test @Test
public void shouldImportDataToDataBase() { public void shouldImportDataToDataBase() {
final InputStream inputStream = getClass().getClassLoader() final InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream(TestApplication.TEST_CONFIG_FILE); .getResourceAsStream(TestApplication.TEST_CONFIG_FILE);
final ConfigData data = new ConfigData(null, null, inputStream); final ConfigData data = new ConfigData(
new TourData(new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + 86400000)),
new TourData(new Date(System.currentTimeMillis() + 86400000),
new Date(System.currentTimeMillis() + 2 * 86400000)),
inputStream);
this.configuratorService.config(data); this.configuratorService.config(data);
int courses_ammount = this.courseService.getCoursesAmmount(); int courses_ammount = this.courseService.getCoursesAmmount();
@ -46,4 +57,16 @@ public class ConfiguratorServiceTest {
assertTrue(courses_ammount > 0 && groups_ammount > 0 && lecturers_ammount > 0); assertTrue(courses_ammount > 0 && groups_ammount > 0 && lecturers_ammount > 0);
} }
@Test
public void shouldRetrunNewestConfig() throws InterruptedException {
final Date dateToCheck = new Date(System.currentTimeMillis());
this.appConfigRepo.save(new AppConfig(new TourData(null, null), new TourData(null, null)));
Thread.sleep(2000);
this.appConfigRepo.save(new AppConfig(new TourData(dateToCheck, null), new TourData(null, null)));
AppConfig response = this.configuratorService.getCurrentConfig();
assertTrue(response.getFirstTourStart() != null);
}
} }

View File

@ -1 +1,2 @@
CREATE DATABASE IF NOT EXISTS test; CREATE DATABASE IF NOT EXISTS test;
SET GLOBAL time_zone = '+1:00';

View File

@ -1,8 +1,10 @@
package com.plannaplan; package com.plannaplan;
import java.io.InputStream; import java.io.InputStream;
import java.sql.Date;
import com.plannaplan.models.ConfigData; import com.plannaplan.models.ConfigData;
import com.plannaplan.models.TourData;
import com.plannaplan.entities.User; import com.plannaplan.entities.User;
import com.plannaplan.services.UserService; import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles; import com.plannaplan.types.UserRoles;
@ -38,13 +40,22 @@ public class App {
SpringApplication.run(App.class, args); SpringApplication.run(App.class, args);
} }
/**
* method to import mocked data to testing app after startz. It is called only
* in dev profile
*/
@EventListener(ApplicationReadyEvent.class) @EventListener(ApplicationReadyEvent.class)
public void importData() { public void importData() {
System.out.println(Logo.getInitInfo(isDev)); System.out.println(Logo.getInitInfo(isDev));
if (this.isDev) { if (this.isDev) {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Zajecia.xlsx"); InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Zajecia.xlsx");
ConfigData data = new ConfigData(null, null, inputStream); ConfigData data = new ConfigData(
new TourData(new Date(System.currentTimeMillis()),
new Date(System.currentTimeMillis() + 86400000)),
new TourData(new Date(System.currentTimeMillis() + 86400000),
new Date(System.currentTimeMillis() + 2 * 86400000)),
inputStream);
this.contrl.config(data); this.contrl.config(data);
User newuser = new User(); User newuser = new User();

View File

@ -4,12 +4,15 @@ import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.io.IOException; import java.io.IOException;
import java.util.Date;
import com.plannaplan.App; import com.plannaplan.App;
import com.plannaplan.models.ConfigData; import com.plannaplan.models.ConfigData;
import com.plannaplan.models.TourData;
import com.plannaplan.services.ConfiguratorService; import com.plannaplan.services.ConfiguratorService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -33,13 +36,26 @@ public class ConfigController {
@Autowired @Autowired
private ConfiguratorService contrl; private ConfiguratorService contrl;
@PostMapping("/config") @PostMapping(path = "/config", consumes = { "multipart/form-data" })
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation("Imports data to system. To call you need to provide ADMIN token") @ApiOperation("Imports data to system. To call you need to provide ADMIN token")
public ResponseEntity<String> configApp( public ResponseEntity<String> configApp(
@RequestParam("file") @ApiParam(value = "file .xlsx that contains courses and groups with apoinnted rules") MultipartFile file) { @RequestParam("file") @ApiParam(value = "file .xlsx that contains courses and groups with apoinnted rules") MultipartFile file,
@RequestParam("firstTourBegin") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when first tour begin in format dd.MM.yyyy") Date firstTourBegin,
@RequestParam("firstTourEnd") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when first tour ends in format dd.MM.yyyy") Date firstTourEnd,
@RequestParam("secondTourBegin") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when second tour begin in format dd.MM.yyyy") Date secondTourBegin,
@RequestParam("secondTourEnd") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when second tour ends in format dd.MM.yyyy") Date secondTourEnd) {
try { try {
final ConfigData data = new ConfigData(null, null, file.getInputStream()); if (!(firstTourBegin.before(firstTourEnd)
&& (firstTourEnd.before(secondTourBegin) || firstTourEnd.equals(secondTourBegin))
&& secondTourBegin.before(secondTourEnd))) {
return new ResponseEntity<>("Bad dates", HttpStatus.BAD_REQUEST);
}
final TourData firstTour = new TourData(firstTourBegin, firstTourEnd);
final TourData secondTour = new TourData(secondTourBegin, secondTourEnd);
final ConfigData data = new ConfigData(firstTour, secondTour, file.getInputStream());
this.contrl.config(data); this.contrl.config(data);
return new ResponseEntity<>("Sucess", HttpStatus.OK); return new ResponseEntity<>("Sucess", HttpStatus.OK);
} catch (IOException e) { } catch (IOException e) {

View File

@ -2,11 +2,15 @@ package com.plannaplan.controllers;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;
import java.io.InputStream; import java.io.InputStream;
import java.sql.Date;
import com.plannaplan.entities.AppConfig;
import com.plannaplan.entities.User; import com.plannaplan.entities.User;
import com.plannaplan.services.ConfiguratorService;
import com.plannaplan.services.UserService; import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles; import com.plannaplan.types.UserRoles;
@ -28,9 +32,15 @@ public class ConfigControllerTest extends AbstractControllerTest {
private static final String FILE_NAME = "Zajecia.xlsx"; private static final String FILE_NAME = "Zajecia.xlsx";
private static final String CONFIG_ENDPOINT = "/api/v1/configurator/config"; private static final String CONFIG_ENDPOINT = "/api/v1/configurator/config";
private static final String FIRST_TOUR_START = "firstTourBegin";
private static final String FIRST_TOUR_END = "firstTourEnd";
private static final String SECOND_TOUR_START = "secondTourBegin";
private static final String SECOND_TOUR_END = "secondTourEnd";
@Autowired @Autowired
private UserService service; private UserService service;
@Autowired
private ConfiguratorService configService;
@Test @Test
public void shouldReturnNoAuthorized() throws Exception { public void shouldReturnNoAuthorized() throws Exception {
@ -52,11 +62,40 @@ public class ConfigControllerTest extends AbstractControllerTest {
final String token = this.service.login(usr).getToken(); final String token = this.service.login(usr).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build(); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(multipart(CONFIG_ENDPOINT).file(file).header("Authorization", "Bearer " + token)) mockMvc.perform(multipart(CONFIG_ENDPOINT).file(file).param(FIRST_TOUR_START, "12.12.2020")
.param(FIRST_TOUR_END, "14.12.2020").param(SECOND_TOUR_START, "16.12.2020")
.param(SECOND_TOUR_END, "20.12.2020").header("Authorization", "Bearer " + token))
.andExpect(status().isOk()); .andExpect(status().isOk());
} }
@Test
public void shouldInsertedDataBeSameInDatabase() throws Exception {
final String mail = "shouldReturnOKAuthorized@ConfigController.test";
final User usr = this.service.save(new User(null, null, mail, UserRoles.ADMIN));
final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(FILE_NAME);
final MockMultipartFile file = new MockMultipartFile("file", inputStream);
final String token = this.service.login(usr).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(multipart(CONFIG_ENDPOINT).file(file).param(FIRST_TOUR_START, "12.12.2020")
.param(FIRST_TOUR_END, "14.12.2020").param(SECOND_TOUR_START, "16.12.2020")
.param(SECOND_TOUR_END, "20.12.2020").header("Authorization", "Bearer " + token))
.andExpect(status().isOk());
final AppConfig config = this.configService.getCurrentConfig();
assertTrue(config.getFirstTourStart().compareTo(Date.valueOf("2020-12-12")) == 0,
"Date in database is wrong. Perhabs database has wrong timezone set.");
assertTrue(config.getFirstTourEnd().compareTo(Date.valueOf("2020-12-14")) == 0,
"Date in database is wrong. Perhabs database has wrong timezone set.");
assertTrue(config.getSecondTourStart().compareTo(Date.valueOf("2020-12-16")) == 0,
"Date in database is wrong. Perhabs database has wrong timezone set.");
assertTrue(config.getSecondTourEnd().compareTo(Date.valueOf("2020-12-20")) == 0,
"Date in database is wrong. Perhabs database has wrong timezone set.");
// yyyy-mm-dd
}
@Test @Test
public void shouldReturnDenyNoAdminAuthorized() throws Exception { public void shouldReturnDenyNoAdminAuthorized() throws Exception {
final String mail = "shouldReturnDenyNoAdminAuthorized@ConfigController.test"; final String mail = "shouldReturnDenyNoAdminAuthorized@ConfigController.test";
@ -72,4 +111,112 @@ public class ConfigControllerTest extends AbstractControllerTest {
} }
@Test
public void shouldFailDueToWrongFirstTour() throws Exception {
final String mail = "shouldFailDueToWrongFirstTour@ConfigController.test";
final User usr = this.service.save(new User(null, null, mail, UserRoles.ADMIN));
final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(FILE_NAME);
final MockMultipartFile file = new MockMultipartFile("file", inputStream);
final String token = this.service.login(usr).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(multipart(CONFIG_ENDPOINT).file(file).param(FIRST_TOUR_START, "12.12.2020")
.param(FIRST_TOUR_END, "12.12.2020").param(SECOND_TOUR_START, "16.12.2020")
.param(SECOND_TOUR_END, "20.12.2020").header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldFailDueToWrongSecondTour() throws Exception {
final String mail = "shouldFailDueToWrongSecondTour@ConfigController.test";
final User usr = this.service.save(new User(null, null, mail, UserRoles.ADMIN));
final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(FILE_NAME);
final MockMultipartFile file = new MockMultipartFile("file", inputStream);
final String token = this.service.login(usr).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(multipart(CONFIG_ENDPOINT).file(file).param(FIRST_TOUR_START, "12.12.2020")
.param(FIRST_TOUR_END, "14.12.2020").param(SECOND_TOUR_START, "16.12.2020")
.param(SECOND_TOUR_END, "16.12.2020").header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldFailDueToWrongBothTour() throws Exception {
final String mail = "shouldFailDueToWrongBothTour@ConfigController.test";
final User usr = this.service.save(new User(null, null, mail, UserRoles.ADMIN));
final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(FILE_NAME);
final MockMultipartFile file = new MockMultipartFile("file", inputStream);
final String token = this.service.login(usr).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(multipart(CONFIG_ENDPOINT).file(file).param(FIRST_TOUR_START, "12.12.2020")
.param(FIRST_TOUR_END, "12.12.2020").param(SECOND_TOUR_START, "16.12.2020")
.param(SECOND_TOUR_END, "16.12.2020").header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldFailDueToWrongTourTransition() throws Exception {
final String mail = "shouldFailDueToWrongTourTransition@ConfigController.test";
final User usr = this.service.save(new User(null, null, mail, UserRoles.ADMIN));
final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(FILE_NAME);
final MockMultipartFile file = new MockMultipartFile("file", inputStream);
final String token = this.service.login(usr).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(multipart(CONFIG_ENDPOINT).file(file).param(FIRST_TOUR_START, "12.12.2020")
.param(FIRST_TOUR_END, "14.12.2020").param(SECOND_TOUR_START, "13.12.2020")
.param(SECOND_TOUR_END, "16.12.2020").header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldFailDueToWrongDateFormat() throws Exception {
final String mail = "shouldFailDueToWrongDateFormat@ConfigController.test";
final User usr = this.service.save(new User(null, null, mail, UserRoles.ADMIN));
final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(FILE_NAME);
final MockMultipartFile file = new MockMultipartFile("file", inputStream);
final String token = this.service.login(usr).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(multipart(CONFIG_ENDPOINT).file(file).param(FIRST_TOUR_START, "12.12.2020")
.param(FIRST_TOUR_END, "14.12.2020").param(SECOND_TOUR_START, "16.12.2020")
.param(SECOND_TOUR_END, "20/12/2020").header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldFailDueToNoDate() throws Exception {
final String mail = "shouldFailDueToNoDate@ConfigController.test";
final User usr = this.service.save(new User(null, null, mail, UserRoles.ADMIN));
final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(FILE_NAME);
final MockMultipartFile file = new MockMultipartFile("file", inputStream);
final String token = this.service.login(usr).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(multipart(CONFIG_ENDPOINT).file(file).header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldFailDueToNoFile() throws Exception {
final String mail = "shouldFailDueToNoFile@ConfigController.test";
final User usr = this.service.save(new User(null, null, mail, UserRoles.ADMIN));
final String token = this.service.login(usr).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(multipart(CONFIG_ENDPOINT).param(FIRST_TOUR_START, "12.12.2020")
.param(FIRST_TOUR_END, "14.12.2020").param(SECOND_TOUR_START, "16.12.2020")
.param(SECOND_TOUR_END, "20.12.2020").header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
} }

View File

@ -1,5 +1,6 @@
package com.plannaplan.security.cas; package com.plannaplan.security.cas;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -9,12 +10,15 @@ public class CustomUAMCasValidatorTest {
private String serviceUrl; private String serviceUrl;
@Test @Test
@Ignore
public void shouldValidateWithDomain() { public void shouldValidateWithDomain() {
// you need to privide fresh ticket to make this test pass that's why it is
CustomUAMCasValidator validator = new CustomUAMCasValidator(serviceUrl, "ST-54649-5x4h09vzUpEIyAGmf1sz-cas.amu.edu.pl"); // marked as ignored
validator.validate();
CustomUAMCasValidator validator = new CustomUAMCasValidator(serviceUrl,
"ST-54649-5x4h09vzUpEIyAGmf1sz-cas.amu.edu.pl");
validator.validate();
} }
} }