Merge pull request 'Nowa funkcjonalność: wymiana-przedmiotami' (#41) from wymiana-przedmiotami into master

Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/41
This commit is contained in:
filipizydorczyk 2021-01-13 17:00:48 +01:00
commit 9c1a148e20
17 changed files with 1277 additions and 36 deletions

View File

@ -17,10 +17,22 @@ mvn spring-boot:run
Żeby tesotwać API wpełni potrzebny nam jest token który otrzymujemy na podstawie ticketa z systemu autoryzacyjnego **CAS**. Z tego powodu system autoryzacji działa inaczej niż w "książkowych" restowych aplikacjach i np Postman za nas jej nie dokona. Musimy mu podać już uzyskany token. Aby łatwo go uzyskać odpal skrypt
```
```bash
python gettoken.py
```
Jeżeli chcesz używać skryptu zmiejaniąc gdzie znajduje się backend wpisz:
```bash
python gettoken.py 192.168.0.212
```
Jeżeli chcesz używać skryptu bez uruchamiania przeglądarki wpisz:
```bash
python gettoken.py no-browser
```
Na koniec w przęglądarce dostaniesz w odpowiedzi token. W samym pliku można zmienić porty aplikacji jeśli to potrzebne.
# Profiles

View File

@ -10,7 +10,7 @@ import javax.persistence.ManyToOne;
/**
* Entity of Assignment grouping of state associated about group_id and
* commision_id
*
*
*/
@Entity
@ -28,7 +28,7 @@ public class Assignment {
/**
* Assignment
*
*
* @param group group we would like to assign
* @param commision commision that assignment belongs to
* @param isPastAssignment is assignment past or no
@ -40,16 +40,24 @@ public class Assignment {
/**
* If it returns trues it mesans u are assigned to group accepted by algorythm
*
*
* @return boolean isAccepted
*/
public boolean isAccepted() {
return this.group.getRegisteredStudents().contains(this.commision.getCommisionOwner());
}
/**
* Getter of commision
* @return Commision Commision of given assignments
*/
public Commision getCommision(){
return this.commision;
}
/**
* Assignment
*
*
* @param group group we would like to assign
* @param commision commision that assignment belongs to
*/
@ -60,9 +68,12 @@ public class Assignment {
public Assignment() {
}
public void setCommision(Commision commision) {
this.commision = commision;
}
/**
* Id getter
*
*
* @return id id of assignment
*/
@ -72,7 +83,7 @@ public class Assignment {
/**
* getGroup
*
*
* @return group
*/
public Groups getGroup() {
@ -81,7 +92,7 @@ public class Assignment {
/**
* isPastAssignment getter
*
*
* @return isPastAssignment
*/
public boolean isPastAssignment() {
@ -90,10 +101,10 @@ public class Assignment {
/**
* setter isPastAssignment
*
*
* @param isPastAssignment is assignment past or not
*/
public void setPastAssignment(boolean isPastAssignment) {
this.isPastAssignment = isPastAssignment;
}
}
}

View File

@ -0,0 +1,102 @@
package com.plannaplan.entities;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
/**
* Entity that keeps user exchange offer.
*/
@Entity
public class Exchange {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne
@JoinColumn(name = "owned_id")
private Assignment ownedAssignment;
@OneToOne
@JoinColumn(name = "desired_id")
private Groups desiredAssignment;
private Long ownerId;
private Timestamp dateExchange;
public Exchange(){
}
/**
* @return Long ID of exchange trader
*/
public Long getOwnerId() {
return ownerId;
}
/**
* @param ownerId ID of exchange trader
*/
public void setOwnerId(Long ownerId) {
this.ownerId = ownerId;
}
public Timestamp getDataExchange() {
return this.dateExchange;
}
/**
*
* @param ownedAssignment Assignment which owner would like to trade
* @param desiredAssignment Groups instance that trader wants
*/
public Exchange(Assignment ownedAssignment, Groups desiredAssignment) {
this.ownedAssignment = ownedAssignment;
this.desiredAssignment = desiredAssignment;
this.ownerId = this.ownedAssignment != null ? this.ownedAssignment.getCommision().getCommisionOwner().getId() : null;
this.dateExchange = new Timestamp(System.currentTimeMillis());
}
/**
* @return Long ID in database
*/
public Long getId(){
return this.id;
}
/**
* @return Groups Target group
*/
public Groups getDesiredAssignment() {
return desiredAssignment;
}
/**
* @param desiredAssignment Target group
*/
public void setDesiredAssignment(Groups desiredAssignment) {
this.desiredAssignment = desiredAssignment;
}
/**
* @return Assignment Owned assignment
*/
public Assignment getOwnedAssignment() {
return ownedAssignment;
}
/**
* @param ownedAssignment Owned assignment
*/
public void setOwnedAssignment(Assignment ownedAssignment) {
this.ownedAssignment = ownedAssignment;
}
}

View File

@ -47,6 +47,11 @@ public class User {
return this.studentRegisteredGrups;
}
public void removeGroup(Long id) {
final Groups groupToDelete = this.studentRegisteredGrups.stream().filter(e -> e.getId().equals(id)).findFirst().get();
this.studentRegisteredGrups.remove(groupToDelete);
}
public void claimGroup(Groups group) {
if (this.studentRegisteredGrups == null) {
this.studentRegisteredGrups = new HashSet<>();
@ -58,7 +63,7 @@ public class User {
}
/**
*
*
* @param name name given to the user
* @param surname surname given to the user
* @param mail mail given to the user
@ -72,7 +77,7 @@ public class User {
}
/**
*
*
* @param name name given to the user
* @param surname surname given to the user
* @param mail mail given to the user
@ -85,7 +90,7 @@ public class User {
}
/**
*
*
* @param name name given to the user
* @param surname surname given to the user
* @param mail mail given to the user
@ -101,7 +106,7 @@ public class User {
/**
* usos id getter
*
*
* @return usosid
*/
public String getUsosId() {
@ -110,7 +115,7 @@ public class User {
/**
* email getter
*
*
* @return mailof user
*/
public String getEmail() {
@ -119,7 +124,7 @@ public class User {
/**
* email setter
*
*
* @param email user email
*/
public void setEmail(String email) {
@ -128,7 +133,7 @@ public class User {
/**
* token usage getter
*
*
* @return Timestamp when token was used
*/
public Timestamp getTokenUsageDate() {
@ -137,7 +142,7 @@ public class User {
/**
* token getter
*
*
* @return user token
*/
public String getToken() {
@ -153,7 +158,7 @@ public class User {
/**
* token seter. Sets token and automaticly set time when was set
*
*
* @param token token to set
*/
public void setToken(String token) {
@ -164,7 +169,7 @@ public class User {
/**
* name setter
*
*
* @return String user name
*/
public String getName() {
@ -173,7 +178,7 @@ public class User {
/**
* user rolse getter
*
*
* @return UserRoles of user
*/
public UserRoles getRole() {
@ -182,7 +187,7 @@ public class User {
/**
* user role setter
*
*
* @param role to be set
*/
public void setRole(UserRoles role) {
@ -191,7 +196,7 @@ public class User {
/**
* surname getter
*
*
* @return string surname
*/
public String getSurname() {
@ -200,7 +205,7 @@ public class User {
/**
* surname setter
*
*
* @param surname string to be set as surnames
*/
public void setSurname(String surname) {
@ -209,7 +214,7 @@ public class User {
/**
* name stter
*
*
* @param name stirng to be set as name
*/
public void setName(String name) {
@ -218,7 +223,7 @@ public class User {
/**
* id getter
*
*
* @return id in database
*/
public Long getId() {
@ -227,7 +232,7 @@ public class User {
/**
* Ranking points are [100;500]. It's calculated by gradesAvg*100*studiesYear
*
*
* @return ranking points [100;500]
*/
public Integer getRanking() {
@ -237,7 +242,7 @@ public class User {
/**
* Ranking points setter. Ranking points are [100;500]. It's calculated by
* gradesAvg*100*studiesYear
*
*
* @param ranking ranking points [100;500]
*/
public void setRanking(Integer ranking) {
@ -246,7 +251,7 @@ public class User {
/**
* updates user entity with data got by UsosApiService::getUserData
*
*
* @param usosData UserApiResponse model with needed data
*/
public void updateWithUsosData(UserApiResponse usosData) {
@ -257,7 +262,7 @@ public class User {
/**
* it checks if given ammount of time passed since last token usage. If not
* 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() {

View File

@ -0,0 +1,45 @@
package com.plannaplan.models;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.User;
/**
* Class to keepm data to be send after exchanges being accept
*/
public class EmailExchangesData {
private Map<Long, List<Exchange>> data;
public EmailExchangesData() {
this.data = new HashMap<>();
}
/**
* method to add user and his event to data to be send
*
* @param user owner of exchange being performed
* @param data exchange that was executed
*/
public void addExchange(User user, Exchange data) {
final Long id = user.getId();
if (this.data.get(id) == null) {
this.data.put(id, new ArrayList<>());
}
this.data.get(id).add(data);
}
/**
* get datas entry set
*
* @return set with entries that contains Long that is user id and list of hiss
* performed Exchanges
*/
public Set<Map.Entry<Long, List<Exchange>>> getDataEntry() {
return this.data.entrySet();
}
}

View File

@ -0,0 +1,66 @@
package com.plannaplan.models;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Exchange;
public class MatchData {
private Exchange exchangeOne;
private Exchange exchangeTwo;
public MatchData(Exchange exchangeOne, Exchange exchangeTwo) {
this.exchangeOne = exchangeOne;
this.exchangeTwo = exchangeTwo;
}
public Exchange getExchangeOne() {
return this.exchangeOne;
}
public Exchange getExchangeTwo() {
return this.exchangeTwo;
}
public Assignment getAssignmentTwo() {
return this.exchangeTwo.getOwnedAssignment();
}
public Assignment getAssignmentOne() {
return this.exchangeOne.getOwnedAssignment();
}
@Override
public int hashCode() {
return this.getAssignmentOne().hashCode() + this.getAssignmentTwo().hashCode();
}
@Override
public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
/*
* Check if o is an instance of Complex or not "null instanceof [type]" also
* returns false
*/
if (!(o instanceof MatchData)) {
return false;
}
// typecast o to Complex so that we can compare data members
MatchData c = (MatchData) o;
// Compare the data members and return accordingly
return (this.getAssignmentOne().equals(c.getAssignmentOne()) && this.getAssignmentTwo().equals(c.getAssignmentTwo())) || (this.getAssignmentOne().equals(c.getAssignmentTwo()) && this.getAssignmentTwo().equals(c.getAssignmentOne()));
}
public int compare(MatchData m1) {
return Long.compare(m1.getExchangesMsValue(), this.getExchangesMsValue());
}
public long getExchangesMsValue(){
return this.exchangeOne.getDataExchange().getTime() + this.exchangeTwo.getDataExchange().getTime();
}
}

View File

@ -0,0 +1,26 @@
package com.plannaplan.repositories;
import java.util.List;
import java.util.Optional;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface ExchangeRepository extends JpaRepository<Exchange, Long>{
@Query("FROM Exchange WHERE owned_id = ?1 AND desired_id = ?2")
Optional<Exchange> checkForExchange(@Param("owned_id") Assignment assignment, @Param("desired_id") Groups group);
@Query("FROM Exchange WHERE ownerId = ?1")
List<Exchange> getByUserId(@Param("id") Long id);
@Query("Select e1,e2 FROM Exchange e1, Exchange e2 WHERE e1.ownedAssignment.group.id = e2.desiredAssignment.id")
List<Object[]> getMatches();
}

View File

@ -1,7 +1,13 @@
package com.plannaplan.services;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.User;
import com.plannaplan.models.EmailAcceptedData;
import com.plannaplan.models.EmailExchangesData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@ -18,6 +24,9 @@ public class EmailService {
@Autowired
private JavaMailSender emailSender;
@Autowired
private UserService userService;
@Value("${plannaplan.email}")
private String appEmail;
@ -54,4 +63,39 @@ public class EmailService {
mailMessage.setText(data.getEmailMessage());
emailSender.send(mailMessage);
}
/**
* method to send email for students whose groups were swaped
*
* @param data EmailExchangesData instance that contains pair of datas user and
* list of performed exhanges
*/
public void sendExchangesResults(EmailExchangesData data) {
for (Map.Entry<Long, List<Exchange>> entry : data.getDataEntry()) {
final User user = this.userService.getById(entry.getKey()).get();
String response = "Znaleźliśmy dla Ciebie osobę, która zamieniła się z Tobą przedmiotami!!!\n Zamienione przedmioty: \n";
final Iterator<Exchange> interator = entry.getValue().iterator();
while (interator.hasNext()) {
final Exchange exchange = interator.next();
final String courseFrom = exchange.getDesiredAssignment().getCourseId() != null
? exchange.getDesiredAssignment().getCourseId().getName()
: "Nieznane zajęcie";
final String courseTo = exchange.getOwnedAssignment().getGroup().getCourseId() != null
? exchange.getOwnedAssignment().getGroup().getCourseId().getName()
: "Nieznane zajęcie";
response += (" - " + courseFrom + " za " + courseTo.toLowerCase());
}
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(appEmail);
mailMessage.setTo(user.getEmail());
mailMessage.setSubject("[PlanNaPlan] Zamiana przedmiotów");
mailMessage.setText(response);
emailSender.send(mailMessage);
}
}
}

View File

@ -6,6 +6,7 @@ import java.util.concurrent.ScheduledFuture;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
@ -14,6 +15,9 @@ import org.springframework.stereotype.Service;
@Service
public class EventService {
@Autowired
private ExchangeService exchangeService;
public static final int FIRST_TOUR_SCHEDULE = 0;
public static final int SECOND_TOUR_SCHEDULE = 1;
@ -25,9 +29,15 @@ public class EventService {
System.out.println("Checking for groups");
}
@Scheduled(cron = "0 0 0 * * *")
public void performExchangeService() {
System.out.println("Performing Exchange");
this.exchangeService.performExchange();
}
/**
* Schedule provided task to perform
*
*
* @param taskId static filed of this class that represents to what event
* we want to assign task
* @param task runnable class that perform task in implemented run method

View File

@ -0,0 +1,143 @@
package com.plannaplan.services;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.models.EmailExchangesData;
import com.plannaplan.models.MatchData;
import com.plannaplan.repositories.ExchangeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ExchangeService {
@Autowired
private ExchangeRepository repo;
@Autowired
private AssignmentService assignmentService;
@Autowired
private UserService userService;
@Autowired
private EmailService emailService;
/**
* @param exchange Instance to save in database
* @return Exchange Instance contains database id
*/
public Exchange save(Exchange exchange) {
return this.repo.save(exchange);
}
/**
* @param id Id of exchange in database
* @return Optional Exchange if found
*/
public Optional<Exchange> getById(Long id) {
return this.repo.findById(id);
}
public List<Exchange> getAllExchanges() {
return this.repo.findAll();
}
/**
* @param id Id of user
* @return List of exchanges that belong to user
*/
public List<Exchange> getByUserId(Long id) {
return this.repo.getByUserId(id);
}
/**
* @param entity Exchange entity which we would like to delete
*/
public void deleteExchange(Exchange entity) {
this.repo.delete(entity);
}
/**
* @param assignment Assignment to trade for
* @param group Desired group
* @return Optional with Exchange if exist
*/
public Optional<Exchange> checkForExchange(Assignment assignment, Groups group) {
return this.repo.checkForExchange(assignment, group);
}
public void performExchange() {
final List<MatchData> matchData = this.getMatches();
final List<Long> performedAssignmentExchanges = new ArrayList<>();
final EmailExchangesData emailData = new EmailExchangesData();
final List<Exchange> exchangesToDelete = new ArrayList<>();
matchData.forEach(m -> {
final Assignment assignmentOne = m.getAssignmentOne();
final Assignment assignmentTwo = m.getAssignmentTwo();
final Exchange exchange1 = m.getExchangeOne();
final Exchange exchange2 = m.getExchangeTwo();
if (!(performedAssignmentExchanges.contains(assignmentOne.getId())
|| performedAssignmentExchanges.contains(assignmentTwo.getId()))) {
final Commision commisionOne = assignmentOne.getCommision();
final User userOne = commisionOne.getCommisionOwner();
final Commision commisionTwo = assignmentTwo.getCommision();
final User userTwo = commisionTwo.getCommisionOwner();
assignmentOne.setCommision(commisionTwo);
assignmentTwo.setCommision(commisionOne);
userOne.removeGroup(assignmentOne.getGroup().getId());
userTwo.removeGroup(assignmentTwo.getGroup().getId());
userOne.claimGroup(assignmentTwo.getGroup());
userTwo.claimGroup(assignmentOne.getGroup());
this.assignmentService.save(assignmentOne);
this.assignmentService.save(assignmentTwo);
this.userService.save(userOne);
this.userService.save(userTwo);
performedAssignmentExchanges.add(assignmentOne.getId());
performedAssignmentExchanges.add(assignmentTwo.getId());
emailData.addExchange(exchange1.getOwnedAssignment().getCommision().getCommisionOwner(), exchange1);
emailData.addExchange(exchange2.getOwnedAssignment().getCommision().getCommisionOwner(), exchange2);
}
exchangesToDelete.add(exchange1);
exchangesToDelete.add(exchange2);
});
this.emailService.sendExchangesResults(emailData);
this.repo.deleteAll(exchangesToDelete);
}
public List<MatchData> getMatches() {
final List<MatchData> matches = this.repo.getMatches().stream().map(m -> {
final Exchange exchangeOne = (Exchange) m[0];
final Exchange exchangeTwo = (Exchange) m[1];
return new MatchData(exchangeOne, exchangeTwo);
}).collect(Collectors.toList());
final Set<MatchData> uniqData = new HashSet<>(matches);
final List<MatchData> matchDataListSorted = uniqData.stream().sorted((m1, m2) -> -1 * m1.compare(m2))
.collect(Collectors.toList());
return matchDataListSorted;
}
}

View File

@ -0,0 +1,69 @@
package com.plannaplan.repositories;
import static org.junit.Assert.assertTrue;
import java.util.List;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.services.AssignmentService;
import com.plannaplan.services.GroupService;
import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles;
import com.plannaplan.types.WeekDay;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.MethodMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class ExchangeRepositoryTest{
@Autowired
private ExchangeRepository exchangeRepository;
@Autowired
private AssignmentService assignmentService;
@Autowired
private GroupService groupService;
@Autowired
private UserService userService;
@Autowired
private CommisionRepository commisionRepository;
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldReturnMatches() {
final User user1 = this.userService.save(
new User(null, null, "shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Groups group1 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision1 = this.commisionRepository.save(new Commision(user1));
final User user2 = this.userService.save(
new User(null, null, "shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Groups group2 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision2 = this.commisionRepository.save(new Commision(user2));
final Assignment assignmentUser1 = this.assignmentService.save(new Assignment(group1, commision1));
final Assignment assignmentUser2 = this.assignmentService.save(new Assignment(group2, commision2));
this.assignmentService.callAcceptAlgorythm();
this.exchangeRepository.save(new Exchange(assignmentUser1, group2));
this.exchangeRepository.save(new Exchange(assignmentUser2, group1));
final List<Object[]> exchangeRepoMatches = this.exchangeRepository.getMatches();
assertTrue(exchangeRepoMatches.size() == 2);
}
}

View File

@ -0,0 +1,208 @@
package com.plannaplan.services;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.models.MatchData;
import com.plannaplan.repositories.CommisionRepository;
import com.plannaplan.types.UserRoles;
import com.plannaplan.types.WeekDay;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.MethodMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class ExchangeServiceTest {
@Autowired
private AssignmentService assignmentService;
@Autowired
private GroupService groupService;
@Autowired
private UserService userService;
@Autowired
private CommisionRepository commisionRepository;
@Autowired
private ExchangeService exchangeService;
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldReturnUniqMatches() {
final User user1 = this.userService.save(
new User(null, null, "shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Groups group1 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision1 = this.commisionRepository.save(new Commision(user1));
final User user2 = this.userService.save(
new User(null, null, "shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Groups group2 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision2 = this.commisionRepository.save(new Commision(user2));
final Assignment assignmentUser1 = this.assignmentService.save(new Assignment(group1, commision1));
final Assignment assignmentUser2 = this.assignmentService.save(new Assignment(group2, commision2));
this.assignmentService.callAcceptAlgorythm();
this.exchangeService.save(new Exchange(assignmentUser1, group2));
this.exchangeService.save(new Exchange(assignmentUser2, group1));
final List<MatchData> uniqList = this.exchangeService.getMatches();
assertTrue(uniqList.size() == 1);
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldPerformExchange() throws Exception{
User user1 = this.userService.save(
new User(null, null, "1shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Long user1Id = user1.getId();
final Groups group1 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision1 = this.commisionRepository.save(new Commision(user1));
User user2 = this.userService.save(
new User(null, null, "2shouldReturnMatches@ExchangeRepository.test", "123455", UserRoles.STUDENT, 452));
final Long user2Id = user2.getId();
final Groups group2 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.THURSDAY, null));
final Commision commision2 = this.commisionRepository.save(new Commision(user2));
User user3 = this.userService.save(
new User(null, null, "3shouldReturnMatches@ExchangeRepository.test", "123456", UserRoles.STUDENT, 453));
final Long user3Id = user3.getId();
final Groups group3 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.WEDNESDAY, null));
final Commision commision3 = this.commisionRepository.save(new Commision(user3));
User user4 = this.userService.save(
new User(null, null, "2shouldReturnMatches@ExchangeRepository.test", "123457", UserRoles.STUDENT, 455));
final Long user4Id = user4.getId();
final Groups group4 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.FRIDAY, null));
final Commision commision4 = this.commisionRepository.save(new Commision(user4));
final Assignment assignmentUser1 = this.assignmentService.save(new Assignment(group1, commision1));
final Assignment assignmentUser2 = this.assignmentService.save(new Assignment(group2, commision2));
final Assignment assignmentUser3 = this.assignmentService.save(new Assignment(group2, commision3));
final Assignment assignmentUser4 = this.assignmentService.save(new Assignment(group4, commision4));
this.assignmentService.callAcceptAlgorythm();
this.exchangeService.save(new Exchange(assignmentUser1, group2));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser2, group1));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser3, group1));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser4, group3));
this.exchangeService.performExchange();
user1 = this.userService.getById(user1Id).get();
Thread.sleep(1000);
user2 = this.userService.getById(user2Id).get();
Thread.sleep(1000);
user3 = this.userService.getById(user3Id).get();
Thread.sleep(1000);
user4 = this.userService.getById(user4Id).get();
Thread.sleep(1000);
final List<Long> listGroupsOfUser1 = user1.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
final List<Long> listGroupsOfUser2 = user2.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
final List<Long> listGroupsOfUser3 = user3.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
final List<Long> listGroupsOfUser4 = user4.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
assertTrue(listGroupsOfUser1.contains(group2.getId()));
assertTrue(listGroupsOfUser2.contains(group1.getId()));
assertTrue(listGroupsOfUser3.contains(group2.getId()));
assertTrue(listGroupsOfUser4.contains(group4.getId()));
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldRemoveOutDatedExchnages() throws Exception {
User user1 = this.userService.save(
new User(null, null, "1shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Long user1Id = user1.getId();
final Groups group1 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision1 = this.commisionRepository.save(new Commision(user1));
User user2 = this.userService.save(
new User(null, null, "2shouldReturnMatches@ExchangeRepository.test", "123455", UserRoles.STUDENT, 452));
final Long user2Id = user2.getId();
final Groups group2 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.THURSDAY, null));
final Commision commision2 = this.commisionRepository.save(new Commision(user2));
final Groups group3 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.THURSDAY, null));
final Groups group4 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.THURSDAY, null));
final Assignment assignmentUser1 = this.assignmentService.save(new Assignment(group1, commision1));
final Assignment assignmentUser2 = this.assignmentService.save(new Assignment(group2, commision2));
this.assignmentService.callAcceptAlgorythm();
this.exchangeService.save(new Exchange(assignmentUser1, group2));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser2, group1));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser1, group3));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser1, group4));
Thread.sleep(1000);
this.exchangeService.performExchange();
user1 = this.userService.getById(user1Id).get();
user2 = this.userService.getById(user2Id).get();
final List<Long> listGroupsOfUser1 = user1.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
final List<Long> listGroupsOfUser2 = user2.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
assertTrue(listGroupsOfUser1.contains(group2.getId()));
assertTrue(listGroupsOfUser2.contains(group1.getId()));
assertTrue(this.exchangeService.getAllExchanges().size() == 2);
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldSortExchanges() throws Exception{
final List<MatchData> listMatrix = new ArrayList<>();
final Exchange exchange1 = new Exchange(null, null);
Thread.sleep(1000);
final Exchange exchange2 = new Exchange(null, null);
Thread.sleep(1000);
final Exchange exchange3 = new Exchange(null, null);
Thread.sleep(1000);
final Exchange exchange4 = new Exchange(null, null);
Thread.sleep(1000);
listMatrix.add(new MatchData(exchange2, exchange4));
listMatrix.add(new MatchData(exchange1, exchange3));
final List<MatchData> matchDataListSorted = listMatrix.stream().sorted((m1, m2) -> -1 * m1.compare(m2)).collect(Collectors.toList());
assertTrue(listMatrix.get(0).equals(matchDataListSorted.get(1)));
assertTrue(listMatrix.get(1).equals(matchDataListSorted.get(0)));
assertTrue(matchDataListSorted.size() == 2);
}
}

View File

@ -6,10 +6,14 @@ from urllib.parse import parse_qs
import sys
import requests as r
if len(sys.argv) > 1 :
API_ADDRESS = "http://" + sys.argv[1] + ":1285"
else:
API_ADDRESS = "http://localhost:1285"
no_browser = False
API_ADDRESS = "http://localhost:1285"
if len(sys.argv) > 1 :
if (sys.argv[1] == "no-browser" or sys.argv[2] == "no-browser"):
no_browser = True
else:
API_ADDRESS = "http://" + sys.argv[1] + ":1285"
PORT = 3000
@ -39,5 +43,6 @@ def wait_for_request(server_class=HTTPServer,
url = 'https://cas.amu.edu.pl/cas/login?service=http://localhost:' + \
str(PORT) + '&locale=pl'
webbrowser.open_new_tab(url)
if no_browser == False:
webbrowser.open_new_tab(url)
wait_for_request()

View File

@ -0,0 +1,151 @@
package com.plannaplan.controllers;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.plannaplan.App;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
import com.plannaplan.responses.mappers.ExchangeResponseMappers;
import com.plannaplan.responses.models.ExchangeResponse;
import com.plannaplan.services.AssignmentService;
import com.plannaplan.services.ExchangeService;
import com.plannaplan.services.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@RestController
@CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/exchanges")
@Api(tags = { "Exchange" }, value = "Exchange", description = "Endpoint to exchange with accepted assignments.")
public class ExchangeController extends TokenBasedController{
@Autowired
private GroupService groupService;
@Autowired
private AssignmentService assignmentService;
@Autowired
private ExchangeService exchangeService;
@PostMapping("/exchange")
@ApiOperation(value = "Creates exchange offer.")
public ResponseEntity<String> createExchange(
@ApiParam( value = "Json object that contains assignment to trade and desired group")
@RequestBody
Map<String, Long> exchangeRequest)
throws UserNotFoundException {
final User asker = this.getCurrentUser()
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final Long assignmentId = exchangeRequest.get("assignment");
final Long groupId = exchangeRequest.get("group");
final List<Long> ownedGroups = asker.getStudentRegisteredGrups().stream().map(Groups::getId).collect(Collectors.toList());
if(ownedGroups.contains(groupId)){
return new ResponseEntity<>("User has already got this group.", HttpStatus.BAD_REQUEST);
}
if(assignmentId == null || groupId == null ){
return new ResponseEntity<>("Some of values are missing", HttpStatus.BAD_REQUEST);
}
final Optional<Assignment> assignment = this.assignmentService.getById(assignmentId);
final Optional<Groups> group = this.groupService.getGroupById(groupId);
if(assignment.isEmpty() || group.isEmpty()){
return new ResponseEntity<>("Some of provided value does not exist.", HttpStatus.BAD_REQUEST);
}
final Assignment assignmentInstance = assignment.get();
final Groups groupInstance = group.get();
if(!(assignmentInstance.getCommision().getCommisionOwner().getId().equals(asker.getId()) && assignmentInstance.isAccepted())){
return new ResponseEntity<>("Some of problems appeared. Check if you have access to given assignment and if it is accepted or the exchange has not been already added.", HttpStatus.BAD_REQUEST);
}
this.exchangeService.save(new Exchange(assignmentInstance, groupInstance));
return new ResponseEntity<>("Success", HttpStatus.OK);
}
@DeleteMapping("/exchange/{id}")
@ApiOperation(value = "Delete exchange offer")
public ResponseEntity<String> deleteExchange(@PathVariable(name = "id", required = false) Long offerId)
throws UserNotFoundException {
final User asker = this.getCurrentUser()
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final Optional<Exchange> exchange = this.exchangeService.getById(offerId);
if(exchange.isEmpty()){
return new ResponseEntity<>("Given offer does not exist.", HttpStatus.BAD_REQUEST);
}
final Exchange exchangeToDelete = exchange.get();
if(!(exchangeToDelete.getOwnedAssignment().getCommision().getCommisionOwner().getId().equals(asker.getId()))){
return new ResponseEntity<>("You have not permission for that action.", HttpStatus.BAD_REQUEST);
}
this.exchangeService.deleteExchange(exchangeToDelete);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
@GetMapping("/exchange/all")
@ApiOperation(value = "Get exchange offers")
public ResponseEntity<List<ExchangeResponse>> getExchange()
throws UserNotFoundException {
final User asker = this.getCurrentUser()
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final List<Exchange> response = exchangeService.getByUserId(asker.getId());
final List<ExchangeResponse> listOfResponses = ExchangeResponseMappers.mapToDefaultResponse(response);
return new ResponseEntity<>(listOfResponses, HttpStatus.OK);
}
@GetMapping("/exchange/{id}")
@ApiOperation(value = "Get exchange offers")
public ResponseEntity<ExchangeResponse> getExchangeById(@PathVariable(name = "id", required = false) Long offerId)
throws UserNotFoundException {
final User asker = this.getCurrentUser()
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final Optional<Exchange> exchange = this.exchangeService.getById(offerId);
if(exchange.isEmpty()){
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
final Exchange exchangeInstance = exchange.get();
if(!exchangeInstance.getOwnerId().equals(asker.getId())){
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new ExchangeResponse(exchangeInstance), HttpStatus.OK);
}
}

View File

@ -0,0 +1,14 @@
package com.plannaplan.responses.mappers;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import com.plannaplan.entities.Exchange;
import com.plannaplan.responses.models.ExchangeResponse;
public class ExchangeResponseMappers {
public static final List<ExchangeResponse> mapToDefaultResponse(List<Exchange> exchanges) {
return exchanges.stream().filter(Objects::nonNull).map(ExchangeResponse::new).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,36 @@
package com.plannaplan.responses.models;
import com.plannaplan.entities.Exchange;
public class ExchangeResponse {
private Long id;
private GroupDefaultResponse ownedAssignment;
private GroupDefaultResponse desiredGroup;
public ExchangeResponse(Exchange exchange){
this.id = exchange.getId();
this.ownedAssignment = new GroupDefaultResponse(exchange.getOwnedAssignment().getGroup());
this.desiredGroup = new GroupDefaultResponse(exchange.getDesiredAssignment());
}
public GroupDefaultResponse getDesiredGroup() {
return desiredGroup;
}
public void setDesiredGroup(GroupDefaultResponse desiredGroup) {
this.desiredGroup = desiredGroup;
}
public GroupDefaultResponse getOwnedAssignment() {
return ownedAssignment;
}
public void setOwnedAssignment(GroupDefaultResponse ownedAssignment) {
this.ownedAssignment = ownedAssignment;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,294 @@
package com.plannaplan.controllers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.MethodMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.nio.charset.Charset;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.services.AssignmentService;
import com.plannaplan.services.CommisionService;
import com.plannaplan.services.ExchangeService;
import com.plannaplan.services.GroupService;
import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles;
import com.plannaplan.types.WeekDay;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class ExchangeControllerTest extends AbstractControllerTest {
private final static String EXCHANGE_ENDPOINT = "/api/v1/exchanges/exchange";
private static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
@Autowired
private UserService userService;
@Autowired
private GroupService groupService;
@Autowired
private AssignmentService assignmentService;
@Autowired
private CommisionService commisionService;
@Autowired
private ExchangeService exchangeService;
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldGetAllUsersExchanges() throws Exception {
final User user = this.userService.save(new User(null, null,
"shouldGetAllUsersExchanges@ExchangeController.test", "11111", UserRoles.STUDENT, 320));
final String token = this.userService.login(user).getToken();
final Groups group = this.groupService.save(new Groups(215, "A2-2", null, 520, WeekDay.TUESDAY, null));
final Groups groupDesired = this.groupService.save(new Groups(216, "A2-3", null, 530, WeekDay.MONDAY, null));
final Commision commision = this.commisionService.save(new Commision(user));
final Assignment assignment = this.assignmentService.save(new Assignment(group, commision));
this.exchangeService.save(new Exchange(assignment, groupDesired));
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(get(EXCHANGE_ENDPOINT + "/all").header("Authorization", "Bearer " +
token)).andExpect(status().isOk());
}
@Test
public void shouldFailGettingNotExistingExchange() throws Exception {
final User user = this.userService.save(new User(null, null,
"shouldFailGettingNotExistingExchange@ExchangeController.test", UserRoles.STUDENT));
final String token = this.userService.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(get(EXCHANGE_ENDPOINT + "/" + user.getId()).header("Authorization", "Bearer " + token)).andExpect(status().isBadRequest());
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldGetSingleExchange() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldGetSingleExchange@ExchangeController.test", "11111", UserRoles.STUDENT, 320));
final String token = this.userService.login(user).getToken();
final Groups group = this.groupService.save(new Groups(215, "A2-2", null, 520, WeekDay.TUESDAY, null));
final Groups groupDesired = this.groupService.save(new Groups(216, "A2-3", null, 530, WeekDay.MONDAY, null));
final Commision commision = this.commisionService.save(new Commision(user));
final Assignment assignment = this.assignmentService.save(new Assignment(group, commision));
final Exchange exchange = this.exchangeService.save(new Exchange(assignment, groupDesired));
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(get(EXCHANGE_ENDPOINT + "/" + exchange.getId()).header("Authorization", "Bearer " +
token)).andExpect(status().isOk());
}
@Test
public void shouldFailGettingExchangeDueToPermission() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldFailGettingExchangeDueToPermission@ExchangeController.test", "11111", UserRoles.STUDENT, 320));
final Groups group = this.groupService.save(new Groups(215, "A2-2", null, 520, WeekDay.TUESDAY, null));
final Groups groupDesired = this.groupService.save(new Groups(216, "A2-3", null, 530, WeekDay.MONDAY, null));
final Commision commision = this.commisionService.save(new Commision(user));
final Assignment assignment = this.assignmentService.save(new Assignment(group, commision));
final Exchange exchange = this.exchangeService.save(new Exchange(assignment, groupDesired));
final User user2 = this.userService.save(new User(null, null,
"shouldFailGettingExchangeDueToPermission2@ExchangeController.test", "11112", UserRoles.STUDENT, 321));
final String token2 = this.userService.login(user2).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(EXCHANGE_ENDPOINT + "/" + exchange.getId()).header("Authorization", "Bearer " +
token2)).andExpect(status().is4xxClientError());
}
@Test
public void shouldFailPostDueToAssignmentNotFound() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldFailPostDueToAssignmentNotFound@ExchangeController.test", UserRoles.STUDENT));
final String token = this.userService.login(user).getToken();
final Groups group = this.groupService.save(new Groups(212, "A2-1", null, 420, WeekDay.WEDNESDAY, null));
MockMvc mockMvc =
MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(EXCHANGE_ENDPOINT).header("Authorization", "Bearer " +
token).contentType(APPLICATION_JSON_UTF8).content("{\"assignment\": "+ user.getId() +", \"group\": "+ group.getId() +" }")).andExpect(status().isBadRequest());
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldInsertExchange() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldInsertExchange@ExchangeController.test", "11111", UserRoles.STUDENT, 320));
final String token = this.userService.login(user).getToken();
final Groups group = this.groupService.save(new Groups(215, "A2-2", null, 520, WeekDay.TUESDAY, null));
final Groups groupDesired = this.groupService.save(new Groups(216, "A2-3", null, 530, WeekDay.MONDAY, null));
final Commision commision = this.commisionService.save(new Commision(user));
final Assignment assignment = this.assignmentService.save(new Assignment(group, commision));
this.assignmentService.callAcceptAlgorythm();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(EXCHANGE_ENDPOINT).header("Authorization", "Bearer " +
token).contentType(APPLICATION_JSON_UTF8).content("{\"assignment\": "+ assignment.getId() +", \"group\": "+ groupDesired.getId() +" }")).andExpect(status().isOk());
}
@Test
public void shouldFailInsertExchangeDueToMissingGroup() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldFailInsertExchangeDueToMissingGroup@ExchangeController.test", UserRoles.STUDENT));
final String token = this.userService.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(EXCHANGE_ENDPOINT).header("Authorization", "Bearer " +
token).contentType(APPLICATION_JSON_UTF8).content("{\"assignment\": "+ user.getId() +" }")).andExpect(status().isBadRequest());
}
@Test
public void shouldFailInsertExchangeDueToMissingAssignment() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldFailInsertExchangeDueToMissingAssignment@ExchangeController.test", UserRoles.STUDENT));
final String token = this.userService.login(user).getToken();
final Groups group = this.groupService.save(new Groups(212, "A2-1", null, 420, WeekDay.WEDNESDAY, null));
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(EXCHANGE_ENDPOINT).header("Authorization", "Bearer " +
token).contentType(APPLICATION_JSON_UTF8).content("{\"group\": "+ group.getId() +" }")).andExpect(status().isBadRequest());
}
@Test
public void shouldFailInsertExchangeDueToMissingParam() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldFailInsertExchangeDueToMissingParam@ExchangeController.test", UserRoles.STUDENT));
final String token = this.userService.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(EXCHANGE_ENDPOINT).header("Authorization", "Bearer " +
token).contentType(APPLICATION_JSON_UTF8)).andExpect(status().isBadRequest());
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldDenyExchangeDueToAssigmentOverlapping() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldDenyExchangeDueToAssigmentOverlapping@ExchangeController.test", "11111", UserRoles.STUDENT, 320));
final String token = this.userService.login(user).getToken();
final Groups group = this.groupService.save(new Groups(215, "A2-2", null, 520, WeekDay.TUESDAY, null));
final Commision commision = this.commisionService.save(new Commision(user));
final Assignment assignment = this.assignmentService.save(new Assignment(group, commision));
this.exchangeService.save(new Exchange(assignment, group));
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(EXCHANGE_ENDPOINT).header("Authorization", "Bearer " +
token).contentType(APPLICATION_JSON_UTF8).content("{\"assignment\": "+ user.getId() +", \"group\": "+ group.getId() +" }")).andExpect(status().isBadRequest());
}
@Test
public void shouldDenyPostDueToAssignmentNotAccepted() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldDenyPostDueToAssignmentNotAccepted@ExchangeController.test", UserRoles.STUDENT));
final String token = this.userService.login(user).getToken();
final Groups group = this.groupService.save(new Groups(212, "A2-1", null, 420, WeekDay.WEDNESDAY, null));
final Groups group2 = this.groupService.save(new Groups(213, "A2-2", null, 420, WeekDay.MONDAY, null));
final Commision commision = this.commisionService.save(new Commision(user));
final Assignment assignment = this.assignmentService.save(new Assignment(group,commision));
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(EXCHANGE_ENDPOINT).header("Authorization", "Bearer " +
token).contentType(APPLICATION_JSON_UTF8).content("{\"assignment\": "+ assignment.getId() +", \"group\": "+ group2.getId() +" }")).andExpect(status().isBadRequest());
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldDeleteExchange() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldDeleteExchange@ExchangeController.test", "11111", UserRoles.STUDENT, 320));
final String token = this.userService.login(user).getToken();
final Groups group = this.groupService.save(new Groups(215, "A2-2", null, 520, WeekDay.TUESDAY, null));
final Groups groupDesired = this.groupService.save(new Groups(216, "A2-3", null, 530, WeekDay.MONDAY, null));
final Commision commision = this.commisionService.save(new Commision(user));
final Assignment assignment = this.assignmentService.save(new Assignment(group, commision));
final Exchange exchange = this.exchangeService.save(new Exchange(assignment, groupDesired));
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(delete(EXCHANGE_ENDPOINT + "/" + exchange.getId()).header("Authorization", "Bearer " +
token)).andExpect(status().isOk());
}
@Test
public void shouldFailDeleteDueToWrongPermissions() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldFailDeleteDueToWrongPermissions@ExchangeController.test", "11111", UserRoles.STUDENT, 320));
final Groups group = this.groupService.save(new Groups(215, "A2-2", null, 520, WeekDay.TUESDAY, null));
final Groups groupDesired = this.groupService.save(new Groups(216, "A2-3", null, 530, WeekDay.MONDAY, null));
final Commision commision = this.commisionService.save(new Commision(user));
final Assignment assignment = this.assignmentService.save(new Assignment(group, commision));
final Exchange exchange = this.exchangeService.save(new Exchange(assignment, groupDesired));
final User user2 = this.userService.save(new User(null, null,
"shouldFailDeleteDueToWrongPermissions@ExchangeController2.test", "11112", UserRoles.STUDENT, 322));
final String token2 = this.userService.login(user2).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(get(EXCHANGE_ENDPOINT + "/" + exchange.getId()).header("Authorization", "Bearer " +
token2)).andExpect(status().isBadRequest());
}
@Test
public void shouldFailDeleteDueToMissingParam() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldFailDeleteDueToMissingParam@ExchangeController.test", UserRoles.STUDENT));
final String token = this.userService.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(delete(EXCHANGE_ENDPOINT).header("Authorization", "Bearer " + token)).andExpect(status().is4xxClientError());
}
@Test
public void shouldFailDeleteDueToExchangeNotFound() throws Exception{
final User user = this.userService.save(new User(null, null,
"shouldFailDeleteDueToExchangeNotFound@ExchangeController.test", UserRoles.STUDENT));
final String token = this.userService.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(delete(EXCHANGE_ENDPOINT + "/" + user.getId()).header("Authorization", "Bearer " +
token)).andExpect(status().isBadRequest());
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldFailPostDueToGroupAlreadyAccepted() throws Exception{
final User user = this.userService.save(new User(null, null, "shouldFailPostDueToGroupAlreadyAccepted@ExchangeController.test", "11111", UserRoles.STUDENT, 320));
final String token = this.userService.login(user).getToken();
final Groups group = this.groupService.save(new Groups(215, "A2-2", null, 520, WeekDay.TUESDAY, null));
final Groups group2 = this.groupService.save(new Groups(216, "A2-3", null, 530, WeekDay.MONDAY, null));
final Commision commision = this.commisionService.save(new Commision(user));
final Assignment assignment = this.assignmentService.save(new Assignment(group, commision));
this.assignmentService.save(new Assignment(group2, commision));
this.assignmentService.callAcceptAlgorythm();
this.exchangeService.save(new Exchange(assignment, group2));
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(EXCHANGE_ENDPOINT).header("Authorization", "Bearer " +
token).contentType(APPLICATION_JSON_UTF8).content("{\"assignment\": "+ assignment.getId() +", \"group\": "+ group2.getId() +" }")).andExpect(status().isBadRequest());
}
}