| repo
				 stringlengths 1 191 ⌀ | file
				 stringlengths 23 351 | code
				 stringlengths 0 5.32M | file_length
				 int64 0 5.32M | avg_line_length
				 float64 0 2.9k | max_line_length
				 int64 0 288k | extension_type
				 stringclasses 1
				value | 
|---|---|---|---|---|---|---|
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/application/service/MineService.java | 
	package org.codecritters.code_critters.application.service;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.application.exception.IncompleteDataException;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.persistence.entities.Game;
import org.codecritters.code_critters.persistence.entities.Mine;
import org.codecritters.code_critters.persistence.repository.GameRepository;
import org.codecritters.code_critters.persistence.repository.MineRepository;
import org.codecritters.code_critters.web.dto.MineDTO;
import org.codecritters.code_critters.web.dto.MinesDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class MineService {
    private final GameRepository gameRepository;
    private final MineRepository mineRepository;
    @Autowired
    public MineService(GameRepository gameRepository, MineRepository mineRepository) {
        this.gameRepository = gameRepository;
        this.mineRepository = mineRepository;
    }
    /**
     * Saves all mines passed in the given mine dto list.
     * @param mines The list containing the mines and game id.
     */
    public void saveMines(MinesDTO mines) {
        if (mines.getGame() == null) {
            throw new IncompleteDataException("Cannot save mines for game with id null!");
        }
        Optional<Game> game = gameRepository.findById(mines.getGame());
        if (!game.isPresent()) {
            throw new NotFoundException("Could not find game with id " + mines.getGame());
        }
        for (MineDTO dto : mines.getMines()) {
            Mine mine = createMine(dto);
            mine.setGame(game.get());
            mineRepository.save(mine);
        }
    }
    private Mine createMine(MineDTO dto) {
        Mine mine = new Mine();
        if (dto.getXml() != null) {
            mine.setXml(dto.getXml());
        }
        if (dto.getCode() != null) {
            mine.setCode(dto.getCode());
        }
        return mine;
    }
}
 | 2,846 | 32.494118 | 90 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/application/service/MutantsService.java | 
	package org.codecritters.code_critters.application.service;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.entities.Mutant;
import org.codecritters.code_critters.persistence.repository.LevelRepository;
import org.codecritters.code_critters.persistence.repository.MutantRepository;
import org.codecritters.code_critters.web.dto.MutantDTO;
import org.codecritters.code_critters.web.dto.MutantsDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MutantsService {
    private final LevelRepository levelRepository;
    private final MutantRepository mutantRepository;
    @Autowired
    public MutantsService(LevelRepository levelRepository, MutantRepository mutantRepository) {
        this.levelRepository = levelRepository;
        this.mutantRepository = mutantRepository;
    }
    public void createMutants(MutantsDTO dto) {
        Level level = levelRepository.findByName(dto.getName());
        for (MutantDTO critter : dto.getMutants()) {
            Mutant mutant = new Mutant(level, critter.getCode(), critter.getInit(), critter.getXml());
            mutantRepository.save(mutant);
        }
    }
    public void updateMutants(MutantsDTO dto) {
        Level level = levelRepository.findByName(dto.getName());
        for (MutantDTO critter : dto.getMutants()) {
            Mutant mutant = new Mutant(critter.getId(), level, critter.getCode(), critter.getInit(), critter.getXml());
            mutantRepository.save(mutant);
        }
    }
}
 | 2,366 | 37.177419 | 119 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/application/service/PasswordService.java | 
	package org.codecritters.code_critters.application.service;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.entities.User;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
@Service
public class PasswordService {
    public User hashPassword(String password, User user) {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(salt.toString());
        password = pbkdf2PasswordEncoder.encode(password);
        user.setPassword(password);
        user.setSalt(salt.toString());
        return user;
    }
    boolean verifyPassword(String rawPassword, String encodedPassword, String salt) {
        Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(salt);
        return pbkdf2PasswordEncoder.matches(rawPassword, encodedPassword);
    }
}
 | 1,774 | 33.134615 | 97 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/application/service/ResultService.java | 
	package org.codecritters.code_critters.application.service;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.entities.Result;
import org.codecritters.code_critters.persistence.entities.Score;
import org.codecritters.code_critters.persistence.entities.User;
import org.codecritters.code_critters.persistence.repository.LevelRepository;
import org.codecritters.code_critters.persistence.repository.ResultRepository;
import org.codecritters.code_critters.persistence.repository.ScoreRepository;
import org.codecritters.code_critters.persistence.repository.UserRepositiory;
import org.codecritters.code_critters.web.dto.ResultDTO;
import org.codecritters.code_critters.web.dto.ScoreDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ResultService {
    private final ResultRepository resultRepository;
    private final LevelRepository levelRepository;
    private final UserRepositiory userRepositiory;
    private final ScoreRepository scoreRepository;
    @Autowired
    public ResultService(ResultRepository resultRepository, LevelRepository levelRepository, UserRepositiory userRepositiory, ScoreRepository scoreRepository) {
        this.resultRepository = resultRepository;
        this.levelRepository = levelRepository;
        this.userRepositiory = userRepositiory;
        this.scoreRepository = scoreRepository;
    }
    public void createResult(ResultDTO resultDTO, String cookie) {
        Level level = levelRepository.findByName(resultDTO.getLevel());
        User user = userRepositiory.findByCookie(cookie);
        Result result;
        if(user != null)  {
            result = resultRepository.getResultByLevelAndUser(level, user);
            cookie = null;
        } else {
            result = resultRepository.getResultByLevelAndCookie(level, cookie);
        }
        if (result != null) {
            result.setScore(resultDTO.getScore());
            result.setStars(resultDTO.getStars());
        } else{
            result = new Result(resultDTO.getScore(), cookie, level, resultDTO.getStars(), user);
        }
        resultRepository.save(result);
    }
    public ScoreDTO getMyScore(String cookie) {
        User user = userRepositiory.findByCookie(cookie);
        if(user == null){
            throw new NotFoundException("No such User");
        }
        Score score = scoreRepository.findByUsername(user.getUsername());
        if(score == null){
            ScoreDTO scoreDTO = new ScoreDTO(user.getUsername());
            scoreDTO.setPosition(scoreRepository.countAll() + 1);
            return scoreDTO;
        }
        return createScoreDTO(score);
    }
    public ScoreDTO[] getHighscore() {
        List<Score> scores = scoreRepository.findTop10();
        ScoreDTO[] highscore = new ScoreDTO[scores.size() < 10 ? scores.size() : 10];
        for (int i = 0; i < highscore.length; i++) {
            highscore[i] = (createScoreDTO(scores.get(i)));
        }
        return highscore;
    }
    private ScoreDTO createScoreDTO(Score score) {
        return new ScoreDTO(score.getUsername(), score.getScore(), score.getLevels(), score.getPosition());
    }
}
 | 4,124 | 38.285714 | 160 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/application/service/RowService.java | 
	package org.codecritters.code_critters.application.service;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.application.exception.AlreadyExistsException;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.codecritters.code_critters.persistence.repository.RowRepository;
import org.codecritters.code_critters.web.dto.RowDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.ConstraintViolationException;
@Service
public class RowService {
    private final RowRepository rowRepository;
    @Autowired
    public RowService(RowRepository rowRepository) {
        this.rowRepository = rowRepository;
    }
    /**
     * Deletes the row with the given id from the database along with all levels belonging to that row.
     * @param dto The RowDTO containing the name and id of the row to be deleted.
     */
    public void deleteRow(RowDTO dto) {
        if (dto.getId() == null) {
            throw new IllegalArgumentException("Cannot delete a row with id null!");
        }
        CritterRow row = rowRepository.findCritterRowById(dto.getId());
        if (row == null) {
            throw new NotFoundException("There's no row with id: " + dto.getId());
        }
        rowRepository.delete(row);
    }
    /**
     * Updates the name of the given row to the specified value.
     * @param dto The RowDTO containing the row information.
     */
    public void updateRow(RowDTO dto) {
        if (dto.getId() == null) {
            throw new IllegalArgumentException("Cannot update a row with id null!");
        } else if (dto.getName() == null || dto.getName().trim().equals("")) {
            throw new IllegalArgumentException("Cannot update the row name to null!");
        }
        CritterRow row = rowRepository.findCritterRowById(dto.getId());
        if (row == null) {
            throw new NotFoundException("There's no row with id: " + dto.getId());
        }
        row.setName(dto.getName());
        rowRepository.save(row);
    }
    /**
     * Inserts a new row with the given values into the database.
     * @param dto The RowDTO containing the row information.
     * @return The newly created row.
     */
    public RowDTO addRow(RowDTO dto) {
        if (dto.getName() == null || dto.getName().trim().equals("")) {
            throw new IllegalArgumentException("Cannot add a row with name null!");
        } else if (dto.getPosition() < 0) {
            throw new IllegalArgumentException("Cannot add a row with an invalid position: " + dto.getPosition());
        }
        CritterRow row = createRowDAO(dto);
        CritterRow addRow;
        try {
            addRow = rowRepository.save(row);
        } catch (ConstraintViolationException e) {
            throw new AlreadyExistsException("Failed to insert the new row", e);
        }
        return createRowDTO(addRow);
    }
    private CritterRow createRowDAO(RowDTO dto) {
        CritterRow critterRow = new CritterRow();
        if (dto.getId() != null) {
            critterRow.setId(dto.getId());
        }
        if (dto.getName() != null) {
            critterRow.setName(dto.getName());
        }
        if (dto.getPosition() >= 0) {
            critterRow.setPosition(dto.getPosition());
        }
        return critterRow;
    }
    private RowDTO createRowDTO(CritterRow row) {
        RowDTO dto = new RowDTO();
        dto.setId(row.getId());
        dto.setName(row.getName());
        dto.setPosition(row.getPosition());
        return dto;
    }
}
 | 4,420 | 33.007692 | 114 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/application/service/TranslationsService.java | 
	package org.codecritters.code_critters.application.service;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.web.enums.Language;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Properties;
@Service
public class TranslationsService {
    private static final Logger logger = LogManager.getLogger(TranslationsService.class);
    public static String translate(Language language, String key){
        try {
            Resource resource = new ClassPathResource("/static/translation/" + language.toString() + ".properties");
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            return  properties.getProperty(key, key);
        } catch (IOException e) {
            logger.warn("Translations for " + language.toString() + "not found");
            return key;
        }
    }
}
 | 1,857 | 34.056604 | 116 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/application/service/UserService.java | 
	package org.codecritters.code_critters.application.service;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.application.exception.AlreadyExistsException;
import org.codecritters.code_critters.application.exception.IllegalActionException;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.persistence.entities.User;
import org.codecritters.code_critters.persistence.repository.ResultRepository;
import org.codecritters.code_critters.persistence.repository.UserRepositiory;
import org.codecritters.code_critters.web.dto.UserDTO;
import org.codecritters.code_critters.web.enums.Language;
import org.codecritters.code_critters.web.enums.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class UserService {
    private final UserRepositiory userRepositiory;
    private final ResultRepository resultRepository;
    private final MailService mailService;
    private final PasswordService passwordService;
    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw0123456789";
    @Value("${spring.session.timeout}")
    private int timeout;
    @Autowired
    public UserService(UserRepositiory userRepositiory, MailService mailService, PasswordService passwordService, ResultRepository resultRepository) {
        this.userRepositiory = userRepositiory;
        this.mailService = mailService;
        this.passwordService = passwordService;
        this.resultRepository = resultRepository;
    }
    public void registerUser(UserDTO dto, String url) {
        if(dto.getUsername() == null || dto.getEmail() == null || dto.getPassword() == null) {
            throw new IllegalActionException("These fields cannot be empty", "fill_fields");
        }
        if (dto.getUsername().trim().equals("") || dto.getEmail().trim().equals("") || dto.getPassword().trim().equals("")) {
            throw new IllegalActionException("These fields cannot be empty", "fill_fields");
        }
        if ((dto.getUsername().length() > 50) || (dto.getEmail().length() > 50) || (dto.getPassword().length() > 50)) {
            throw new IllegalActionException("The input has to be less than 50 characters!", "long_data");
        }
        if (userRepositiory.existsByUsername(dto.getUsername())) {
            throw new AlreadyExistsException("User with this username already exists!", "username_exists");
        }
        if(userRepositiory.existsByEmail(dto.getEmail())) {
            throw new AlreadyExistsException("User with this email already exists!", "email_exists");
        }
        User user = new User();
        user.setUsername(dto.getUsername());
        user.setEmail(dto.getEmail());
        if (dto.getLanguage() == null) {
            user.setLanguage(Language.en);
        }
        user.setLanguage(dto.getLanguage());
        user = passwordService.hashPassword(dto.getPassword(), user);
        user.setRole(Role.user);
        user.setActive(false);
        user.setSecret(generateSecret());
        Map<String, String> mailTemplateData = new HashMap();
        String link = url + "/users/activate/" + user.getSecret();
        mailTemplateData.put("receiver", user.getEmail());
        mailTemplateData.put("subject", "welcome");
        mailTemplateData.put("user", user.getUsername());
        mailTemplateData.put("secret", link);
        mailTemplateData.put("baseURL", url);
        mailService.sendMessageFromTemplate("register", mailTemplateData, user.getLanguage());
        userRepositiory.save(user);
    }
    public UserDTO loginUser(UserDTO dto, String cookie) {
        User user = userRepositiory.findByUsernameOrEmail(dto.getUsername(), dto.getEmail());
        if (user != null) {
            if ((dto.getPassword() != null) && (passwordService.verifyPassword(dto.getPassword(), user.getPassword(), user.getSalt()))) {
                user.setCookie(cookie);
                userRepositiory.save(user);
                return userToDTO(user);
            } else {
                throw new NotFoundException("Username or Password incorrect", "invalid_username_or_password");
            }
        }
        throw new NotFoundException("Username or Password incorrect", "invalid_username_or_password");
    }
    public void forgotPassword(UserDTO dto, String url) {
        User user = userRepositiory.findByUsernameOrEmail(dto.getUsername(), dto.getEmail());
        if (user != null) {
            user.setSecret(generateSecret());
            user.setResetPassword(true);
            userRepositiory.save(user);
            Map<String, String> mailTemplateData = new HashMap();
            String link = url + "/resetPassword?secret=" + user.getSecret();
            mailTemplateData.put("receiver", user.getEmail());
            mailTemplateData.put("subject", "reset_pw");
            mailTemplateData.put("user", user.getUsername());
            mailTemplateData.put("secret", link);
            mailTemplateData.put("baseURL", url);
            mailService.sendMessageFromTemplate("forgotPassword", mailTemplateData, user.getLanguage());
        } else {
            throw new NotFoundException("Username or Password incorrect", "invalid_username_or_password");
        }
    }
    public void resetPassword(String secret, UserDTO dto) {
        User user = userRepositiory.findBySecret(secret);
        if (user != null && user.getResetPassword()) {
            user.setSecret(null);
            user.setResetPassword(false);
            user = passwordService.hashPassword(dto.getPassword(), user);
            userRepositiory.save(user);
        } else {
            throw new NotFoundException("Incorrect Secret", "incorrect_secret");
        }
    }
    public boolean activateUser(String secret) {
        User user = userRepositiory.findBySecret(secret);
        if (user != null) {
            user.setSecret(null);
            user.setActive(true);
            return userRepositiory.save(user) != null;
        }
        return false;
    }
    private UserDTO userToDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setUsername(user.getUsername());
        dto.setEmail(user.getEmail());
        dto.setActive(user.getActive());
        dto.setLanguage(user.getLanguage());
        dto.setRole(user.getRole());
        return dto;
    }
    private String generateSecret() {
        int count = 42;
        StringBuilder builder = new StringBuilder();
        while (count-- != 0) {
            int character = (int) (Math.random() * ALPHA_NUMERIC_STRING.length());
            builder.append(ALPHA_NUMERIC_STRING.charAt(character));
        }
        return builder.toString();
    }
    public UserDTO getUserByCookie(String cookie) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, -timeout);
        Date date = cal.getTime();
        return getUserByCookieAndDate(cookie, date);
    }
    public UserDTO getUserByCookieAndDate(String cookie, Date date) {
        User user = userRepositiory.findByCookieAndLastUsedAfter(cookie, date);
        if (user != null) {
            userRepositiory.save(user);
            return userToDTO(user);
        }
        return null;
    }
    public void logoutUser(String cookie) {
        User user = userRepositiory.findByCookie(cookie);
        if (user != null) {
            user.setCookie(null);
            userRepositiory.save(user);
        }
    }
    public void deleteUser(String cookie) {
        User user = userRepositiory.findByCookie(cookie);
        List<User> users = userRepositiory.findAllByRole(Role.admin);
        if (users.size() == 1 && users.contains(user)) {
            throw new IllegalActionException("Cannot delete last remaining admin", "delete_last_admin");
        }
        if (user != null) {
            resultRepository.deleteAllByUser(user);
            userRepositiory.delete(user);
        }
    }
    public void changeUser(UserDTO dto, String cookie, String url) {
        User user = userRepositiory.findByCookie(cookie);
        if(dto.getUsername() == null || dto.getEmail() == null || dto.getUsername().trim().equals("") || dto.getEmail().trim().equals("")) {
            throw new IllegalActionException("These fields cannot be empty", "fill_fields");
        }
        if ((dto.getUsername().length() > 50) || (dto.getEmail().length() > 50)) {
            throw new IllegalActionException("The input has to be less than 50 characters!", "long_data");
        }
        if (dto.getPassword() != null) {
            if (dto.getPassword().length() > 50) {
                throw new IllegalActionException("The input has to be less than 50 characters!", "long_data");
            }
            if (dto.getPassword().trim().equals("") || dto.getOldPassword() == null || dto.getOldPassword().trim().equals("")) {
                throw new IllegalActionException("These fields cannot be empty", "fill_fields");
            }
        }
        if(dto.getOldPassword() != null && !dto.getOldPassword().trim().equals("")){
            if(passwordService.verifyPassword(dto.getOldPassword(), user.getPassword(), user.getSalt())) {
                if (dto.getPassword() != null) {
                    user = passwordService.hashPassword(dto.getPassword(), user);
                } else {
                    user = passwordService.hashPassword(dto.getOldPassword(), user);
                }
                userRepositiory.save(user);
            } else {
                throw new NotFoundException("Password incorrect", "invalid_password");
            }
        }
        if(!dto.getUsername().equals(user.getUsername())){
            if(!userRepositiory.existsByUsername(dto.getUsername())) {
                user.setUsername(dto.getUsername());
            } else {
                throw new AlreadyExistsException("User with this username already exists!", "username_exists");
            }
        }
        if(!dto.getEmail().equals(user.getEmail())){
            if(!userRepositiory.existsByEmail(dto.getEmail())) {
                user.setEmail(dto.getEmail());
                user.setActive(false);
                user.setSecret(generateSecret());
                Map<String, String> mailTemplateData = new HashMap();
                String link = url + "/users/activate/" + user.getSecret();
                mailTemplateData.put("receiver", user.getEmail());
                mailTemplateData.put("subject", "Confirm Email");
                mailTemplateData.put("user", user.getUsername());
                mailTemplateData.put("secret", link);
                mailTemplateData.put("baseURL", url);
                mailService.sendMessageFromTemplate("confirmEmail", mailTemplateData, user.getLanguage());
            } else {
                throw new AlreadyExistsException("User with this email already exists!", "email_exists");
            }
        }
        userRepositiory.save(user);
    }
}
 | 11,856 | 39.467577 | 150 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/customDataTypes/CoordinateDataType.java | 
	package org.codecritters.code_critters.persistence.customDataTypes;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
public class CoordinateDataType implements UserType {
    protected static final int[] SQL_TYPES = {Types.VARCHAR};
    @Override
    public int[] sqlTypes() {
        return new int[]{Types.VARCHAR};
    }
    @Override
    public Class returnedClass() {
        return String[][].class;
    }
    @Override
    public boolean equals(Object x, Object y) throws HibernateException {
        if (x == null) {
            return y == null;
        }
        if (x instanceof HashMap && y instanceof HashMap) {
            HashMap<String, Integer> tempX = (HashMap<String, Integer>) x;
            HashMap<String, Integer> tempY = (HashMap<String, Integer>) y;
            return tempX.equals(tempY);
        }
        return false;
    }
    @Override
    public int hashCode(Object x) throws HibernateException {
        return x.hashCode();
    }
    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
        if (rs.wasNull()) {
            return null;
        }
        if (rs.getString(names[0]) == null) {
            return new Integer[0];
        }
        return parseStringToHashMap(rs.getString(names[0]));
    }
    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
        if (value == null) {
            st.setNull(index, SQL_TYPES[0]);
        } else {
            HashMap<String, Integer> castObject = (HashMap<String, Integer>) value;
            st.setString(index, parseHashMapToString(castObject));
        }
    }
    @Override
    public Object deepCopy(Object value) throws HibernateException {
        return value;
    }
    @Override
    public boolean isMutable() {
        return true;
    }
    @Override
    public Serializable disassemble(Object value) throws HibernateException {
        return (Integer[]) this.deepCopy(value);
    }
    @Override
    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return this.deepCopy(cached);
    }
    @Override
    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return original;
    }
    private String parseHashMapToString(HashMap<String, Integer> level) {
        StringBuilder res = new StringBuilder();
        for (Map.Entry<String, Integer> entry : level.entrySet()) {
            res.append("{");
            res.append("[").append(entry.getKey()).append("]");
            res.append("[").append(entry.getValue()).append("]");
            res.append("}");
        }
        return res.toString();
    }
    private HashMap<String, Integer> parseStringToHashMap(String level) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        level = level.replace("{", "");
        String[] temp = level.split("}");
        for (int i = 0; i < temp.length; ++i) {
            temp[i] = temp[i].replace("[", "");
            String[] temp2 = temp[i].split("]");
            map.put(temp2[0], Integer.parseInt(temp2[1]));
        }
        return map;
    }
}
 | 4,368 | 30.431655 | 158 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/customDataTypes/LevelDataType.java | 
	package org.codecritters.code_critters.persistence.customDataTypes;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import org.springframework.util.StringUtils;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
public class LevelDataType implements UserType {
    protected static final int[] SQL_TYPES = {Types.CLOB};
    @Override
    public int[] sqlTypes() {
        return new int[]{Types.CLOB};
    }
    @Override
    public Class returnedClass() {
        return String[][].class;
    }
    @Override
    public boolean equals(Object x, Object y) throws HibernateException {
        if (x == null) {
            return y == null;
        }
        if (x instanceof String[][] && y instanceof String[][]) {
            String[][] tempX = (String[][]) x;
            String[][] tempY = (String[][]) y;
            return Arrays.deepEquals(tempX, tempY);
        }
        return false;
    }
    @Override
    public int hashCode(Object x) throws HibernateException {
        return x.hashCode();
    }
    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
        if (rs.wasNull()) {
            return null;
        }
        if (rs.getString(names[0]) == null) {
            return new Integer[0];
        }
        return parseStringToArray(rs.getString(names[0]));
    }
    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
        if (value == null) {
            st.setNull(index, SQL_TYPES[0]);
        } else {
            String[][] castObject = (String[][]) value;
            st.setString(index, parseArrayToString(castObject));
        }
    }
    @Override
    public Object deepCopy(Object value) throws HibernateException {
        return value;
    }
    @Override
    public boolean isMutable() {
        return true;
    }
    @Override
    public Serializable disassemble(Object value) throws HibernateException {
        return (Integer[]) this.deepCopy(value);
    }
    @Override
    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return this.deepCopy(cached);
    }
    @Override
    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return original;
    }
    private String parseArrayToString(String[][] level) {
        StringBuilder res = new StringBuilder();
        for (String[] row : level) {
            res.append("{");
            for (String column : row) {
                res.append("[").append(column).append("]");
            }
            res.append("}");
        }
        return res.toString();
    }
    private String[][] parseStringToArray(String level) {
        String[][] array = new String[StringUtils.countOccurrencesOf(level, "{")][];
        level = level.replace("{", "");
        String[] temp = level.split("}");
        for (int i = 0; i < temp.length; ++i) {
            temp[i] = temp[i].replace("[", "");
            array[i] = temp[i].split("]");
        }
        return array;
    }
}
 | 4,181 | 29.086331 | 158 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/customDataTypes/LevelResultType.java | 
	package org.codecritters.code_critters.persistence.customDataTypes;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
public interface LevelResultType {
    String getName();
    Integer getScore();
    Integer getStars();
}
 | 931 | 27.242424 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/entities/CritterRow.java | 
	package org.codecritters.code_critters.persistence.entities;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class CritterRow {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    @NotEmpty
    @Column(unique = true)
    private String name;
    private int position;
    public CritterRow(String name, int position) {
        this.name = name;
        this.position = position;
    }
    public CritterRow() {
    }
    public int getPosition() {
        return position;
    }
    public void setPosition(int position) {
        this.position = position;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
 | 1,860 | 23.168831 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/entities/Game.java | 
	package org.codecritters.code_critters.persistence.entities;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.time.LocalDateTime;
import java.util.Objects;
@Entity
public class Game {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    @ManyToOne
    @JoinColumn(name = "level_id")
    private Level level;
    private LocalDateTime start;
    private LocalDateTime end;
    private int score;
    private int mutantsKilled;
    private int humansFinished;
    private double gameTime;
    @Column(name = "user_id")
    private String userID;
    public Game() {}
    public Game(Level level, LocalDateTime start) {
        this.level = level;
        this.start = start;
    }
    public Game(Level level, LocalDateTime start, String userID) {
        this.level = level;
        this.start = start;
        this.userID = userID;
    }
    public Game(Level level, LocalDateTime start, LocalDateTime end) {
        this.level = level;
        this.start = start;
        this.end = end;
    }
    public Game(Level level, LocalDateTime start, LocalDateTime end, String userID) {
        this.level = level;
        this.start = start;
        this.end = end;
        this.userID = userID;
    }
    public Game(String id, Level level, LocalDateTime start, LocalDateTime end, int score, int mutantsKilled,
                int humansFinished, double gameTime) {
        this.id = id;
        this.level = level;
        this.start = start;
        this.end = end;
        this.score = score;
        this.mutantsKilled = mutantsKilled;
        this.humansFinished = humansFinished;
        this.gameTime = gameTime;
    }
    public Game(String id, Level level, LocalDateTime start, LocalDateTime end, int score, int mutantsKilled,
                int humansFinished, double gameTime, String userID) {
        this.id = id;
        this.level = level;
        this.start = start;
        this.end = end;
        this.score = score;
        this.mutantsKilled = mutantsKilled;
        this.humansFinished = humansFinished;
        this.gameTime = gameTime;
        this.userID = userID;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Level getLevel() {
        return level;
    }
    public void setLevel(Level level) {
        this.level = level;
    }
    public LocalDateTime getStart() {
        return start;
    }
    public void setStart(LocalDateTime start) {
        this.start = start;
    }
    public LocalDateTime getEnd() {
        return end;
    }
    public void setEnd(LocalDateTime end) {
        this.end = end;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public int getMutantsKilled() {
        return mutantsKilled;
    }
    public void setMutantsKilled(int mutantsKilled) {
        this.mutantsKilled = mutantsKilled;
    }
    public int getHumansFinished() {
        return humansFinished;
    }
    public void setHumansFinished(int humansFinished) {
        this.humansFinished = humansFinished;
    }
    public double getGameTime() {
        return gameTime;
    }
    public void setGameTime(double gameTime) {
        this.gameTime = gameTime;
    }
    public String getUserID() {
        return userID;
    }
    public void setUserID(String userID) {
        this.userID = userID;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Game game = (Game) o;
        return id.equals(game.id);
    }
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}
 | 4,803 | 24.151832 | 109 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/entities/Level.java | 
	package org.codecritters.code_critters.persistence.entities;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.HashMap;
@Entity
//@Table(indexes = {@Index(columnList = "name", name = "level_name")})
public class Level {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    @NotEmpty
    @Column(unique = true)
    private String name;
    @Column(columnDefinition = "int default 10")
    private int numberOfCritters;
    @Column(columnDefinition = "int default 5")
    private int numberOfHumans;
    @NotEmpty
    @Column(columnDefinition = "text")
    private String CUT;
    @Column(columnDefinition = "text")
    private String init;
    @Column(columnDefinition = "text")
    private String xml;
    @Column(columnDefinition = "text")
    private String test;
    @NotEmpty
    @Type(type = "org.codecritters.code_critters.persistence.customDataTypes.LevelDataType")
    private String[][] level;
    @NotEmpty
    @Type(type = "org.codecritters.code_critters.persistence.customDataTypes.CoordinateDataType")
    private HashMap<String, Integer> tower;
    @NotEmpty
    @Type(type = "org.codecritters.code_critters.persistence.customDataTypes.CoordinateDataType")
    private HashMap<String, Integer> spawn;
    @ManyToOne(cascade = CascadeType.REMOVE)
    @JoinColumn(name = "row_id")
    private CritterRow row;
    @Column(columnDefinition = "int default 2")
    private int freeMines;
    public Level(CritterRow row, String name, int numberOfCritters, int numberOfHumans, String CUT, String test, String xml, String init, String[][] level, int freeMines) {
        this.row = row;
        this.name = name;
        this.numberOfCritters = numberOfCritters;
        this.numberOfHumans = numberOfHumans;
        this.CUT = CUT;
        this.test = test;
        this.level = level;
        this.init = init;
        this.xml = xml;
        this.freeMines = freeMines;
    }
    public Level() {
    }
    public Level(String id) {
        this.id = id;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getNumberOfCritters() {
        return numberOfCritters;
    }
    public void setNumberOfCritters(int numberOfCritters) {
        this.numberOfCritters = numberOfCritters;
    }
    public int getNumberOfHumans() {
        return numberOfHumans;
    }
    public void setNumberOfHumans(int numberOfHumans) {
        this.numberOfHumans = numberOfHumans;
    }
    public String getCUT() {
        return CUT;
    }
    public void setCUT(String CUT) {
        this.CUT = CUT;
    }
    public String getTest() {
        return test;
    }
    public void setTest(String test) {
        this.test = test;
    }
    public String[][] getLevel() {
        return level;
    }
    public HashMap<String, Integer> getTower() {
        return tower;
    }
    public void setTower(HashMap<String, Integer> tower) {
        this.tower = tower;
    }
    public HashMap<String, Integer> getSpawn() {
        return spawn;
    }
    public void setSpawn(HashMap<String, Integer> spawn) {
        this.spawn = spawn;
    }
    public void setLevel(String[][] level) {
        this.level = level;
    }
    public String getInit() {
        return init;
    }
    public void setInit(String init) {
        this.init = init;
    }
    public String getXml() {
        return xml;
    }
    public void setXml(String xml) {
        this.xml = xml;
    }
    public CritterRow getRow() {
        return row;
    }
    public void setRow(CritterRow row) {
        this.row = row;
    }
    public int getFreeMines() {
        return freeMines;
    }
    public void setFreeMines(int freeMines) {
        this.freeMines = freeMines;
    }
}
 | 4,859 | 23.795918 | 172 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/entities/Mine.java | 
	package org.codecritters.code_critters.persistence.entities;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Mine {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    @ManyToOne
    @JoinColumn(name = "game_id")
    private Game game;
    @Column(columnDefinition = "text")
    private String code;
    @Column(columnDefinition = "text")
    private String xml;
    public Mine() {}
    public Mine(Game game, String code, String xml) {
        this.game = game;
        this.code = code;
        this.xml = xml;
    }
    public Mine(String id, Game game, String code, String xml) {
        this.id = id;
        this.game = game;
        this.code = code;
        this.xml = xml;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Game getGame() {
        return game;
    }
    public void setGame(Game game) {
        this.game = game;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getXml() {
        return xml;
    }
    public void setXml(String xml) {
        this.xml = xml;
    }
}
 | 2,268 | 22.635417 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/entities/Mutant.java | 
	package org.codecritters.code_critters.persistence.entities;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
@Entity
public class Mutant {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    @ManyToOne
    @JoinColumn(name = "level_id")
    private Level level;
    @NotEmpty
    @Column(columnDefinition = "text")
    private String code;
    @Column(columnDefinition = "text")
    private String init;
    @Column(columnDefinition = "text")
    private String xml;
    public Mutant() {
    }
    public Mutant(Level level, String code, String init, String xml) {
        this.level = level;
        this.code = code;
        this.init = init;
        this.xml = xml;
    }
    public Mutant(String id, Level level, String code, String init, String xml) {
        this.id = id;
        this.level = level;
        this.code = code;
        this.init = init;
        this.xml = xml;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Level getLevel() {
        return level;
    }
    public void setLevel(Level level) {
        this.level = level;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getInit() {
        return init;
    }
    public void setInit(String init) {
        this.init = init;
    }
    public String getXml() {
        return xml;
    }
    public void setXml(String xml) {
        this.xml = xml;
    }
}
 | 2,451 | 22.132075 | 81 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/entities/Result.java | 
	package org.codecritters.code_critters.persistence.entities;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
@Entity
//@Table(indexes = {@Index(columnList = "name", name = "level_name")})
public class Result {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    private int score;
    private int stars;
    private String cookie;
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;
    @ManyToOne
    @JoinColumn(name = "level_id")
    private Level level;
    private Date updated;
    public Result() {
    }
    public Result(int score, int stars, String cookie, Level level, Date updated, User user) {
        this.score = score;
        this.stars = stars;
        this.cookie = cookie;
        this.level = level;
        this.updated = updated;
        this.user = user;
    }
    public Result(int score, String cookie, Level level, int stars, User user) {
        this.score = score;
        this.cookie = cookie;
        this.level = level;
        this.stars = stars;
        this.user = user;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public String getCookie() {
        return cookie;
    }
    public void setCookie(String cookie) {
        this.cookie = cookie;
    }
    public Level getLevel() {
        return level;
    }
    public void setLevel(Level level) {
        this.level = level;
    }
    public int getStars() {
        return stars;
    }
    public void setStars(int stars) {
        this.stars = stars;
    }
    public Date getUpdated() {
        return updated;
    }
    public void setUpdated(Date updated) {
        this.updated = updated;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    @PrePersist
    protected void onCreate() {
        updated = new Date();
    }
    @PreUpdate
    protected void onUpdate() {
        updated = new Date();
    }
}
 | 3,023 | 20.913043 | 94 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/entities/Score.java | 
	package org.codecritters.code_critters.persistence.entities;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Score {
    @Id
    private String username;
    private int score;
    private int levels;
    private int position;
    public Score(String username, int score, int levels, int position) {
        this.username = username;
        this.score = score;
        this.levels = levels;
        this.position = position;
    }
    public Score() {
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public int getLevels() {
        return levels;
    }
    public void setLevels(int levels) {
        this.levels = levels;
    }
    public int getPosition() {
        return position;
    }
    public void setPosition(int position) {
        this.position = position;
    }
}
 | 1,822 | 21.7875 | 72 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/entities/User.java | 
	package org.codecritters.code_critters.persistence.entities;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.web.enums.Language;
import org.codecritters.code_critters.web.enums.Role;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.Date;
import java.util.Objects;
@Entity
public class User {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    @NotEmpty
    @Column(unique = true)
    private String username;
    @NotEmpty
    @Column(unique = true)
    private String email;
    private String password;
    @Column(unique = true)
    private String cookie;
    private String secret;
    private String salt;
    private boolean resetPassword;
    private boolean active;
    @Enumerated(EnumType.STRING)
    private Language language;
    @Enumerated(EnumType.STRING)
    private Role role;
    private Date lastUsed;
    public User(String username, String email, String password, String cookie, String secret, String salt, boolean resetPassword, boolean active, Language language, Role role, Date lastUsed) {
        this.username = username;
        this.email = email;
        this.password = password;
        this.cookie = cookie;
        this.secret = secret;
        this.salt = salt;
        this.resetPassword = resetPassword;
        this.active = active;
        this.language = language;
        this.role = role;
        this.lastUsed = lastUsed;
    }
    public User() {
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getCookie() {
        return cookie;
    }
    public void setCookie(String cookie) {
        this.cookie = cookie;
    }
    public String getSecret() {
        return secret;
    }
    public void setSecret(String secret) {
        this.secret = secret;
    }
    public String getSalt() {
        return salt;
    }
    public void setSalt(String salt) {
        this.salt = salt;
    }
    public boolean getResetPassword() {
        return resetPassword;
    }
    public void setResetPassword(boolean resetPassword) {
        this.resetPassword = resetPassword;
    }
    public boolean getActive() {
        return active;
    }
    public void setActive(boolean active) {
        this.active = active;
    }
    public Language getLanguage() {
        return language;
    }
    public void setLanguage(Language language) {
        this.language = language;
    }
    public Role getRole() {
        return role;
    }
    public Date getLastUsed() {
        return lastUsed;
    }
    public void setLastUsed(Date lastUsed) {
        this.lastUsed = lastUsed;
    }
    public void setRole(Role role) {
        this.role = role;
    }
    @PrePersist
    protected void onCreate() {
        lastUsed = new Date();
    }
    @PreUpdate
    protected void onUpdate() {
        lastUsed = new Date();
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(id, user.id);
    }
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}
 | 4,556 | 22.25 | 192 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/repository/GameRepository.java | 
	package org.codecritters.code_critters.persistence.repository;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.entities.Game;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface GameRepository extends CrudRepository<Game, String> {
    Optional<Game> findById(@Param("id") String id);
}
 | 1,221 | 32.027027 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/repository/LevelRepository.java | 
	package org.codecritters.code_critters.persistence.repository;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.customDataTypes.LevelResultType;
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.codecritters.code_critters.persistence.entities.User;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface LevelRepository extends CrudRepository<Level, String> {
    Level findByName(String name);
    @Query("SELECT l.name FROM Level as l ORDER BY l.name ASC")
    List<String> getLevelNames();
    @Query("SELECT l.id FROM Level AS l WHERE l.name = :name")
    String getIdByName(@Param("name") String name);
    @Query("SELECT l.test FROM Level AS l WHERE l.name = :name")
    String getTestByName(@Param("name") String name);
    @Query("SELECT l.CUT FROM Level AS l WHERE l.name = :name")
    String getCUTByName(@Param("name") String name);
    @Query("SELECT l.init FROM Level AS l WHERE l.name = :name")
    String getInitByName(@Param("name") String name);
    @Query("SELECT l.name FROM Level as l WHERE l.row = :rid ORDER BY l.name ASC")
    List<String> getLevelNamesByGroup(@Param("rid") CritterRow row);
    @Query(nativeQuery = true, value = "SELECT l.name, r.score, r.stars FROM level as l LEFT JOIN ( SELECT r2.score, r2.level_id, r2.stars FROM result AS r2 WHERE r2.cookie = :cookie) AS r ON l.id = r.level_id WHERE l.row_id = :rid ORDER BY l.name ASC")
    List<LevelResultType> getLevelNamesAndResultByGroup(@Param("rid") CritterRow row, @Param("cookie") String cookie);
    @Query(nativeQuery = true, value = "SELECT l.name, r.score, r.stars FROM level as l LEFT JOIN ( SELECT r2.score, r2.level_id, r2.stars FROM result AS r2 WHERE r2.user_id = :user) AS r ON l.id = r.level_id WHERE l.row_id = :rid ORDER BY l.name ASC")
    List<LevelResultType> getLevelNamesAndResultByGroup(@Param("rid") CritterRow row, @Param("user") User user);
    @Modifying
    @Query("DELETE FROM Level AS l WHERE l.id = :id")
    void deleteById(@Param("id") String id);
}
 | 3,108 | 43.414286 | 253 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/repository/MineRepository.java | 
	package org.codecritters.code_critters.persistence.repository;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.entities.Mine;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface MineRepository extends CrudRepository<Mine, String> {
}
 | 1,083 | 32.875 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/repository/MutantRepository.java | 
	package org.codecritters.code_critters.persistence.repository;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.entities.Mutant;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface MutantRepository extends CrudRepository<Mutant, String> {
    @Query("SELECT m.code, m.init, m.id, m.xml FROM Mutant AS m WHERE m.level = :level")
    List<String[]> getCodeByLevel(@Param("level") Level level);
    void deleteAllByLevel(Level level);
}
 | 1,477 | 34.190476 | 88 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/repository/ResultRepository.java | 
	package org.codecritters.code_critters.persistence.repository;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.entities.Result;
import org.codecritters.code_critters.persistence.entities.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
@Repository
public interface ResultRepository extends CrudRepository<Result, String> {
    Result getResultByLevelAndCookie(Level level, String cookie);
    Result getResultByLevelAndUser(Level level, User user);
    List<Result> getAllByUpdatedBeforeAndUserIsNull(Date date);
    void deleteAllByUser(User user);
    void deleteAllByLevel(Level level);
}
 | 1,533 | 30.958333 | 74 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/repository/RowRepository.java | 
	package org.codecritters.code_critters.persistence.repository;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Collection;
@Repository
public interface RowRepository extends CrudRepository<CritterRow, String> {
    @Query("SELECT r FROM CritterRow as r ORDER BY r.position ASC")
    Collection<CritterRow> getRows();
    CritterRow findCritterRowById(String id);
}
 | 1,325 | 32.15 | 75 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/repository/ScoreRepository.java | 
	package org.codecritters.code_critters.persistence.repository;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.entities.Score;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ScoreRepository extends CrudRepository<Score, String> {
    @Query(nativeQuery = true,
            value = "SELECT * FROM score AS s ORDER BY s.score DESC LIMIT 10")
    List<Score> findTop10();
    Score findByUsername(String username);
    @Query(nativeQuery = true,
            value = "SELECT COUNT(*) as number FROM score AS s")
    int countAll();
}
 | 1,458 | 31.422222 | 78 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/persistence/repository/UserRepositiory.java | 
	package org.codecritters.code_critters.persistence.repository;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.entities.User;
import org.codecritters.code_critters.web.enums.Role;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
@Repository
public interface UserRepositiory extends CrudRepository<User, String> {
    boolean existsByUsernameOrEmail(String username, String email);
    User findByUsernameOrEmail(String username, String email);
    User findBySecret(String secret);
    User findByCookie(String cookie);
    User findByCookieAndLastUsedAfter(String cookie, Date date);
    User findByUsernameAndEmail(String username, String email);
    List<User> findAllByRole(Role role);
    boolean existsByCookie(String cookie);
    boolean existsByEmail(String email);
    boolean existsByUsername(String username);
}
 | 1,696 | 29.303571 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/CustomAuthentication.java | 
	package org.codecritters.code_critters.spring;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
public class CustomAuthentication implements Authentication {
    private boolean authenticated;
    private String cookie;
    private Collection<GrantedAuthority> authorities;
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }
    @Override
    public Object getCredentials() {
        return null;
    }
    @Override
    public Object getDetails() {
        return null;
    }
    @Override
    public Object getPrincipal() {
        return null;
    }
    @Override
    public boolean isAuthenticated() {
        return authenticated;
    }
    @Override
    public void setAuthenticated(boolean b) throws IllegalArgumentException {
        this.authenticated = b;
    }
    @Override
    public String getName() {
        return null;
    }
    public void setCookie(String cookie) {
        this.cookie = cookie;
    }
    public String getCookie() {
        return cookie;
    }
    public void setAuthorities(Collection<GrantedAuthority> authorities) {
        this.authorities = authorities;
    }
}
 | 2,034 | 23.518072 | 77 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/CustomAuthenticationProvider.java | 
	package org.codecritters.code_critters.spring;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.application.service.UserService;
import org.codecritters.code_critters.web.dto.UserDTO;
import org.codecritters.code_critters.web.enums.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
    UserService userService;
    @Autowired
    public CustomAuthenticationProvider(UserService userService) {
        this.userService = userService;
    }
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        assert authentication instanceof CustomAuthentication : "Illegal Authentication type";
        //timeout check implied in getUserByCookie
        UserDTO dto = userService.getUserByCookie(((CustomAuthentication) authentication).getCookie());
        Set<GrantedAuthority> authorities = new HashSet<>();
        GrantedAuthority grantedAuthorityAnonymous = new SimpleGrantedAuthority("ROLE_ANONYMOUS");
        authorities.add(grantedAuthorityAnonymous);
        authentication.setAuthenticated(true);
        if (dto != null && dto.getRole() != null && dto.getActive()) {
            if (dto.getRole() == Role.user || dto.getRole() == Role.admin) {
                GrantedAuthority grantedAuthorityUser = new SimpleGrantedAuthority("ROLE_USER");
                authorities.add(grantedAuthorityUser);
            }
            if (dto.getRole() == Role.admin) {
                GrantedAuthority grantedAuthorityAdmin = new SimpleGrantedAuthority("ROLE_ADMIN");
                authorities.add(grantedAuthorityAdmin);
            }
        }
        ((CustomAuthentication) authentication).setAuthorities(authorities);
        return authentication;
    }
    @Override
    public boolean supports(Class<?> aClass) {
        return CustomAuthentication.class.isAssignableFrom(aClass);
    }
}
 | 3,143 | 38.797468 | 103 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/CustomErrorAttributes.java | 
	package org.codecritters.code_critters.spring;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.application.exception.ApplicationException;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;
import java.util.Map;
@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> data = super.getErrorAttributes(webRequest, includeStackTrace);
        Throwable e = getError(webRequest);
        if(e instanceof ApplicationException){
            data.put("msg_key", ((ApplicationException) e).getMsg_key());
        }
        return data;
    }
}
 | 1,582 | 32.680851 | 101 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/HtmlResponseWrapper.java | 
	package org.codecritters.code_critters.spring;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class HtmlResponseWrapper extends HttpServletResponseWrapper {
    private final ByteArrayOutputStream capture;
    private ServletOutputStream output;
    private PrintWriter writer;
    public HtmlResponseWrapper(HttpServletResponse response) {
        super(response);
        capture = new ByteArrayOutputStream(response.getBufferSize());
    }
    @Override
    public ServletOutputStream getOutputStream() {
        if (writer != null) {
            throw new IllegalStateException(
                    "getWriter() has already been called on this response.");
        }
        if (output == null) {
            output = new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    capture.write(b);
                }
                @Override
                public void flush() throws IOException {
                    capture.flush();
                }
                @Override
                public void close() throws IOException {
                    capture.close();
                }
                @Override
                public boolean isReady() {
                    return false;
                }
                @Override
                public void setWriteListener(WriteListener arg0) {
                }
            };
        }
        return output;
    }
    @Override
    public PrintWriter getWriter() throws IOException {
        if (output != null) {
            throw new IllegalStateException(
                    "getOutputStream() has already been called on this response.");
        }
        if (writer == null) {
            writer = new PrintWriter(new OutputStreamWriter(capture,
                    getCharacterEncoding()));
        }
        return writer;
    }
    @Override
    public void flushBuffer() throws IOException {
        super.flushBuffer();
        if (writer != null) {
            writer.flush();
        } else if (output != null) {
            output.flush();
        }
    }
    public byte[] getCaptureAsBytes() throws IOException {
        if (writer != null) {
            writer.close();
        } else if (output != null) {
            output.close();
        }
        return capture.toByteArray();
    }
    public String getCaptureAsString() throws IOException {
        return new String(getCaptureAsBytes(), getCharacterEncoding());
    }
}
 | 3,528 | 27.459677 | 83 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/configuration/ErrorHandlingConfiguration.java | 
	package org.codecritters.code_critters.spring.configuration;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.web.controller.CustomErrorController;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
@AutoConfigureBefore({ErrorMvcAutoConfiguration.class})
public class ErrorHandlingConfiguration {
    @Bean
    @ConditionalOnMissingBean(CustomErrorController.class)
    public CustomErrorController customErrorController(ErrorAttributes errorAttributes,
                                                       ServerProperties serverProperties,
                                                       List<ErrorViewResolver> errorViewResolvers) {
        return new CustomErrorController(errorAttributes, serverProperties.getError(), errorViewResolvers);
    }
}
 | 2,065 | 40.32 | 107 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/configuration/JpaTestConfiguration.java | 
	package org.codecritters.code_critters.spring.configuration;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import java.util.Objects;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = "org.codecritters.code_critters.persistence.repository")
@PropertySource("application.properties")
@EnableTransactionManagement
@Profile("test")
public class JpaTestConfiguration {
    @Autowired
    private Environment env;
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(Objects.requireNonNull(env.getProperty("jdbc.driverClassName")));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));
        return dataSource;
    }
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan("org.codecritters.code_critters.persistence.entities");
        em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        em.setJpaProperties(additionalProperties());
        return em;
    }
    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }
    final Properties additionalProperties() {
        final Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
        hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        return hibernateProperties;
    }
}
 | 3,668 | 38.880435 | 109 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/configuration/SecurityConfig.java | 
	package org.codecritters.code_critters.spring.configuration;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.spring.CustomAuthenticationProvider;
import org.codecritters.code_critters.spring.filter.CookieAuthFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
 * Configuration, welche Spring Security konfiguriert
 */
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
@Profile("!test")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    CookieAuthFilter cookieAuthFilter;
    CustomAuthenticationProvider authenticationProvider;
    @Autowired
    public SecurityConfig(CookieAuthFilter cookieAuthFilter, CustomAuthenticationProvider authenticationProvider) {
        this.cookieAuthFilter = cookieAuthFilter;
        this.authenticationProvider = authenticationProvider;
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
    }
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(cookieAuthFilter);
        registrationBean.setEnabled(false);
        return registrationBean;
    }
    /**
     * Konfiguriter die HttpSecurity
     *
     * @param http zu konfigurierende HttpSecurity
     * @throws Exception Falls ein Fehler auftritt
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/level-generator", "/xml-generator", "/manage-levels").hasRole("ADMIN")
                .antMatchers("/profile").hasRole("USER")
                .anyRequest().permitAll()
                .and()
                .headers().frameOptions().sameOrigin()
                .and()
                .addFilterBefore(cookieAuthFilter, UsernamePasswordAuthenticationFilter.class)
                .authenticationProvider(authenticationProvider);
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/critter_components/**")
                .antMatchers("/lib/**")
                .antMatchers("/static/**")
                .antMatchers("/style/**")
                .antMatchers("/translation/**")
                .antMatchers("/favicon.ico")
                .antMatchers("/game")
                .antMatchers("/");
    }
}
 | 4,231 | 38.551402 | 115 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/configuration/SecurityTestConfig.java | 
	package org.codecritters.code_critters.spring.configuration;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
@Configuration
@Profile("test")
public class SecurityTestConfig {
    @Bean
    public WebSecurityConfigurerAdapter securityDisabled() {
        return new WebSecurityConfigurerAdapter() {
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.cors().and().authorizeRequests().anyRequest().permitAll();
            }
        };
    }
}
 | 1,684 | 34.104167 | 101 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/configuration/StaticResourceConfiguration.java | 
	package org.codecritters.code_critters.spring.configuration;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/game").setViewName("forward:/game.html");
        registry.addViewController("/mutants").setViewName("forward:/mutants.html");
        registry.addViewController("/profile").setViewName("forward:/profile.html");
        registry.addViewController("/resetPassword").setViewName("forward:/resetPassword.html");
        registry.addViewController("/forgotPassword").setViewName("forward:/forgotPassword.html");
        registry.addViewController("/manage-levels").setViewName("forward:/manageLevels.html");
        registry.addViewController("/xml-generator").setViewName("forward:/generators/xml-generator/xml-generator.html");
        registry.addViewController("/level-generator").setViewName("forward:/generators/level-generator/level-generator.html");
        registry.addViewController("/customBlocks.js").setViewName("forward:/critter_components/critter-blockly/iFrame/customBlocks.js");
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/xml-generator/**").addResourceLocations("classpath:/static/generators/xml-generator/");
        registry.addResourceHandler("/level-generator/**").addResourceLocations("classpath:/static/generators/level-generator/");
        registry.addResourceHandler("/lib/**").addResourceLocations("classpath:/static/node_modules/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/node_modules/");
        registry.addResourceHandler("/critter_components/**").addResourceLocations("classpath:/static/critter_components/");
        registry.addResourceHandler("/style/**").addResourceLocations("classpath:/static/style/");
        registry.addResourceHandler("/images/**").addResourceLocations("file:./images/");
        registry.addResourceHandler("/translation/**").addResourceLocations("classpath:/static/translation/");
        //registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/critter_components/critter-blockly/iFrame/images/");
   }
}
 | 3,362 | 56 | 144 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/filter/CookieAuthFilter.java | 
	package org.codecritters.code_critters.spring.filter;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.spring.CustomAuthentication;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
public class CookieAuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (this.isAuthenticationRequired()) {
            CustomAuthentication auth = new CustomAuthentication();
            Cookie cookie = WebUtils.getCookie((HttpServletRequest) request, "id");
            auth.setCookie(cookie != null ? cookie.getValue() : null);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
    private boolean isAuthenticationRequired() {
        // apparently filters have to check this themselves.  So make sure they have a proper AuthenticatedAccount in their session.
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if ((existingAuth == null) || !existingAuth.isAuthenticated()) {
            return true;
        }
        return !(existingAuth instanceof CustomAuthentication);
    }
}
 | 2,445 | 34.449275 | 132 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/filter/PolymerResourceCacheFilter.java | 
	package org.codecritters.code_critters.spring.filter;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.spring.HtmlResponseWrapper;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
@Component
public class PolymerResourceCacheFilter implements Filter {
    private static String TEMPDIR = "./temp";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        // only /lib files needs to be modified
        if (httpRequest.getRequestURI().startsWith("/lib/")) {
            File file = new File(TEMPDIR + httpRequest.getRequestURI());
            if (file.exists() && !file.isDirectory()) {
                //check age of the file
                RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
                if (file.lastModified() >= bean.getStartTime()) {
                    //If younger then runtime use existing one
                    InputStream is = new FileInputStream(file);
                    response.setContentLength((int) file.length());
                    response.setContentType("application/javascript;charset=ISO-8859-1");
                    IOUtils.copy(is, response.getOutputStream());
                    is.close();
                } else {
                    //Create new cached file
                    String responseContent = cacheFile(request, response, chain, file);
                    response.setContentLength(responseContent.length());
                    response.getWriter().write(responseContent);
                }
            } else {
                //Create new cached file
                String responseContent = cacheFile(request, response, chain, file);
                response.setContentLength(responseContent.length());
                response.getWriter().write(responseContent);
            }
        } else {
            //Do nothing and handle as normal request
            chain.doFilter(request, response);
        }
    }
    /**
     * Caches the files addressed by /lib/* and changes their content so that the
     * browser can resolve the paths
     *
     * @param request  Request coming from the browser
     * @param response Response to send back to the browser
     * @param chain    Filterchain doing some more filters and executes the reques
     * @param f        The file to write the data in
     * @return the responses string content
     * @throws IOException      if an error occurs during writing the file
     * @throws ServletException comes from the filter chain
     */
    private String cacheFile(ServletRequest request, ServletResponse response, FilterChain chain, File f) throws IOException, ServletException {
        HtmlResponseWrapper capturingResponseWrapper = new HtmlResponseWrapper(
                (HttpServletResponse) response);
        chain.doFilter(request, capturingResponseWrapper);
        //add "/lib/" in import paths in the file where "@polymer" or "@webcombonent" is
        String pattern = "(?<=(import\\s.{0,100}))(?=(@.{3,20}/))";
        String[] componentsArray = capturingResponseWrapper.getCaptureAsString().split(pattern);
        String responseContent = componentsArray[0];
        for (int i = 1; i < componentsArray.length; ++i) {
            responseContent += "/lib/" + componentsArray[i];
        }
        //create directory and file
        f.getParentFile().mkdirs();
        f.createNewFile();
        FileWriter writer = new FileWriter(f);
        writer.write(responseContent);
        writer.close();
        return responseContent;
    }
    @Override
    public void destroy() {
    }
}
 | 4,804 | 40.068376 | 144 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/spring/filter/RequestLoggingFilter.java | 
	package org.codecritters.code_critters.spring.filter;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
public class RequestLoggingFilter implements Filter {
    private final Logger logger = LogManager.getLogger(RequestLoggingFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
//        logger.info(httpRequest.getMethod() + ":" + httpRequest.getRequestURI());
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
}
 | 1,690 | 29.745455 | 132 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/controller/CustomErrorController.java | 
	package org.codecritters.code_critters.web.controller;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public class CustomErrorController extends BasicErrorController {
    public CustomErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }
    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("forward:/error.html");
        return modelAndView;
    }
}
 | 1,829 | 36.346939 | 144 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/controller/GameController.java | 
	package org.codecritters.code_critters.web.controller;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codecritters.code_critters.application.service.GameService;
import org.codecritters.code_critters.application.service.MineService;
import org.codecritters.code_critters.web.dto.GameDTO;
import org.codecritters.code_critters.web.dto.MinesDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/game")
public class GameController {
    private final Logger logger = LogManager.getLogger(GameController.class);
    private final GameService gameService;
    private final MineService mineService;
    @Autowired
    public GameController(GameService gameService, MineService mineService) {
        this.gameService = gameService;
        this.mineService = mineService;
    }
    /**
     * Creates a new game data set with the given values for the given user, if registered.
     * @param dto The game dto containing the initial values to be inserted.
     * @param cookie The cookie for the current user.
     * @return The inserted game data.
     */
    @PostMapping(path = "/create")
    public GameDTO createGame(@RequestBody GameDTO dto, @CookieValue("id") String cookie) {
        return gameService.createGame(dto, cookie);
    }
    /**
     * Updates an existing game data set with the given values.
     * @param dto The dto containing the updated values.
     */
    @PostMapping(path = "/save")
    public void saveGame(@RequestBody GameDTO dto) {
        gameService.saveGame(dto);
    }
    /**
     * Saves the given mine data.
     * @param mines The list of mines to save.
     */
    @PostMapping(path = "/mines")
    public void saveMines(@RequestBody MinesDTO mines) {
        mineService.saveMines(mines);
    }
}
 | 2,910 | 34.938272 | 91 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/controller/GeneratorController.java | 
	package org.codecritters.code_critters.web.controller;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.application.exception.AlreadyExistsException;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.application.service.LevelService;
import org.codecritters.code_critters.application.service.MutantsService;
import org.codecritters.code_critters.application.service.RowService;
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.codecritters.code_critters.web.dto.LevelDTO;
import org.codecritters.code_critters.web.dto.MutantsDTO;
import org.codecritters.code_critters.web.dto.RowDTO;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
 * Schnittstelle zum Levelmanagement
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/generator")
public class GeneratorController {
    private final Logger logger = LogManager.getLogger(GeneratorController.class);
    private final LevelService levelService;
    private final MutantsService mutantsService;
    private final RowService rowService;
    @Autowired
    public GeneratorController(LevelService levelService, MutantsService mutantsService, RowService rowService) {
        this.levelService = levelService;
        this.mutantsService = mutantsService;
        this.rowService = rowService;
    }
    /**
     * Returns the toolbox
     */
    @GetMapping(path = "/toolbox")
    @Secured("ROLE_ADMIN")
    public void getToolbox(HttpServletResponse response) {
        try {
            // get your file as InputStream
            InputStream is = this.getClass().getResourceAsStream("/data/full_toolbox.tb");
            // copy it to response's OutputStream
            IOUtils.copy(is, response.getOutputStream());
            is.close();
            response.flushBuffer();
        } catch (IOException ex) {
            logger.info("Error writing file to output stream. Filename was '{}'", ex);
            throw new RuntimeException("IOError writing file to output stream");
        }
    }
    /**
     * Saves the created image of the new level.
     */
    @PostMapping(path = "/level/image")
    @Secured("ROLE_ADMIN")
    public void createLevelImage(@RequestParam("file") MultipartFile image) {
        levelService.storeImage(image);
    }
    /**
     * Creates a new level.
     */
    @PostMapping(path = "/level/create")
    @Secured("ROLE_ADMIN")
    public void createLevel(@RequestBody LevelDTO dto, HttpServletResponse response) {
        try {
            levelService.createLevel(dto);
        } catch (AlreadyExistsException e) {
            response.setStatus(460);
        }
    }
    /**
     * Deletes the level with the given name along with its mutants and scores.
     *
     * @param name The name of the level to be deleted.
     * @param response The servlet response.
     */
    @Transactional
    @PostMapping(path = "/level/delete")
    @Secured("ROLE_ADMIN")
    public void deleteLevel(@RequestBody String name, HttpServletResponse response) {
        try {
            levelService.deleteLevel(name);
        } catch (NotFoundException e) {
            response.setStatus(404);
        }
    }
    @PostMapping(path = "/level/update")
    @Secured("ROLE_ADMIN")
    public void updateLevel(@RequestBody LevelDTO dto, HttpServletResponse response) {
        try {
            levelService.updateLevel(dto);
        } catch (AlreadyExistsException e) {
            response.setStatus(460);
        }
    }
    /**
     * Creates new mutants
     */
    @PostMapping(path = "/mutants/create")
    @Secured("ROLE_ADMIN")
    public void createMutants(@RequestBody MutantsDTO dto) {
        mutantsService.createMutants(dto);
    }
    /**
     * Updates the given mutants
     */
    @PostMapping(path = "/mutants/update")
    @Secured("ROLE_ADMIN")
    public void updateMutants(@RequestBody MutantsDTO dto) {
        mutantsService.updateMutants(dto);
    }
    /**
     * Deletes the given row along with all levels belonging to it.
     */
    @PostMapping(path = "/row/delete")
    @Secured("ROLE_ADMIN")
    public void deleteRow(@RequestBody RowDTO dto, HttpServletResponse response) {
        try {
            rowService.deleteRow(dto);
        } catch (NotFoundException e) {
            response.setStatus(404);
        }
    }
    /**
     * Updates the name of the given row.
     */
    @PostMapping(path = "/row/update")
    @Secured("ROLE_ADMIN")
    public void updateRow(@RequestBody RowDTO dto, HttpServletResponse response) {
        try {
            rowService.updateRow(dto);
        } catch (NotFoundException e) {
            response.setStatus(404);
        }
    }
    /**
     * Adds a new row with the given name and position.
     */
    @PostMapping(path = "/row/add")
    @Secured("ROLE_ADMIN")
    public RowDTO addRow(@RequestBody RowDTO dto, HttpServletResponse response) {
        try {
            return rowService.addRow(dto);
        } catch (AlreadyExistsException e) {
            response.setStatus(460);
            return null;
        }
    }
    @GetMapping(path = "/names")
    public List<String> getLevelNames() {
        return levelService.getLevelNames();
    }
    @GetMapping(path = "/rows")
    @Secured("ROLE_ADMIN")
    public List<RowDTO> getRows() {
        return levelService.getRows();
    }
}
 | 6,641 | 30.932692 | 113 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/controller/LevelController.java | 
	package org.codecritters.code_critters.web.controller;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.application.service.LevelService;
import org.codecritters.code_critters.web.dto.LevelDTO;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
/**
 * Schnittstelle zum Levelmanagement
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/level")
public class LevelController {
    private final Logger logger = LogManager.getLogger(LevelController.class);
    private final LevelService levelService;
    @Autowired
    public LevelController(LevelService levelService) {
        this.levelService = levelService;
    }
    /**
     * Returns the entire level data for a given level.
     * @param level The level for which the data should be retrieved.
     * @return A map containing all of the level data.
     */
    @GetMapping(path = "/get")
    public HashMap getLevelData(@RequestParam String level) {
        LevelDTO dto = levelService.getLevel(level);
        String toolbox;
        try {
            // gets the user toolbox as an InputStream
            InputStream is = this.getClass().getResourceAsStream("/data/user_toolbox.tb");
            // copies it to the response's OutputStream
            StringWriter writer = new StringWriter();
            toolbox = IOUtils.toString(is, "UTF-8");
            is.close();
        } catch (IOException ex) {
            logger.info("Error writing file to output stream. Filename was '{}'", ex);
            throw new RuntimeException("IOError writing file to output stream");
        }
        HashMap map = new HashMap<String, Object>();
        map.put("id", dto.getId());
        map.put("level", dto.getLevel());
        map.put("tower", dto.getTower());
        map.put("spawn", dto.getSpawn());
        map.put("width", 16);
        map.put("height", 16);
        map.put("numberOfCritters", dto.getNumberOfCritters());
        map.put("numberOfHumans", dto.getNumberOfHumans());
        map.put("cut", dto.getCUT());
        map.put("init", dto.getInit());
        map.put("xml", dto.getXml());
        map.put("test", dto.getTest());
        map.put("toolbox", toolbox);
        map.put("row", dto.getRow());
        map.put("freeMines", dto.getFreeMines());
        return map;
    }
    /**
     * Returns the mutants for the given level.
     * @param level The level for which the mutant data is to be retrieved.
     * @return A list of mutants.
     */
    @GetMapping(path = "/mutants")
    public List getMutants(@RequestParam String level) {
        return levelService.getMutants(level);
    }
    /**
     * Returns a list containing level names, the achieved score and stars grouped by CritterRows.
     * @param cookie The current user cookie.
     * @return A list of LevelResultTypes.
     */
    @GetMapping(path = "/levels")
    public List getLevels(@CookieValue("id") String cookie) {
        return levelService.getLevelsGrouped(cookie);
    }
}
 | 4,014 | 32.739496 | 98 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/controller/ResultController.java | 
	package org.codecritters.code_critters.web.controller;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.application.service.ResultService;
import org.codecritters.code_critters.web.dto.ResultDTO;
import org.codecritters.code_critters.web.dto.ScoreDTO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
@CrossOrigin
@RestController
public class ResultController {
    private final Logger logger = LogManager.getLogger(LevelController.class);
    private final ResultService resultService;
    @Autowired
    public ResultController(ResultService resultService) {
        this.resultService = resultService;
    }
    /**
     * Stores a user's result in the database.
     * @param dto The UserDTO containing the user data.
     * @param cookie The current user cookie.
     */
    @PostMapping(path = "/result")
    public void storeResult(@RequestBody ResultDTO dto, @CookieValue("id") String cookie) {
        resultService.createResult(dto, cookie);
    }
    /**
     * Returns the score data of the ten users with the highest score.
     * @return The list of ScoreDTOs.
     */
    @GetMapping(path = "/highscore/data")
    public ScoreDTO[] getHighscore() {
        return resultService.getHighscore();
    }
    /**
     * Returns the current user's score data.
     * @param cookie The current user cookie identifying the user.
     * @return The user's score data.
     */
    @GetMapping(path = "/highscore/me")
    @Secured("ROLE_USER")
    public ScoreDTO getMyScore(@CookieValue("id") String cookie) {
        return resultService.getMyScore(cookie);
    }
}
 | 2,534 | 31.5 | 91 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/controller/UserController.java | 
	package org.codecritters.code_critters.web.controller;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.application.service.UserService;
import org.codecritters.code_critters.web.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping(value = "/users")
public class UserController {
    private final UserService userService;
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
    /**
     * Used for the registration of a new user.
     * @param dto The UserDTO containing the user data.
     * @param request The request containing the data for computing the base URL.
     * @throws MalformedURLException Thrown if the request URL is not well formatted.
     */
    @PostMapping(path = "/register")
    public void registerUser(@RequestBody UserDTO dto, HttpServletRequest request) throws MalformedURLException {
        userService.registerUser(dto, this.getBaseURL(request));
    }
    /**
     * Used for user login.
     * @param dto The UserDTO containing the user data.
     * @param cookie The current user cookie.
     * @param httpServletRequest The request to the server.
     * @param httpServletResponse The response to the client.
     * @return Returns the user data, if the login information was correct, or an error notice, if not.
     */
    @PostMapping(path = "/login")
    public Map<String, String> loginUser(@RequestBody UserDTO dto, @CookieValue("id") String cookie, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        UserDTO user = new UserDTO();
        Map<String, String> data = new HashMap<>();
        try {
            user = userService.loginUser(dto, cookie);
            if (!user.getActive()) {
                httpServletResponse.setStatus(404);
                data.put("error", "activate_first");
            } else {
                data.put("username", user.getUsername());
                data.put("email", user.getEmail());
                data.put("role", user.getRole().toString());
                data.put("language", user.getLanguage().toString());
                SecurityContextHolder.clearContext();
                HttpSession session = httpServletRequest.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
            }
        } catch (Exception e){
            httpServletResponse.setStatus(404);
            data.put("error", e.getMessage());
        }
        return data;
    }
    /**
     * Deals with the user logout. Can only be called when a user is actually logged in. Invalidates the current session
     * and clears the cookie information.
     * @param cookie The current user cookie.
     * @param httpServletRequest The request to the server.
     */
    @PostMapping(path = "/logout")
    @Secured("ROLE_USER")
    public void logoutUser(@CookieValue("id") String cookie, HttpServletRequest httpServletRequest) {
        userService.logoutUser(cookie);
        SecurityContextHolder.clearContext();
        HttpSession session = httpServletRequest.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }
    /**
     * Used to delete a user. Can only be called when the user is logged in. Invalidates the current session.
     * @param cookie The current user cookie.
     * @param httpServletRequest The request to the server.
     */
    @DeleteMapping(path = "/delete")
    @Secured("ROLE_USER")
    public void deleteUser(@CookieValue("id") String cookie, HttpServletRequest httpServletRequest) {
        userService.deleteUser(cookie);
        SecurityContextHolder.clearContext();
        HttpSession session = httpServletRequest.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }
    /**
     * Used to update user information.
     * @param dto The UserDTO containing the user data.
     * @param cookie The current user cookie.
     * @param request The request to the server.
     * @throws MalformedURLException Thrown if the request URL is not well formatted.
     */
    @PostMapping(path = "/change")
    public void changeUser(@RequestBody UserDTO dto, @CookieValue("id") String cookie, HttpServletRequest request) throws MalformedURLException {
        userService.changeUser(dto, cookie, this.getBaseURL(request));
    }
    /**
     * First step to reset a forgotten password.
     * @param dto The UserDTO containing the user data.
     * @param request The request to the server.
     * @throws MalformedURLException Thrown if the request URL is not well formatted.
     */
    @PostMapping(path = "/forgot")
    public void forgotPassword(@RequestBody UserDTO dto, HttpServletRequest request) throws MalformedURLException {
        userService.forgotPassword(dto, this.getBaseURL(request));
    }
    /**
     * Used to activate a registered user. The user is sent a secret by mail on which they have to click to activate
     * their profile.
     * @param secret The secret referring to a specific user.
     * @param httpServletResponse The response to rewrite the URL.
     * @param request The request data for computing the URL.
     * @throws MalformedURLException Thrown if the request URL is not well formatted.
     */
    @GetMapping(path = "/activate/{secret}")
    public void activateUser(@PathVariable(value = "secret") String secret, HttpServletResponse httpServletResponse, HttpServletRequest request) throws MalformedURLException {
        String url = getBaseURL(request) + "?activated=";
        url += userService.activateUser(secret);
        httpServletResponse.setHeader("Location", url);
        httpServletResponse.setStatus(302);
    }
    /**
     * Used to reset a user's password.
     * @param dto The UserDTO containing the user information.
     * @param secret The secret referring to a specific user.
     */
    @PostMapping(path = "/reset/{secret}")
    public void resetPassword(@RequestBody UserDTO dto, @PathVariable(value = "secret") String secret) {
        userService.resetPassword(secret, dto);
    }
    /**
     * Returns the user data to the application when a user is logged in.
     * @param cookie The current user cookie.
     * @return Returns a map containing the user data if a user was found, or throws an exception.
     */
    @GetMapping(path = "/me")
    @Secured("ROLE_USER")
    public Map<String, String> getMe(@CookieValue("id") String cookie) {
        UserDTO user = userService.getUserByCookie(cookie);
        if(user == null){
            throw new NotFoundException("Cookie invalid", "invalid_cookie");
        }
        Map<String, String> data = new HashMap<>();
        data.put("username", user.getUsername());
        data.put("email", user.getEmail());
        data.put("role", user.getRole().toString());
        data.put("language", user.getLanguage().toString());
        return data;
    }
    /**
     * Computes the base URL of a given request.
     * @param request The request containing the data.
     * @return The computed base URL.
     * @throws MalformedURLException Thrown if the request URL is not well formatted.
     */
    private String getBaseURL(HttpServletRequest request) throws MalformedURLException {
        URL requestURL = new URL(request.getRequestURL().toString());
        String port = requestURL.getPort() == -1 ? "" : ":" + requestURL.getPort();
        return requestURL.getProtocol() + "://" + requestURL.getHost() + port;
    }
}
 | 8,829 | 39.691244 | 182 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/dto/GameDTO.java | 
	package org.codecritters.code_critters.web.dto;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.persistence.entities.Level;
