Skip to content

Instantly share code, notes, and snippets.

@karol-lotkowski
Created October 18, 2015 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karol-lotkowski/e166b5ecaa23b6761899 to your computer and use it in GitHub Desktop.
Save karol-lotkowski/e166b5ecaa23b6761899 to your computer and use it in GitHub Desktop.
Rules repository implementation to read data from JSON file
package com.karollotkowski.cleancode.repositories;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.karollotkowski.cleancode.core.Rule;
import io.dropwizard.jackson.Jackson;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class JsonFileRulesRepository implements RulesRepository {
private static final String RULES_FILE = "rules.json";
private static final ObjectMapper MAPPER = Jackson.newObjectMapper();
private final List<Rule> rules;
public JsonFileRulesRepository() {
rules = fetchRules();
System.out.println("Number of defined rules: " + rules.size());
}
@Override
public Optional<Rule> random() {
Collections.shuffle(rules);
return Optional.ofNullable(rules.iterator().next());
}
private List<Rule> fetchRules() {
final URL rulesResource = getClass().getClassLoader().getResource(RULES_FILE);
try {
return MAPPER.readValue(rulesResource, new TypeReference<ArrayList<Rule>>() {});
} catch (IOException e) {
return Collections.emptyList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment