Search in sources :

Example 41 with ApiException

use of com.faforever.api.error.ApiException in project faf-java-api by FAForever.

the class ClanServiceTest method acceptPlayerInvitationTokenWrongPlayer.

@Test
public void acceptPlayerInvitationTokenWrongPlayer() throws IOException {
    String stringToken = "1234";
    Player newMember = new Player();
    newMember.setId(2);
    Clan clan = ClanFactory.builder().build();
    Player otherPlayer = new Player();
    otherPlayer.setId(3);
    long expire = System.currentTimeMillis() + 1000 * 3;
    Jwt jwtToken = Mockito.mock(Jwt.class);
    when(jwtToken.getClaims()).thenReturn(String.format("{\"expire\":%s,\"newMember\":{\"id\":%s},\"clan\":{\"id\":%s}}", expire, newMember.getId(), clan.getId()));
    when(jwtService.decodeAndVerify(any())).thenReturn(jwtToken);
    when(clanRepository.findById(clan.getId())).thenReturn(Optional.of(clan));
    when(playerRepository.findById(newMember.getId())).thenReturn(Optional.of(newMember));
    when(playerService.getPlayer(any())).thenReturn(otherPlayer);
    try {
        instance.acceptPlayerInvitationToken(stringToken, null);
        fail();
    } catch (ApiException e) {
        assertThat(e, apiExceptionWithCode(ErrorCode.CLAN_ACCEPT_WRONG_PLAYER));
    }
    verify(clanMembershipRepository, Mockito.never()).save(any(ClanMembership.class));
}
Also used : Player(com.faforever.api.data.domain.Player) Clan(com.faforever.api.data.domain.Clan) Jwt(org.springframework.security.jwt.Jwt) ClanMembership(com.faforever.api.data.domain.ClanMembership) ApiException(com.faforever.api.error.ApiException) Test(org.junit.Test)

Example 42 with ApiException

use of com.faforever.api.error.ApiException in project faf-java-api by FAForever.

the class ClanServiceTest method acceptPlayerInvitationTokenInvalidClan.

@Test
public void acceptPlayerInvitationTokenInvalidClan() throws IOException {
    String stringToken = "1234";
    long expire = System.currentTimeMillis() + 1000 * 3;
    Jwt jwtToken = Mockito.mock(Jwt.class);
    when(jwtToken.getClaims()).thenReturn(String.format("{\"expire\":%s,\"clan\":{\"id\":42}}", expire));
    when(jwtService.decodeAndVerify(any())).thenReturn(jwtToken);
    try {
        instance.acceptPlayerInvitationToken(stringToken, null);
        fail();
    } catch (ApiException e) {
        assertThat(e, apiExceptionWithCode(ErrorCode.CLAN_NOT_EXISTS));
    }
    verify(clanMembershipRepository, Mockito.never()).save(any(ClanMembership.class));
}
Also used : Jwt(org.springframework.security.jwt.Jwt) ClanMembership(com.faforever.api.data.domain.ClanMembership) ApiException(com.faforever.api.error.ApiException) Test(org.junit.Test)

Example 43 with ApiException

use of com.faforever.api.error.ApiException in project faf-java-api by FAForever.

the class ClanServiceTest method createClanWithSameTag.

@Test
public void createClanWithSameTag() {
    String clanName = "My cool Clan";
    String tag = "123";
    String description = "A cool clan for testing";
    Player creator = new Player();
    creator.setId(1);
    when(clanRepository.findOneByName(clanName)).thenReturn(Optional.empty());
    when(clanRepository.findOneByTag(tag)).thenReturn(Optional.of(new Clan()));
    try {
        instance.create(clanName, tag, description, creator);
        fail();
    } catch (ApiException e) {
        assertThat(e, apiExceptionWithCode(ErrorCode.CLAN_TAG_EXISTS));
    }
    ArgumentCaptor<Clan> clanCaptor = ArgumentCaptor.forClass(Clan.class);
    verify(clanRepository, Mockito.times(0)).save(clanCaptor.capture());
}
Also used : Player(com.faforever.api.data.domain.Player) Clan(com.faforever.api.data.domain.Clan) ApiException(com.faforever.api.error.ApiException) Test(org.junit.Test)

Example 44 with ApiException

use of com.faforever.api.error.ApiException in project faf-java-api by FAForever.

the class VotingService method saveVote.

@Transactional
public void saveVote(Vote vote, Player player) {
    vote.setPlayer(player);
    Assert.notNull(vote.getVotingSubject(), "You must specify a subject");
    List<Error> errors = ableToVote(player, vote.getVotingSubject().getId());
    if (vote.getVotingAnswers() == null) {
        vote.setVotingAnswers(Collections.emptySet());
    }
    VotingSubject subject = votingSubjectRepository.findById(vote.getVotingSubject().getId()).orElseThrow(() -> new IllegalArgumentException("Subject of vote not found"));
    vote.getVotingAnswers().forEach(votingAnswer -> {
        VotingChoice votingChoice = votingAnswer.getVotingChoice();
        VotingChoice one = votingChoiceRepository.findById(votingChoice.getId()).orElseThrow(() -> new ApiException(new Error(ErrorCode.VOTING_CHOICE_DOES_NOT_EXIST, votingChoice.getId())));
        votingAnswer.setVotingChoice(one);
        votingAnswer.setVote(vote);
    });
    subject.getVotingQuestions().forEach(votingQuestion -> {
        List<VotingAnswer> votingAnswers = vote.getVotingAnswers().stream().filter(votingAnswer -> votingAnswer.getVotingChoice().getVotingQuestion().equals(votingQuestion)).collect(Collectors.toList());
        long countOfAnswers = votingAnswers.size();
        int maxAnswers = votingQuestion.getMaxAnswers();
        if (maxAnswers < countOfAnswers) {
            errors.add(new Error(ErrorCode.TOO_MANY_ANSWERS, countOfAnswers, maxAnswers));
        }
        if (votingQuestion.isAlternativeQuestion()) {
            for (int i = 0; i < countOfAnswers; i++) {
                int finalI = i;
                long answersWithOrdinal = votingAnswers.stream().filter(votingAnswer -> Objects.equals(votingAnswer.getAlternativeOrdinal(), finalI)).count();
                if (answersWithOrdinal == 1) {
                    continue;
                }
                errors.add(new Error(ErrorCode.MALFORMATTED_ALTERNATIVE_ORDINALS));
            }
        }
    });
    if (!errors.isEmpty()) {
        throw new ApiException(errors.toArray(new Error[0]));
    }
    voteRepository.save(vote);
}
Also used : Error(com.faforever.api.error.Error) ErrorCode(com.faforever.api.error.ErrorCode) VotingAnswer(com.faforever.api.data.domain.VotingAnswer) Transactional(javax.transaction.Transactional) ApiException(com.faforever.api.error.ApiException) GamePlayerStatsRepository(com.faforever.api.game.GamePlayerStatsRepository) Vote(com.faforever.api.data.domain.Vote) Player(com.faforever.api.data.domain.Player) Collectors(java.util.stream.Collectors) VotingChoice(com.faforever.api.data.domain.VotingChoice) ArrayList(java.util.ArrayList) Objects(java.util.Objects) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) Validity(com.faforever.api.data.domain.Validity) Service(org.springframework.stereotype.Service) Optional(java.util.Optional) VotingSubject(com.faforever.api.data.domain.VotingSubject) Collections(java.util.Collections) Assert(org.springframework.util.Assert) VotingAnswer(com.faforever.api.data.domain.VotingAnswer) Error(com.faforever.api.error.Error) VotingSubject(com.faforever.api.data.domain.VotingSubject) VotingChoice(com.faforever.api.data.domain.VotingChoice) ApiException(com.faforever.api.error.ApiException) Transactional(javax.transaction.Transactional)

Example 45 with ApiException

use of com.faforever.api.error.ApiException in project faf-java-api by FAForever.

the class MapService method postProcessZipFiles.

@SneakyThrows
private void postProcessZipFiles(MapUploadData mapUploadData) {
    Optional<Path> mapFolder;
    try (Stream<Path> mapFolderStream = Files.list(mapUploadData.getBaseDir())) {
        mapFolder = mapFolderStream.filter(path -> Files.isDirectory(path)).findFirst();
    }
    if (!mapFolder.isPresent()) {
        throw new ApiException(new Error(ErrorCode.MAP_MISSING_MAP_FOLDER_INSIDE_ZIP));
    }
    try (Stream<Path> mapFolderStream = Files.list(mapUploadData.getBaseDir())) {
        if (mapFolderStream.count() != 2) {
            throw new ApiException(new Error(ErrorCode.MAP_INVALID_ZIP));
        }
    }
    mapUploadData.setOriginalMapFolder(mapFolder.get());
    mapUploadData.setUploadFolderName(mapUploadData.getOriginalMapFolder().getFileName().toString());
    List<Path> filePaths = new ArrayList<>();
    try (Stream<Path> mapFileStream = Files.list(mapUploadData.getOriginalMapFolder())) {
        mapFileStream.forEach(filePaths::add);
        Arrays.stream(REQUIRED_FILES).forEach(filePattern -> {
            if (filePaths.stream().noneMatch(filePath -> filePath.toString().endsWith(filePattern))) {
                throw new ApiException(new Error(ErrorCode.MAP_FILE_INSIDE_ZIP_MISSING, filePattern));
            }
        });
    }
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) ProgrammingError(com.faforever.api.error.ProgrammingError) Error(com.faforever.api.error.Error) ApiException(com.faforever.api.error.ApiException) SneakyThrows(lombok.SneakyThrows)

Aggregations

ApiException (com.faforever.api.error.ApiException)48 Error (com.faforever.api.error.Error)29 Player (com.faforever.api.data.domain.Player)18 Test (org.junit.Test)18 ProgrammingError (com.faforever.api.error.ProgrammingError)13 SneakyThrows (lombok.SneakyThrows)11 Clan (com.faforever.api.data.domain.Clan)10 ClanMembership (com.faforever.api.data.domain.ClanMembership)7 InputStream (java.io.InputStream)7 Path (java.nio.file.Path)7 BufferedInputStream (java.io.BufferedInputStream)6 FileInputStream (java.io.FileInputStream)6 ArrayList (java.util.ArrayList)6 ZipInputStream (java.util.zip.ZipInputStream)6 Map (com.faforever.api.config.FafApiProperties.Map)5 Vote (com.faforever.api.data.domain.Vote)5 VotingSubject (com.faforever.api.data.domain.VotingSubject)5 NotFoundApiException (com.faforever.api.error.NotFoundApiException)5 Jwt (org.springframework.security.jwt.Jwt)5 LuaValue (org.luaj.vm2.LuaValue)4