import java.time.LocalDateTime;
public class GameDTO {
    private String name;
    private String id;
    private Level level;
    private LocalDateTime start;
    private LocalDateTime end;
    private int score;
    private int mutantsKilled;
    private int humansFinished;
    private double gameTime;
    private String userID;
    public GameDTO() {}
    public GameDTO(String name, String id, Level level, LocalDateTime start, LocalDateTime end, int score,
                   int mutantsKilled, int humansFinished, double gameTime, String userID) {
        this.name = name;
        this.id = id;
        this.level = level;
        this.start = start;
        this.end = end;
        this.score = score;
        this.mutantsKilled = mutantsKilled;
        this.humansFinished = humansFinished;
        this.gameTime = gameTime;
        this.userID = userID;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Level getLevel() {
        return level;
    }
    public void setLevel(Level level) {
        this.level = level;
    }
    public LocalDateTime getStart() {
        return start;
    }
    public void setStart(LocalDateTime start) {
        this.start = start;
    }
    public LocalDateTime getEnd() {
        return end;
    }
    public void setEnd(LocalDateTime end) {
        this.end = end;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public int getMutantsKilled() {
        return mutantsKilled;
    }
    public void setMutantsKilled(int mutantsKilled) {
        this.mutantsKilled = mutantsKilled;
    }
    public int getHumansFinished() {
        return humansFinished;
    }
    public void setHumansFinished(int humansFinished) {
        this.humansFinished = humansFinished;
    }
    public double getGameTime() {
        return gameTime;
    }
    public void setGameTime(double gameTime) {
        this.gameTime = gameTime;
    }
    public String getUserID() {
        return userID;
    }
    public void setUserID(String userID) {
        this.userID = userID;
    }
}
 | 3,212 | 22.282609 | 106 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/dto/LevelDTO.java | 
	package org.codecritters.code_critters.web.dto;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import java.util.HashMap;
public class LevelDTO {
    private String id;
    private String name;
    private int numberOfCritters;
    private int numberOfHumans;
    private String CUT;
    private String init;
    private String xml;
    private String test;
    private String[][] level;
    private HashMap<String, Integer> tower;
    private HashMap<String, Integer> spawn;
    private String row;
    private int freeMines;
    public LevelDTO(String id, String name, int numberOfCritters, int numberOfHumans, String CUT, String init, String xml, String test, String[][] level, HashMap<String, Integer> tower, HashMap<String, Integer> spawn, String row, int freeMines) {
        this.id = id;
        this.name = name;
        this.numberOfCritters = numberOfCritters;
        this.numberOfHumans = numberOfHumans;
        this.CUT = CUT;
        this.init = init;
        this.xml = xml;
        this.test = test;
        this.level = level;
        this.tower = tower;
        this.spawn = spawn;
        this.row = row;
        this.freeMines = freeMines;
    }
    public LevelDTO(String id, String name, int numberOfCritters, int numberOfHumans, String CUT, String xml, String test, String init, String[][] level, int freeMines) {
        this.id = id;
        this.name = name;
        this.numberOfCritters = numberOfCritters;
        this.numberOfHumans = numberOfHumans;
        this.CUT = CUT;
        this.init = init;
        this.test = test;
        this.level = level;
        this.xml = xml;
        this.freeMines = freeMines;
    }
    public LevelDTO() {
    }
    public LevelDTO(String name, int numberOfCritters, int numberOfHumans, String CUT, String test, String[][] level,
                    HashMap<String, Integer> spawn, HashMap<String, Integer> tower) {
        this.name = name;
        this.numberOfCritters = numberOfCritters;
        this.numberOfHumans = numberOfHumans;
        this.CUT = CUT;
        this.test = test;
        this.level = level;
        this.spawn = spawn;
        this.tower = tower;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getNumberOfCritters() {
        return numberOfCritters;
    }
    public void setNumberOfCritters(int numberOfCritters) {
        this.numberOfCritters = numberOfCritters;
    }
    public int getNumberOfHumans() {
        return numberOfHumans;
    }
    public void setNumberOfHumans(int numberOfHumans) {
        this.numberOfHumans = numberOfHumans;
    }
    public String getCUT() {
        return CUT;
    }
    public void setCUT(String CUT) {
        this.CUT = CUT;
    }
    public String getInit() {
        return init;
    }
    public void setInit(String init) {
        this.init = init;
    }
    public String getTest() {
        return test;
    }
    public void setTest(String test) {
        this.test = test;
    }
    public String[][] getLevel() {
        return level;
    }
    public void setLevel(String[][] level) {
        this.level = level;
    }
    public HashMap<String, Integer> getTower() {
        return tower;
    }
    public void setTower(HashMap<String, Integer> tower) {
        this.tower = tower;
    }
    public HashMap<String, Integer> getSpawn() {
        return spawn;
    }
    public void setSpawn(HashMap<String, Integer> spawn) {
        this.spawn = spawn;
    }
    public String getXml() {
        return xml;
    }
    public void setXml(String xml) {
        this.xml = xml;
    }
    public String getRow() {
        return row;
    }
    public void setRow(String row) {
        this.row = row;
    }
    public int getFreeMines() {
        return freeMines;
    }
    public void setFreeMines(int freeMines) {
        this.freeMines = freeMines;
    }
}
 | 4,765 | 23.822917 | 246 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/dto/MineDTO.java | 
	package org.codecritters.code_critters.web.dto;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
public class MineDTO {
    private String id;
    private String code;
    private String xml;
    public MineDTO() {}
    public MineDTO(String id, String code, String xml) {
        this.id = id;
        this.code = code;
        this.xml = xml;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getXml() {
        return xml;
    }
    public void setXml(String xml) {
        this.xml = xml;
    }
}
 | 1,439 | 21.857143 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/dto/MinesDTO.java | 
	package org.codecritters.code_critters.web.dto;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 - 2021 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import java.util.List;
public class MinesDTO {
    private String game;
    private List<MineDTO> mines;
    public String getGame() {
        return game;
    }
    public void setGame(String game) {
        this.game = game;
    }
    public List<MineDTO> getMines() {
        return mines;
    }
    public void setMines(List<MineDTO> mines) {
        this.mines = mines;
    }
}
 | 1,197 | 23.958333 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/dto/MutantDTO.java | 
	package org.codecritters.code_critters.web.dto;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
public class MutantDTO {
    private String code;
    private String init;
    private String id;
    private String xml;
    public MutantDTO(String code, String init, String id, String xml) {
        this.code = code;
        this.init = init;
        this.id = id;
        this.xml = xml;
    }
    public MutantDTO() {
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getInit() {
        return init;
    }
    public void setInit(String init) {
        this.init = init;
    }
    public String getId() {
        return id;
    }
    public String getXml() {
        return xml;
    }
    public void setXml(String xml) {
        this.xml = xml;
    }
}
 | 1,573 | 21.485714 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/dto/MutantsDTO.java | 
	package org.codecritters.code_critters.web.dto;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import java.util.List;
public class MutantsDTO {
    private String name;
    private List<MutantDTO> mutants;
    public MutantsDTO(String name, List<MutantDTO> mutants) {
        this.name = name;
        this.mutants = mutants;
    }
    public MutantsDTO() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<MutantDTO> getMutants() {
        return mutants;
    }
    public void setMutants(List<MutantDTO> mutants) {
        this.mutants = mutants;
    }
}
 | 1,372 | 23.517857 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/dto/ResultDTO.java | 
	package org.codecritters.code_critters.web.dto;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
public class ResultDTO {
    private int score;
    private int stars;
    private String level;
    public ResultDTO() {
    }
    public ResultDTO(int score, String level, int stars) {
        this.score = score;
        this.level = level;
        this.stars = stars;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public String getLevel() {
        return level;
    }
    public void setLevel(String level) {
        this.level = level;
    }
    public int getStars() {
        return this.stars;
    }
    public void setStars(int stars) {
        this.stars = stars;
    }
}
 | 1,484 | 22.203125 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/dto/RowDTO.java | 
	package org.codecritters.code_critters.web.dto;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
public class RowDTO {
    private String id;
    private String name;
    private int position;
    /**
     * Specifies the row to which a level belongs.
     * @param id The row's id.
     * @param name The row's name.
     */
    public RowDTO(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public RowDTO(String id, String name, int position) {
        this.id = id;
        this.name = name;
        this.position = position;
    }
    public RowDTO() {
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPosition() {
        return  position;
    }
    public void setPosition(int position) {
        this.position = position;
    }
}
 | 1,705 | 22.054054 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/dto/ScoreDTO.java | 
	package org.codecritters.code_critters.web.dto;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
public class ScoreDTO {
    private String user;
    private int score;
    private int levels;
    private int position;
    /**
     * Used to retrieve score information to be displayed in the highscore table.
     * @param user The user achieving the score.
     * @param score The scores summed up over all levels played.
     * @param levels The number of levels played.
     * @param position The overall position in the user ranking based on the achieved score.
     */
    public ScoreDTO(String user, int score, int levels, int position) {
        this.user = user;
        this.score = score;
        this.levels = levels;
        this.position = position;
    }
    public ScoreDTO(String user, int score, int levels) {
        this.user = user;
        this.score = score;
        this.levels = levels;
    }
    public ScoreDTO() {
    }
    public ScoreDTO(String user) {
        this.user = user;
        this.score = 0;
        this.levels = 0;
    }
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public int getLevels() {
        return levels;
    }
    public void setLevels(int levels) {
        this.levels = levels;
    }
    public int getPosition() {
        return position;
    }
    public void setPosition(int position) {
        this.position = position;
    }
}
 | 2,319 | 23.946237 | 92 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/dto/UserDTO.java | 
	package org.codecritters.code_critters.web.dto;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import org.codecritters.code_critters.web.enums.Language;
import org.codecritters.code_critters.web.enums.Role;
public class UserDTO {
    private String username;
    private String email;
    private String password;
    private String oldPassword;
    private String cookie;
    private boolean active;
    private Language language;
    private Role role;
    /** The parameters needed for changing user information. */
    public UserDTO(String username, String email, String oldPassword, String password, Language language) {
        this.username = username;
        this.email = email;
        this.oldPassword = oldPassword;
        this.password = password;
        this.language = language;
    }
    /** The parameters needed for the user registration. */
    public UserDTO(String username, String email, String password, Language language) {
        this.username = username;
        this.email = email;
        this.password = password;
        this.language = language;
    }
    /** The parameters needed for the user login. */
    public UserDTO(String username, String email, String password) {
        this.username = username;
        this.email = email;
        this.password = password;
    }
    /** Used for password resets. */
    public UserDTO(String password) {
        this.password = password;
    }
    public UserDTO() {
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getCookie() {
        return cookie;
    }
    public void setCookie(String cookie) {
        this.cookie = cookie;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public boolean getActive() {
        return active;
    }
    public void setActive(boolean active) {
        this.active = active;
    }
    public Language getLanguage() {
        return language;
    }
    public void setLanguage(Language language) {
        this.language = language;
    }
    public Role getRole() {
        return role;
    }
    public void setRole(Role role) {
        this.role = role;
    }
    public String getOldPassword() {
        return oldPassword;
    }
    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }
}
 | 3,356 | 23.866667 | 107 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/enums/Language.java | 
	package org.codecritters.code_critters.web.enums;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public enum Language {
    de ("de-DE"),
    en ("en-US");
    private final String name;
    Language(String s){
        name = s;
    }
    public boolean equalsName(String otherName) {
        return name.equals(otherName);
    }
    public String toString() {
        return this.name;
    }
    @JsonCreator
    public static Language forValue(String value) {
        for (Language lang : Language.values()) {
            if(lang.toString().equals(value)){
                return lang;
            }
        }
        //default value en
        return Language.en;
    }
    @JsonValue
    public String toValue() {
        return this.toString();
    }
}
 | 1,575 | 24.419355 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/main/java/org/codecritters/code_critters/web/enums/Role.java | 
	package org.codecritters.code_critters.web.enums;
/*-
 * #%L
 * Code Critters
 * %%
 * Copyright (C) 2019 Michael Gruber
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
public enum Role {
    admin,
    user
}
 | 844 | 28.137931 | 71 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/application/service/GameServiceTest.java | 
	package org.codecritters.code_critters.application.service;
import org.codecritters.code_critters.application.exception.IncompleteDataException;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.persistence.entities.Game;
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.entities.User;
import org.codecritters.code_critters.persistence.repository.GameRepository;
import org.codecritters.code_critters.persistence.repository.LevelRepository;
import org.codecritters.code_critters.persistence.repository.UserRepositiory;
import org.codecritters.code_critters.web.dto.GameDTO;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.time.LocalDateTime;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class GameServiceTest {
    @InjectMocks
    private GameService gameService;
    @Mock
    private LevelRepository levelRepository;
    @Mock
    private UserRepositiory userRepositiory;
    @Mock
    private GameRepository gameRepository;
    private static final String COOKIE = "cookie";
    private static final String ID = "1";
    private final Level level = new Level();
    private final User user = new User();
    private final GameDTO gameDTO = new GameDTO("level", ID, level, LocalDateTime.now(), LocalDateTime.now(), 0, 0, 0,
            0, null);
    private final Game game = new Game(ID, level, LocalDateTime.now(), LocalDateTime.now(), 0, 0, 0, 0, ID);
    @BeforeEach
    public void setup() {
        user.setId(ID);
        game.setUserID(ID);
        gameDTO.setId(ID);
    }
    @Test
    public void testCreateGame() {
        when(levelRepository.findByName(gameDTO.getName())).thenReturn(level);
        when(userRepositiory.findByCookie(COOKIE)).thenReturn(user);
        when(gameRepository.save(any())).thenReturn(game);
        GameDTO saved = gameService.createGame(gameDTO, COOKIE);
        assertAll(
                () -> assertEquals(ID, saved.getId()),
                () -> assertEquals(level, saved.getLevel()),
                () -> assertEquals(ID, saved.getUserID()),
                () -> assertEquals(game.getStart(), saved.getStart()),
                () -> assertEquals(game.getEnd(), saved.getEnd())
        );
        verify(gameRepository).save(any());
    }
    @Test
    public void testCreateGameUserNull() {
        game.setUserID(null);
        when(levelRepository.findByName(gameDTO.getName())).thenReturn(level);
        when(gameRepository.save(any())).thenReturn(game);
        GameDTO saved = gameService.createGame(gameDTO, COOKIE);
        assertAll(
                () -> assertEquals(ID, saved.getId()),
                () -> assertEquals(level, saved.getLevel()),
                () -> assertNull(saved.getUserID()),
                () -> assertEquals(game.getStart(), saved.getStart()),
                () -> assertEquals(game.getEnd(), saved.getEnd())
        );
        verify(gameRepository).save(any());
    }
    @Test
    public void testCreateGameGameIdNull() {
        when(levelRepository.findByName(gameDTO.getName())).thenReturn(level);
        when(userRepositiory.findByCookie(COOKIE)).thenReturn(user);
        when(gameRepository.save(any())).thenReturn(new Game());
        assertThrows(IllegalStateException.class,
                () -> gameService.createGame(gameDTO, COOKIE)
        );
    }
    @Test
    public void testCreateGameLevelNull() {
        assertThrows(NotFoundException.class,
                () -> gameService.createGame(gameDTO, COOKIE)
        );
    }
    @Test
    public void testSaveGame() {
        when(levelRepository.findByName(gameDTO.getName())).thenReturn(level);
        gameService.saveGame(gameDTO);
        verify(gameRepository).save(any());
    }
    @Test
    public void testSaveGameIdNull() {
        gameDTO.setId(null);
        when(levelRepository.findByName(gameDTO.getName())).thenReturn(level);
        assertThrows(IncompleteDataException.class,
                () -> gameService.saveGame(gameDTO)
        );
    }
    @Test
    public void testSaveGameLevelNull() {
        assertThrows(NotFoundException.class,
                () -> gameService.saveGame(gameDTO)
        );
    }
}
 | 4,786 | 33.941606 | 118 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/application/service/LevelServiceTest.java | 
	package org.codecritters.code_critters.application.service;
import org.codecritters.code_critters.application.exception.AlreadyExistsException;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.repository.LevelRepository;
import org.codecritters.code_critters.persistence.repository.MutantRepository;
import org.codecritters.code_critters.persistence.repository.ResultRepository;
import org.codecritters.code_critters.persistence.repository.RowRepository;
import org.codecritters.code_critters.persistence.repository.UserRepositiory;
import org.codecritters.code_critters.web.dto.LevelDTO;
import org.codecritters.code_critters.web.dto.MutantDTO;
import org.codecritters.code_critters.web.dto.RowDTO;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import javax.validation.ConstraintViolationException;
import java.util.*;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class LevelServiceTest {
    @InjectMocks
    private LevelService levelService;
    @Mock
    private LevelRepository levelRepository;
    @Mock
    private MutantRepository mutantRepository;
    @Mock
    private RowRepository rowRepository;
    @Mock
    private UserRepositiory userRepository;
    private LevelDTO levelDTO;
    private CritterRow row = new CritterRow("name", 1);
    private final String level2 = "level_2";
    @Before
    public void setup() {
        String[][] levelArray = {
                {"wood", "grass", "wood"},
                {"grass", "grass", "wood"}
        };
        HashMap<String, Integer> spawn = new HashMap<>();
        spawn.put("x", 1);
        spawn.put("y", 8);
        HashMap<String, Integer> tower = new HashMap<>();
        tower.put("x", 14);
        tower.put("y", 8);
        levelDTO = new LevelDTO("id1", "level_1", 10, 5, "cut1", "init", "xml", "test", levelArray, tower, spawn, row.getName(), 2);
    }
    @Test
    public void createLevelTest() {
        when(rowRepository.findCritterRowById(any())).thenReturn(new CritterRow());
        levelService.createLevel(levelDTO);
        verify(levelRepository, times(1)).save(any());
    }
    @Test
    public void createLevelExceptionTest() {
        when(rowRepository.findCritterRowById(any())).thenReturn(new CritterRow());
        given(levelRepository.save(any())).willThrow(ConstraintViolationException.class);
        Exception exception = assertThrows(AlreadyExistsException.class,
                () -> levelService.createLevel(levelDTO)
        );
        assertEquals("Should throw an exception", "Tried to insert a level that already exists",
                exception.getMessage());
        verify(levelRepository, times(1)).save(any());
    }
    @Test
    public void createLevelNameAlreadyExistsTest() {
        when(levelRepository.findByName(levelDTO.getName())).thenReturn(new Level());
        assertThrows(AlreadyExistsException.class, () -> levelService.createLevel(levelDTO));
    }
    @Test
    public void getLevelTest() {
        Level level = new Level();
        level.setRow(row);
        given(levelRepository.findByName(levelDTO.getName())).willReturn(level);
        levelService.getLevel(levelDTO.getName());
        Exception exception = assertThrows(NotFoundException.class,
                () -> levelService.getLevel(level2)
        );
        assertEquals("There's no level with name: " + level2, exception.getMessage());
        verify(levelRepository, times(1)).findByName(levelDTO.getName());
        verify(levelRepository, times(1)).findByName(level2);
    }
    @Test
    public void getTestTest() {
        given(levelRepository.getTestByName(levelDTO.getName())).willReturn(levelDTO.getTest());
        String test = levelService.getTest(levelDTO.getName());
        Exception exception = assertThrows(NotFoundException.class,
                () -> levelService.getTest(level2)
        );
        assertAll("Should return levelDTO test for level_1 and throw exception for level2",
                () -> assertEquals("There's no level with name: " + level2, exception.getMessage()),
                () -> assertEquals(test, levelDTO.getTest())
        );
        verify(levelRepository, times(1)).getTestByName(levelDTO.getName());
        verify(levelRepository, times(1)).getTestByName(level2);
    }
    @Test
    public void getCUTTest() {
        given(levelRepository.getCUTByName(levelDTO.getName())).willReturn(levelDTO.getCUT());
        String cut = levelService.getCUT(levelDTO.getName());
        Exception exception = assertThrows(NotFoundException.class,
                () -> levelService.getCUT(level2)
        );
        assertAll("Should return levelDTO cut for level_1 and throw exception for level2",
                () -> assertEquals("There's no level with name: " + level2, exception.getMessage()),
                () -> assertEquals(cut, levelDTO.getCUT())
        );
        verify(levelRepository, times(1)).getCUTByName(levelDTO.getName());
        verify(levelRepository, times(1)).getCUTByName(level2);
    }
    @Test
    public void existsLevelTest() {
        given(levelRepository.findByName(levelDTO.getName())).willReturn(new Level());
        assertAll("Test if levels exists",
                () -> assertTrue(levelService.existsLevel(levelDTO.getName())),
                () -> assertFalse(levelService.existsLevel(level2))
        );
        verify(levelRepository, times(2)).findByName(any());
    }
    @Test
    public void getLevelsTest() {
        given(levelRepository.getLevelNames()).willReturn(Arrays.asList(levelDTO.getName()));
        List<String> levelNames = levelService.getLevelNames();
        assertAll("Should return levelDTO name",
                () -> assertEquals(1, levelNames.size()),
                () -> assertTrue(levelNames.contains(levelDTO.getName()))
        );
        verify(levelRepository, times(1)).getLevelNames();
    }
    @Test
    public void getMutantsExceptionsTest() {
        given(levelRepository.getIdByName(levelDTO.getName())).willReturn(levelDTO.getId());
        Exception noMutants = assertThrows(NotFoundException.class,
                () -> levelService.getMutants(levelDTO.getName())
        );
        Exception noLevel = assertThrows(NotFoundException.class,
                () -> levelService.getMutants(level2)
        );
        assertAll("Should return no mutants for level_1 and no level for level2",
                () -> assertEquals("No such level", noLevel.getMessage()),
                () -> assertEquals("No mutants could be found", noMutants.getMessage())
        );
        verify(levelRepository, times(2)).getIdByName(any());
        verify(mutantRepository, times(1)).getCodeByLevel(any());
    }
    @Test
    public void getMutantsTest() {
        String[] mutants = {"code1", "init1", "id1", "xml1"};
        List<String[]> list = new ArrayList<>();
        list.add(mutants);
        given(levelRepository.getIdByName(levelDTO.getName())).willReturn(levelDTO.getId());
        given(mutantRepository.getCodeByLevel(any())).willReturn(list);
        List<MutantDTO> mutantDTOS = levelService.getMutants(levelDTO.getName());
        MutantDTO mutant = mutantDTOS.get(0);
        assertAll("Should return the mutants String[]",
                () -> assertEquals(1, mutantDTOS.size()),
                () -> assertEquals("code1", mutant.getCode()),
                () -> assertEquals("id1", mutant.getId()),
                () -> assertEquals("xml1", mutant.getXml())
        );
        verify(mutantRepository, times(1)).getCodeByLevel(any());
    }
    @Test
    public void getInitTest() {
        given(levelRepository.getInitByName(levelDTO.getName())).willReturn(levelDTO.getInit());
        String init = levelService.getInit(levelDTO.getName());
        Exception exception = assertThrows(NotFoundException.class,
                () -> levelService.getInit(level2)
        );
        assertAll("Should return levelDTO init for level_1 and no level for level2",
                () -> assertEquals(levelDTO.getInit(), init),
                () -> assertEquals("There's no level with name: " + level2, exception.getMessage())
        );
        verify(levelRepository, times(1)).getInitByName(levelDTO.getName());
        verify(levelRepository, times(1)).getInitByName(level2);
    }
    @Test
    public void getLevelsGroupedNoUserTest() {
        String cookie = "cookie";
        Collection<CritterRow> rows = new ArrayList<>();
        CritterRow row1 = new CritterRow("Tutorial", 0);
        rows.add(row1);
        given(rowRepository.getRows()).willReturn(rows);
        given(userRepository.existsByCookie(cookie)).willReturn(false);
        List groupedLevels = levelService.getLevelsGrouped(cookie);
        assertEquals("{name=Tutorial, id=null, position=0, levels=[]}", groupedLevels.get(0).toString());
        verify(rowRepository, times(1)).getRows();
        verify(userRepository, times(1)).existsByCookie(cookie);
        verify(userRepository, times(0)).findByCookie(cookie);
    }
    @Test
    public void getLevelsGroupedWithUserTest() {
        String cookie = "cookie";
        Collection<CritterRow> rows = new ArrayList<>();
        CritterRow row1 = new CritterRow("Tutorial", 0);
        rows.add(row1);
        given(rowRepository.getRows()).willReturn(rows);
        given(userRepository.existsByCookie(cookie)).willReturn(true);
        List groupedLevels = levelService.getLevelsGrouped(cookie);
        assertEquals("{name=Tutorial, id=null, position=0, levels=[]}", groupedLevels.get(0).toString());
        verify(rowRepository, times(1)).getRows();
        verify(userRepository, times(1)).existsByCookie(cookie);
        verify(userRepository, times(1)).findByCookie(cookie);
    }
    @Test
    public void getRowsTest() {
        Collection<CritterRow> rows = new ArrayList<>();
        CritterRow row1 = new CritterRow("Tutorial", 0);
        CritterRow row2 = new CritterRow("Beginner", 1);
        rows.add(row1);
        rows.add(row2);
        given(rowRepository.getRows()).willReturn(rows);
        List<RowDTO> rowDTOs = levelService.getRows();
        assertAll(
                () -> assertEquals(2, rowDTOs.size()),
                () -> assertEquals("Tutorial", rowDTOs.get(0).getName()),
                () -> assertEquals("Beginner", rowDTOs.get(1).getName())
        );
        verify(rowRepository, times(1)).getRows();
    }
    @Test
    public void deleteLevelTest() {
        Level level = new Level(new CritterRow(), levelDTO.getName(), levelDTO.getNumberOfCritters(),
                levelDTO.getNumberOfHumans(), levelDTO.getCUT(), levelDTO.getTest(), levelDTO.getXml(),
                levelDTO.getInit(), levelDTO.getLevel(), levelDTO.getFreeMines());
        level.setId("id");
        when(levelRepository.findByName(levelDTO.getName())).thenReturn(level);
        levelService.deleteLevel(levelDTO.getName());
        verify(levelRepository).deleteById(level.getId());
    }
    @Test
    public void deleteLevelNotFoundExceptionTest() {
        assertThrows(NotFoundException.class, () -> levelService.deleteLevel(levelDTO.getName()));
    }
    @Test
    public void updateLevelTest() {
        when(rowRepository.findCritterRowById(row.getName())).thenReturn(row);
        levelService.updateLevel(levelDTO);
        verify(levelRepository).save(any());
    }
    @Test
    public void updateLevelConstraintViolationTest() {
        when(rowRepository.findCritterRowById(row.getName())).thenReturn(row);
        when(levelRepository.save(any())).thenThrow(ConstraintViolationException.class);
        assertThrows(AlreadyExistsException.class, () -> levelService.updateLevel(levelDTO));
    }
} | 12,354 | 42.04878 | 132 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/application/service/MineServiceTest.java | 
	package org.codecritters.code_critters.application.service;
import org.codecritters.code_critters.application.exception.IncompleteDataException;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.persistence.entities.Game;
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.repository.GameRepository;
import org.codecritters.code_critters.persistence.repository.MineRepository;
import org.codecritters.code_critters.web.dto.MineDTO;
import org.codecritters.code_critters.web.dto.MinesDTO;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MineServiceTest {
    @InjectMocks
    private MineService mineService;
    @Mock
    private GameRepository gameRepository;
    @Mock
    private MineRepository mineRepository;
    private static final String ID = "1";
    private static final String ID2 = "2";
    private static final String CODE = "code";
    private static final String XML = "xml";
    private final Game game = new Game(ID, new Level(), LocalDateTime.now(), LocalDateTime.now(), 0, 0, 0, 0, ID);
    private MineDTO mine1 = new MineDTO(ID, CODE + ID, XML + ID);
    private MineDTO mine2 = new MineDTO(ID2, CODE + ID2, XML + ID2);
    private MinesDTO minesDTO = new MinesDTO();
    private List<MineDTO> mines = new ArrayList<>();
    @Before
    public void setup() {
        mines.add(mine1);
        mines.add(mine2);
        minesDTO.setGame(ID);
        minesDTO.setMines(mines);
    }
    @Test
    public void testSaveMines() {
        when(gameRepository.findById(ID)).thenReturn(Optional.of(game));
        mineService.saveMines(minesDTO);
        verify(mineRepository, times(2)).save(any());
    }
    @Test
    public void testSaveMinesGameNull() {
        minesDTO.setGame(null);
        assertThrows(IncompleteDataException.class,
                () -> mineService.saveMines(minesDTO)
        );
    }
    @Test
    public void testSaveMinesNotFound() {
        assertThrows(NotFoundException.class,
                () -> mineService.saveMines(minesDTO)
        );
    }
}
 | 2,667 | 31.938272 | 114 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/application/service/MutantsServiceTest.java | 
	package org.codecritters.code_critters.application.service;
import org.codecritters.code_critters.persistence.entities.Mutant;
import org.codecritters.code_critters.persistence.repository.LevelRepository;
import org.codecritters.code_critters.persistence.repository.MutantRepository;
import org.codecritters.code_critters.web.dto.MutantDTO;
import org.codecritters.code_critters.web.dto.MutantsDTO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class MutantsServiceTest {
    @InjectMocks
    private MutantsService mutantsService;
    @Mock
    private MutantRepository mutantRepository;
    @Mock
    private LevelRepository levelRepository;
    private static final String NAME = "level_1";
    @Test
    public void createMutantsTest() {
        MutantDTO mutant = new MutantDTO("1", "new", "id", "xml");
        MutantsDTO mutantsDTO = new MutantsDTO(NAME, Collections.singletonList(mutant));
        mutantsService.createMutants(mutantsDTO);
        verify(levelRepository, times(1)).findByName(NAME);
        verify(mutantRepository, times(1)).save(any(Mutant.class));
    }
    @Test
    public void updateMutantsTest() {
        MutantDTO mutant = new MutantDTO("1", "new", "id", "xml");
        MutantsDTO mutantsDTO = new MutantsDTO(NAME, Collections.singletonList(mutant));
        mutantsService.updateMutants(mutantsDTO);
        verify(levelRepository).findByName(NAME);
        verify(mutantRepository).save(any(Mutant.class));
    }
}
 | 1,684 | 32.039216 | 88 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/application/service/PasswordServiceTest.java | 
	package org.codecritters.code_critters.application.service;
import org.codecritters.code_critters.persistence.entities.User;
import org.codecritters.code_critters.web.enums.Language;
import org.codecritters.code_critters.web.enums.Role;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.*;
@RunWith(MockitoJUnitRunner.class)
public class PasswordServiceTest {
    @InjectMocks
    private PasswordService passwordService;
    private final User user1 = new User("admin1", "admin1@admin.de", "admin1", "cookie1", "secret1", "salt1", false, true, Language.de, Role.admin, new Date());
    private final User user2 = new User("admin2", "admin2@admin.com", "admin2", "cookie2", "secret2", "salt2", false, true, Language.en, Role.admin, new Date());
    @Test
    public void hashPasswordTest() {
        passwordService.hashPassword(user1.getPassword(), user1);
        Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(user1.getSalt());
        assertAll("Password should have been encoded and saved",
                () -> assertTrue(pbkdf2PasswordEncoder.matches("admin1", user1.getPassword())),
                () -> assertNotEquals("salt1", user1.getSalt())
        );
    }
    @Test
    public void verifyPassword() {
        passwordService.hashPassword(user2.getPassword(), user2);
        assertAll("Password should have been encoded, decoding should give the proper match",
                () -> assertTrue(passwordService.verifyPassword("admin2", user2.getPassword(), user2.getSalt())),
                () -> assertFalse(passwordService.verifyPassword("admin1", user2.getPassword(), user2.getSalt()))
        );
    }
}
 | 1,886 | 41.886364 | 161 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/application/service/ResultServiceTest.java | 
	package org.codecritters.code_critters.application.service;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.entities.Result;
import org.codecritters.code_critters.persistence.entities.Score;
import org.codecritters.code_critters.persistence.entities.User;
import org.codecritters.code_critters.persistence.repository.LevelRepository;
import org.codecritters.code_critters.persistence.repository.ResultRepository;
import org.codecritters.code_critters.persistence.repository.ScoreRepository;
import org.codecritters.code_critters.persistence.repository.UserRepositiory;
import org.codecritters.code_critters.web.dto.ResultDTO;
import org.codecritters.code_critters.web.dto.ScoreDTO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class ResultServiceTest {
    @InjectMocks
    private ResultService resultService;
    @Mock
    private ResultRepository results;
    @Mock
    private LevelRepository levels;
    @Mock
    private UserRepositiory users;
    @Mock
    private ScoreRepository scores;
    private final ResultDTO result1 = new ResultDTO(950, "level_1", 3);
    private final String cookie = "cookie";
    @Test
    public void createResultWithUserTest() {
        Result result = new Result(800, cookie, new Level(), 2, new User());
        given(levels.findByName(result1.getLevel())).willReturn(any());
        given(users.findByCookie(cookie)).willReturn(new User());
        given(results.getResultByLevelAndUser(any(), any())).willReturn(result);
        resultService.createResult(result1, cookie);
        assertAll("Should update the given result",
                () -> assertEquals(result1.getScore(), result.getScore()),
                () -> assertEquals(result1.getStars(), result.getStars())
        );
        verify(levels, times(1)).findByName(result1.getLevel());
        verify(users, times(1)).findByCookie(cookie);
        verify(results, times(1)).getResultByLevelAndUser(any(), any());
        verify(results, times(1)).save(result);
    }
    @Test
    public void createResultNoUserAndNoResultTest() {
        given(levels.findByName(result1.getLevel())).willReturn(any());
        given(users.findByCookie(cookie)).willReturn(null);
        resultService.createResult(result1, cookie);
        verify(levels, times(1)).findByName(result1.getLevel());
        verify(users, times(1)).findByCookie(cookie);
        verify(results, times(1)).getResultByLevelAndCookie(any(), anyString());
        verify(results, times(1)).save(any());
    }
    @Test
    public void getMyScoreWithUserTest() {
        Score score = new Score("user", 950, 1, 1);
        given(users.findByCookie(cookie)).willReturn(new User());
        given(scores.findByUsername(any())).willReturn(score);
        ScoreDTO scoreDTO = resultService.getMyScore(cookie);
        assertAll("Should return a ScoreDTO with score's values",
                () -> assertEquals(950, scoreDTO.getScore()),
                () -> assertEquals("user", score.getUsername())
        );
        verify(users, times(1)).findByCookie(cookie);
        verify(scores, times(1)).findByUsername(any());
    }
    @Test
    public void getMyScoreNoUserAndNoScoreTest() {
        given(users.findByCookie(cookie)).willReturn(new User());
        given(scores.findByUsername(any())).willReturn(null);
        given(scores.countAll()).willReturn(0);
        ScoreDTO scoreDTO = resultService.getMyScore(cookie);
        Exception exception = assertThrows(NotFoundException.class,
                () -> resultService.getMyScore("no cookie")
        );
        assertAll(
                () -> assertEquals("No such User", exception.getMessage()),
                () -> assertEquals(1, scoreDTO.getPosition())
        );
        verify(users, times(1)).findByCookie(cookie);
        verify(scores, times(1)).findByUsername(any());
        verify(scores, times(1)).countAll();
    }
    @Test
    public void getHighscoreTest() {
        Score score1 = new Score("user", 950, 1, 1);
        Score score2 = new Score("admin", 800, 1, 2);
        List<Score> highscores = new LinkedList<>();
        highscores.add(score1);
        highscores.add(score2);
        given(scores.findTop10()).willReturn(highscores);
        ScoreDTO[] bestScores = resultService.getHighscore();
        assertEquals("Array should contain two scores", 2, bestScores.length);
        verify(scores, times(1)).findTop10();
    }
}
 | 5,133 | 39.746032 | 80 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/application/service/RowServiceTest.java | 
	package org.codecritters.code_critters.application.service;
import org.codecritters.code_critters.application.exception.AlreadyExistsException;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.codecritters.code_critters.persistence.repository.RowRepository;
import org.codecritters.code_critters.web.dto.RowDTO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import javax.validation.ConstraintViolationException;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class RowServiceTest {
    @InjectMocks
    private RowService rowService;
    @Mock
    private RowRepository rowRepository;
    private String id = "id";
    private RowDTO dto = new RowDTO(id, "row");
    private RowDTO newRow = new RowDTO(null, "newRow", 1);
    private CritterRow row = new CritterRow("row", 0);
    private CritterRow returnRow = new CritterRow("newRow", 1);
    @Test
    public void testDeleteRow() {
        when(rowRepository.findCritterRowById(id)).thenReturn(row);
        rowService.deleteRow(dto);
        verify(rowRepository).delete(row);
    }
    @Test
    public void testDeleteRowNotFound() {
        assertThrows(NotFoundException.class, () -> rowService.deleteRow(dto));
    }
    @Test
    public void testDeleteRowIdNull() {
        assertThrows(IllegalArgumentException.class, () -> rowService.deleteRow(new RowDTO()));
    }
    @Test
    public void testUpdateRow() {
        when(rowRepository.findCritterRowById(id)).thenReturn(row);
        rowService.updateRow(dto);
        verify(rowRepository).save(row);
    }
    @Test
    public void testUpdateRowNotFound() {
        assertThrows(NotFoundException.class, () -> rowService.updateRow(dto));
    }
    @Test
    public void testUpdateRowIdNull() {
        assertThrows(IllegalArgumentException.class, () -> rowService.updateRow(new RowDTO(null, "name")));
    }
    @Test
    public void testUpdateRowNameNull() {
        assertThrows(IllegalArgumentException.class, () -> rowService.updateRow(new RowDTO(id, null)));
    }
    @Test
    public void testUpdateRowNameEmpty() {
        assertThrows(IllegalArgumentException.class, () -> rowService.updateRow(new RowDTO(id, " ")));
    }
    @Test
    public void testAddRow() {
        returnRow.setId(id);
        when(rowRepository.save(any())).thenReturn(returnRow);
        RowDTO dto = rowService.addRow(newRow);
        assertAll(
                () -> assertEquals(id, dto.getId()),
                () -> assertEquals("newRow", dto.getName()),
                () -> assertEquals(1, dto.getPosition())
        );
    }
    @Test
    public void testAddRowAlreadyExists() {
        when(rowRepository.save(any())).thenThrow(ConstraintViolationException.class);
        assertThrows(AlreadyExistsException.class, () -> rowService.addRow(newRow));
    }
    @Test
    public void testAddRowNameNull() {
        assertThrows(IllegalArgumentException.class, () -> rowService.addRow(new RowDTO(id, null, 1)));
    }
    @Test
    public void testAddRowNameEmpty() {
        assertThrows(IllegalArgumentException.class, () -> rowService.addRow(new RowDTO(id, " ", 1)));
    }
    @Test
    public void testAddRowPositionNegative() {
        assertThrows(IllegalArgumentException.class, () -> rowService.addRow(new RowDTO(id, "name", -1)));
    }
}
 | 3,806 | 32.104348 | 107 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/application/service/UserServiceTest.java | 
	package org.codecritters.code_critters.application.service;
import org.codecritters.code_critters.application.exception.AlreadyExistsException;
import org.codecritters.code_critters.application.exception.IllegalActionException;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.persistence.entities.User;
import org.codecritters.code_critters.persistence.repository.ResultRepository;
import org.codecritters.code_critters.persistence.repository.UserRepositiory;
import org.codecritters.code_critters.web.dto.UserDTO;
import org.codecritters.code_critters.web.enums.Language;
import org.codecritters.code_critters.web.enums.Role;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
    @InjectMocks
    private UserService userService;
    @Mock
    private UserRepositiory userRepositiory;
    @Mock
    private ResultRepository resultRepository;
    @Mock
    private MailService mailService;
    @Mock
    private PasswordService passwordService;
    private final UserDTO user1 = new UserDTO("user1", "user@user.com", "password", null);
    private final UserDTO user2 = new UserDTO("admin1", "admin@admin.de", "admin", Language.de);
    private final String url = "url";
    private final String cookie = "cookie";
    private final String secret = "secret";
    @Test
    public void registerUserDataNullTest() {
        UserDTO usernameNull = new UserDTO(null, "email", "password", null);
        UserDTO emailNull = new UserDTO("user", null, "password", null);
        UserDTO passwordNull = new UserDTO("user", "email", null, null);
        Exception noUsername = assertThrows(IllegalActionException.class,
                () -> userService.registerUser(usernameNull, url)
        );
        Exception noEmail = assertThrows(IllegalActionException.class,
                () -> userService.registerUser(emailNull, url)
        );
        Exception noPassword = assertThrows(IllegalActionException.class,
                () -> userService.registerUser(passwordNull, url)
        );
        assertAll("These inputs are all null and should throw exceptions",
                () -> assertEquals("These fields cannot be empty", noUsername.getMessage()),
                () -> assertEquals("These fields cannot be empty", noEmail.getMessage()),
                () -> assertEquals("These fields cannot be empty", noPassword.getMessage())
        );
    }
    @Test
    public void registerUserEmptyStringTest() {
        UserDTO usernameEmpty = new UserDTO("   ", "email", "password", null);
        UserDTO emailEmpty = new UserDTO("user", "   ", "password", null);
        UserDTO passwordEmpty = new UserDTO("user", "email", "  ", null);
        Exception noUsername = assertThrows(IllegalActionException.class,
                () -> userService.registerUser(usernameEmpty, url)
        );
        Exception noEmail = assertThrows(IllegalActionException.class,
                () -> userService.registerUser(emailEmpty, url)
        );
        Exception noPassword = assertThrows(IllegalActionException.class,
                () -> userService.registerUser(passwordEmpty, url)
        );
        assertAll("These inputs are all empty and should throw exceptions",
                () -> assertEquals("These fields cannot be empty", noUsername.getMessage()),
                () -> assertEquals("These fields cannot be empty", noEmail.getMessage()),
                () -> assertEquals("These fields cannot be empty", noPassword.getMessage())
        );
    }
    @Test
    public void registerUserInputTooLongTest() {
        UserDTO longUsername = new UserDTO("suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuper long username", "email", "password", null);
        UserDTO longEmail = new UserDTO("user", "suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuper long email", "password", null);
        UserDTO longPassword = new UserDTO("user", "email", "suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuper long password", null);
        Exception usernameTooLong = assertThrows(IllegalActionException.class,
                () -> userService.registerUser(longUsername, url)
        );
        Exception emailTooLong = assertThrows(IllegalActionException.class,
                () -> userService.registerUser(longEmail, url)
        );
        Exception passwordTooLong = assertThrows(IllegalActionException.class,
                () -> userService.registerUser(longPassword, url)
        );
        assertAll("These inputs should all be too long and throw exceptions",
                () -> assertEquals("The input has to be less than 50 characters!", usernameTooLong.getMessage()),
                () -> assertEquals("The input has to be less than 50 characters!", emailTooLong.getMessage()),
                () -> assertEquals("The input has to be less than 50 characters!", passwordTooLong.getMessage())
        );
    }
    @Test
    public void registerUserUsernameOrEmailExistsTest() {
        UserDTO usernameExists = new UserDTO("user1", "email1", "password1", null);
        UserDTO emailExists = new UserDTO("user2", "email2", "password2", null);
        given(userRepositiory.existsByUsername(usernameExists.getUsername())).willReturn(true);
        given(userRepositiory.existsByEmail(emailExists.getEmail())).willReturn(true);
        Exception foundUsername = assertThrows(AlreadyExistsException.class,
                () -> userService.registerUser(usernameExists, url)
        );
        Exception foundEmail = assertThrows(AlreadyExistsException.class,
                () -> userService.registerUser(emailExists, url)
        );
        assertAll("These inputs should throw AlreadyExistsExceptions",
                () -> assertEquals("User with this username already exists!", foundUsername.getMessage()),
                () -> assertEquals("User with this email already exists!", foundEmail.getMessage())
        );
        verify(userRepositiory, times(1)).existsByUsername(usernameExists.getUsername());
        verify(userRepositiory, times(1)).existsByUsername(emailExists.getUsername());
        verify(userRepositiory, times(1)).existsByEmail(emailExists.getEmail());
    }
    @Test
    public void registerUserTest() {
        given(userRepositiory.existsByUsername(anyString())).willReturn(false);
        given(userRepositiory.existsByEmail(anyString())).willReturn(false);
        given(passwordService.hashPassword(anyString(), any())).willReturn(new User());
        userService.registerUser(user1, url);
        userService.registerUser(user2, url);
        verify(userRepositiory, times(2)).save(any());
    }
    @Test
    public void loginUserTest() {
        given(userRepositiory.findByUsernameOrEmail(user1.getUsername(), user1.getEmail())).willReturn(new User());
        given(passwordService.verifyPassword(any(), any(), any())).willReturn(true);
        userService.loginUser(user1, cookie);
        verify(userRepositiory, times(1)).save(any());
    }
    @Test
    public void loginUserExceptionsTest() {
        given(userRepositiory.findByUsernameOrEmail(user1.getUsername(), user1.getEmail())).willReturn(new User());
        given(userRepositiory.findByUsernameOrEmail(user2.getUsername(), user2.getEmail())).willReturn(null);
        given(passwordService.verifyPassword(any(), any(), any())).willReturn(false);
        Exception verifyPasswordFalse = assertThrows(NotFoundException.class,
                () -> userService.loginUser(user1, cookie)
        );
        Exception userNull = assertThrows(NotFoundException.class,
                () -> userService.loginUser(user2, cookie)
        );
        assertAll("Both login attempts should throw exceptions",
                () -> assertEquals("Username or Password incorrect", verifyPasswordFalse.getMessage()),
                () -> assertEquals("Username or Password incorrect", userNull.getMessage())
        );
        verify(userRepositiory, times(2)).findByUsernameOrEmail(anyString(), anyString());
        verify(passwordService, times(1)).verifyPassword(any(), any(), any());
    }
    @Test
    public void forgotPasswordTest() {
        when(userRepositiory.findByUsernameOrEmail(user1.getUsername(), user1.getEmail())).thenReturn(new User());
        when(userRepositiory.findByUsernameOrEmail(user2.getUsername(), user2.getEmail())).thenReturn(null);
        Exception noUser = assertThrows(NotFoundException.class,
                () -> userService.forgotPassword(user2, url)
        );
        userService.forgotPassword(user1, url);
        assertEquals("This should get an exception message", "Username or Password incorrect", noUser.getMessage());
        verify(userRepositiory, times(1)).save(any());
    }
    @Test
    public void resetPasswordTest() {
        User user = new User();
        user.setResetPassword(true);
        given(userRepositiory.findBySecret(secret)).willReturn(user);
        given(passwordService.hashPassword(any(), any())).willReturn(user);
        Exception noUser = assertThrows(NotFoundException.class,
                () -> userService.resetPassword("no secret", user1)
        );
        userService.resetPassword(secret, user1);
        assertAll("resetPassword test",
                () -> assertEquals("Incorrect Secret", noUser.getMessage()),
                () -> assertFalse(user.getResetPassword())
        );
        verify(userRepositiory, times(1)).save(any());
    }
    @Test
    public void activateUserTest() {
        given(userRepositiory.findBySecret(secret)).willReturn(new User());
        given(userRepositiory.save(any())).willReturn(new User());
        assertAll(
                () -> assertTrue(userService.activateUser(secret)),
                () -> assertFalse(userService.activateUser("no secret"))
        );
        verify(userRepositiory, times(1)).save(any());
    }
    @Test
    public void getUserByCookieTest() {
        given(userRepositiory.findByCookieAndLastUsedAfter(anyString(), any())).willReturn(new User());
        assertNotNull(userService.getUserByCookie(cookie));
        verify(userRepositiory, times(1)).save(any());
    }
    @Test
    public void logoutUserTest() {
        given(userRepositiory.findByCookie(cookie)).willReturn(new User());
        userService.logoutUser(cookie);
        verify(userRepositiory, times(1)).save(any());
    }
    @Test
    public void deleteUserExceptionTest() {
        User lastAdmin = new User();
        List<User> users = new ArrayList<User>();
        users.add(lastAdmin);
        given(userRepositiory.findByCookie(cookie)).willReturn(lastAdmin);
        given(userRepositiory.findAllByRole(Role.admin)).willReturn(users);
        Exception exception = assertThrows(IllegalActionException.class,
                () -> userService.deleteUser(cookie)
        );
        assertEquals("Cannot delete last remaining admin", exception.getMessage());
    }
    @Test
    public void deleteUserTest() {
        given(userRepositiory.findByCookie(cookie)).willReturn(new User());
        given(userRepositiory.findAllByRole(Role.admin)).willReturn(new LinkedList<>());
        userService.deleteUser(cookie);
        verify(resultRepository, times(1)).deleteAllByUser(any());
        verify(userRepositiory, times(1)).delete(any());
    }
    @Test
    public void changeUserUsernameOrEmailWrongTest() {
        UserDTO dto1 = new UserDTO(null, "email", "oldPassword", "password", Language.en);
        UserDTO dto2 = new UserDTO("user", null, "oldPassword", "password", Language.en);
        UserDTO dto3 = new UserDTO("", "email", "oldPassword", "password", Language.de);
        UserDTO dto4 = new UserDTO("user", "", "oldPassword", "password", Language.de);
        Exception usernameNull = assertThrows(IllegalActionException.class,
                () -> userService.changeUser(dto1, cookie, url)
        );
        Exception emailNull = assertThrows(IllegalActionException.class,
                () -> userService.changeUser(dto2, cookie, url)
        );
        Exception usernameEmpty = assertThrows(IllegalActionException.class,
                () -> userService.changeUser(dto3, cookie, url)
        );
        Exception emailEmpty = assertThrows(IllegalActionException.class,
                () -> userService.changeUser(dto4, cookie, url)
        );
        assertAll("Should all contain the same message",
                () -> assertEquals("These fields cannot be empty", usernameNull.getMessage()),
                () -> assertEquals("These fields cannot be empty", emailNull.getMessage()),
                () -> assertEquals("These fields cannot be empty", usernameEmpty.getMessage()),
                () -> assertEquals("These fields cannot be empty", emailEmpty.getMessage())
        );
    }
    @Test
    public void changeUserLongUsernameOrEmailTest() {
        UserDTO dto1 = new UserDTO("suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuper long username", "email", "oldPassword", "password", Language.de);
        UserDTO dto2 = new UserDTO("user", "suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuper long email", "oldPassword", "password", Language.en);
        Exception longUsername = assertThrows(IllegalActionException.class,
                () -> userService.changeUser(dto1, cookie, url)
        );
        Exception longEmail = assertThrows(IllegalActionException.class,
                () -> userService.changeUser(dto2, cookie, url)
        );
        assertAll("Should all contain the same message",
                () -> assertEquals("The input has to be less than 50 characters!", longUsername.getMessage()),
                () -> assertEquals("The input has to be less than 50 characters!", longEmail.getMessage())
        );
    }
    @Test
    public void changeUserPasswordExceptionsTest() {
        UserDTO dto1 = new UserDTO("user", "email", "suuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuper long password");
        UserDTO dto2 = new UserDTO("user", "email", "");
        Exception longPassword = assertThrows(IllegalActionException.class,
                () -> userService.changeUser(dto1, cookie, url)
        );
        Exception PasswordEmpty = assertThrows(IllegalActionException.class,
                () -> userService.changeUser(dto2, cookie, url)
        );
        assertAll("Should get two different messages",
                () -> assertEquals("The input has to be less than 50 characters!", longPassword.getMessage()),
                () -> assertEquals("These fields cannot be empty", PasswordEmpty.getMessage())
        );
    }
    @Test
    public void changeUserOldPasswordTest() {
        UserDTO dto = new UserDTO("user", "email", "oldPassword", "password", Language.en);
        given(userRepositiory.findByCookie(cookie)).willReturn(new User());
        given(passwordService.verifyPassword(anyString(), any(), any())).willReturn(true);
        given(passwordService.hashPassword(anyString(), any())).willReturn(new User());
        userService.changeUser(dto, cookie, url);
        verify(userRepositiory, times(2)).save(any());
    }
    @Test
    public void changeUserOldPasswordExceptionTest() {
        UserDTO dto = new UserDTO("user", "email", "oldPassword", "password", Language.en);
        given(userRepositiory.findByCookie(cookie)).willReturn(new User());
        given(passwordService.verifyPassword(anyString(), any(), any())).willReturn(false);
        Exception exception = assertThrows(NotFoundException.class,
                () -> userService.changeUser(dto, cookie, url)
        );
        assertEquals("Password incorrect", exception.getMessage());
    }
    @Test
    public void changeUserChangeUsernameTest() {
        User user = new User();
        user.setUsername(user2.getUsername());
        user1.setPassword("password");
        user1.setOldPassword("password");
        when(passwordService.verifyPassword(any(), any(), any())).thenReturn(true);
        when(passwordService.hashPassword(any(), any())).thenReturn(user);
        given(userRepositiory.findByCookie(cookie)).willReturn(new User());
        given(userRepositiory.existsByUsername(user1.getUsername())).willReturn(true);
        Exception exception = assertThrows(AlreadyExistsException.class,
                () -> userService.changeUser(user1, cookie, url)
        );
        assertEquals("User with this username already exists!", exception.getMessage());
        verify(userRepositiory, times(1)).save(any());
    }
    @Test
    public void changeUserChangeEmailTest() {
        User user = new User();
        user.setUsername(user2.getUsername());
        user2.setPassword("password");
        user2.setOldPassword("password");
        when(passwordService.verifyPassword(any(), any(), any())).thenReturn(true);
        when(passwordService.hashPassword(any(), any())).thenReturn(user);
        given(userRepositiory.findByCookie(cookie)).willReturn(new User());
        given(userRepositiory.existsByEmail(user2.getEmail())).willReturn(true);
        Exception exception = assertThrows(AlreadyExistsException.class,
                () -> userService.changeUser(user2, cookie, url)
        );
        assertEquals("User with this email already exists!", exception.getMessage());
        verify(userRepositiory, times(1)).save(any());
    }
} | 17,846 | 46.847185 | 168 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/persistence/GameRepositoryTest.java | 
	package org.codecritters.code_critters.persistence;
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.codecritters.code_critters.persistence.entities.Game;
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.repository.GameRepository;
import org.codecritters.code_critters.persistence.repository.LevelRepository;
import org.codecritters.code_critters.persistence.repository.RowRepository;
import org.codecritters.code_critters.spring.configuration.JpaTestConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@RunWith(SpringRunner.class)
@ContextConfiguration(
        classes = {JpaTestConfiguration.class },
        loader = AnnotationConfigContextLoader.class)
@Transactional
@ActiveProfiles("test")
public class GameRepositoryTest {
    @Resource
    private GameRepository gameRepository;
    @Resource
    private LevelRepository levelRepository;
    @Resource
    private RowRepository rowRepository;
    private final CritterRow row1 = new CritterRow("Tutorial", 0);
    String[][] levelArray = {
            {"wood", "grass", "wood"},
            {"grass", "grass", "wood"}
    };
    private final Level level = new Level(row1, "level_1", 10, 5, "cut1", "test1", "xml1", "init1", levelArray, 2);
    private static final String ID = "1";
    private final Game game = new Game(ID, level, LocalDateTime.now(), LocalDateTime.now(), 0, 0, 0, 0);
    @Before
    public void setup() {
        HashMap<String, Integer> spawn = new HashMap<>();
        spawn.put("x", 1);
        spawn.put("y", 8);
        HashMap<String, Integer> tower = new HashMap<>();
        tower.put("x", 14);
        tower.put("y", 8);
        level.setSpawn(spawn);
        level.setTower(tower);
        rowRepository.save(row1);
        levelRepository.save(level);
        Game savedGame = gameRepository.save(game);
        game.setId(savedGame.getId());
    }
    @Test
    public void testFindById() {
        Optional<Game> findGame = gameRepository.findById(game.getId());
        Optional<Game> none = gameRepository.findById(ID);
        assertAll(
                () -> assertFalse(none.isPresent()),
                () -> assertTrue(findGame.isPresent()),
                () -> assertEquals(game.getId(), findGame.get().getId()),
                () -> assertEquals(game.getStart(), findGame.get().getStart()),
                () -> assertEquals(game.getEnd(), findGame.get().getEnd()),
                () -> assertEquals(game.getScore(), findGame.get().getScore()),
                () -> assertEquals(game.getMutantsKilled(), findGame.get().getMutantsKilled()),
                () -> assertEquals(game.getHumansFinished(), findGame.get().getHumansFinished()),
                () -> assertEquals(game.getGameTime(), findGame.get().getGameTime())
        );
    }
}
 | 3,586 | 39.303371 | 115 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/persistence/LevelRepositoryTest.java | 
	package org.codecritters.code_critters.persistence;
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.repository.LevelRepository;
import org.codecritters.code_critters.persistence.repository.RowRepository;
import org.codecritters.code_critters.spring.configuration.JpaTestConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertAll;
@RunWith(SpringRunner.class)
@ContextConfiguration(
        classes = {JpaTestConfiguration.class },
        loader = AnnotationConfigContextLoader.class)
@Transactional
@ActiveProfiles("test")
public class LevelRepositoryTest {
    @Resource
    LevelRepository repository;
    @Resource
    RowRepository rows;
    private final CritterRow row1 = new CritterRow("Tutorial", 0);
    String[][] levelArray = {
            {"wood", "grass", "wood"},
            {"grass", "grass", "wood"}
    };
    private final Level level1 = new Level(row1, "level_1", 10, 5, "cut1", "test1", "xml1", "init1", levelArray, 2);
    private final Level level2 = new Level(row1, "level_2", 15, 4, "cut2", "test2", "xml2", "init2", levelArray, 2);
    @Before
    public void setup() {
        HashMap<String, Integer> spawn = new HashMap<>();
        spawn.put("x", 1);
        spawn.put("y", 8);
        HashMap<String, Integer> tower = new HashMap<>();
        tower.put("x", 14);
        tower.put("y", 8);
        level1.setSpawn(spawn);
        level2.setSpawn(spawn);
        level1.setTower(tower);
        level2.setTower(tower);
        rows.save(row1);
        repository.save(level1);
        repository.save(level2);
    }
    @Test
    public void findByNameTest() {
        Level findLevel = repository.findByName(level1.getName());
        assertEquals("Find level1 by name", level1.getId(), findLevel.getId());
    }
    @Test
    public void getLevelNamesTest() {
        List<String> levelNames = repository.getLevelNames();
        assertAll("This should get all level names",
                () -> assertEquals(2, levelNames.size()),
                () -> assertTrue(levelNames.contains(level1.getName())),
                () -> assertTrue(levelNames.contains(level2.getName()))
        );
    }
    @Test
    public void getIdByNameTest() {
        String id = repository.getIdByName(level1.getName());
        assertEquals("This should get the id of level1", level1.getId(), id);
    }
    @Test
    public void getTestByNameTest() {
        String test = repository.getTestByName(level2.getName());
        assertEquals("This should get the test of level2", level2.getTest(), test);
    }
    @Test
    public void getCUTByNameTest() {
        String cut = repository.getCUTByName(level1.getName());
        assertEquals("Should get the cut fo level1", level1.getCUT(), cut);
    }
    @Test
    public void getInitByNameTest() {
        String init = repository.getInitByName(level2.getName());
        assertEquals("Should get level2's init", level2.getInit(), init);
    }
    @Test
    public void getLevelNamesByGroupTest() {
        List<String> levelNames = repository.getLevelNamesByGroup(row1);
        assertAll("This should get all level names for row1",
                () -> assertEquals(2, levelNames.size()),
                () -> assertTrue(levelNames.contains(level1.getName())),
                () -> assertTrue(levelNames.contains(level2.getName()))
        );
    }
    @Test
    public void deleteById() {
        repository.deleteById(level1.getId());
        assertNull(repository.findByName(level1.getName()));
    }
} | 4,263 | 34.533333 | 116 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/persistence/MutantRepositoryTest.java | 
	package org.codecritters.code_critters.persistence;
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.entities.Mutant;
import org.codecritters.code_critters.persistence.repository.LevelRepository;
import org.codecritters.code_critters.persistence.repository.MutantRepository;
import org.codecritters.code_critters.persistence.repository.RowRepository;
import org.codecritters.code_critters.spring.configuration.JpaTestConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@RunWith(SpringRunner.class)
@ContextConfiguration(
        classes = {JpaTestConfiguration.class },
        loader = AnnotationConfigContextLoader.class)
@Transactional
@ActiveProfiles("test")
public class MutantRepositoryTest {
    @Resource
    MutantRepository repository;
    @Resource
    LevelRepository levels;
    @Resource
    RowRepository rows;
    private final CritterRow row1 = new CritterRow("Tutorial", 0);
    String[][] levelArray = {
            {"wood", "grass", "wood"},
            {"grass", "grass", "wood"}
    };
    private Level level = new Level(row1, "level_1", 10, 5, "cut", "test", "xml", "init", levelArray, 2);
    private final Mutant mutant1 = new Mutant(level, "mutantCode", "init", "xml");
    @Before
    public void saveMutants() {
        HashMap<String, Integer> spawn = new HashMap<>();
        spawn.put("x", 1);
        spawn.put("y", 8);
        HashMap<String, Integer> tower = new HashMap<>();
        tower.put("x", 14);
        tower.put("y", 8);
        level.setSpawn(spawn);
        level.setTower(tower);
        rows.save(row1);
        levels.save(level);
        repository.save(mutant1);
    }
    @Test
    public void getCodeByLevelTest() {
        List<String[]> mutants = repository.getCodeByLevel(level);
        assertEquals(1, mutants.size());
    }
    @Test
    public void deleteAllByLevel() {
        repository.deleteAllByLevel(level);
        assertEquals(0, repository.getCodeByLevel(level).size());
    }
}
 | 2,751 | 33.4 | 105 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/persistence/ResultRepositoryTest.java | 
	package org.codecritters.code_critters.persistence;
import org.codecritters.code_critters.persistence.customDataTypes.LevelResultType;
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.codecritters.code_critters.persistence.entities.Level;
import org.codecritters.code_critters.persistence.entities.Result;
import org.codecritters.code_critters.persistence.entities.User;
import org.codecritters.code_critters.persistence.repository.LevelRepository;
import org.codecritters.code_critters.persistence.repository.ResultRepository;
import org.codecritters.code_critters.persistence.repository.RowRepository;
import org.codecritters.code_critters.persistence.repository.UserRepositiory;
import org.codecritters.code_critters.spring.configuration.JpaTestConfiguration;
import org.codecritters.code_critters.web.enums.Language;
import org.codecritters.code_critters.web.enums.Role;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@RunWith(SpringRunner.class)
@ContextConfiguration(
        classes = {JpaTestConfiguration.class },
        loader = AnnotationConfigContextLoader.class)
@Transactional
@ActiveProfiles("test")
public class ResultRepositoryTest {
    @Resource
    ResultRepository repository;
    @Resource
    LevelRepository levels;
    @Resource
    RowRepository rows;
    @Resource
    UserRepositiory users;
    private final User user1 = new User("admin1", "admin1@admin.de", "admin1", "cookie1", "secret1", "salt1", false, true, Language.de, Role.admin, new Date());
    private final User user2 = new User("user1", "user1@user.de", "user1", "cookie3", "secret3", "salt3", false, true, Language.de, Role.user, new Date());
    private final CritterRow row1 = new CritterRow("Tutorial", 0);
    String[][] levelArray = {
            {"wood", "grass", "wood"},
            {"grass", "grass", "wood"}
    };
    private final Level level1 = new Level(row1, "level_1", 10, 5, "cut", "test", "xml", "init", levelArray, 2);
    private final Level level2 = new Level(row1, "level_2", 10, 5, "cut", "test", "xml", "init", levelArray, 2);
    private final Result result1 = new Result(800, "cookie3", level1, 2, user2);
    private final Result result2 = new Result(950, "cookie3", level2, 3, user2);
    private final Result result3 = new Result(500, "cookie1", level1, 1, user1);
    private final Result result4 = new Result(950, "cookie4", level1, 3, null);
    @Before
    public void saveResults() throws InterruptedException {
        HashMap<String, Integer> spawn = new HashMap<>();
        spawn.put("x", 1);
        spawn.put("y", 8);
        HashMap<String, Integer> tower = new HashMap<>();
        tower.put("x", 14);
        tower.put("y", 8);
        level1.setSpawn(spawn);
        level2.setSpawn(spawn);
        level1.setTower(tower);
        level2.setTower(tower);
        users.save(user1);
        users.save(user2);
        rows.save(row1);
        levels.save(level1);
        levels.save(level2);
        repository.save(result1);
        repository.save(result2);
        repository.save(result3);
        repository.save(result4);
        Thread.sleep(1000);
    }
    @Test
    public void getResultByLevelAndCookieTest() {
        Result findResult = repository.getResultByLevelAndCookie(level1, "cookie3");
        Result noResult = repository.getResultByLevelAndCookie(level1, "cookie5");
        assertAll("Test if getResultByLevelAndCookie works",
                () -> assertNull(noResult),
                () -> assertEquals(result1.getId(), findResult.getId())
        );
    }
    @Test
    public void getResultByLevelAndUserTest() {
        Result findResult = repository.getResultByLevelAndUser(level2, user2);
        Result noResult = repository.getResultByLevelAndUser(null, user2);
        assertAll("Test if getResultByLevelAndUser works",
                () -> assertNull(noResult),
                () -> assertEquals(result2.getId(), findResult.getId())
        );
    }
    @Test
    public void getAllByUpdatedBeforeAndUserIsNullTest() {
        List<Result> findResult = repository.getAllByUpdatedBeforeAndUserIsNull(new Date());
        assertEquals(1, findResult.size());
    }
    @Test
    public void deleteAllByUserTest() {
        repository.deleteAllByUser(user2);
        assertAll("All result data should have been deleted",
                () -> assertNull(repository.getResultByLevelAndUser(level1, user2)),
                () -> assertNull(repository.getResultByLevelAndUser(level2, user2))
        );
    }
    @Test
    public void getLevelNamesAndResultByGroupWithCookieTest() {
        List<LevelResultType> levelResults = levels.getLevelNamesAndResultByGroup(row1, "cookie3");
        int score1 = levelResults.get(0).getScore();
        int score2 = levelResults.get(1).getScore();
        assertAll("LevelRepository method should return all scores for a given cookie and CritterRow",
                () -> assertEquals(2, levelResults.size()),
                () -> assertEquals(result1.getScore(), score1),
                () -> assertEquals(result2.getScore(), score2)
        );
    }
    @Test
    public void getLevelNamesAndResultByGroupWithUserTest() {
        List<LevelResultType> levelResults = levels.getLevelNamesAndResultByGroup(row1, user1);
        int score1 = levelResults.get(0).getScore();
        assertAll("LevelRepository method should return all scores for a given CritterRow and User",
                () -> assertEquals(2, levelResults.size()),
                () -> assertEquals(result3.getScore(), score1),
                () -> assertNull(levelResults.get(1).getScore())
        );
    }
    @Test
    public void deleteAllByLevel() {
        repository.deleteAllByLevel(level1);
        assertAll("LevelRepository method should have deleted two results 1 and 3 but keep 2",
                () -> assertNull(repository.getResultByLevelAndCookie(level1, "cookie3")),
                () -> assertNull(repository.getResultByLevelAndCookie(level1, "cookie1")),
                () -> assertEquals(result2.getScore(), repository.getResultByLevelAndCookie(level2, "cookie3").getScore())
        );
    }
} | 6,702 | 41.157233 | 160 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/persistence/RowRepositoryTest.java | 
	package org.codecritters.code_critters.persistence;
import org.codecritters.code_critters.persistence.repository.RowRepository;
import org.codecritters.code_critters.persistence.entities.CritterRow;
import org.codecritters.code_critters.spring.configuration.JpaTestConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
@RunWith(SpringRunner.class)
@ContextConfiguration(
        classes = {JpaTestConfiguration.class },
        loader = AnnotationConfigContextLoader.class)
@Transactional
@ActiveProfiles("test")
public class RowRepositoryTest {
    @Resource
    private RowRepository repository;
    private final CritterRow row1 = new CritterRow("Tutorial", 0);
    private final CritterRow row2 = new CritterRow("Beginner", 1);
    @Test
    public void getCritterRowTest() {
        repository.save(row1);
        repository.save(row2);
        Collection<CritterRow> collection = repository.getRows();
        Optional<CritterRow> firstElement = collection.stream().findFirst();
        assertAll("getRows() should return all CritterRows ordered by position",
                () -> assertEquals(2, collection.size()),
                () -> assertEquals(row1.getId(), firstElement.get().getId()),
                () -> assertTrue(collection.contains(row2))
        );
    }
    @Test
    public void findCritterRowById() {
        repository.save(row1);
        repository.save(row2);
        CritterRow row = repository.findCritterRowById(row1.getId());
        assertAll("Check, if all attributes are the same",
                () -> assertEquals(row.getId(), row1.getId()),
                () -> assertEquals(row.getName(), row1.getName()),
                () -> assertEquals(row.getPosition(), row1.getPosition())
        );
    }
}
 | 2,232 | 35.606557 | 80 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/persistence/ScoreRepositoryTest.java | 
	package org.codecritters.code_critters.persistence;
import org.codecritters.code_critters.persistence.entities.Score;
import org.codecritters.code_critters.persistence.repository.ScoreRepository;
import org.codecritters.code_critters.spring.configuration.JpaTestConfiguration;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertAll;
@RunWith(SpringRunner.class)
@ContextConfiguration(
        classes = {JpaTestConfiguration.class },
        loader = AnnotationConfigContextLoader.class)
@Transactional
@ActiveProfiles("test")
public class ScoreRepositoryTest {
    @Resource
    private ScoreRepository repository;
    private final Score score1 = new Score("admin1", 2000, 5, 1);
    private final Score score2 = new Score("admin2", 1900, 4, 2);
    private final Score score3 = new Score("admin3", 1800, 5, 3);
    private final Score score4 = new Score("admin4", 700, 3, 4);
    private final Score score5 = new Score("admin5", 500, 1, 5);
    private final List<Score> scoreList = Arrays.asList(score1, score2, score3, score4, score5);
    @BeforeEach
    public void clearRepository() {
        repository.deleteAll();
    }
    @Test
    public void saveAndFindByUsernameTest() {
        repository.save(score1);
        Score score = repository.findByUsername("admin1");
        assertAll("Score properties don't match!",
                () -> assertTrue(repository.existsById("admin1")),
                () -> assertEquals(score.getUsername(), score1.getUsername()),
                () -> assertEquals(score.getLevels(), score1.getLevels()),
                () -> assertEquals(score.getPosition(), score1.getPosition()),
                () -> assertEquals(score.getScore(), score1.getScore())
        );
    }
    @Test
    public void saveAndCountAllTest() {
        repository.saveAll(scoreList);
        assertEquals("Repository should only contain 5 entries!", 5, repository.countAll());
    }
    @Test
    public void saveAndFindTop10With5ScoresTest() {
        repository.saveAll(scoreList);
        assertEquals("Repository should only contain 5 entries!", 5, repository.findTop10().size());
    }
    @Test
    public void saveAndFindTop10With11ScoresTest() {
        Score score6 = new Score("admin6", 450, 2, 6);
        Score score7 = new Score("admin7", 400, 2, 7);
        Score score8 = new Score("admin8", 350, 1, 8);
        Score score9 = new Score("admin9", 300, 1, 9);
        Score score10 = new Score("admin10", 250, 1, 10);
        Score score11 = new Score("admin11", 0, 0, 11);
        List<Score> scores = Arrays.asList(score1, score2, score3, score4, score5, score5, score6, score7, score8, score9, score10, score11);
        repository.saveAll(scores);
        assertEquals("This should give exactly 10 results!", 10, repository.findTop10().size());
    }
    @Test
    public void deleteAndNotExistsTest() {
        repository.save(score1);
        repository.delete(score1);
        assertNull("This entry should have been deleted!", repository.findByUsername("admin1"));
    }
}
 | 3,568 | 39.101124 | 141 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/persistence/UserRepositoryTest.java | 
	package org.codecritters.code_critters.persistence;
import org.codecritters.code_critters.persistence.entities.User;
import org.codecritters.code_critters.persistence.repository.UserRepositiory;
import org.codecritters.code_critters.spring.configuration.JpaTestConfiguration;
import org.codecritters.code_critters.web.enums.Language;
import org.codecritters.code_critters.web.enums.Role;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertAll;
@RunWith(SpringRunner.class)
@ContextConfiguration(
        classes = {JpaTestConfiguration.class },
        loader = AnnotationConfigContextLoader.class)
@Transactional
@ActiveProfiles("test")
public class UserRepositoryTest {
    @Resource
    private UserRepositiory repository;
    private final User user1 = new User("admin1", "admin1@admin.de", "admin1", "cookie1", "secret1", "salt1", false, true, Language.de, Role.admin, new Date());
    private final User user2 = new User("admin2", "admin2@admin.com", "admin2", "cookie2", "secret2", "salt2", false, true, Language.en, Role.admin, new Date());
    private final User user3 = new User("user1", "user1@user.de", "user1", "cookie3", "secret3", "salt3", false, true, Language.de, Role.user, new Date());
    @Before
    public void setup() {
        repository.save(user1);
        repository.save(user2);
        repository.save(user3);
    }
    @Test
    public void existsByUsernameOrEmailTest() {
        assertAll("Test if existsByUsernameOrEmail works",
                () -> assertTrue(repository.existsByUsernameOrEmail(user1.getUsername(), user1.getEmail())),
                () -> assertTrue(repository.existsByUsernameOrEmail("user", user2.getEmail())),
                () -> assertTrue(repository.existsByUsernameOrEmail(user3.getUsername(), "some email")),
                () -> assertFalse(repository.existsByUsernameOrEmail("admin3", "admin3@admin.com"))
        );
    }
    @Test
    public void findByUsernameOrEmailTest() {
        User findUser = repository.findByUsernameOrEmail(user1.getUsername(), "admin");
        User noUser = repository.findByUsernameOrEmail("user3", "user");
        assertAll("Test if findByUsernameOrEmail works",
                () -> assertNull(noUser),
                () -> assertEquals(user1.getId(), findUser.getId())
        );
    }
    @Test
    public void findBySecretTest() {
        User findUser = repository.findBySecret(user1.getSecret());
        assertEquals(user1.getId(), findUser.getId());
    }
    @Test
    public void findByCookieTest() {
        User findUser = repository.findByCookie(user1.getCookie());
        assertEquals(user1.getId(), findUser.getId());
    }
    @Test
    public void findByCookieAndLastUsedAfterTest() throws ParseException {
        String target = "Sat Aug 29 16:15:50 CEST 2020";
        DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
        Date result =  df.parse(target);
        User findUser = repository.findByCookieAndLastUsedAfter(user3.getCookie(), result);
        User noUser = repository.findByCookieAndLastUsedAfter(user1.getCookie(), new Date());
        assertAll("Test if findByCookieAndLastUsedAfter works",
                () -> assertNull(noUser),
                () -> assertEquals(findUser.getId(), user3.getId())
        );
    }
    @Test
    public void findByUsernameAndEmailTest() {
        User findUser = repository.findByUsernameAndEmail(user1.getUsername(), user1.getEmail());
        User noUser = repository.findByUsernameAndEmail(user1.getUsername(), "user@user.com");
        assertAll("Test if findByUsernameAndEmail works",
                () -> assertNull(repository.findByUsernameAndEmail(user1.getId(), "user@user.com")),
                () -> assertEquals(findUser.getId(), user1.getId())
        );
    }
    @Test
    public void findAllByRoleTest() {
        List<User> admins = repository.findAllByRole(Role.admin);
        List<User> users = repository.findAllByRole(Role.user);
        assertAll("Test if findAllByRole works",
                () -> assertEquals(2, admins.size()),
                () -> assertEquals(1, users.size())
        );
    }
    @Test
    public void existsByCookieTest() {
        assertAll("Test if existsByCookieTest works",
                () -> assertTrue(repository.existsByCookie(user1.getCookie())),
                () -> assertFalse(repository.existsByCookie("cookie4"))
        );
    }
    @Test
    public void existsByEmailTest() {
        assertAll("Test if existsByEmail works",
                () -> assertTrue(repository.existsByEmail(user2.getEmail())),
                () -> assertFalse(repository.existsByEmail("admin1@admin.com"))
        );
    }
    @Test
    public void existsByUsernameTest() {
        assertAll("Test if existsByUsername works",
                () -> assertTrue(repository.existsByUsername(user3.getUsername())),
                () -> assertFalse(repository.existsByUsername("user2"))
        );
    }
} | 5,619 | 39.431655 | 161 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/web/controller/GameControllerTest.java | 
	package org.codecritters.code_critters.web.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.codecritters.code_critters.application.service.GameService;
import org.codecritters.code_critters.application.service.MineService;
import org.codecritters.code_critters.spring.configuration.SecurityTestConfig;
import org.codecritters.code_critters.web.dto.GameDTO;
import org.codecritters.code_critters.web.dto.MinesDTO;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockCookie;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(GameController.class)
@Import(SecurityTestConfig.class)
@ActiveProfiles("test")
public class GameControllerTest {
    @Autowired
    private MockMvc mvc;
    @MockBean
    private GameService gameService;
    @MockBean
    private MineService mineService;
    private MinesDTO minesDTO = new MinesDTO();
    private final GameDTO gameDTO = new GameDTO();
    private final MockCookie cookie = new MockCookie("id", "123");
    private final String TOKEN_ATTR_NAME = "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN";
    private final HttpSessionCsrfTokenRepository httpSessionCsrfTokenRepository = new HttpSessionCsrfTokenRepository();
    private final CsrfToken csrfToken = httpSessionCsrfTokenRepository.generateToken(new MockHttpServletRequest());
    @AfterEach
    public void resetService() {reset(gameService, mineService);}
    @Test
    public void testCreateGame() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String game = mapper.writeValueAsString(gameDTO);
        System.out.println(game);
        when(gameService.createGame(any(), anyString())).thenReturn(gameDTO);
        mvc.perform(post("/game/create")
                .content(game)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
        verify(gameService).createGame(any(), anyString());
    }
    @Test
    public void testSaveGame() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String game = mapper.writeValueAsString(gameDTO);
        mvc.perform(post("/game/save")
                .content(game)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
        verify(gameService).saveGame(any());
    }
    @Test
    public void testSaveMines() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String mines = mapper.writeValueAsString(minesDTO);
        mvc.perform(post("/game/mines")
                .content(mines)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
        verify(mineService).saveMines(any());
    }
}
 | 4,458 | 42.291262 | 125 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/web/controller/GeneratorControllerTest.java | 
	package org.codecritters.code_critters.web.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.codecritters.code_critters.application.exception.AlreadyExistsException;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.application.service.LevelService;
import org.codecritters.code_critters.application.service.MutantsService;
import org.codecritters.code_critters.application.service.RowService;
import org.codecritters.code_critters.spring.configuration.SecurityTestConfig;
import org.codecritters.code_critters.web.dto.LevelDTO;
import org.codecritters.code_critters.web.dto.MutantDTO;
import org.codecritters.code_critters.web.dto.MutantsDTO;
import org.codecritters.code_critters.web.dto.RowDTO;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockCookie;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(GeneratorController.class)
@Import(SecurityTestConfig.class)
@ActiveProfiles("test")
public class GeneratorControllerTest {
    @Autowired
    private MockMvc mvc;
    @MockBean
    private LevelService levelService;
    @MockBean
    private RowService rowService;
    @MockBean
    private MutantsService mutantsService;
    private LevelDTO levelDTO;
    private final String level = "level";
    private final MockCookie cookie = new MockCookie("id", "123");
    private final MutantDTO mutant1 = new MutantDTO("code1", "init1", "id1", "xml1");
    private final MutantDTO mutant2 = new MutantDTO("code2", "init2", "id2", "xml2");
    private final RowDTO row1 = new RowDTO("row1", "Advanced", 2);
    private final RowDTO row2 = new RowDTO("row2", "Beginner", 1);
    private final String TOKEN_ATTR_NAME = "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN";
    private final HttpSessionCsrfTokenRepository httpSessionCsrfTokenRepository = new HttpSessionCsrfTokenRepository();
    private final CsrfToken csrfToken = httpSessionCsrfTokenRepository.generateToken(new MockHttpServletRequest());
    private String levelDTOContent;
    private String rowDTOContent;
    private ObjectMapper mapper;
    @Before
    public void setup() throws JsonProcessingException {
        String[][] levelArray = {
                {"wood", "grass", "wood"},
                {"grass", "grass", "wood"}
        };
        HashMap<String, Integer> spawn = new HashMap<>();
        spawn.put("x", 1);
        spawn.put("y", 8);
        HashMap<String, Integer> tower = new HashMap<>();
        tower.put("x", 14);
        tower.put("y", 8);
        levelDTO = new LevelDTO("id1", "level_1", 10, 5, "cut1", "init", "xml", "test", levelArray, tower, spawn, "row1", 2);
        mapper = new ObjectMapper();
        levelDTOContent = mapper.writeValueAsString(levelDTO);
        rowDTOContent = mapper.writeValueAsString(row1);
    }
    @AfterEach
    public void resetService() {
        reset(levelService, mutantsService, rowService);
    }
    @Test
    public void testCreateLevel() throws Exception {
        mvc.perform(post("/generator/level/create")
                .contentType(MediaType.APPLICATION_JSON)
                .content(levelDTOContent)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().isOk());
        verify(levelService).createLevel(any());
    }
    @Test
    public void testCreateLevelExists() throws Exception {
        doThrow(NotFoundException.class).when(levelService).createLevel(any());
        mvc.perform(post("/generator/level/create")
                .contentType(MediaType.APPLICATION_JSON)
                .content(levelDTOContent)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().is(404));
    }
    @Test
    public void testDeleteLevel() throws Exception {
        mvc.perform(post("/generator/level/delete")
                .contentType(MediaType.APPLICATION_JSON)
                .content(level)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().isOk());
        verify(levelService).deleteLevel(level);
    }
    @Test
    public void testDeleteLevelNotFound() throws Exception {
        doThrow(NotFoundException.class).when(levelService).deleteLevel(level);
        mvc.perform(post("/generator/level/delete")
                .contentType(MediaType.APPLICATION_JSON)
                .content(level)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().is(404));
        verify(levelService).deleteLevel(level);
    }
    @Test
    public void testUpdateLevel() throws Exception {
        mvc.perform(post("/generator/level/update")
                .contentType(MediaType.APPLICATION_JSON)
                .content(levelDTOContent)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().isOk());
        verify(levelService).updateLevel(any());
    }
    @Test
    public void testUpdateLevelExists() throws Exception {
        doThrow(AlreadyExistsException.class).when(levelService).updateLevel(any());
        mvc.perform(post("/generator/level/update")
                .contentType(MediaType.APPLICATION_JSON)
                .content(levelDTOContent)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().is(460));
        verify(levelService).updateLevel(any());
    }
    @Test
    public void testCreateMutants() throws Exception {
        List<MutantDTO> mutants = new ArrayList<>();
        mutants.add(mutant1);
        mutants.add(mutant2);
        MutantsDTO mutantsDTO = new MutantsDTO(levelDTO.getName(), mutants);
        String content = mapper.writeValueAsString(mutantsDTO);
        mvc.perform(post("/generator/mutants/create")
                .contentType(MediaType.APPLICATION_JSON)
                .content(content)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().isOk());
        verify(mutantsService).createMutants(any());
    }
    @Test
    public void testUpdateMutants()  throws Exception {
        List<MutantDTO> mutants = new ArrayList<>();
        mutants.add(mutant1);
        mutants.add(mutant2);
        MutantsDTO mutantsDTO = new MutantsDTO(levelDTO.getName(), mutants);
        String content = mapper.writeValueAsString(mutantsDTO);
        mvc.perform(post("/generator/mutants/update")
                .contentType(MediaType.APPLICATION_JSON)
                .content(content)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().isOk());
        verify(mutantsService).updateMutants(any());
    }
    @Test
    public void testDeleteRow() throws Exception {
        mvc.perform(post("/generator/row/delete")
                .contentType(MediaType.APPLICATION_JSON)
                .content(rowDTOContent)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().isOk());
        verify(rowService).deleteRow(any());
    }
    @Test
    public void testDeleteRowNotFound() throws Exception {
        doThrow(NotFoundException.class).when(rowService).deleteRow(any());
        mvc.perform(post("/generator/row/delete")
                .contentType(MediaType.APPLICATION_JSON)
                .content(rowDTOContent)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().is(404));
        verify(rowService).deleteRow(any());
    }
    @Test
    public void testUpdateRow() throws Exception {
        mvc.perform(post("/generator/row/update")
                .contentType(MediaType.APPLICATION_JSON)
                .content(rowDTOContent)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().isOk());
        verify(rowService).updateRow(any());
    }
    @Test
    public void testUpdateRowNotFound() throws Exception {
        doThrow(NotFoundException.class).when(rowService).updateRow(any());
        mvc.perform(post("/generator/row/update")
                .contentType(MediaType.APPLICATION_JSON)
                .content(rowDTOContent)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().is(404));
        verify(rowService).updateRow(any());
    }
    @Test
    public void testAddRow() throws Exception {
        mvc.perform(post("/generator/row/add")
                .contentType(MediaType.APPLICATION_JSON)
                .content(rowDTOContent)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().isOk());
        verify(rowService).addRow(any());
    }
    @Test
    public void testAddRowNotFound() throws Exception {
        doThrow(AlreadyExistsException.class).when(rowService).addRow(any());
        mvc.perform(post("/generator/row/add")
                .contentType(MediaType.APPLICATION_JSON)
                .content(rowDTOContent)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().is(460));
        verify(rowService).addRow(any());
    }
    @Test
    public void testGetLevelNames() throws Exception {
        List<String> names = new ArrayList<>();
        names.add(level);
        names.add(levelDTO.getName());
        when(levelService.getLevelNames()).thenReturn(names);
        MvcResult result = mvc.perform(get("/generator/names")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andReturn();
        String content = result.getResponse().getContentAsString();
        assertAll(
                () -> assertTrue(content.contains(level)),
                () -> assertTrue(content.contains(levelDTO.getName()))
        );
        verify(levelService).getLevelNames();
    }
    @Test
    public void testGetRows() throws Exception {
        List<RowDTO> rows = new ArrayList<>();
        rows.add(row1);
        rows.add(row2);
        when(levelService.getRows()).thenReturn(rows);
        mvc.perform(get("/generator/rows")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$[0].id", is(row1.getId())))
                .andExpect(jsonPath("$[0].name", is(row1.getName())))
                .andExpect(jsonPath("$[0].position", is(row1.getPosition())))
                .andExpect(jsonPath("$[1].id", is(row2.getId())))
                .andExpect(jsonPath("$[1].name", is(row2.getName())))
                .andExpect(jsonPath("$[1].position", is(row2.getPosition())))
                .andReturn();
        verify(levelService).getRows();
    }
}
 | 13,960 | 38.661932 | 125 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/web/controller/LevelControllerTest.java | 
	package org.codecritters.code_critters.web.controller;
import org.codecritters.code_critters.application.service.LevelService;
import org.codecritters.code_critters.spring.configuration.SecurityTestConfig;
import org.codecritters.code_critters.web.dto.LevelDTO;
import org.codecritters.code_critters.web.dto.MutantDTO;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockCookie;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(LevelController.class)
@Import(SecurityTestConfig.class)
@ActiveProfiles("test")
public class LevelControllerTest {
    @Autowired
    private MockMvc mvc;
    @MockBean
    private LevelService levelService;
    private LevelDTO levelDTO;
    private final String level = "level";
    private final MockCookie cookie = new MockCookie("id", "123");
    private final String TOKEN_ATTR_NAME = "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN";
    private final HttpSessionCsrfTokenRepository httpSessionCsrfTokenRepository = new HttpSessionCsrfTokenRepository();
    private final CsrfToken csrfToken = httpSessionCsrfTokenRepository.generateToken(new MockHttpServletRequest());
    @Before
    public void setup() {
        String[][] levelArray = {
                {"wood", "grass", "wood"},
                {"grass", "grass", "wood"}
        };
        HashMap<String, Integer> spawn = new HashMap<>();
        spawn.put("x", 1);
        spawn.put("y", 8);
        HashMap<String, Integer> tower = new HashMap<>();
        tower.put("x", 14);
        tower.put("y", 8);
        levelDTO = new LevelDTO("id1", "level_1", 10, 5, "cut1", "init", "xml", "test", levelArray, tower, spawn, "row1", 2);
    }
    @AfterEach
    public void resetService() {reset(levelService);}
    @Test
    public void getLevelDataTest() throws Exception {
        given(levelService.getLevel(level)).willReturn(levelDTO);
        mvc.perform(get("/level/get")
                .param("level", level)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.init", is(levelDTO.getInit())))
                .andExpect(jsonPath("$.cut", is(levelDTO.getCUT())))
                .andExpect(jsonPath("$.test", is(levelDTO.getTest())));
        verify(levelService, times(1)).getLevel(level);
    }
    @Test
    public void getMutantsTest() throws Exception {
        List<MutantDTO> mutantsList = new ArrayList<>();
        MutantDTO mutant1 = new MutantDTO("code1", "init1", "id1", "xml");
        MutantDTO mutant2 = new MutantDTO("code2", "init2", "id2", "xml");
        mutantsList.add(mutant1);
        mutantsList.add(mutant2);
        given(levelService.getMutants(level)).willReturn(mutantsList);
        mvc.perform(get("/level/mutants")
                .param("level", level)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$[0].code", is(mutant1.getCode())))
                .andExpect(jsonPath("$[0].init", is(mutant1.getInit())))
                .andExpect(jsonPath("$[1].code", is(mutant2.getCode())))
                .andExpect(jsonPath("$[1].init", is(mutant2.getInit())));
        verify(levelService, times(1)).getMutants(level);
    }
    @Test
    public void getLevelsTest() throws Exception {
        List groupedLevels = new LinkedList();
        HashMap map = new HashMap<String, Object>();
        map.put("name", "Tutorial");
        map.put("levels", 0);
        groupedLevels.add(map);
        given(levelService.getLevelsGrouped(cookie.getValue())).willReturn(groupedLevels);
        mvc.perform(get("/level/levels")
                .contentType(MediaType.APPLICATION_JSON)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$[0].name", is("Tutorial")))
                .andExpect(jsonPath("$[0].levels", is(0)));
        verify(levelService, times(1)).getLevelsGrouped(cookie.getValue());
    }
}
 | 5,504 | 42.690476 | 125 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/web/controller/ResultControllerTest.java | 
	package org.codecritters.code_critters.web.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.codecritters.code_critters.application.service.ResultService;
import org.codecritters.code_critters.spring.configuration.SecurityTestConfig;
import org.codecritters.code_critters.web.dto.ResultDTO;
import org.codecritters.code_critters.web.dto.ScoreDTO;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockCookie;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
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.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(ResultController.class)
@Import(SecurityTestConfig.class)
@ActiveProfiles("test")
public class ResultControllerTest {
    @Autowired
    private MockMvc mvc;
    @MockBean
    private ResultService resultService;
    private final ScoreDTO myScore = new ScoreDTO("admin", 500, 2, 1);
    private final MockCookie cookie = new MockCookie("id", "123");
    private final String TOKEN_ATTR_NAME = "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN";
    private final HttpSessionCsrfTokenRepository httpSessionCsrfTokenRepository = new HttpSessionCsrfTokenRepository();
    private final CsrfToken csrfToken = httpSessionCsrfTokenRepository.generateToken(new MockHttpServletRequest());
    @AfterEach
    public void resetService() {
        reset(resultService);
    }
    @Test
    public void storeResultTest() throws Exception {
        ResultDTO resultDto = new ResultDTO(950, "level_2", 3);
        ObjectMapper mapper = new ObjectMapper();
        String result = mapper.writeValueAsString(resultDto);
        mvc.perform(post("/result")
                .content(result)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
        verify(resultService, times(1)).createResult(any(), anyString());
    }
    @Test
    public void getHighscoreTest() throws Exception {
        ScoreDTO[] scoreDTOS = {myScore};
        given(resultService.getHighscore()).willReturn(scoreDTOS);
        mvc.perform(get("/highscore/data")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$[0].user", is(myScore.getUser())))
                .andExpect(jsonPath("$[0].score", is(myScore.getScore())))
                .andExpect(jsonPath("$[0].levels", is(myScore.getLevels())))
                .andExpect(jsonPath("$[0].position", is(myScore.getPosition())));
        verify(resultService, times(1)).getHighscore();
    }
    @Test
    public void getMyScoreTest() throws Exception {
        given(resultService.getMyScore(anyString())).willReturn(myScore);
        mvc.perform(get("/highscore/me")
                .contentType(MediaType.APPLICATION_JSON)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.user", is(myScore.getUser())))
                .andExpect(jsonPath("$.score", is(myScore.getScore())))
                .andExpect(jsonPath("$.levels", is(myScore.getLevels())))
                .andExpect(jsonPath("$.position", is(myScore.getPosition())));
        verify(resultService, times(1)).getMyScore(anyString());
    }
} | 4,808 | 43.943925 | 125 | 
	java | 
| 
	code-critters | 
	code-critters-master/src/test/java/org/codecritters/code_critters/web/controller/UserControllerTest.java | 
	package org.codecritters.code_critters.web.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.codecritters.code_critters.application.exception.NotFoundException;
import org.codecritters.code_critters.application.service.UserService;
import org.codecritters.code_critters.spring.configuration.SecurityTestConfig;
import org.codecritters.code_critters.web.dto.UserDTO;
import org.codecritters.code_critters.web.enums.Language;
import org.codecritters.code_critters.web.enums.Role;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockCookie;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
@Import(SecurityTestConfig.class)
@ActiveProfiles("test")
public class UserControllerTest {
    @Autowired
    private MockMvc mvc;
    @MockBean
    private UserService userService;
    private final UserDTO user1 = new UserDTO("user1", "email1", "password1", Language.de);
    private final UserDTO user2 = new UserDTO("admin1", "email2", "password2", Language.en);
    private final MockCookie cookie = new MockCookie("id", "123");
    private final String TOKEN_ATTR_NAME = "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN";
    private final HttpSessionCsrfTokenRepository httpSessionCsrfTokenRepository = new HttpSessionCsrfTokenRepository();
    private final CsrfToken csrfToken = httpSessionCsrfTokenRepository.generateToken(new MockHttpServletRequest());
    @Before
    public void setup() {
        user1.setRole(Role.user);
        user2.setRole(Role.admin);
        user2.setActive(true);
    }
    @AfterEach
    public void resetService() {reset(userService);}
    @Test
    public void registerUserTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String user = mapper.writeValueAsString(user1);
        mvc.perform(post("/users/register")
                .content(user)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
        verify(userService, times(1)).registerUser(any(), any());
    }
    @Test
    public void loginUserActiveTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String admin = mapper.writeValueAsString(user2);
        given(userService.loginUser(any(), any())).willReturn(user2);
        mvc.perform(post("/users/login")
                .content(admin)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.role", is(user2.getRole().toString())))
                .andExpect(jsonPath("$.language", is(user2.getLanguage().toString())))
                .andExpect(jsonPath("$.email", is(user2.getEmail())))
                .andExpect(jsonPath("$.username", is(user2.getUsername())));
        verify(userService, times(1)).loginUser(any(), any());
    }
    @Test
    public void loginUserInactiveTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String user = mapper.writeValueAsString(user1);
        given(userService.loginUser(any(), any())).willReturn(user1);
        mvc.perform(post("/users/login")
                .content(user)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isNotFound())
                .andExpect(jsonPath("$.error", is("activate_first")));
        verify(userService, times(1)).loginUser(any(), any());
    }
    @Test
    public void loginUserExceptionTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String user = mapper.writeValueAsString(user1);
        given(userService.loginUser(any(), any())).willThrow(NotFoundException.class);
        mvc.perform(post("/users/login")
                .content(user)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isNotFound());
        verify(userService, times(1)).loginUser(any(), any());
    }
    @Test
    public void logoutUserTest() throws Exception {
        mvc.perform(post("/users/logout")
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
        verify(userService, times(1)).logoutUser(cookie.getValue());
    }
    @Test
    public void deleteUserTest() throws Exception {
        mvc.perform(delete("/users/delete")
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
        verify(userService, times(1)).deleteUser(cookie.getValue());
    }
    @Test
    public void changeUserTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String user = mapper.writeValueAsString(user1);
        mvc.perform(post("/users/change")
                .content(user)
                .cookie(cookie)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
        verify(userService, times(1)).changeUser(any(), any(), any());
    }
    @Test
    public void forgotPasswordTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String user = mapper.writeValueAsString(user1);
        mvc.perform(post("/users/forgot")
                .content(user)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
        verify(userService, times(1)).forgotPassword(any(), any());
    }
    @Test
    public void activateUserTest() throws Exception {
        given(userService.activateUser(anyString())).willReturn(true);
        mvc.perform(get("/users/activate/secret")
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("http://localhost?activated=true"));
        verify(userService, times(1)).activateUser(anyString());
    }
    @Test
    public void resetPasswordTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String user = mapper.writeValueAsString(user1);
        mvc.perform(post("/users/reset/secret")
                .content(user)
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
        verify(userService, times(1)).resetPassword(anyString(), any());
    }
    @Test
    public void getMeTest() throws Exception{
        given(userService.getUserByCookie(cookie.getValue())).willReturn(user1);
        mvc.perform(get("/users/me")
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.role", is(user1.getRole().toString())))
                .andExpect(jsonPath("$.language", is(user1.getLanguage().toString())))
                .andExpect(jsonPath("$.email", is(user1.getEmail())))
                .andExpect(jsonPath("$.username", is(user1.getUsername())));
        verify(userService, times(1)).getUserByCookie(cookie.getValue());
    }
    @Test
    public void getMeExceptionTest() throws Exception{
        given(userService.getUserByCookie(cookie.getValue())).willReturn(null);
        mvc.perform(get("/users/me")
                .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                .param(csrfToken.getParameterName(), csrfToken.getToken())
                .cookie(cookie)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isNotFound());
        verify(userService, times(1)).getUserByCookie(cookie.getValue());
    }
}
 | 10,753 | 44.184874 | 125 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/Main.java | 
	import com.openalpr.jni.Alpr;
import com.openalpr.jni.AlprPlate;
import com.openalpr.jni.AlprPlateResult;
import com.openalpr.jni.AlprResults;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
public class Main {
    public static void main(String[] args) throws Exception {
        String country = "", configfile = "", runtimeDataDir = "", licensePlate = "";
        if (args.length == 4) {
                country = args[0];
                configfile = args[1];
                runtimeDataDir = args[2];
                licensePlate = args[3];
        }
        else
        {
            System.err.println("Program requires 4 arguments: Country, Config File, runtime_data dir, and license plate image");
            System.exit(1);
        }
        Alpr alpr = new Alpr(country, configfile, runtimeDataDir);
        alpr.setTopN(10);
        alpr.setDefaultRegion("wa");
        // Read an image into a byte array and send it to OpenALPR
        Path path = Paths.get(licensePlate);
        byte[] imagedata = Files.readAllBytes(path);
        AlprResults results = alpr.recognize(imagedata);
        System.out.println("OpenALPR Version: " + alpr.getVersion());
        System.out.println("Image Size: " + results.getImgWidth() + "x" + results.getImgHeight());
        System.out.println("Processing Time: " + results.getTotalProcessingTimeMs() + " ms");
        System.out.println("Found " + results.getPlates().size() + " results");
        System.out.format("  %-15s%-8s\n", "Plate Number", "Confidence");
        for (AlprPlateResult result : results.getPlates())
        {
            for (AlprPlate plate : result.getTopNPlates()) {
                if (plate.isMatchesTemplate())
                    System.out.print("  * ");
                else
                    System.out.print("  - ");
                System.out.format("%-15s%-8f\n", plate.getCharacters(), plate.getOverallConfidence());
            }
        }
        // Make sure to call this to release memory
        alpr.unload();
    }
}
 | 2,062 | 33.383333 | 128 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/Alpr.java | 
	package com.openalpr.jni;
import com.openalpr.jni.json.JSONException;
public class Alpr {
    static {
        // Load the OpenALPR library at runtime
        // openalprjni.dll (Windows) or libopenalprjni.so (Linux/Mac)
        System.loadLibrary("openalprjni");
    }
    private native void initialize(String country, String configFile, String runtimeDir);
    private native void dispose();
    private native boolean is_loaded();
    private native String native_recognize(String imageFile);
    private native String native_recognize(byte[] imageBytes);
    private native String native_recognize(long imageData, int bytesPerPixel, int imgWidth, int imgHeight);
    private native void set_default_region(String region);
    private native void detect_region(boolean detectRegion);
    private native void set_top_n(int topN);
    private native String get_version();
    public Alpr(String country, String configFile, String runtimeDir)
    {
        initialize(country, configFile, runtimeDir);
    }
    public void unload()
    {
        dispose();
    }
    public boolean isLoaded()
    {
        return is_loaded();
    }
    public AlprResults recognize(String imageFile) throws AlprException
    {
        try {
            String json = native_recognize(imageFile);
            return new AlprResults(json);
        } catch (JSONException e)
        {
            throw new AlprException("Unable to parse ALPR results");
        }
    }
    public AlprResults recognize(byte[] imageBytes) throws AlprException
    {
        try {
            String json = native_recognize(imageBytes);
            return new AlprResults(json);
        } catch (JSONException e)
        {
            throw new AlprException("Unable to parse ALPR results");
        }
    }
    public AlprResults recognize(long imageData, int bytesPerPixel, int imgWidth, int imgHeight) throws AlprException
    {
        try {
            String json = native_recognize(imageData, bytesPerPixel, imgWidth, imgHeight);
            return new AlprResults(json);
        } catch (JSONException e)
        {
            throw new AlprException("Unable to parse ALPR results");
        }
    }
    public void setTopN(int topN)
    {
        set_top_n(topN);
    }
    public void setDefaultRegion(String region)
    {
        set_default_region(region);
    }
    public void setDetectRegion(boolean detectRegion)
    {
        detect_region(detectRegion);
    }
    public String getVersion()
    {
        return get_version();
    }
}
 | 2,538 | 24.908163 | 117 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/AlprCoordinate.java | 
	package com.openalpr.jni;
import com.openalpr.jni.json.JSONException;
import com.openalpr.jni.json.JSONObject;
public class AlprCoordinate {
    private final int x;
    private final int y;
    AlprCoordinate(JSONObject coordinateObj) throws JSONException
    {
        x = coordinateObj.getInt("x");
        y = coordinateObj.getInt("y");
    }
    public int getX() {
        return x;
    }
    public int getY() {
        return y;
    }
}
 | 451 | 17.08 | 65 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/AlprException.java | 
	package com.openalpr.jni;
public class AlprException extends Exception {
    public AlprException(String s) {
        super(s);
    }
}
 | 139 | 13 | 46 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/AlprPlate.java | 
	package com.openalpr.jni;
import com.openalpr.jni.json.JSONException;
import com.openalpr.jni.json.JSONObject;
public class AlprPlate {
    private final String characters;
    private final float overall_confidence;
    private final boolean matches_template;
    AlprPlate(JSONObject plateObj) throws JSONException
    {
        characters = plateObj.getString("plate");
        overall_confidence = (float) plateObj.getDouble("confidence");
        matches_template = plateObj.getInt("matches_template") != 0;
    }
    public String getCharacters() {
        return characters;
    }
    public float getOverallConfidence() {
        return overall_confidence;
    }
    public boolean isMatchesTemplate() {
        return matches_template;
    }
}
 | 760 | 23.548387 | 70 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/AlprPlateResult.java | 
	package com.openalpr.jni;
import com.openalpr.jni.json.JSONArray;
import com.openalpr.jni.json.JSONException;
import com.openalpr.jni.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class AlprPlateResult {
    // The number requested is always >= the topNPlates count
    private final int requested_topn;
    // the best plate is the topNPlate with the highest confidence
    private final AlprPlate bestPlate;
    // A list of possible plate number permutations
    private List<AlprPlate> topNPlates;
    // The processing time for this plate
    private final float processing_time_ms;
    // the X/Y coordinates of the corners of the plate (clock-wise from top-left)
    private List<AlprCoordinate> plate_points;
    // The index of the plate if there were multiple plates returned
    private final int plate_index;
    // When region detection is enabled, this returns the region.  Region detection is experimental
    private final int regionConfidence;
    private final String region;
    AlprPlateResult(JSONObject plateResult) throws JSONException
    {
        requested_topn = plateResult.getInt("requested_topn");
        JSONArray candidatesArray = plateResult.getJSONArray("candidates");
        if (candidatesArray.length() > 0)
            bestPlate = new AlprPlate((JSONObject) candidatesArray.get(0));
        else
            bestPlate = null;
        topNPlates = new ArrayList<AlprPlate>(candidatesArray.length());
        for (int i = 0; i < candidatesArray.length(); i++)
        {
            JSONObject candidateObj = (JSONObject) candidatesArray.get(i);
            AlprPlate newPlate = new AlprPlate(candidateObj);
            topNPlates.add(newPlate);
        }
        JSONArray coordinatesArray = plateResult.getJSONArray("coordinates");
        plate_points = new ArrayList<AlprCoordinate>(coordinatesArray.length());
        for (int i = 0; i < coordinatesArray.length(); i++)
        {
            JSONObject coordinateObj = (JSONObject) coordinatesArray.get(i);
            AlprCoordinate coordinate = new AlprCoordinate(coordinateObj);
            plate_points.add(coordinate);
        }
        processing_time_ms = (float) plateResult.getDouble("processing_time_ms");
        plate_index = plateResult.getInt("plate_index");
        regionConfidence = plateResult.getInt("region_confidence");
        region = plateResult.getString("region");
    }
    public int getRequestedTopn() {
        return requested_topn;
    }
    public AlprPlate getBestPlate() {
        return bestPlate;
    }
    public List<AlprPlate> getTopNPlates() {
        return topNPlates;
    }
    public float getProcessingTimeMs() {
        return processing_time_ms;
    }
    public List<AlprCoordinate> getPlatePoints() {
        return plate_points;
    }
    public int getPlateIndex() {
        return plate_index;
    }
    public int getRegionConfidence() {
        return regionConfidence;
    }
    public String getRegion() {
        return region;
    }
}
 | 3,040 | 28.813725 | 99 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/AlprRegionOfInterest.java | 
	package com.openalpr.jni;
import com.openalpr.jni.json.JSONException;
import com.openalpr.jni.json.JSONObject;
public class AlprRegionOfInterest {
    private final int x;
    private final int y;
    private final int width;
    private final int height;
    AlprRegionOfInterest(JSONObject roiObj) throws JSONException
    {
        x = roiObj.getInt("x");
        y = roiObj.getInt("y");
        width = roiObj.getInt("width");
        height = roiObj.getInt("height");
    }
    public int getX() {
        return x;
    }
    public int getY() {
        return y;
    }
    public int getWidth() {
        return width;
    }
    public int getHeight() {
        return height;
    }
}
 | 699 | 17.918919 | 64 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/AlprResults.java | 
	package com.openalpr.jni;
import com.openalpr.jni.json.JSONArray;
import com.openalpr.jni.json.JSONException;
import com.openalpr.jni.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class AlprResults {
    private final long epoch_time;
    private final int img_width;
    private final int img_height;
    private final float total_processing_time_ms;
    private List<AlprPlateResult> plates;
    private List<AlprRegionOfInterest> regionsOfInterest;
    AlprResults(String json) throws JSONException
    {
        JSONObject jobj = new JSONObject(json);
        epoch_time = jobj.getLong("epoch_time");
        img_width = jobj.getInt("img_width");
        img_height = jobj.getInt("img_height");
        total_processing_time_ms = (float) jobj.getDouble("processing_time_ms");
        JSONArray resultsArray = jobj.getJSONArray("results");
        plates = new ArrayList<AlprPlateResult>(resultsArray.length());
        for (int i = 0; i < resultsArray.length(); i++)
        {
            JSONObject plateObj = (JSONObject) resultsArray.get(i);
            AlprPlateResult result = new AlprPlateResult(plateObj);
            plates.add(result);
        }
        JSONArray roisArray = jobj.getJSONArray("regions_of_interest");
        regionsOfInterest = new ArrayList<AlprRegionOfInterest>(roisArray.length());
        for (int i = 0; i < roisArray.length(); i++)
        {
            JSONObject roiObj = (JSONObject) roisArray.get(i);
            AlprRegionOfInterest roi = new AlprRegionOfInterest(roiObj);
            regionsOfInterest.add(roi);
        }
    }
    public long getEpochTime() {
        return epoch_time;
    }
    public int getImgWidth() {
        return img_width;
    }
    public int getImgHeight() {
        return img_height;
    }
    public float getTotalProcessingTimeMs() {
        return total_processing_time_ms;
    }
    public List<AlprPlateResult> getPlates() {
        return plates;
    }
    public List<AlprRegionOfInterest> getRegionsOfInterest() {
        return regionsOfInterest;
    }
}
 | 2,083 | 27.944444 | 84 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/json/JSON.java | 
	/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.openalpr.jni.json;
class JSON {
    /**
     * Returns the input if it is a JSON-permissible value; throws otherwise.
     */
    static double checkDouble(double d) throws JSONException {
        if (Double.isInfinite(d) || Double.isNaN(d)) {
            throw new JSONException("Forbidden numeric value: " + d);
        }
        return d;
    }
    static Boolean toBoolean(Object value) {
        if (value instanceof Boolean) {
            return (Boolean) value;
        } else if (value instanceof String) {
            String stringValue = (String) value;
            if ("true".equalsIgnoreCase(stringValue)) {
                return true;
            } else if ("false".equalsIgnoreCase(stringValue)) {
                return false;
            }
        }
        return null;
    }
    static Double toDouble(Object value) {
        if (value instanceof Double) {
            return (Double) value;
        } else if (value instanceof Number) {
            return ((Number) value).doubleValue();
        } else if (value instanceof String) {
            try {
                return Double.valueOf((String) value);
            } catch (NumberFormatException ignored) {
            }
        }
        return null;
    }
    static Integer toInteger(Object value) {
        if (value instanceof Integer) {
            return (Integer) value;
        } else if (value instanceof Number) {
            return ((Number) value).intValue();
        } else if (value instanceof String) {
            try {
                return (int) Double.parseDouble((String) value);
            } catch (NumberFormatException ignored) {
            }
        }
        return null;
    }
    static Long toLong(Object value) {
        if (value instanceof Long) {
            return (Long) value;
        } else if (value instanceof Number) {
            return ((Number) value).longValue();
        } else if (value instanceof String) {
            try {
                return (long) Double.parseDouble((String) value);
            } catch (NumberFormatException ignored) {
            }
        }
        return null;
    }
    static String toString(Object value) {
        if (value instanceof String) {
            return (String) value;
        } else if (value != null) {
            return String.valueOf(value);
        }
        return null;
    }
    public static JSONException typeMismatch(Object indexOrName, Object actual,
            String requiredType) throws JSONException {
        if (actual == null) {
            throw new JSONException("Value at " + indexOrName + " is null.");
        } else {
            throw new JSONException("Value " + actual + " at " + indexOrName
                    + " of type " + actual.getClass().getName()
                    + " cannot be converted to " + requiredType);
        }
    }
    public static JSONException typeMismatch(Object actual, String requiredType)
            throws JSONException {
        if (actual == null) {
            throw new JSONException("Value is null.");
        } else {
            throw new JSONException("Value " + actual
                    + " of type " + actual.getClass().getName()
                    + " cannot be converted to " + requiredType);
        }
    }
}
 | 3,897 | 32.316239 | 80 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/json/JSONArray.java | 
	/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.openalpr.jni.json;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
// Note: this class was written without inspecting the non-free org.json sourcecode.
/**
 * A dense indexed sequence of values. Values may be any mix of
 * {@link JSONObject JSONObjects}, other {@link JSONArray JSONArrays}, Strings,
 * Booleans, Integers, Longs, Doubles, {@code null} or {@link JSONObject#NULL}.
 * Values may not be {@link Double#isNaN() NaNs}, {@link Double#isInfinite()
 * infinities}, or of any type not listed here.
 *
 * <p>{@code JSONArray} has the same type coercion behavior and
 * optional/mandatory accessors as {@link JSONObject}. See that class'
 * documentation for details.
 *
 * <p><strong>Warning:</strong> this class represents null in two incompatible
 * ways: the standard Java {@code null} reference, and the sentinel value {@link
 * JSONObject#NULL}. In particular, {@code get} fails if the requested index
 * holds the null reference, but succeeds if it holds {@code JSONObject.NULL}.
 *
 * <p>Instances of this class are not thread safe. Although this class is
 * nonfinal, it was not designed for inheritance and should not be subclassed.
 * In particular, self-use by overridable methods is not specified. See
 * <i>Effective Java</i> Item 17, "Design and Document or inheritance or else
 * prohibit it" for further information.
 */
public class JSONArray {
    private final List<Object> values;
    /**
     * Creates a {@code JSONArray} with no values.
     */
    public JSONArray() {
        values = new ArrayList<Object>();
    }
    /**
     * Creates a new {@code JSONArray} by copying all values from the given
     * collection.
     *
     * @param copyFrom a collection whose values are of supported types.
     *     Unsupported values are not permitted and will yield an array in an
     *     inconsistent state.
     */
    /* Accept a raw type for API compatibility */
    public JSONArray(Collection copyFrom) {
        this();
        Collection<?> copyFromTyped = (Collection<?>) copyFrom;
        values.addAll(copyFromTyped);
    }
    /**
     * Creates a new {@code JSONArray} with values from the next array in the
     * tokener.
     *
     * @param readFrom a tokener whose nextValue() method will yield a
     *     {@code JSONArray}.
     * @throws JSONException if the parse fails or doesn't yield a
     *     {@code JSONArray}.
     */
    public JSONArray(JSONTokener readFrom) throws JSONException {
        /*
         * Getting the parser to populate this could get tricky. Instead, just
         * parse to temporary JSONArray and then steal the data from that.
         */
        Object object = readFrom.nextValue();
        if (object instanceof JSONArray) {
            values = ((JSONArray) object).values;
        } else {
            throw JSON.typeMismatch(object, "JSONArray");
        }
    }
    /**
     * Creates a new {@code JSONArray} with values from the JSON string.
     *
     * @param json a JSON-encoded string containing an array.
     * @throws JSONException if the parse fails or doesn't yield a {@code
     *     JSONArray}.
     */
    public JSONArray(String json) throws JSONException {
        this(new JSONTokener(json));
    }
    /**
     * Returns the number of values in this array.
     */
    public int length() {
        return values.size();
    }
    /**
     * Appends {@code value} to the end of this array.
     *
     * @return this array.
     */
    public JSONArray put(boolean value) {
        values.add(value);
        return this;
    }
    /**
     * Appends {@code value} to the end of this array.
     *
     * @param value a finite value. May not be {@link Double#isNaN() NaNs} or
     *     {@link Double#isInfinite() infinities}.
     * @return this array.
     */
    public JSONArray put(double value) throws JSONException {
        values.add(JSON.checkDouble(value));
        return this;
    }
    /**
     * Appends {@code value} to the end of this array.
     *
     * @return this array.
     */
    public JSONArray put(int value) {
        values.add(value);
        return this;
    }
    /**
     * Appends {@code value} to the end of this array.
     *
     * @return this array.
     */
    public JSONArray put(long value) {
        values.add(value);
        return this;
    }
    /**
     * Appends {@code value} to the end of this array.
     *
     * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean,
     *     Integer, Long, Double, {@link JSONObject#NULL}, or {@code null}. May
     *     not be {@link Double#isNaN() NaNs} or {@link Double#isInfinite()
     *     infinities}. Unsupported values are not permitted and will cause the
     *     array to be in an inconsistent state.
     * @return this array.
     */
    public JSONArray put(Object value) {
        values.add(value);
        return this;
    }
    /**
     * Sets the value at {@code index} to {@code value}, null padding this array
     * to the required length if necessary. If a value already exists at {@code
     * index}, it will be replaced.
     *
     * @return this array.
     */
    public JSONArray put(int index, boolean value) throws JSONException {
        return put(index, (Boolean) value);
    }
    /**
     * Sets the value at {@code index} to {@code value}, null padding this array
     * to the required length if necessary. If a value already exists at {@code
     * index}, it will be replaced.
     *
     * @param value a finite value. May not be {@link Double#isNaN() NaNs} or
     *     {@link Double#isInfinite() infinities}.
     * @return this array.
     */
    public JSONArray put(int index, double value) throws JSONException {
        return put(index, (Double) value);
    }
    /**
     * Sets the value at {@code index} to {@code value}, null padding this array
     * to the required length if necessary. If a value already exists at {@code
     * index}, it will be replaced.
     *
     * @return this array.
     */
    public JSONArray put(int index, int value) throws JSONException {
        return put(index, (Integer) value);
    }
    /**
     * Sets the value at {@code index} to {@code value}, null padding this array
     * to the required length if necessary. If a value already exists at {@code
     * index}, it will be replaced.
     *
     * @return this array.
     */
    public JSONArray put(int index, long value) throws JSONException {
        return put(index, (Long) value);
    }
    /**
     * Sets the value at {@code index} to {@code value}, null padding this array
     * to the required length if necessary. If a value already exists at {@code
     * index}, it will be replaced.
     *
     * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean,
     *     Integer, Long, Double, {@link JSONObject#NULL}, or {@code null}. May
     *     not be {@link Double#isNaN() NaNs} or {@link Double#isInfinite()
     *     infinities}.
     * @return this array.
     */
    public JSONArray put(int index, Object value) throws JSONException {
        if (value instanceof Number) {
            // deviate from the original by checking all Numbers, not just floats & doubles
            JSON.checkDouble(((Number) value).doubleValue());
        }
        while (values.size() <= index) {
            values.add(null);
        }
        values.set(index, value);
        return this;
    }
    /**
     * Returns true if this array has no value at {@code index}, or if its value
     * is the {@code null} reference or {@link JSONObject#NULL}.
     */
    public boolean isNull(int index) {
        Object value = opt(index);
        return value == null || value == JSONObject.NULL;
    }
    /**
     * Returns the value at {@code index}.
     *
     * @throws JSONException if this array has no value at {@code index}, or if
     *     that value is the {@code null} reference. This method returns
     *     normally if the value is {@code JSONObject#NULL}.
     */
    public Object get(int index) throws JSONException {
        try {
            Object value = values.get(index);
            if (value == null) {
                throw new JSONException("Value at " + index + " is null.");
            }
            return value;
        } catch (IndexOutOfBoundsException e) {
            throw new JSONException("Index " + index + " out of range [0.." + values.size() + ")");
        }
    }
    /**
     * Returns the value at {@code index}, or null if the array has no value
     * at {@code index}.
     */
    public Object opt(int index) {
        if (index < 0 || index >= values.size()) {
            return null;
        }
        return values.get(index);
    }
    /**
     * Returns the value at {@code index} if it exists and is a boolean or can
     * be coerced to a boolean.
     *
     * @throws JSONException if the value at {@code index} doesn't exist or
     *     cannot be coerced to a boolean.
     */
    public boolean getBoolean(int index) throws JSONException {
        Object object = get(index);
        Boolean result = JSON.toBoolean(object);
        if (result == null) {
            throw JSON.typeMismatch(index, object, "boolean");
        }
        return result;
    }
    /**
     * Returns the value at {@code index} if it exists and is a boolean or can
     * be coerced to a boolean. Returns false otherwise.
     */
    public boolean optBoolean(int index) {
        return optBoolean(index, false);
    }
    /**
     * Returns the value at {@code index} if it exists and is a boolean or can
     * be coerced to a boolean. Returns {@code fallback} otherwise.
     */
    public boolean optBoolean(int index, boolean fallback) {
        Object object = opt(index);
        Boolean result = JSON.toBoolean(object);
        return result != null ? result : fallback;
    }
    /**
     * Returns the value at {@code index} if it exists and is a double or can
     * be coerced to a double.
     *
     * @throws JSONException if the value at {@code index} doesn't exist or
     *     cannot be coerced to a double.
     */
    public double getDouble(int index) throws JSONException {
        Object object = get(index);
        Double result = JSON.toDouble(object);
        if (result == null) {
            throw JSON.typeMismatch(index, object, "double");
        }
        return result;
    }
    /**
     * Returns the value at {@code index} if it exists and is a double or can
     * be coerced to a double. Returns {@code NaN} otherwise.
     */
    public double optDouble(int index) {
        return optDouble(index, Double.NaN);
    }
    /**
     * Returns the value at {@code index} if it exists and is a double or can
     * be coerced to a double. Returns {@code fallback} otherwise.
     */
    public double optDouble(int index, double fallback) {
        Object object = opt(index);
        Double result = JSON.toDouble(object);
        return result != null ? result : fallback;
    }
    /**
     * Returns the value at {@code index} if it exists and is an int or
     * can be coerced to an int.
     *
     * @throws JSONException if the value at {@code index} doesn't exist or
     *     cannot be coerced to a int.
     */
    public int getInt(int index) throws JSONException {
        Object object = get(index);
        Integer result = JSON.toInteger(object);
        if (result == null) {
            throw JSON.typeMismatch(index, object, "int");
        }
        return result;
    }
    /**
     * Returns the value at {@code index} if it exists and is an int or
     * can be coerced to an int. Returns 0 otherwise.
     */
    public int optInt(int index) {
        return optInt(index, 0);
    }
    /**
     * Returns the value at {@code index} if it exists and is an int or
     * can be coerced to an int. Returns {@code fallback} otherwise.
     */
    public int optInt(int index, int fallback) {
        Object object = opt(index);
        Integer result = JSON.toInteger(object);
        return result != null ? result : fallback;
    }
    /**
     * Returns the value at {@code index} if it exists and is a long or
     * can be coerced to a long.
     *
     * @throws JSONException if the value at {@code index} doesn't exist or
     *     cannot be coerced to a long.
     */
    public long getLong(int index) throws JSONException {
        Object object = get(index);
        Long result = JSON.toLong(object);
        if (result == null) {
            throw JSON.typeMismatch(index, object, "long");
        }
        return result;
    }
    /**
     * Returns the value at {@code index} if it exists and is a long or
     * can be coerced to a long. Returns 0 otherwise.
     */
    public long optLong(int index) {
        return optLong(index, 0L);
    }
    /**
     * Returns the value at {@code index} if it exists and is a long or
     * can be coerced to a long. Returns {@code fallback} otherwise.
     */
    public long optLong(int index, long fallback) {
        Object object = opt(index);
        Long result = JSON.toLong(object);
        return result != null ? result : fallback;
    }
    /**
     * Returns the value at {@code index} if it exists, coercing it if
     * necessary.
     *
     * @throws JSONException if no such value exists.
     */
    public String getString(int index) throws JSONException {
        Object object = get(index);
        String result = JSON.toString(object);
        if (result == null) {
            throw JSON.typeMismatch(index, object, "String");
        }
        return result;
    }
    /**
     * Returns the value at {@code index} if it exists, coercing it if
     * necessary. Returns the empty string if no such value exists.
     */
    public String optString(int index) {
        return optString(index, "");
    }
    /**
     * Returns the value at {@code index} if it exists, coercing it if
     * necessary. Returns {@code fallback} if no such value exists.
     */
    public String optString(int index, String fallback) {
        Object object = opt(index);
        String result = JSON.toString(object);
        return result != null ? result : fallback;
    }
    /**
     * Returns the value at {@code index} if it exists and is a {@code
     * JSONArray}.
     *
     * @throws JSONException if the value doesn't exist or is not a {@code
     *     JSONArray}.
     */
    public JSONArray getJSONArray(int index) throws JSONException {
        Object object = get(index);
        if (object instanceof JSONArray) {
            return (JSONArray) object;
        } else {
            throw JSON.typeMismatch(index, object, "JSONArray");
        }
    }
    /**
     * Returns the value at {@code index} if it exists and is a {@code
     * JSONArray}. Returns null otherwise.
     */
    public JSONArray optJSONArray(int index) {
        Object object = opt(index);
        return object instanceof JSONArray ? (JSONArray) object : null;
    }
    /**
     * Returns the value at {@code index} if it exists and is a {@code
     * JSONObject}.
     *
     * @throws JSONException if the value doesn't exist or is not a {@code
     *     JSONObject}.
     */
    public JSONObject getJSONObject(int index) throws JSONException {
        Object object = get(index);
        if (object instanceof JSONObject) {
            return (JSONObject) object;
        } else {
            throw JSON.typeMismatch(index, object, "JSONObject");
        }
    }
    /**
     * Returns the value at {@code index} if it exists and is a {@code
     * JSONObject}. Returns null otherwise.
     */
    public JSONObject optJSONObject(int index) {
        Object object = opt(index);
        return object instanceof JSONObject ? (JSONObject) object : null;
    }
    /**
     * Returns a new object whose values are the values in this array, and whose
     * names are the values in {@code names}. Names and values are paired up by
     * index from 0 through to the shorter array's length. Names that are not
     * strings will be coerced to strings. This method returns null if either
     * array is empty.
     */
    public JSONObject toJSONObject(JSONArray names) throws JSONException {
        JSONObject result = new JSONObject();
        int length = Math.min(names.length(), values.size());
        if (length == 0) {
            return null;
        }
        for (int i = 0; i < length; i++) {
            String name = JSON.toString(names.opt(i));
            result.put(name, opt(i));
        }
        return result;
    }
    /**
     * Returns a new string by alternating this array's values with {@code
     * separator}. This array's string values are quoted and have their special
     * characters escaped. For example, the array containing the strings '12"
     * pizza', 'taco' and 'soda' joined on '+' returns this:
     * <pre>"12\" pizza"+"taco"+"soda"</pre>
     */
    public String join(String separator) throws JSONException {
        JSONStringer stringer = new JSONStringer();
        stringer.open(JSONStringer.Scope.NULL, "");
        for (int i = 0, size = values.size(); i < size; i++) {
            if (i > 0) {
                stringer.out.append(separator);
            }
            stringer.value(values.get(i));
        }
        stringer.close(JSONStringer.Scope.NULL, JSONStringer.Scope.NULL, "");
        return stringer.out.toString();
    }
    /**
     * Encodes this array as a compact JSON string, such as:
     * <pre>[94043,90210]</pre>
     */
    @Override public String toString() {
        try {
            JSONStringer stringer = new JSONStringer();
            writeTo(stringer);
            return stringer.toString();
        } catch (JSONException e) {
            return null;
        }
    }
    /**
     * Encodes this array as a human readable JSON string for debugging, such
     * as:
     * <pre>
     * [
     *     94043,
     *     90210
     * ]</pre>
     *
     * @param indentSpaces the number of spaces to indent for each level of
     *     nesting.
     */
    public String toString(int indentSpaces) throws JSONException {
        JSONStringer stringer = new JSONStringer(indentSpaces);
        writeTo(stringer);
        return stringer.toString();
    }
    void writeTo(JSONStringer stringer) throws JSONException {
        stringer.array();
        for (Object value : values) {
            stringer.value(value);
        }
        stringer.endArray();
    }
    @Override public boolean equals(Object o) {
        return o instanceof JSONArray && ((JSONArray) o).values.equals(values);
    }
    @Override public int hashCode() {
        // diverge from the original, which doesn't implement hashCode
        return values.hashCode();
    }
}
 | 19,400 | 32.107509 | 99 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/json/JSONException.java | 
	/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.openalpr.jni.json;
// Note: this class was written without inspecting the non-free org.json sourcecode.
/**
 * Thrown to indicate a problem with the JSON API. Such problems include:
 * <ul>
 *   <li>Attempts to parse or construct malformed documents
 *   <li>Use of null as a name
 *   <li>Use of numeric types not available to JSON, such as {@link
 *       Double#isNaN() NaNs} or {@link Double#isInfinite() infinities}.
 *   <li>Lookups using an out of range index or nonexistent name
 *   <li>Type mismatches on lookups
 * </ul>
 *
 * <p>Although this is a checked exception, it is rarely recoverable. Most
 * callers should simply wrap this exception in an unchecked exception and
 * rethrow:
 * <pre>  public JSONArray toJSONObject() {
 *     try {
 *         JSONObject result = new JSONObject();
 *         ...
 *     } catch (JSONException e) {
 *         throw new RuntimeException(e);
 *     }
 * }</pre>
 */
public class JSONException extends Exception {
    public JSONException(String s) {
        super(s);
    }
}
 | 1,665 | 32.32 | 84 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/json/JSONObject.java | 
	/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.openalpr.jni.json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
// Note: this class was written without inspecting the non-free org.json sourcecode.
/**
 * A modifiable set of name/value mappings. Names are unique, non-null strings.
 * Values may be any mix of {@link JSONObject JSONObjects}, {@link JSONArray
 * JSONArrays}, Strings, Booleans, Integers, Longs, Doubles or {@link #NULL}.
 * Values may not be {@code null}, {@link Double#isNaN() NaNs}, {@link
 * Double#isInfinite() infinities}, or of any type not listed here.
 *
 * <p>This class can coerce values to another type when requested.
 * <ul>
 *   <li>When the requested type is a boolean, strings will be coerced using a
 *       case-insensitive comparison to "true" and "false".
 *   <li>When the requested type is a double, other {@link Number} types will
 *       be coerced using {@link Number#doubleValue() doubleValue}. Strings
 *       that can be coerced using {@link Double#valueOf(String)} will be.
 *   <li>When the requested type is an int, other {@link Number} types will
 *       be coerced using {@link Number#intValue() intValue}. Strings
 *       that can be coerced using {@link Double#valueOf(String)} will be,
 *       and then cast to int.
 *   <li>When the requested type is a long, other {@link Number} types will
 *       be coerced using {@link Number#longValue() longValue}. Strings
 *       that can be coerced using {@link Double#valueOf(String)} will be,
 *       and then cast to long. This two-step conversion is lossy for very
 *       large values. For example, the string "9223372036854775806" yields the
 *       long 9223372036854775807.
 *   <li>When the requested type is a String, other non-null values will be
 *       coerced using {@link String#valueOf(Object)}. Although null cannot be
 *       coerced, the sentinel value {@link JSONObject#NULL} is coerced to the
 *       string "null".
 * </ul>
 *
 * <p>This class can look up both mandatory and optional values:
 * <ul>
 *   <li>Use <code>get<i>Type</i>()</code> to retrieve a mandatory value. This
 *       fails with a {@code JSONException} if the requested name has no value
 *       or if the value cannot be coerced to the requested type.
 *   <li>Use <code>opt<i>Type</i>()</code> to retrieve an optional value. This
 *       returns a system- or user-supplied default if the requested name has no
 *       value or if the value cannot be coerced to the requested type.
 * </ul>
 *
 * <p><strong>Warning:</strong> this class represents null in two incompatible
 * ways: the standard Java {@code null} reference, and the sentinel value {@link
 * JSONObject#NULL}. In particular, calling {@code put(name, null)} removes the
 * named entry from the object but {@code put(name, JSONObject.NULL)} stores an
 * entry whose value is {@code JSONObject.NULL}.
 *
 * <p>Instances of this class are not thread safe. Although this class is
 * nonfinal, it was not designed for inheritance and should not be subclassed.
 * In particular, self-use by overrideable methods is not specified. See
 * <i>Effective Java</i> Item 17, "Design and Document or inheritance or else
 * prohibit it" for further information.
 */
public class JSONObject {
    private static final Double NEGATIVE_ZERO = -0d;
    /**
     * A sentinel value used to explicitly define a name with no value. Unlike
     * {@code null}, names with this value:
     * <ul>
     *   <li>show up in the {@link #names} array
     *   <li>show up in the {@link #keys} iterator
     *   <li>return {@code true} for {@link #has(String)}
     *   <li>do not throw on {@link #get(String)}
     *   <li>are included in the encoded JSON string.
     * </ul>
     *
     * <p>This value violates the general contract of {@link Object#equals} by
     * returning true when compared to {@code null}. Its {@link #toString}
     * method returns "null".
     */
    public static final Object NULL = new Object() {
        @Override public boolean equals(Object o) {
            return o == this || o == null; // API specifies this broken equals implementation
        }
        @Override public String toString() {
            return "null";
        }
    };
    private final Map<String, Object> nameValuePairs;
    /**
     * Creates a {@code JSONObject} with no name/value mappings.
     */
    public JSONObject() {
        nameValuePairs = new HashMap<String, Object>();
    }
    /**
     * Creates a new {@code JSONObject} by copying all name/value mappings from
     * the given map.
     *
     * @param copyFrom a map whose keys are of type {@link String} and whose
     *     values are of supported types.
     * @throws NullPointerException if any of the map's keys are null.
     */
    /* (accept a raw type for API compatibility) */
    public JSONObject(Map copyFrom) {
        this();
        Map<?, ?> contentsTyped = (Map<?, ?>) copyFrom;
        for (Map.Entry<?, ?> entry : contentsTyped.entrySet()) {
            /*
             * Deviate from the original by checking that keys are non-null and
             * of the proper type. (We still defer validating the values).
             */
            String key = (String) entry.getKey();
            if (key == null) {
                throw new NullPointerException("key == null");
            }
            nameValuePairs.put(key, entry.getValue());
        }
    }
    /**
     * Creates a new {@code JSONObject} with name/value mappings from the next
     * object in the tokener.
     *
     * @param readFrom a tokener whose nextValue() method will yield a
     *     {@code JSONObject}.
     * @throws JSONException if the parse fails or doesn't yield a
     *     {@code JSONObject}.
     */
    public JSONObject(JSONTokener readFrom) throws JSONException {
        /*
         * Getting the parser to populate this could get tricky. Instead, just
         * parse to temporary JSONObject and then steal the data from that.
         */
        Object object = readFrom.nextValue();
        if (object instanceof JSONObject) {
            this.nameValuePairs = ((JSONObject) object).nameValuePairs;
        } else {
            throw JSON.typeMismatch(object, "JSONObject");
        }
    }
    /**
     * Creates a new {@code JSONObject} with name/value mappings from the JSON
     * string.
     *
     * @param json a JSON-encoded string containing an object.
     * @throws JSONException if the parse fails or doesn't yield a {@code
     *     JSONObject}.
     */
    public JSONObject(String json) throws JSONException {
        this(new JSONTokener(json));
    }
    /**
     * Creates a new {@code JSONObject} by copying mappings for the listed names
     * from the given object. Names that aren't present in {@code copyFrom} will
     * be skipped.
     */
    public JSONObject(JSONObject copyFrom, String[] names) throws JSONException {
        this();
        for (String name : names) {
            Object value = copyFrom.opt(name);
            if (value != null) {
                nameValuePairs.put(name, value);
            }
        }
    }
    /**
     * Returns the number of name/value mappings in this object.
     */
    public int length() {
        return nameValuePairs.size();
    }
    /**
     * Maps {@code name} to {@code value}, clobbering any existing name/value
     * mapping with the same name.
     *
     * @return this object.
     */
    public JSONObject put(String name, boolean value) throws JSONException {
        nameValuePairs.put(checkName(name), value);
        return this;
    }
    /**
     * Maps {@code name} to {@code value}, clobbering any existing name/value
     * mapping with the same name.
     *
     * @param value a finite value. May not be {@link Double#isNaN() NaNs} or
     *     {@link Double#isInfinite() infinities}.
     * @return this object.
     */
    public JSONObject put(String name, double value) throws JSONException {
        nameValuePairs.put(checkName(name), JSON.checkDouble(value));
        return this;
    }
    /**
     * Maps {@code name} to {@code value}, clobbering any existing name/value
     * mapping with the same name.
     *
     * @return this object.
     */
    public JSONObject put(String name, int value) throws JSONException {
        nameValuePairs.put(checkName(name), value);
        return this;
    }
    /**
     * Maps {@code name} to {@code value}, clobbering any existing name/value
     * mapping with the same name.
     *
     * @return this object.
     */
    public JSONObject put(String name, long value) throws JSONException {
        nameValuePairs.put(checkName(name), value);
        return this;
    }
    /**
     * Maps {@code name} to {@code value}, clobbering any existing name/value
     * mapping with the same name. If the value is {@code null}, any existing
     * mapping for {@code name} is removed.
     *
     * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean,
     *     Integer, Long, Double, {@link #NULL}, or {@code null}. May not be
     *     {@link Double#isNaN() NaNs} or {@link Double#isInfinite()
     *     infinities}.
     * @return this object.
     */
    public JSONObject put(String name, Object value) throws JSONException {
        if (value == null) {
            nameValuePairs.remove(name);
            return this;
        }
        if (value instanceof Number) {
            // deviate from the original by checking all Numbers, not just floats & doubles
            JSON.checkDouble(((Number) value).doubleValue());
        }
        nameValuePairs.put(checkName(name), value);
        return this;
    }
    /**
     * Equivalent to {@code put(name, value)} when both parameters are non-null;
     * does nothing otherwise.
     */
    public JSONObject putOpt(String name, Object value) throws JSONException {
        if (name == null || value == null) {
            return this;
        }
        return put(name, value);
    }
    /**
     * Appends {@code value} to the array already mapped to {@code name}. If
     * this object has no mapping for {@code name}, this inserts a new mapping.
     * If the mapping exists but its value is not an array, the existing
     * and new values are inserted in order into a new array which is itself
     * mapped to {@code name}. In aggregate, this allows values to be added to a
     * mapping one at a time.
     *
     * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean,
     *     Integer, Long, Double, {@link #NULL} or null. May not be {@link
     *     Double#isNaN() NaNs} or {@link Double#isInfinite() infinities}.
     */
    public JSONObject accumulate(String name, Object value) throws JSONException {
        Object current = nameValuePairs.get(checkName(name));
        if (current == null) {
            return put(name, value);
        }
        // check in accumulate, since array.put(Object) doesn't do any checking
        if (value instanceof Number) {
            JSON.checkDouble(((Number) value).doubleValue());
        }
        if (current instanceof JSONArray) {
            JSONArray array = (JSONArray) current;
            array.put(value);
        } else {
            JSONArray array = new JSONArray();
            array.put(current);
            array.put(value);
            nameValuePairs.put(name, array);
        }
        return this;
    }
    String checkName(String name) throws JSONException {
        if (name == null) {
            throw new JSONException("Names must be non-null");
        }
        return name;
    }
    /**
     * Removes the named mapping if it exists; does nothing otherwise.
     *
     * @return the value previously mapped by {@code name}, or null if there was
     *     no such mapping.
     */
    public Object remove(String name) {
        return nameValuePairs.remove(name);
    }
    /**
     * Returns true if this object has no mapping for {@code name} or if it has
     * a mapping whose value is {@link #NULL}.
     */
    public boolean isNull(String name) {
        Object value = nameValuePairs.get(name);
        return value == null || value == NULL;
    }
    /**
     * Returns true if this object has a mapping for {@code name}. The mapping
     * may be {@link #NULL}.
     */
    public boolean has(String name) {
        return nameValuePairs.containsKey(name);
    }
    /**
     * Returns the value mapped by {@code name}.
     *
     * @throws JSONException if no such mapping exists.
     */
    public Object get(String name) throws JSONException {
        Object result = nameValuePairs.get(name);
        if (result == null) {
            throw new JSONException("No value for " + name);
        }
        return result;
    }
    /**
     * Returns the value mapped by {@code name}, or null if no such mapping
     * exists.
     */
    public Object opt(String name) {
        return nameValuePairs.get(name);
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a boolean or
     * can be coerced to a boolean.
     *
     * @throws JSONException if the mapping doesn't exist or cannot be coerced
     *     to a boolean.
     */
    public boolean getBoolean(String name) throws JSONException {
        Object object = get(name);
        Boolean result = JSON.toBoolean(object);
        if (result == null) {
            throw JSON.typeMismatch(name, object, "boolean");
        }
        return result;
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a boolean or
     * can be coerced to a boolean. Returns false otherwise.
     */
    public boolean optBoolean(String name) {
        return optBoolean(name, false);
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a boolean or
     * can be coerced to a boolean. Returns {@code fallback} otherwise.
     */
    public boolean optBoolean(String name, boolean fallback) {
        Object object = opt(name);
        Boolean result = JSON.toBoolean(object);
        return result != null ? result : fallback;
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a double or
     * can be coerced to a double.
     *
     * @throws JSONException if the mapping doesn't exist or cannot be coerced
     *     to a double.
     */
    public double getDouble(String name) throws JSONException {
        Object object = get(name);
        Double result = JSON.toDouble(object);
        if (result == null) {
            throw JSON.typeMismatch(name, object, "double");
        }
        return result;
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a double or
     * can be coerced to a double. Returns {@code NaN} otherwise.
     */
    public double optDouble(String name) {
        return optDouble(name, Double.NaN);
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a double or
     * can be coerced to a double. Returns {@code fallback} otherwise.
     */
    public double optDouble(String name, double fallback) {
        Object object = opt(name);
        Double result = JSON.toDouble(object);
        return result != null ? result : fallback;
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is an int or
     * can be coerced to an int.
     *
     * @throws JSONException if the mapping doesn't exist or cannot be coerced
     *     to an int.
     */
    public int getInt(String name) throws JSONException {
        Object object = get(name);
        Integer result = JSON.toInteger(object);
        if (result == null) {
            throw JSON.typeMismatch(name, object, "int");
        }
        return result;
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is an int or
     * can be coerced to an int. Returns 0 otherwise.
     */
    public int optInt(String name) {
        return optInt(name, 0);
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is an int or
     * can be coerced to an int. Returns {@code fallback} otherwise.
     */
    public int optInt(String name, int fallback) {
        Object object = opt(name);
        Integer result = JSON.toInteger(object);
        return result != null ? result : fallback;
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a long or
     * can be coerced to a long.
     *
     * @throws JSONException if the mapping doesn't exist or cannot be coerced
     *     to a long.
     */
    public long getLong(String name) throws JSONException {
        Object object = get(name);
        Long result = JSON.toLong(object);
        if (result == null) {
            throw JSON.typeMismatch(name, object, "long");
        }
        return result;
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a long or
     * can be coerced to a long. Returns 0 otherwise.
     */
    public long optLong(String name) {
        return optLong(name, 0L);
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a long or
     * can be coerced to a long. Returns {@code fallback} otherwise.
     */
    public long optLong(String name, long fallback) {
        Object object = opt(name);
        Long result = JSON.toLong(object);
        return result != null ? result : fallback;
    }
    /**
     * Returns the value mapped by {@code name} if it exists, coercing it if
     * necessary.
     *
     * @throws JSONException if no such mapping exists.
     */
    public String getString(String name) throws JSONException {
        Object object = get(name);
        String result = JSON.toString(object);
        if (result == null) {
            throw JSON.typeMismatch(name, object, "String");
        }
        return result;
    }
    /**
     * Returns the value mapped by {@code name} if it exists, coercing it if
     * necessary. Returns the empty string if no such mapping exists.
     */
    public String optString(String name) {
        return optString(name, "");
    }
    /**
     * Returns the value mapped by {@code name} if it exists, coercing it if
     * necessary. Returns {@code fallback} if no such mapping exists.
     */
    public String optString(String name, String fallback) {
        Object object = opt(name);
        String result = JSON.toString(object);
        return result != null ? result : fallback;
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a {@code
     * JSONArray}.
     *
     * @throws JSONException if the mapping doesn't exist or is not a {@code
     *     JSONArray}.
     */
    public JSONArray getJSONArray(String name) throws JSONException {
        Object object = get(name);
        if (object instanceof JSONArray) {
            return (JSONArray) object;
        } else {
            throw JSON.typeMismatch(name, object, "JSONArray");
        }
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a {@code
     * JSONArray}. Returns null otherwise.
     */
    public JSONArray optJSONArray(String name) {
        Object object = opt(name);
        return object instanceof JSONArray ? (JSONArray) object : null;
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a {@code
     * JSONObject}.
     *
     * @throws JSONException if the mapping doesn't exist or is not a {@code
     *     JSONObject}.
     */
    public JSONObject getJSONObject(String name) throws JSONException {
        Object object = get(name);
        if (object instanceof JSONObject) {
            return (JSONObject) object;
        } else {
            throw JSON.typeMismatch(name, object, "JSONObject");
        }
    }
    /**
     * Returns the value mapped by {@code name} if it exists and is a {@code
     * JSONObject}. Returns null otherwise.
     */
    public JSONObject optJSONObject(String name) {
        Object object = opt(name);
        return object instanceof JSONObject ? (JSONObject) object : null;
    }
    /**
     * Returns an array with the values corresponding to {@code names}. The
     * array contains null for names that aren't mapped. This method returns
     * null if {@code names} is either null or empty.
     */
    public JSONArray toJSONArray(JSONArray names) throws JSONException {
        JSONArray result = new JSONArray();
        if (names == null) {
            return null;
        }
        int length = names.length();
        if (length == 0) {
            return null;
        }
        for (int i = 0; i < length; i++) {
            String name = JSON.toString(names.opt(i));
            result.put(opt(name));
        }
        return result;
    }
    /**
     * Returns an iterator of the {@code String} names in this object. The
     * returned iterator supports {@link Iterator#remove() remove}, which will
     * remove the corresponding mapping from this object. If this object is
     * modified after the iterator is returned, the iterator's behavior is
     * undefined. The order of the keys is undefined.
     */
    /* Return a raw type for API compatibility */
    public Iterator keys() {
        return nameValuePairs.keySet().iterator();
    }
    /**
     * Returns an array containing the string names in this object. This method
     * returns null if this object contains no mappings.
     */
    public JSONArray names() {
        return nameValuePairs.isEmpty()
                ? null
                : new JSONArray(new ArrayList<String>(nameValuePairs.keySet()));
    }
    /**
     * Encodes this object as a compact JSON string, such as:
     * <pre>{"query":"Pizza","locations":[94043,90210]}</pre>
     */
    @Override public String toString() {
        try {
            JSONStringer stringer = new JSONStringer();
            writeTo(stringer);
            return stringer.toString();
        } catch (JSONException e) {
            return null;
        }
    }
    /**
     * Encodes this object as a human readable JSON string for debugging, such
     * as:
     * <pre>
     * {
     *     "query": "Pizza",
     *     "locations": [
     *         94043,
     *         90210
     *     ]
     * }</pre>
     *
     * @param indentSpaces the number of spaces to indent for each level of
     *     nesting.
     */
    public String toString(int indentSpaces) throws JSONException {
        JSONStringer stringer = new JSONStringer(indentSpaces);
        writeTo(stringer);
        return stringer.toString();
    }
    void writeTo(JSONStringer stringer) throws JSONException {
        stringer.object();
        for (Map.Entry<String, Object> entry : nameValuePairs.entrySet()) {
            stringer.key(entry.getKey()).value(entry.getValue());
        }
        stringer.endObject();
    }
    /**
     * Encodes the number as a JSON string.
     *
     * @param number a finite value. May not be {@link Double#isNaN() NaNs} or
     *     {@link Double#isInfinite() infinities}.
     */
    public static String numberToString(Number number) throws JSONException {
        if (number == null) {
            throw new JSONException("Number must be non-null");
        }
        double doubleValue = number.doubleValue();
        JSON.checkDouble(doubleValue);
        // the original returns "-0" instead of "-0.0" for negative zero
        if (number.equals(NEGATIVE_ZERO)) {
            return "-0";
        }
        long longValue = number.longValue();
        if (doubleValue == (double) longValue) {
            return Long.toString(longValue);
        }
        return number.toString();
    }
    /**
     * Encodes {@code data} as a JSON string. This applies quotes and any
     * necessary character escaping.
     *
     * @param data the string to encode. Null will be interpreted as an empty
     *     string.
     */
    public static String quote(String data) {
        if (data == null) {
            return "\"\"";
        }
        try {
            JSONStringer stringer = new JSONStringer();
            stringer.open(JSONStringer.Scope.NULL, "");
            stringer.value(data);
            stringer.close(JSONStringer.Scope.NULL, JSONStringer.Scope.NULL, "");
            return stringer.toString();
        } catch (JSONException e) {
            throw new AssertionError();
        }
    }
}
 | 25,009 | 33.687933 | 93 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/json/JSONStringer.java | 
	/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.openalpr.jni.json;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// Note: this class was written without inspecting the non-free org.json sourcecode.
/**
 * Implements {@link JSONObject#toString} and {@link JSONArray#toString}. Most
 * application developers should use those methods directly and disregard this
 * API. For example:<pre>
 * JSONObject object = ...
 * String json = object.toString();</pre>
 *
 * <p>Stringers only encode well-formed JSON strings. In particular:
 * <ul>
 *   <li>The stringer must have exactly one top-level array or object.
 *   <li>Lexical scopes must be balanced: every call to {@link #array} must
 *       have a matching call to {@link #endArray} and every call to {@link
 *       #object} must have a matching call to {@link #endObject}.
 *   <li>Arrays may not contain keys (property names).
 *   <li>Objects must alternate keys (property names) and values.
 *   <li>Values are inserted with either literal {@link #value(Object) value}
 *       calls, or by nesting arrays or objects.
 * </ul>
 * Calls that would result in a malformed JSON string will fail with a
 * {@link JSONException}.
 *
 * <p>This class provides no facility for pretty-printing (ie. indenting)
 * output. To encode indented output, use {@link JSONObject#toString(int)} or
 * {@link JSONArray#toString(int)}.
 *
 * <p>Some implementations of the API support at most 20 levels of nesting.
 * Attempts to create more than 20 levels of nesting may fail with a {@link
 * JSONException}.
 *
 * <p>Each stringer may be used to encode a single top level value. Instances of
 * this class are not thread safe. Although this class is nonfinal, it was not
 * designed for inheritance and should not be subclassed. In particular,
 * self-use by overrideable methods is not specified. See <i>Effective Java</i>
 * Item 17, "Design and Document or inheritance or else prohibit it" for further
 * information.
 */
public class JSONStringer {
    /** The output data, containing at most one top-level array or object. */
    final StringBuilder out = new StringBuilder();
    /**
     * Lexical scoping elements within this stringer, necessary to insert the
     * appropriate separator characters (ie. commas and colons) and to detect
     * nesting errors.
     */
    enum Scope {
        /**
         * An array with no elements requires no separators or newlines before
         * it is closed.
         */
        EMPTY_ARRAY,
        /**
         * A array with at least one value requires a comma and newline before
         * the next element.
         */
        NONEMPTY_ARRAY,
        /**
         * An object with no keys or values requires no separators or newlines
         * before it is closed.
         */
        EMPTY_OBJECT,
        /**
         * An object whose most recent element is a key. The next element must
         * be a value.
         */
        DANGLING_KEY,
        /**
         * An object with at least one name/value pair requires a comma and
         * newline before the next element.
         */
        NONEMPTY_OBJECT,
        /**
         * A special bracketless array needed by JSONStringer.join() and
         * JSONObject.quote() only. Not used for JSON encoding.
         */
        NULL,
    }
    /**
     * Unlike the original implementation, this stack isn't limited to 20
     * levels of nesting.
     */
    private final List<Scope> stack = new ArrayList<Scope>();
    /**
     * A string containing a full set of spaces for a single level of
     * indentation, or null for no pretty printing.
     */
    private final String indent;
    public JSONStringer() {
        indent = null;
    }
    JSONStringer(int indentSpaces) {
        char[] indentChars = new char[indentSpaces];
        Arrays.fill(indentChars, ' ');
        indent = new String(indentChars);
    }
    /**
     * Begins encoding a new array. Each call to this method must be paired with
     * a call to {@link #endArray}.
     *
     * @return this stringer.
     */
    public JSONStringer array() throws JSONException {
        return open(Scope.EMPTY_ARRAY, "[");
    }
    /**
     * Ends encoding the current array.
     *
     * @return this stringer.
     */
    public JSONStringer endArray() throws JSONException {
        return close(Scope.EMPTY_ARRAY, Scope.NONEMPTY_ARRAY, "]");
    }
    /**
     * Begins encoding a new object. Each call to this method must be paired
     * with a call to {@link #endObject}.
     *
     * @return this stringer.
     */
    public JSONStringer object() throws JSONException {
        return open(Scope.EMPTY_OBJECT, "{");
    }
    /**
     * Ends encoding the current object.
     *
     * @return this stringer.
     */
    public JSONStringer endObject() throws JSONException {
        return close(Scope.EMPTY_OBJECT, Scope.NONEMPTY_OBJECT, "}");
    }
    /**
     * Enters a new scope by appending any necessary whitespace and the given
     * bracket.
     */
    JSONStringer open(Scope empty, String openBracket) throws JSONException {
        if (stack.isEmpty() && out.length() > 0) {
            throw new JSONException("Nesting problem: multiple top-level roots");
        }
        beforeValue();
        stack.add(empty);
        out.append(openBracket);
        return this;
    }
    /**
     * Closes the current scope by appending any necessary whitespace and the
     * given bracket.
     */
    JSONStringer close(Scope empty, Scope nonempty, String closeBracket) throws JSONException {
        Scope context = peek();
        if (context != nonempty && context != empty) {
            throw new JSONException("Nesting problem");
        }
        stack.remove(stack.size() - 1);
        if (context == nonempty) {
            newline();
        }
        out.append(closeBracket);
        return this;
    }
    /**
     * Returns the value on the top of the stack.
     */
    private Scope peek() throws JSONException {
        if (stack.isEmpty()) {
            throw new JSONException("Nesting problem");
        }
        return stack.get(stack.size() - 1);
    }
    /**
     * Replace the value on the top of the stack with the given value.
     */
    private void replaceTop(Scope topOfStack) {
        stack.set(stack.size() - 1, topOfStack);
    }
    /**
     * Encodes {@code value}.
     *
     * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean,
     *     Integer, Long, Double or null. May not be {@link Double#isNaN() NaNs}
     *     or {@link Double#isInfinite() infinities}.
     * @return this stringer.
     */
    public JSONStringer value(Object value) throws JSONException {
        if (stack.isEmpty()) {
            throw new JSONException("Nesting problem");
        }
        if (value instanceof JSONArray) {
            ((JSONArray) value).writeTo(this);
            return this;
        } else if (value instanceof JSONObject) {
            ((JSONObject) value).writeTo(this);
            return this;
        }
        beforeValue();
        if (value == null
                || value instanceof Boolean
                || value == JSONObject.NULL) {
            out.append(value);
        } else if (value instanceof Number) {
            out.append(JSONObject.numberToString((Number) value));
        } else {
            string(value.toString());
        }
        return this;
    }
    /**
     * Encodes {@code value} to this stringer.
     *
     * @return this stringer.
     */
    public JSONStringer value(boolean value) throws JSONException {
        if (stack.isEmpty()) {
            throw new JSONException("Nesting problem");
        }
        beforeValue();
        out.append(value);
        return this;
    }
    /**
     * Encodes {@code value} to this stringer.
     *
     * @param value a finite value. May not be {@link Double#isNaN() NaNs} or
     *     {@link Double#isInfinite() infinities}.
     * @return this stringer.
     */
    public JSONStringer value(double value) throws JSONException {
        if (stack.isEmpty()) {
            throw new JSONException("Nesting problem");
        }
        beforeValue();
        out.append(JSONObject.numberToString(value));
        return this;
    }
    /**
     * Encodes {@code value} to this stringer.
     *
     * @return this stringer.
     */
    public JSONStringer value(long value) throws JSONException {
        if (stack.isEmpty()) {
            throw new JSONException("Nesting problem");
        }
        beforeValue();
        out.append(value);
        return this;
    }
    private void string(String value) {
        out.append("\"");
        for (int i = 0, length = value.length(); i < length; i++) {
            char c = value.charAt(i);
            /*
             * From RFC 4627, "All Unicode characters may be placed within the
             * quotation marks except for the characters that must be escaped:
             * quotation mark, reverse solidus, and the control characters
             * (U+0000 through U+001F)."
             */
            switch (c) {
                case '"':
                case '\\':
                case '/':
                    out.append('\\').append(c);
                    break;
                case '\t':
                    out.append("\\t");
                    break;
                case '\b':
                    out.append("\\b");
                    break;
                case '\n':
                    out.append("\\n");
                    break;
                case '\r':
                    out.append("\\r");
                    break;
                case '\f':
                    out.append("\\f");
                    break;
                default:
                    if (c <= 0x1F) {
                        out.append(String.format("\\u%04x", (int) c));
                    } else {
                        out.append(c);
                    }
                    break;
            }
        }
        out.append("\"");
    }
    private void newline() {
        if (indent == null) {
            return;
        }
        out.append("\n");
        for (int i = 0; i < stack.size(); i++) {
            out.append(indent);
        }
    }
    /**
     * Encodes the key (property name) to this stringer.
     *
     * @param name the name of the forthcoming value. May not be null.
     * @return this stringer.
     */
    public JSONStringer key(String name) throws JSONException {
        if (name == null) {
            throw new JSONException("Names must be non-null");
        }
        beforeKey();
        string(name);
        return this;
    }
    /**
     * Inserts any necessary separators and whitespace before a name. Also
     * adjusts the stack to expect the key's value.
     */
    private void beforeKey() throws JSONException {
        Scope context = peek();
        if (context == Scope.NONEMPTY_OBJECT) { // first in object
            out.append(',');
        } else if (context != Scope.EMPTY_OBJECT) { // not in an object!
            throw new JSONException("Nesting problem");
        }
        newline();
        replaceTop(Scope.DANGLING_KEY);
    }
    /**
     * Inserts any necessary separators and whitespace before a literal value,
     * inline array, or inline object. Also adjusts the stack to expect either a
     * closing bracket or another element.
     */
    private void beforeValue() throws JSONException {
        if (stack.isEmpty()) {
            return;
        }
        Scope context = peek();
        if (context == Scope.EMPTY_ARRAY) { // first in array
            replaceTop(Scope.NONEMPTY_ARRAY);
            newline();
        } else if (context == Scope.NONEMPTY_ARRAY) { // another in array
            out.append(',');
            newline();
        } else if (context == Scope.DANGLING_KEY) { // value for key
            out.append(indent == null ? ":" : ": ");
            replaceTop(Scope.NONEMPTY_OBJECT);
        } else if (context != Scope.NULL) {
            throw new JSONException("Nesting problem");
        }
    }
    /**
     * Returns the encoded JSON string.
     *
     * <p>If invoked with unterminated arrays or unclosed objects, this method's
     * return value is undefined.
     *
     * <p><strong>Warning:</strong> although it contradicts the general contract
     * of {@link Object#toString}, this method returns null if the stringer
     * contains no data.
     */
    @Override public String toString() {
        return out.length() == 0 ? null : out.toString();
    }
}
 | 13,199 | 29.484988 | 95 | 
	java | 
| 
	openalpr | 
	openalpr-master/src/bindings/java/src/com/openalpr/jni/json/JSONTokener.java | 
	/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.openalpr.jni.json;
// Note: this class was written without inspecting the non-free org.json sourcecode.
/**
 * Parses a JSON (<a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>)
 * encoded string into the corresponding object. Most clients of
 * this class will use only need the {@link #JSONTokener(String) constructor}
 * and {@link #nextValue} method. Example usage: <pre>
 * String json = "{"
 *         + "  \"query\": \"Pizza\", "
 *         + "  \"locations\": [ 94043, 90210 ] "
 *         + "}";
 *
 * JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
 * String query = object.getString("query");
 * JSONArray locations = object.getJSONArray("locations");</pre>
 *
 * <p>For best interoperability and performance use JSON that complies with
 * RFC 4627, such as that generated by {@link JSONStringer}. For legacy reasons
 * this parser is lenient, so a successful parse does not indicate that the
 * input string was valid JSON. All of the following syntax errors will be
 * ignored:
 * <ul>
 *   <li>End of line comments starting with {@code //} or {@code #} and ending
 *       with a newline character.
 *   <li>C-style comments starting with {@code /*} and ending with
 *       {@code *}{@code /}. Such comments may not be nested.
 *   <li>Strings that are unquoted or {@code 'single quoted'}.
 *   <li>Hexadecimal integers prefixed with {@code 0x} or {@code 0X}.
 *   <li>Octal integers prefixed with {@code 0}.
 *   <li>Array elements separated by {@code ;}.
 *   <li>Unnecessary array separators. These are interpreted as if null was the
 *       omitted value.
 *   <li>Key-value pairs separated by {@code =} or {@code =>}.
 *   <li>Key-value pairs separated by {@code ;}.
 * </ul>
 *
 * <p>Each tokener may be used to parse a single JSON string. Instances of this
 * class are not thread safe. Although this class is nonfinal, it was not
 * designed for inheritance and should not be subclassed. In particular,
 * self-use by overrideable methods is not specified. See <i>Effective Java</i>
 * Item 17, "Design and Document or inheritance or else prohibit it" for further
 * information.
 */
public class JSONTokener {
    /** The input JSON. */
    private final String in;
    /**
     * The index of the next character to be returned by {@link #next}. When
     * the input is exhausted, this equals the input's length.
     */
    private int pos;
    /**
     * @param in JSON encoded string. Null is not permitted and will yield a
     *     tokener that throws {@code NullPointerExceptions} when methods are
     *     called.
     */
    public JSONTokener(String in) {
        // consume an optional byte order mark (BOM) if it exists
        if (in != null && in.startsWith("\ufeff")) {
            in = in.substring(1);
        }
        this.in = in;
    }
    /**
     * Returns the next value from the input.
     *
     * @return a {@link JSONObject}, {@link JSONArray}, String, Boolean,
     *     Integer, Long, Double or {@link JSONObject#NULL}.
     * @throws JSONException if the input is malformed.
     */
    public Object nextValue() throws JSONException {
        int c = nextCleanInternal();
        switch (c) {
            case -1:
                throw syntaxError("End of input");
            case '{':
                return readObject();
            case '[':
                return readArray();
            case '\'':
            case '"':
                return nextString((char) c);
            default:
                pos--;
                return readLiteral();
        }
    }
    private int nextCleanInternal() throws JSONException {
        while (pos < in.length()) {
            int c = in.charAt(pos++);
            switch (c) {
                case '\t':
                case ' ':
                case '\n':
                case '\r':
                    continue;
                case '/':
                    if (pos == in.length()) {
                        return c;
                    }
                    char peek = in.charAt(pos);
                    switch (peek) {
                        case '*':
                            // skip a /* c-style comment */
                            pos++;
                            int commentEnd = in.indexOf("*/", pos);
                            if (commentEnd == -1) {
                                throw syntaxError("Unterminated comment");
                            }
                            pos = commentEnd + 2;
                            continue;
                        case '/':
                            // skip a // end-of-line comment
                            pos++;
                            skipToEndOfLine();
                            continue;
                        default:
                            return c;
                    }
                case '#':
                    /*
                     * Skip a # hash end-of-line comment. The JSON RFC doesn't
                     * specify this behavior, but it's required to parse
                     * existing documents. See http://b/2571423.
                     */
                    skipToEndOfLine();
                    continue;
                default:
                    return c;
            }
        }
        return -1;
    }
    /**
     * Advances the position until after the next newline character. If the line
     * is terminated by "\r\n", the '\n' must be consumed as whitespace by the
     * caller.
     */
    private void skipToEndOfLine() {
        for (; pos < in.length(); pos++) {
            char c = in.charAt(pos);
            if (c == '\r' || c == '\n') {
                pos++;
                break;
            }
        }
    }
    /**
     * Returns the string up to but not including {@code quote}, unescaping any
     * character escape sequences encountered along the way. The opening quote
     * should have already been read. This consumes the closing quote, but does
     * not include it in the returned string.
     *
     * @param quote either ' or ".
     * @throws NumberFormatException if any unicode escape sequences are
     *     malformed.
     */
    public String nextString(char quote) throws JSONException {
        /*
         * For strings that are free of escape sequences, we can just extract
         * the result as a substring of the input. But if we encounter an escape
         * sequence, we need to use a StringBuilder to compose the result.
         */
        StringBuilder builder = null;
        /* the index of the first character not yet appended to the builder. */
        int start = pos;
        while (pos < in.length()) {
            int c = in.charAt(pos++);
            if (c == quote) {
                if (builder == null) {
                    // a new string avoids leaking memory
                    return new String(in.substring(start, pos - 1));
                } else {
                    builder.append(in, start, pos - 1);
                    return builder.toString();
                }
            }
            if (c == '\\') {
                if (pos == in.length()) {
                    throw syntaxError("Unterminated escape sequence");
                }
                if (builder == null) {
                    builder = new StringBuilder();
                }
                builder.append(in, start, pos - 1);
                builder.append(readEscapeCharacter());
                start = pos;
            }
        }
        throw syntaxError("Unterminated string");
    }
    /**
     * Unescapes the character identified by the character or characters that
     * immediately follow a backslash. The backslash '\' should have already
     * been read. This supports both unicode escapes "u000A" and two-character
     * escapes "\n".
     *
     * @throws NumberFormatException if any unicode escape sequences are
     *     malformed.
     */
    private char readEscapeCharacter() throws JSONException {
        char escaped = in.charAt(pos++);
        switch (escaped) {
            case 'u':
                if (pos + 4 > in.length()) {
                    throw syntaxError("Unterminated escape sequence");
                }
                String hex = in.substring(pos, pos + 4);
                pos += 4;
                return (char) Integer.parseInt(hex, 16);
            case 't':
                return '\t';
            case 'b':
                return '\b';
            case 'n':
                return '\n';
            case 'r':
                return '\r';
            case 'f':
                return '\f';
            case '\'':
            case '"':
            case '\\':
            default:
                return escaped;
        }
    }
    /**
     * Reads a null, boolean, numeric or unquoted string literal value. Numeric
     * values will be returned as an Integer, Long, or Double, in that order of
     * preference.
     */
    private Object readLiteral() throws JSONException {
        String literal = nextToInternal("{}[]/\\:,=;# \t\f");
        if (literal.length() == 0) {
            throw syntaxError("Expected literal value");
        } else if ("null".equalsIgnoreCase(literal)) {
            return JSONObject.NULL;
        } else if ("true".equalsIgnoreCase(literal)) {
            return Boolean.TRUE;
        } else if ("false".equalsIgnoreCase(literal)) {
            return Boolean.FALSE;
        }
        /* try to parse as an integral type... */
        if (literal.indexOf('.') == -1) {
            int base = 10;
            String number = literal;
            if (number.startsWith("0x") || number.startsWith("0X")) {
                number = number.substring(2);
                base = 16;
            } else if (number.startsWith("0") && number.length() > 1) {
                number = number.substring(1);
                base = 8;
            }
            try {
                long longValue = Long.parseLong(number, base);
                if (longValue <= Integer.MAX_VALUE && longValue >= Integer.MIN_VALUE) {
                    return (int) longValue;
                } else {
                    return longValue;
                }
            } catch (NumberFormatException e) {
                /*
                 * This only happens for integral numbers greater than
                 * Long.MAX_VALUE, numbers in exponential form (5e-10) and
                 * unquoted strings. Fall through to try floating point.
                 */
            }
        }
        /* ...next try to parse as a floating point... */
        try {
            return Double.valueOf(literal);
        } catch (NumberFormatException ignored) {
        }
        /* ... finally give up. We have an unquoted string */
        return new String(literal); // a new string avoids leaking memory
    }
    /**
     * Returns the string up to but not including any of the given characters or
     * a newline character. This does not consume the excluded character.
     */
    private String nextToInternal(String excluded) {
        int start = pos;
        for (; pos < in.length(); pos++) {
            char c = in.charAt(pos);
            if (c == '\r' || c == '\n' || excluded.indexOf(c) != -1) {
                return in.substring(start, pos);
            }
        }
        return in.substring(start);
    }
    /**
     * Reads a sequence of key/value pairs and the trailing closing brace '}' of
     * an object. The opening brace '{' should have already been read.
     */
    private JSONObject readObject() throws JSONException {
        JSONObject result = new JSONObject();
        /* Peek to see if this is the empty object. */
        int first = nextCleanInternal();
        if (first == '}') {
            return result;
        } else if (first != -1) {
            pos--;
        }
        while (true) {
            Object name = nextValue();
            if (!(name instanceof String)) {
                if (name == null) {
                    throw syntaxError("Names cannot be null");
                } else {
                    throw syntaxError("Names must be strings, but " + name
                            + " is of type " + name.getClass().getName());
                }
            }
            /*
             * Expect the name/value separator to be either a colon ':', an
             * equals sign '=', or an arrow "=>". The last two are bogus but we
             * include them because that's what the original implementation did.
             */
            int separator = nextCleanInternal();
            if (separator != ':' && separator != '=') {
                throw syntaxError("Expected ':' after " + name);
            }
            if (pos < in.length() && in.charAt(pos) == '>') {
                pos++;
            }
            result.put((String) name, nextValue());
            switch (nextCleanInternal()) {
                case '}':
                    return result;
                case ';':
                case ',':
                    continue;
                default:
                    throw syntaxError("Unterminated object");
            }
        }
    }
    /**
     * Reads a sequence of values and the trailing closing brace ']' of an
     * array. The opening brace '[' should have already been read. Note that
     * "[]" yields an empty array, but "[,]" returns a two-element array
     * equivalent to "[null,null]".
     */
    private JSONArray readArray() throws JSONException {
        JSONArray result = new JSONArray();
        /* to cover input that ends with ",]". */
        boolean hasTrailingSeparator = false;
        while (true) {
            switch (nextCleanInternal()) {
                case -1:
                    throw syntaxError("Unterminated array");
                case ']':
                    if (hasTrailingSeparator) {
                        result.put(null);
                    }
                    return result;
                case ',':
                case ';':
                    /* A separator without a value first means "null". */
                    result.put(null);
                    hasTrailingSeparator = true;
                    continue;
                default:
                    pos--;
            }
            result.put(nextValue());
            switch (nextCleanInternal()) {
                case ']':
                    return result;
                case ',':
                case ';':
                    hasTrailingSeparator = true;
                    continue;
                default:
                    throw syntaxError("Unterminated array");
            }
        }
    }
    /**
     * Returns an exception containing the given message plus the current
     * position and the entire input string.
     */
    public JSONException syntaxError(String message) {
        return new JSONException(message + this);
    }
    /**
     * Returns the current position and the entire input string.
     */
    @Override public String toString() {
        // consistent with the original implementation
        return " at character " + pos + " of " + in;
    }
    /*
     * Legacy APIs.
     *
     * None of the methods below are on the critical path of parsing JSON
     * documents. They exist only because they were exposed by the original
     * implementation and may be used by some clients.
     */
    /**
     * Returns true until the input has been exhausted.
     */
    public boolean more() {
        return pos < in.length();
    }
    /**
     * Returns the next available character, or the null character '\0' if all
     * input has been exhausted. The return value of this method is ambiguous
     * for JSON strings that contain the character '\0'.
     */
    public char next() {
        return pos < in.length() ? in.charAt(pos++) : '\0';
    }
    /**
     * Returns the next available character if it equals {@code c}. Otherwise an
     * exception is thrown.
     */
    public char next(char c) throws JSONException {
        char result = next();
        if (result != c) {
            throw syntaxError("Expected " + c + " but was " + result);
        }
        return result;
    }
    /**
     * Returns the next character that is not whitespace and does not belong to
     * a comment. If the input is exhausted before such a character can be
     * found, the null character '\0' is returned. The return value of this
     * method is ambiguous for JSON strings that contain the character '\0'.
     */
    public char nextClean() throws JSONException {
        int nextCleanInt = nextCleanInternal();
        return nextCleanInt == -1 ? '\0' : (char) nextCleanInt;
    }
    /**
     * Returns the next {@code length} characters of the input.
     *
     * <p>The returned string shares its backing character array with this
     * tokener's input string. If a reference to the returned string may be held
     * indefinitely, you should use {@code new String(result)} to copy it first
     * to avoid memory leaks.
     *
     * @throws JSONException if the remaining input is not long enough to
     *     satisfy this request.
     */
    public String next(int length) throws JSONException {
        if (pos + length > in.length()) {
            throw syntaxError(length + " is out of bounds");
        }
        String result = in.substring(pos, pos + length);
        pos += length;
        return result;
    }
    /**
     * Returns the {@link String#trim trimmed} string holding the characters up
     * to but not including the first of:
     * <ul>
     *   <li>any character in {@code excluded}
     *   <li>a newline character '\n'
     *   <li>a carriage return '\r'
     * </ul>
     *
     * <p>The returned string shares its backing character array with this
     * tokener's input string. If a reference to the returned string may be held
     * indefinitely, you should use {@code new String(result)} to copy it first
     * to avoid memory leaks.
     *
     * @return a possibly-empty string
     */
    public String nextTo(String excluded) {
        if (excluded == null) {
            throw new NullPointerException("excluded == null");
        }
        return nextToInternal(excluded).trim();
    }
    /**
     * Equivalent to {@code nextTo(String.valueOf(excluded))}.
     */
    public String nextTo(char excluded) {
        return nextToInternal(String.valueOf(excluded)).trim();
    }
    /**
     * Advances past all input up to and including the next occurrence of
     * {@code through}. If the remaining input doesn't contain {@code through}, the
     * input is exhausted.
     */
    public void skipPast(String through) {
        int throughStart = in.indexOf(through, pos);
        pos = throughStart == -1 ? in.length() : (throughStart + through.length());
    }
    /**
     * Advances past all input up to but not including the next occurrence of
     * {@code to}. If the remaining input doesn't contain {@code to}, the input
     * is unchanged.
     */
    public char skipTo(char to) {
        int index = in.indexOf(to, pos);
        if (index != -1) {
            pos = index;
            return to;
        } else {
            return '\0';
        }
    }
    /**
     * Unreads the most recent character of input. If no input characters have
     * been read, the input is unchanged.
     */
    public void back() {
        if (--pos == -1) {
            pos = 0;
        }
    }
    /**
     * Returns the integer [0..15] value for the given hex character, or -1
     * for non-hex input.
     *
     * @param hex a character in the ranges [0-9], [A-F] or [a-f]. Any other
     *     character will yield a -1 result.
     */
    public static int dehexchar(char hex) {
        if (hex >= '0' && hex <= '9') {
            return hex - '0';
        } else if (hex >= 'A' && hex <= 'F') {
            return hex - 'A' + 10;
        } else if (hex >= 'a' && hex <= 'f') {
            return hex - 'a' + 10;
        } else {
            return -1;
        }
    }
}
 | 20,681 | 32.794118 | 87 | 
	java | 
| 
	openwhisk | 
	openwhisk-master/core/scheduler/src/main/java/Empty.java | 
	/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class Empty {
    // Workaround for this issue https://github.com/akka/akka-grpc/issues/289
    // Gradle complains about no java sources.
    // Note. Openwhisk is using a lower gradle version, so the latest akka-grpc version cannot be used.
}
 | 1,055 | 44.913043 | 103 | 
	java | 
| 
	openwhisk | 
	openwhisk-master/tests/dat/actions/src/java/sleep/src/main/java/Sleep.java | 
	/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Build instructions:
 * - Assumption: the dependency GSON is in the local dicrectory, e.g. "gson-2.8.2.jar"
 * - Compile with "javac -cp gson-2.8.2.jar Sleep.java"
 * - Create .jar archive with "jar cvf sleep.jar Sleep.class"
 */
/**
 * Java based OpenWhisk action that sleeps for the specified number
 * of milliseconds before returning.
 * The function actually sleeps slightly longer than requested.
 *
 * @param parm JSON object with Number property sleepTimeInMs
 * @returns JSON object with String property msg describing how long the function slept
 */
import com.google.gson.JsonObject;
public class Sleep {
    public static JsonObject main(JsonObject parm) throws InterruptedException {
        int sleepTimeInMs = 1;
        if (parm.has("sleepTimeInMs")) {
            sleepTimeInMs = parm.getAsJsonPrimitive("sleepTimeInMs").getAsInt();
        }
        System.out.println("Specified sleep time is " + sleepTimeInMs + " ms.");
        final String responseText = "Terminated successfully after around " + sleepTimeInMs + " ms.";
        final JsonObject response = new JsonObject();
        response.addProperty("msg", responseText);
        Thread.sleep(sleepTimeInMs);
        System.out.println(responseText);
        return response;
    }
}
 | 2,074 | 38.150943 | 101 | 
	java | 
| 
	openwhisk | 
	openwhisk-master/tests/dat/actions/unicode.tests/src/java/unicode/src/main/java/Unicode.java | 
	/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import com.google.gson.JsonObject;
public class Unicode {
    public static JsonObject main(JsonObject args) throws InterruptedException {
        String delimiter = args.getAsJsonPrimitive("delimiter").getAsString();
        JsonObject response = new JsonObject();
        String str = delimiter + " ☃ " + delimiter;
        System.out.println(str);
        response.addProperty("winter", str);
        return response;
    }
}
 | 1,233 | 40.133333 | 80 | 
	java | 
| 
	openwhisk | 
	openwhisk-master/tests/performance/gatling_tests/src/gatling/resources/data/src/java/src/main/java/JavaAction.java | 
	/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Build the jar with the following commands:
//
// javac -cp gson-2.8.2.jar JavaAction.java
// jar cvf javaAction.jar JavaAction.class
import com.google.gson.JsonObject;
public class JavaAction {
    public static JsonObject main(JsonObject args) {
        String text;
        try {
            text = args.getAsJsonPrimitive("text").getAsString();
        } catch(Exception e) {
            text = "stranger";
        }
        JsonObject response = new JsonObject();
        System.out.println("Hello " + text + "!");
        response.addProperty("payload", "Hello " + text + "!");
        return response;
    }
}
 | 1,426 | 33.804878 | 75 | 
	java | 
| 
	openwhisk | 
	openwhisk-master/tests/src/test/scala/common/Pair.java | 
	/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package common;
public class Pair {
    public final String fst;
    public final String snd;
    public Pair(String a, String b) {
        this.fst = a;
        this.snd = b;
    }
}
 | 989 | 33.137931 | 75 | 
	java | 
| 
	openwhisk | 
	openwhisk-master/tests/src/test/scala/common/TestUtils.java | 
	/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package common;
import static common.TestUtils.RunResult.executor;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import junit.runner.Version;
/**
 * Miscellaneous utilities used in whisk test suite
 */
public class TestUtils {
    protected static final Logger logger = Logger.getLogger("basic");
    public static final int SUCCESS_EXIT        = 0;
    public static final int ERROR_EXIT          = 1;
    public static final int MISUSE_EXIT         = 2;
    public static final int NETWORK_ERROR_EXIT  = 3;
    public static final int DONTCARE_EXIT       = -1;       // any value is ok
    public static final int ANY_ERROR_EXIT      = -2;       // any non-zero value is ok
    public static final int ACCEPTED        = 202;      // 202
    public static final int BAD_REQUEST     = 144;      // 400 - 256 = 144
    public static final int UNAUTHORIZED    = 145;      // 401 - 256 = 145
    public static final int FORBIDDEN       = 147;      // 403 - 256 = 147
    public static final int NOT_FOUND       = 148;      // 404 - 256 = 148
    public static final int NOT_ALLOWED     = 149;      // 405 - 256 = 149
    public static final int CONFLICT        = 153;      // 409 - 256 = 153
    public static final int TOO_LARGE       = 157;      // 413 - 256 = 157
    public static final int THROTTLED       = 173;      // 429 (TOO_MANY_REQUESTS) - 256 = 173
    public static final int APP_ERROR       = 246;      // 502 - 256 = 246
    public static final int TIMEOUT         = 246;      // 502 (GATEWAY_TIMEOUT) - 256 = 246
    private static final File catalogDir = WhiskProperties.getFileRelativeToWhiskHome("catalog");
    private static final File testActionsDir = WhiskProperties.getFileRelativeToWhiskHome("tests/dat/actions");
    private static final File testApiGwDir = WhiskProperties.getFileRelativeToWhiskHome("tests/dat/apigw");
    private static final File vcapFile = WhiskProperties.getVCAPServicesFile();
    private static final String envServices = System.getenv("VCAP_SERVICES");
    private static final String loggerLevel = System.getProperty("LOG_LEVEL", Level.WARNING.toString());
    static {
        logger.setLevel(Level.parse(loggerLevel.trim()));
        System.out.println("JUnit version is: " + Version.id());
    }
    /**
     * Gets path to file relative to catalog directory.
     *
     * (@)deprecated this method will be removed in future version; use {@link #getTestActionFilename()} instead
     * @param name relative filename
     */
    public static String getCatalogFilename(String name) {
        return new File(catalogDir, name).toString();
    }
    /**
     * Gets path to test action file relative to test catalog directory.
     *
     * @param name the filename of the test action
     * @return
     */
    public static String getTestActionFilename(String name) {
        return new File(testActionsDir, name).toString();
    }
    /**
     * Gets path to test apigw file relative to test catalog directory.
     *
     * @param name the filename of the test action
     * @return
     */
    public static String getTestApiGwFilename(String name) {
        return new File(testApiGwDir, name).toString();
    }
    /**
     * Gets the value of VCAP_SERVICES.
     *
     * @return VCAP_SERVICES as a JSON object
     */
    public static JsonObject getVCAPServices() {
        try {
            if (envServices != null) {
                return new JsonParser().parse(envServices).getAsJsonObject();
            } else {
                return new JsonParser().parse(new FileReader(vcapFile)).getAsJsonObject();
            }
        } catch (Throwable t) {
            System.out.println("failed to parse VCAP" + t);
            return new JsonObject();
        }
    }
    /**
     * Gets a VCAP_SERVICES credentials.
     *
     * @return VCAP credentials as a <String, String> map for each
     *         <property, value> pair in credentials
     */
    public static Map<String, String> getVCAPcredentials(String vcapService) {
        try {
            JsonObject credentials = getCredentials(vcapService);
            Map<String, String> map = new HashMap<String, String>();
            for (Map.Entry<String, JsonElement> entry : credentials.entrySet()) {
                map.put(entry.getKey(), credentials.get(entry.getKey()).getAsString());
            }
            return map;
        } catch (Throwable t) {
            System.out.println("failed to parse VCAP" + t);
            return Collections.emptyMap();
        }
    }
    /**
     * Gets a VCAP_SERVICES credentials as the json objects.
     *
     * @return VCAP credentials as a json object.
     */
    public static JsonObject getCredentials(String vcapService) {
        JsonArray vcapArray = getVCAPServices().get(vcapService).getAsJsonArray();
        JsonObject vcapObject = vcapArray.get(0).getAsJsonObject();
        JsonObject credentials = vcapObject.get("credentials").getAsJsonObject();
        return credentials;
    }
    /**
     * Creates a JUnit test watcher. Use with @rule.
     * @return a junit {@link TestWatcher} that prints a message when each test starts and ends
     */
    public static TestWatcher makeTestWatcher() {
        return new TestWatcher() {
            protected void starting(Description description) {
                System.out.format("\nStarting test %s at %s\n", description.getMethodName(), getDateTime());
            }
            protected void finished(Description description) {
                System.out.format("Finished test %s at %s\n\n", description.getMethodName(), getDateTime());
            }
        };
    }
    /**
     * @return a formatted string representing the date and time
     */
    public static String getDateTime() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        return sdf.format(date);
    }
    /**
     * @return a formatted string representing the time of day
     */
    public static String getTime() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
        return sdf.format(date);
    }
    /**
     * Determines if the test build is running for main repo and not on any fork or PR
     */
    public static boolean isBuildingOnMainRepo(){
        //Based on https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables
        String repoName = System.getenv("TRAVIS_REPO_SLUG");
        if (repoName == null) {
            return false; //Not a travis build
        } else {
            return repoName.startsWith("apache/") && "false".equals(System.getenv("TRAVIS_PULL_REQUEST"));
        }
    }
    /**
     * Encapsulates the result of running a native command, providing:
     *   exitCode the exit code of the process
     *   stdout the messages printed to standard out
     *   stderr the messages printed to standard error
     */
    public static class RunResult {
        public static final ExecutorService executor = Executors.newFixedThreadPool(2);
        public final int exitCode;
        public final String stdout;
        public final String stderr;
        protected RunResult(int exitCode, String stdout, String stderr) {
            this.exitCode = exitCode;
            this.stdout = stdout;
            this.stderr = stderr;
        }
        public Pair logs() {
            return new Pair(stdout, stderr);
        }
        public void validateExitCode(int expectedExitCode) {
            if (expectedExitCode == TestUtils.DONTCARE_EXIT)
                return;
            boolean ok = (exitCode == expectedExitCode) || (expectedExitCode == TestUtils.ANY_ERROR_EXIT && exitCode != 0);
            if (!ok) {
                System.out.format("expected exit code = %d\n%s", expectedExitCode, toString());
                assertTrue("Exit code:" + exitCode, exitCode == expectedExitCode);
            }
        }
        @Override
        public String toString() {
            StringBuilder fmt = new StringBuilder();
            fmt.append(String.format("exit code = %d\n", exitCode));
            fmt.append(String.format("stdout: %s\n", stdout));
            fmt.append(String.format("stderr: %s\n", stderr));
            return fmt.toString();
        }
    }
    /**
     * Runs a command in another process.
     *
     * @param expectedExitCode the expected exit code for the process
     * @param dir the working directory the command runs with
     * @param params the parameters (including executable) to run
     * @return RunResult instance
     * @throws IOException
     */
    public static RunResult runCmd(int expectedExitCode, File dir, String... params) throws IOException {
        return runCmd(expectedExitCode, dir, logger, null, params);
    }
    /**
     * Runs a command in another process.
     *
     * @param expectedExitCode the exit code expected from the command when it exists
     * @param dir the working directory the command runs with
     * @param logger the object to manage logging message
     * @param env an environment map
     * @param params the parameters (including executable) to run
     * @return RunResult instance
     * @throws IOException
     */
    public static RunResult runCmd(int expectedExitCode, File dir, Logger logger, Map<String, String> env, String... params) throws IOException {
        return runCmd(expectedExitCode, dir, logger, env, null, params);
    }
    /**
     * Runs a command in another process.
     *
     * @param expectedExitCode the exit code expected from the command when it exists
     * @param dir the working directory the command runs with
     * @param logger the object to manage logging message
     * @param env an environment map
     * @param fileStdin a file to use as the command's stdin input
     * @param params the parameters (including executable) to run
     * @return RunResult instance
     * @throws IOException
     */
    public static RunResult runCmd(int expectedExitCode, File dir, Logger logger, Map<String, String> env, File fileStdin, String... params) throws IOException {
        ProcessBuilder pb = new ProcessBuilder(params);
        pb.directory(dir);
        if (env != null) {
            pb.environment().putAll(env);
        }
        if (fileStdin != null) {
            pb.redirectInput(fileStdin);
        }
        Process p = pb.start();
        Future<String> stdoutFuture = executor.submit(() -> inputStreamToString(p.getInputStream()));
        Future<String> stderrFuture = executor.submit(() -> inputStreamToString(p.getErrorStream()));
        String stdout = "";
        String stderr = "";
        try {
            stdout = stdoutFuture.get();
            stderr = stderrFuture.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        RunResult rr = new RunResult(p.exitValue(), stdout, stderr);
        if (logger != null) {
            logger.info("RunResult: " + rr);
        }
        rr.validateExitCode(expectedExitCode);
        return rr;
    }
    private static String inputStreamToString(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append(System.getProperty("line.separator"));
        }
        return builder.toString();
    }
}
 | 13,197 | 37.034582 | 161 | 
	java | 
| 
	openwhisk | 
	openwhisk-master/tests/src/test/scala/common/WhiskProperties.java | 
	/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package common;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Properties;
import static org.junit.Assert.assertTrue;
/**
 * Properties that describe a whisk installation
 */
public class WhiskProperties {
    /**
     * System property key which refers to OpenWhisk Edge Host url
     */
    public static final String WHISK_SERVER = "whisk.server";
    /**
     * System property key which refers to authentication key to be used for testing
     */
    private static final String WHISK_AUTH = "whisk.auth";
    /**
     * The name of the properties file.
     */
    protected static final String WHISK_PROPS_FILE = "whisk.properties";
    /**
     * Default concurrency level if otherwise unspecified
     */
    private static final int DEFAULT_CONCURRENCY = 20;
    /**
     * If true, then tests will direct to the router rather than the edge
     * components.
     */
    public static final boolean testRouter = System.getProperty("test.router", "false").equals("true");
    /**
     * The root of the whisk installation, used to retrieve files relative to
     * home.
     */
    private static final String whiskHome;
    /**
     * The properties read from the WHISK_PROPS_FILE.
     */
    private static final Properties whiskProperties;
    static {
        /**
         * Finds the whisk home directory. This is resolved to either (in
         * order):
         *
         * 1. a system property openwhisk.dir
         *
         * 2. OPENWHISK_HOME from the environment
         *
         * 3. a path in the directory tree containing WHISK_PROPS_FILE.
         *
         * @return the path to whisk home as a string
         * @throws assertion
         *             failure if whisk home cannot be determined
         */
        String wskdir = System.getProperty("openwhisk.home", System.getenv("OPENWHISK_HOME"));
        if (wskdir == null) {
            String dir = System.getProperty("user.dir");
            if (dir != null) {
                File propfile = findFileRecursively(dir, WHISK_PROPS_FILE);
                if (propfile != null) {
                    wskdir = propfile.getParent();
                }
            }
        }
        assertTrue("could not determine openwhisk home", wskdir != null);
        if (isWhiskPropertiesRequired()) {
            File wskpropsFile = new File(wskdir, WHISK_PROPS_FILE);
            assertTrue(String.format("'%s' does not exists but required", wskpropsFile), wskpropsFile.exists());
            // loads properties from file
            whiskProperties = loadProperties(wskpropsFile);
            // set whisk home from read properties
            whiskHome = whiskProperties.getProperty("openwhisk.home");
        } else {
            whiskProperties = new Properties();
            whiskHome = wskdir;
        }
        System.out.format("test router? %s\n", testRouter);
    }
    /**
     * The path to the Go CLI executable.
     */
    public static String getCLIPath() {
        return whiskHome + "/bin/wsk";
    }
    public static File getFileRelativeToWhiskHome(String name) {
        return new File(whiskHome, name);
    }
    public static int getControllerInstances() {
        return Integer.parseInt(whiskProperties.getProperty("controller.instances"));
    }
    public static String getProperty(String name) {
        return whiskProperties.getProperty(name);
    }
    public static Boolean getBooleanProperty(String name, Boolean defaultValue) {
        String value = whiskProperties.getProperty(name);
        if (value == null) {
            return defaultValue;
        }
        return Boolean.parseBoolean(value);
    }
    public static String getKafkaHosts() {
        return whiskProperties.getProperty("kafka.hosts");
    }
    public static int getKafkaMonitorPort() {
        return Integer.parseInt(whiskProperties.getProperty("kafkaras.host.port"));
    }
    public static String getZookeeperHost() {
        return whiskProperties.getProperty("zookeeper.hosts");
    }
    public static String getMainDockerEndpoint() {
        return whiskProperties.getProperty("main.docker.endpoint");
    }
    public static String[] getInvokerHosts() {
        // split of empty string is non-empty array
        String hosts = whiskProperties.getProperty("invoker.hosts");
        return (hosts == null || hosts.equals("")) ? new String[0] : hosts.split(",");
    }
    public static String[] getAdditionalHosts() {
        // split of empty string is non-empty array
        String hosts = whiskProperties.getProperty("additional.hosts");
        return (hosts == null || hosts.equals("")) ? new String[0] : hosts.split(",");
    }
    public static int numberOfInvokers() {
        return getInvokerHosts().length;
    }
    public static boolean isSSLCheckRelaxed() {
        return Boolean.valueOf(getPropFromSystemOrEnv("whisk.ssl.relax"));
    }
    public static String getSslCertificateChallenge() {
        return whiskProperties.getProperty("whisk.ssl.challenge");
    }
    /**
     * Note that when testRouter == true, we pretend the router host is edge
     * host.
     */
    public static String getEdgeHost() {
        String server = getPropFromSystemOrEnv(WHISK_SERVER);
        if (server != null) {
            return server;
        }
        return testRouter ? getRouterHost() : whiskProperties.getProperty("edge.host");
    }
    public static String getRealEdgeHost() {
        return whiskProperties.getProperty("edge.host");
    }
    public static String getAuthForTesting() {
        return whiskProperties.getProperty("testing.auth");
    }
    public static String getRouterHost() {
        return whiskProperties.getProperty("router.host");
    }
    public static String getApiProto() {
        return whiskProperties.getProperty("whisk.api.host.proto");
    }
    public static String getApiHost() {
        return whiskProperties.getProperty("whisk.api.host.name");
    }
    public static String getApiPort() {
        return whiskProperties.getProperty("whisk.api.host.port");
    }
    public static String getApiHostForAction() {
        String apihost = getApiProto() + "://" + getApiHost() + ":" + getApiPort();
        if (apihost.startsWith("https://") && apihost.endsWith(":443")) {
            return apihost.replaceAll(":443", "");
        } else if (apihost.startsWith("http://") && apihost.endsWith(":80")) {
            return apihost.replaceAll(":80", "");
        } else return apihost;
    }
    public static String getApiHostForClient(String subdomain, boolean includeProtocol) {
        String proto = whiskProperties.getProperty("whisk.api.host.proto");
        String port = whiskProperties.getProperty("whisk.api.host.port");
        String host = whiskProperties.getProperty("whisk.api.localhost.name");
        if (includeProtocol) {
            return proto + "://" + subdomain + "." + host + ":" + port;
        } else {
            return subdomain + "." + host + ":" + port;
        }
    }
    public static int getPartsInVanitySubdomain() {
        return Integer.parseInt(whiskProperties.getProperty("whisk.api.vanity.subdomain.parts"));
    }
    public static int getEdgeHostApiPort() {
        return Integer.parseInt(whiskProperties.getProperty("edge.host.apiport"));
    }
    public static String getControllerHosts() {
        return whiskProperties.getProperty("controller.hosts");
    }
    public static String getDBHosts() {
        return whiskProperties.getProperty("db.hostsList");
    }
    public static int getControllerBasePort() {
        return Integer.parseInt(whiskProperties.getProperty("controller.host.basePort"));
    }
    public static String getBaseControllerHost() {
        return getControllerHosts().split(",")[0];
    }
    public static String getBaseDBHost() {
        return getDBHosts().split(",")[0];
    }
    public static String getBaseControllerAddress() {
        return getBaseControllerHost() + ":" + getControllerBasePort();
    }
    public static String getBaseInvokerAddress(){
        return getInvokerHosts()[0] + ":" + whiskProperties.getProperty("invoker.hosts.basePort");
    }
    public static int getMaxActionInvokesPerMinute() {
        String valStr = whiskProperties.getProperty("limits.actions.invokes.perMinute");
        return Integer.parseInt(valStr);
    }
    /**
     * read the contents of auth key file and return as a Pair
     * <username,password>
     */
    public static Pair getBasicAuth() {
        File f = getAuthFileForTesting();
        String contents = readAuthKey(f);
        String[] parts = contents.split(":");
        assert parts.length == 2;
        return new Pair(parts[0], parts[1]);
    }
    /**
     * @return the path to a file holding the auth key used during junit testing
     */
    public static File getAuthFileForTesting() {
        String testAuth = getAuthForTesting();
        if (testAuth.startsWith(File.separator)) {
            return new File(testAuth);
        } else {
            return WhiskProperties.getFileRelativeToWhiskHome(testAuth);
        }
    }
    /**
     * read the contents of a file which holds an auth key.
     */
    public static String readAuthKey(File filename) {
        // the following funny relative path works both from Eclipse and when
        // running in bin/ directory from ant
        try {
            byte[] encoded = Files.readAllBytes(filename.toPath());
            String authKey = new String(encoded, "UTF-8").trim();
            return authKey;
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
    /**
     * Returns auth key to be used for testing
     */
    public static String getAuthKeyForTesting() {
        String authKey = getPropFromSystemOrEnv(WHISK_AUTH);
        if (authKey == null) {
            authKey = readAuthKey(getAuthFileForTesting());
        }
        return authKey;
    }
    /**
     * @return the path to a file holding the VCAP_SERVICES used during junit
     *         testing
     */
    public static File getVCAPServicesFile() {
        String vcapServices = whiskProperties.getProperty("vcap.services.file");
        if (vcapServices == null) {
            return null;
        } else if (vcapServices.startsWith(File.separator)) {
            return new File(vcapServices);
        } else {
            return WhiskProperties.getFileRelativeToWhiskHome(vcapServices);
        }
    }
    /**
     * are we running on Mac OS X?
     */
    public static boolean onMacOSX() {
        String osname = System.getProperty("os.name");
        return osname.toLowerCase().contains("mac");
    }
    /**
     * are we running on Linux?
     */
    public static boolean onLinux() {
        String osname = System.getProperty("os.name");
        return osname.equalsIgnoreCase("linux");
    }
    public static int getMaxActionSizeMB(){
        return Integer.parseInt(getProperty("whisk.action.size.max", "10"));
    }
    /**
     * python interpreter.
     */
    public static final String python = "python";
    protected static File findFileRecursively(String dir, String needle) {
        if (dir != null) {
            File base = new File(dir);
            File file = new File(base, needle);
            if (file.exists()) {
                return file;
            } else {
                return findFileRecursively(base.getParent(), needle);
            }
        } else {
            return null;
        }
    }
    /**
     * Load properties from whisk.properties
     */
    protected static Properties loadProperties(File propsFile) {
        Properties props = new Properties();
        InputStream input = null;
        try {
            input = new FileInputStream(propsFile);
            // load a properties file
            props.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return props;
    }
    private static boolean isWhiskPropertiesRequired() {
        return getPropFromSystemOrEnv(WHISK_SERVER) == null;
    }
    public static String getProperty(String key, String defaultValue) {
        String value = getPropFromSystemOrEnv(key);
        if (value == null) {
            value = whiskProperties.getProperty(key, defaultValue);
        }
        return value;
    }
    private static String getPropFromSystemOrEnv(String key) {
        String value = System.getProperty(key);
        if (value == null) {
            value = System.getenv(toEnvName(key));
        }
        return value;
    }
    private static String toEnvName(String p) {
        return p.replace('.', '_').toUpperCase();
    }
}
 | 13,806 | 30.74023 | 112 | 
	java | 
| 
	openwhisk | 
	openwhisk-master/tests/src/test/scala/org/apache/openwhisk/core/database/cosmosdb/RecordingLeakDetector.java | 
	/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.openwhisk.core.database.cosmosdb;
import io.netty.util.ResourceLeakDetector;
import org.apache.openwhisk.common.Counter;
public class RecordingLeakDetector<T> extends ResourceLeakDetector<T> {
    private final Counter counter;
    public RecordingLeakDetector(Counter counter, Class<?> resourceType, int samplingInterval) {
        super(resourceType, samplingInterval);
        this.counter = counter;
    }
    @Override
    protected void reportTracedLeak(String resourceType, String records) {
        super.reportTracedLeak(resourceType, records);
        counter.next();
    }
    @Override
    protected void reportUntracedLeak(String resourceType) {
        super.reportUntracedLeak(resourceType);
        counter.next();
    }
}
 | 1,565 | 36.285714 | 96 | 
	java | 
| 
	openwhisk | 
	openwhisk-master/tests/src/test/scala/org/apache/openwhisk/core/database/cosmosdb/RecordingLeakDetectorFactory.java | 
	/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.openwhisk.core.database.cosmosdb;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakDetectorFactory;
import org.apache.openwhisk.common.Counter;
public class RecordingLeakDetectorFactory extends ResourceLeakDetectorFactory {
    static final Counter counter = new Counter();
    @Override
    @SuppressWarnings("deprecation")
    public <T> ResourceLeakDetector<T> newResourceLeakDetector(Class<T> resource, int samplingInterval, long maxActive) {
        return new RecordingLeakDetector<T>(counter, resource, samplingInterval);
    }
    public static void register() {
        ResourceLeakDetectorFactory.setResourceLeakDetectorFactory(new RecordingLeakDetectorFactory());
    }
}
 | 1,535 | 41.666667 | 121 | 
	java | 
| 
	criu | 
	criu-master/test/javaTests/src/org/criu/java/tests/CheckpointRestore.java | 
	package org.criu.java.tests;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CheckpointRestore {
	private MappedByteBuffer mappedByteBuffer = null;
	private String testName = "";
	private String logFolder = Helper.LOG_FOLDER + "/";
	private String outputFolder = Helper.OUTPUT_FOLDER_NAME + "/";
	/**
	 * Create CRlog and output directory if they don't exist.
	 * Delete directories containing .img files from failed Checkpoint-Restore if 'neverCleanFailures' property is not set to true.
	 *
	 * @throws IOException
	 */
	@BeforeSuite
	void suiteSetup() throws IOException {
		System.out.println("Tests are to be run as a privileged user having capabilities mentioned in ReadMe");
		boolean neverCleanFailures = Boolean.getBoolean("neverCleanFailures");
		Path logDir = Paths.get(logFolder);
		Path outputDir = Paths.get(outputFolder);
		if (!Files.exists(logDir)) {
			System.out.println("Logs directory does not exist, creating it");
			Files.createDirectory(logDir);
		}
		if (!Files.exists(outputDir)) {
			System.out.println("Output directory does not exist, creating it");
			Files.createDirectory(outputDir);
		}
		/*
		 * Delete the directories containing the img files from failed Checkpoint-Restore.
		 */
		if (!neverCleanFailures) {
			File output = new File(outputFolder);
			String[] name = output.list();
			for (int i = 0; null != name && i < name.length; i++) {
				File testFolder = new File(outputFolder + name[i]);
				if (testFolder.isDirectory()) {
					String[] list = testFolder.list();
					File file;
					if (null != list) {
						for (int j = 0; j < list.length; j++) {
							file = new File(outputFolder + name[i] + "/" + list[j]);
							if (!file.isDirectory()) {
								Files.delete(file.toPath());
							}
						}
					}
				}
				Files.delete(testFolder.toPath());
			}
		}
	}
	/**
	 * Create the output folder for the test in case it does not exist
	 *
	 * @param testName Name of the java test
	 * @throws IOException
	 */
	private void testSetup(String testName) throws IOException {
		Path testFolderPath = Paths.get(outputFolder + testName + "/");
		if (!Files.exists(testFolderPath)) {
			System.out.println("Creating the test folder");
			Files.createDirectory(testFolderPath);
		}
	}
	/**
	 * Read the pid of process from the pid file of test
	 *
	 * @param name Name of the java test
	 * @return pid Process id of the java test process
	 * @throws IOException
	 */
	private String getPid(String name) throws IOException {
		name = outputFolder + testName + "/" + name + Helper.PID_APPEND;
		File pidfile = new File(name);
		BufferedReader pidReader = new BufferedReader(new FileReader(pidfile));
		String pid = pidReader.readLine();
		pidReader.close();
		return pid;
	}
	/**
	 * @param testName      Name of the java test
	 * @param checkpointOpt Additional options for checkpoint
	 * @param restoreOpt    Additional options for restore
	 * @throws Exception
	 */
	@Test
	@Parameters({"testname", "checkpointOpt", "restoreOpt"})
	public void runtest(String testName, String checkpointOpt, String restoreOpt) throws Exception {
		this.testName = testName;
		String name = Helper.PACKAGE_NAME + "." + testName;
		String pid;
		int exitCode;
		System.out.println("======= Testing " + testName + " ========");
		testSetup(testName);
		File f = new File(Helper.MEMORY_MAPPED_FILE_NAME);
		if (f.exists()) {
			f.delete();
		}
		/*
		 * Create a new file that will be mapped to memory and used to communicate between
		 * this process and the java test process.
		 */
		boolean newFile = f.createNewFile();
		Assert.assertTrue(newFile, "Unable to create a new file to be mapped");
		/*
		 * MappedByteBuffer communicates between this process and java process called.
		 */
		FileChannel channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
		mappedByteBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE);
		mappedByteBuffer.clear();
		channel.close();
		/*
		 * Put MappedByteBuffer in Init state
		 */
		mappedByteBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_INIT);
		/*
		 * Run the test as a separate process
		 */
		System.out.println("Starting the java Test");
		ProcessBuilder builder = new ProcessBuilder("java", "-cp", "target/classes", name);
		Process process = builder.start();
		char currentState = mappedByteBuffer.getChar(Helper.MAPPED_INDEX);
		/*
		 * Loop until the test process changes the state of MappedByteBuffer from init state
		 */
		while (Helper.STATE_INIT == currentState) {
			currentState = mappedByteBuffer.getChar(Helper.MAPPED_INDEX);
			Thread.sleep(100);
		}
		/*
		 * If Mapped Buffer is in Helper.STATE_FAIL state before checkpointing then an exception must
		 * have occurred in the test.
		 */
		while (Helper.STATE_FAIL == currentState) {
			try {
				/*
				 * We exit the test process with exit code 5 in case of an exception
				 */
				exitCode = process.exitValue();
				/*
				 * Reaching here implies that .exitValue() has not thrown an exception, so the process has
				 * exited, We now check the exitCode.
				 */
				if (5 == exitCode) {
					Assert.fail(testName + ": Exception occurred while running the test: check the log file for details.");
				} else {
					Assert.fail(testName + ": ERROR: Unexpected value of exit code: " + exitCode + ", expected: 5");
				}
			} catch (IllegalThreadStateException e) {
				/*
				 * Do nothing, as an Exception is expected if the process has not exited
				 * and we try to get its exitValue.
				 */
			}
			currentState = mappedByteBuffer.getChar(Helper.MAPPED_INDEX);
		}
		/*
		 * Mapped Buffer state should be Helper.STATE_CHECKPOINT for checkpointing or Helper.STATE_END if some error occurs in test
		 */
		if (Helper.STATE_END != currentState) {
			Assert.assertEquals(currentState, Helper.STATE_CHECKPOINT, testName + ": ERROR: Error occurred while running the test: test is not in the excepted 'waiting to be checkpointed state': " + currentState);
		} else {
			Assert.fail(testName + ": ERROR: Error took place in the test check the log file for more details");
		}
		/*
		 * Reaching here implies that MappedByteBuffer is in To Be Checkpointed state.
		 * Get the pid of the test process
		 */
		pid = getPid(testName);
		try {
			/*
			 * Checkpoint the process
			 */
			checkpoint(pid, checkpointOpt);
		} catch (Exception e) {
			/*
			 * If exception occurs put the MappedByteBuffer to Helper.STATE_TERMINATE-Terminate state.
			 * On reading the terminate state, the test process terminates, else it
			 * may go on looping.
			 */
			mappedByteBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_TERMINATE);
			Assert.fail(testName + ": Exception occurred while during checkpointing" + e, e);
		}
		/*
		 * The process has been checkpointed successfully, now restoring the process.
		 */
		try {
			/*
			 * Restore the process
			 */
			restore(restoreOpt);
		} catch (Exception e) {
			mappedByteBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_TERMINATE);
			Assert.fail(testName + ": Exception occurred while restoring the test" + e, e);
		}
		/*
		 * Wait for test process to finish
		 */
		currentState = mappedByteBuffer.getChar(Helper.MAPPED_INDEX);
		while (Helper.STATE_RESTORE == currentState) {
			currentState = mappedByteBuffer.getChar(Helper.MAPPED_INDEX);
		}
		/*
		 * If a test passes it puts the MappedByteBuffer to Helper.STATE_PASS-Pass state,
		 * On failing to Helper.STATE_FAIL-Fail state, and if our Buffer is in Helper.STATE_TERMINATE state
		 * its because the checkpoint-restore of test process failed.
		 */
		Assert.assertNotEquals(currentState, Helper.STATE_TERMINATE, testName + ": ERROR: Checkpoint-Restore failed");
		Assert.assertNotEquals(currentState, Helper.STATE_FAIL, testName + ": ERROR: Test Failed, Check Log for details");
		Assert.assertEquals(currentState, Helper.STATE_PASS, testName + " ERROR: Unexpected State of Mapped Buffer");
		System.out.println("----- " + "PASS" + " -----");
	}
	/**
	 * Remove .img files, dump.log, restore.log, stats-dump and stats-restore files from Log Directory
	 *
	 * @throws IOException
	 */
	@AfterTest
	void cleanup() throws IOException {
		int i;
		String currentPath = System.getProperty("user.dir");
		currentPath = currentPath + "/" + logFolder;
		File deleteFile;
		File dir = new File(currentPath);
		String[] imgFiles = dir.list(new ImgFilter());
		if (null != imgFiles) {
			for (i = 0; i < imgFiles.length; i++) {
				deleteFile = new File(currentPath + imgFiles[i]);
				Files.delete(deleteFile.toPath());
			}
		}
		boolean exists = Files.exists(Paths.get(currentPath + "dump.log"));
		if (exists) {
			Files.delete(Paths.get(currentPath + "dump.log"));
		}
		exists = Files.exists(Paths.get(currentPath + "restore.log"));
		if (exists) {
			Files.delete(Paths.get(currentPath + "restore.log"));
		}
		exists = Files.exists(Paths.get(currentPath + "stats-dump"));
		if (exists) {
			Files.delete(Paths.get(currentPath + "stats-dump"));
		}
		exists = Files.exists(Paths.get(currentPath + "stats-restore"));
		if (exists) {
			Files.delete(Paths.get(currentPath + "stats-restore"));
		}
	}
	/**
	 * Copy .img files, dump.log, restore.log, stats-dump and stats-restore files from Log Directory if they exist
	 * to another folder.
	 *
	 * @throws IOException
	 */
	String copyFiles() throws IOException {
		String currentPath = System.getProperty("user.dir");
		String folderSuffix = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
		String fromPath = currentPath + "/" + logFolder;
		File fromDir = new File(fromPath);
		Path fromFile, toFile;
		boolean exists;
		String toPath = currentPath + "/" + outputFolder + testName + folderSuffix + "/";
		Path dirPath = Paths.get(toPath);
		Files.createDirectory(dirPath);
		String[] imgFiles = fromDir.list(new ImgFilter());
		if (null != imgFiles) {
			for (int i = 0; i < imgFiles.length; i++) {
				fromFile = Paths.get(fromPath + imgFiles[i]);
				toFile = Paths.get(toPath + imgFiles[i]);
				Files.copy(fromFile, toFile);
			}
		}
		fromFile = Paths.get(fromPath + "dump.log");
		exists = Files.exists(fromFile);
		if (exists) {
			toFile = Paths.get(toPath + "dump.log");
			Files.copy(fromFile, toFile);
		}
		fromFile = Paths.get(fromPath + "restore.log");
		exists = Files.exists(fromFile);
		if (exists) {
			toFile = Paths.get(toPath + "restore.log");
			Files.copy(fromFile, toFile);
		}
		fromFile = Paths.get(fromPath + "stats-dump");
		exists = Files.exists(fromFile);
		if (exists) {
			toFile = Paths.get(toPath + "stats-dump");
			Files.copy(fromFile, toFile);
		}
		fromFile = Paths.get(fromPath + "stats-restore");
		exists = Files.exists(fromFile);
		if (exists) {
			toFile = Paths.get(toPath + "stats-restore");
			Files.copy(fromFile, toFile);
		}
		return folderSuffix;
	}
	/**
	 * Checkpoint the process, if process has not been checkpointed correctly
	 * copy the .img, log and stats files, puts MappedBuffer to 'terminate' state and mark
	 * test as failed
	 *
	 * @param pid           Pid of process to be checkpointed
	 * @param checkpointOpt Additional options for checkpoint
	 * @throws IOException
	 * @throws InterruptedException
	 */
	private void checkpoint(String pid, String checkpointOpt) throws IOException, InterruptedException {
		ProcessBuilder builder;
		System.out.println("Checkpointing process " + pid);
		String command = "../../criu/criu dump --shell-job -t " + pid + " --file-locks -v4 -D " + logFolder + " -o dump.log";
		if (0 == checkpointOpt.length()) {
			String[] cmd = command.split(" ");
			builder = new ProcessBuilder(cmd);
		} else {
			command = command + " " + checkpointOpt;
			String[] cmd = command.split(" ");
			builder = new ProcessBuilder(cmd);
		}
		Process process = builder.start();
		BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
		int exitCode = process.waitFor();
		if (0 != exitCode) {
			/*
			 * Print the error stream
			 */
			String line = stdError.readLine();
			while (null != line) {
				System.out.println(line);
				line = stdError.readLine();
			}
			mappedByteBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_TERMINATE);
			/*
			 * If checkpoint fails copy the img files, dump.log, stats-dump, stats-restore
			 */
			String folderSuffix = copyFiles();
			Assert.fail(testName + ": ERROR: Error during checkpoint: exitCode of checkpoint process was not zero.\nFor more details check dump.log in " + outputFolder + testName + folderSuffix);
			return;
		}
		System.out.println("Checkpoint success");
		process.destroy();
	}
	/**
	 * Restore the process, if process has been restored correctly put Mapped Buffer to
	 * 'restored' state, else copy the .img, log and stats files and put MappedBuffer to 'terminate'
	 * state and mark test as failed
	 *
	 * @param restoreOpt Additional options for restore
	 * @throws IOException
	 * @throws InterruptedException
	 */
	private void restore(String restoreOpt) throws IOException, InterruptedException {
		ProcessBuilder builder;
		System.out.println("Restoring process");
		String command = "../../criu/criu restore -d --file-locks -v4 --shell-job -D " + logFolder + " -o restore.log";
		if (0 == restoreOpt.length()) {
			String[] cmd = command.split(" ");
			builder = new ProcessBuilder(cmd);
		} else {
			command = command + " " + restoreOpt;
			String[] cmd = command.split(" ");
			builder = new ProcessBuilder(cmd);
		}
		Process process = builder.start();
		BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
		int exitCode = process.waitFor();
		if (0 != exitCode) {
			/*
			 * Print the error stream
			 */
			String line = stdError.readLine();
			while (null != line) {
				System.out.println(line);
				line = stdError.readLine();
			}
			mappedByteBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_TERMINATE);
			/*
			 * If restore fails copy img files, dump.log, restore.log, stats-dump, stats-restore
			 */
			String folderSuffix = copyFiles();
			Assert.fail(testName + ": ERROR: Error during restore: exitCode of restore process was not zero.\nFor more details check restore.log in " + outputFolder + testName + folderSuffix);
			return;
		} else {
			System.out.println("Restore success");
			mappedByteBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_RESTORE);
		}
		process.destroy();
	}
}
 | 14,846 | 31.847345 | 204 | 
	java | 
			Subsets and Splits
				
	
				
			
				
No community queries yet
The top public SQL queries from the community will appear here once available.
