Passed
Push — main ( 06eb13...1446ae )
by Etienne
01:33
created

TeamConfigManager()   D

Complexity

Conditions 10

Size

Total Lines 78

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
c 0
b 0
f 0
dl 0
loc 78
rs 4.9199

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like de.kleiner3.lasertag.lasertaggame.management.team.TeamConfigManager.TeamConfigManager() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
package de.kleiner3.lasertag.lasertaggame.management.team;
2
3
import com.google.gson.GsonBuilder;
4
import com.google.gson.reflect.TypeToken;
5
import de.kleiner3.lasertag.LasertagMod;
6
import de.kleiner3.lasertag.common.util.FileIO;
7
import de.kleiner3.lasertag.lasertaggame.management.team.serialize.TeamConfigManagerDeserializer;
8
import de.kleiner3.lasertag.lasertaggame.management.team.serialize.TeamDtoSerializer;
9
import net.minecraft.block.Blocks;
10
11
import java.io.File;
12
import java.io.IOException;
13
import java.util.HashMap;
14
import java.util.Optional;
15
16
/**
17
 * Class holding the team config information
18
 *
19
 * @author Étienne Muser
20
 */
21
public class TeamConfigManager {
22
23
    private static final String teamConfigFilePath = LasertagMod.configFolderPath + "\\teamConfig.json";
24
25
    public static final TeamDto SPECTATORS = new TeamDto(0, "Spectators", 128, 128, 128, null);
26
    public HashMap<String, TeamDto> teamConfig = null;
27
28
    public TeamConfigManager() {
29
30
        // Get config file
31
        var teamConfigFile = new File(teamConfigFilePath);
32
33
        // If the config file exists
34
        if (teamConfigFile.exists()) {
35
            try {
36
                // Read config file
37
                var configFileContents = FileIO.readAllFile(teamConfigFile);
38
39
                // get gson builder
40
                var gsonBuilder = new GsonBuilder();
41
42
                // Get deserializer
43
                var deserializer = TeamConfigManagerDeserializer.getDeserializer();
44
45
                // Register type
46
                gsonBuilder.registerTypeAdapter(HashMap.class, deserializer);
47
48
                // Parse
49
                teamConfig = gsonBuilder.create().fromJson(configFileContents, new TypeToken<HashMap<String, TeamDto>>() {
50
                }.getType());
51
            } catch (IOException ex) {
52
                LasertagMod.LOGGER.warn("Reading of team config file failed: " + ex.getMessage());
53
            } catch (Exception ex) {
54
                LasertagMod.LOGGER.error("Unknown exception during loading of team config file: " + ex.getMessage());
55
            }
56
        }
57
58
        // If config couldn't be loaded from file
59
        if (teamConfig == null) {
60
61
            LasertagMod.LOGGER.info("Using default team config...");
62
63
            // Create map
64
            teamConfig = new HashMap<>();
65
66
            // Fill map with default values
67
            teamConfig.put("Red", new TeamDto(1, "Red", 255, 0, 0, Blocks.RED_CONCRETE));
68
            teamConfig.put("Green", new TeamDto(2, "Green", 0, 255, 0, Blocks.LIME_CONCRETE));
69
            teamConfig.put("Blue", new TeamDto(3, "Blue", 0, 0, 255, Blocks.BLUE_CONCRETE));
70
            teamConfig.put("Orange", new TeamDto(4,"Orange", 255, 128, 0, Blocks.ORANGE_CONCRETE));
71
            teamConfig.put("Teal", new TeamDto(5, "Teal", 0, 128, 255, Blocks.LIGHT_BLUE_CONCRETE));
72
            teamConfig.put("Pink", new TeamDto(6, "Pink", 255, 0, 255, Blocks.PINK_CONCRETE));
73
74
            // Get gson builder
75
            var gsonBuilder = new GsonBuilder();
76
77
            // Register type adapter
78
            gsonBuilder.registerTypeAdapter(TeamDto.class, TeamDtoSerializer.getSerializer());
79
80
            // Serialize
81
            var configJson = gsonBuilder.setPrettyPrinting().create().toJson(teamConfig);
82
83
            // Persist
84
            try {
85
                var dir = new File(LasertagMod.configFolderPath);
86
87
                // Create directory if not exists
88
                if (!dir.exists() && !dir.mkdir()) {
89
                    throw new IOException("Make directory for team config failed!");
90
                }
91
92
                // Create file if not exists
93
                if (!teamConfigFile.exists() && !teamConfigFile.createNewFile()) {
94
                    throw new IOException("Creation of file for team config failed!");
95
                }
96
97
                // Write to file
98
                FileIO.writeAllFile(teamConfigFile, configJson);
99
            } catch (IOException e) {
100
                LasertagMod.LOGGER.error("Writing to team config file failed: " + e.getMessage());
101
            }
102
        }
103
104
        // Add dummy team spectators
105
        teamConfig.put(SPECTATORS.name(), SPECTATORS);
106
    }
107
108
    /**
109
     * Gets the team identified by its id
110
     *
111
     * @param id The id of the team
112
     * @return
113
     */
114
    public Optional<TeamDto> getTeamOfId(int id) {
115
116
        return teamConfig.values().stream()
117
                .filter(team -> team.id() == id)
118
                .findFirst();
119
    }
120
}
121