| package pta.de.core.controller; |
| |
| import com.fasterxml.jackson.databind.ObjectMapper; |
| import org.apache.log4j.Logger; |
| import org.eclipse.jetty.http.HttpStatus; |
| import pta.de.api.ServiceDistributionCluster; |
| import pta.de.core.exceptions.HttpStatusException; |
| |
| import javax.validation.ConstraintViolation; |
| import javax.validation.Validation; |
| import javax.validation.Validator; |
| import javax.validation.ValidatorFactory; |
| import java.io.IOException; |
| import java.nio.charset.Charset; |
| import java.nio.file.Files; |
| import java.nio.file.Paths; |
| import java.util.Set; |
| |
| public class ServicesConfigCache { |
| private static final Logger logger = Logger.getLogger(ServicesConfigCache.class.getName()); |
| private static ServicesConfigCache instance = new ServicesConfigCache(); |
| |
| |
| private ServiceDistributionCluster[] cache; |
| |
| private ServicesConfigCache(){ |
| } |
| |
| public static ServicesConfigCache getInstance() { |
| return instance; |
| } |
| |
| |
| public void readServerDistribution(String configFileName) throws HttpStatusException { |
| try { |
| ServiceDistributionCluster[] dcs = readServerDistributionFromText(new String(Files.readAllBytes(Paths.get(configFileName)), Charset.forName("UTF-8"))); |
| cache = dcs; |
| |
| } catch (IOException e) { |
| logger.error("Could not read file "+configFileName+"!", e); |
| throw new HttpStatusException(HttpStatus.INTERNAL_SERVER_ERROR_500); |
| } |
| } |
| |
| private ServiceDistributionCluster[] readServerDistributionFromText(String jsonText) throws HttpStatusException { |
| ServiceDistributionCluster[] dcs; |
| |
| try { |
| final ObjectMapper mapper = new ObjectMapper(); |
| dcs = mapper.readValue(jsonText, ServiceDistributionCluster[].class); |
| } catch (IOException e) { |
| logger.error("Could not parse file!", e); |
| throw new HttpStatusException(HttpStatus.INTERNAL_SERVER_ERROR_500); |
| } |
| |
| ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); |
| Validator validator = factory.getValidator(); |
| |
| for (ServiceDistributionCluster item : dcs) { |
| Set<ConstraintViolation<ServiceDistributionCluster>> violations |
| = validator.validate(item); |
| if (!violations.isEmpty()) { |
| logger.error("Error in configfile!: "); |
| throw new HttpStatusException(HttpStatus.INTERNAL_SERVER_ERROR_500); |
| } |
| } |
| return dcs; |
| } |
| |
| public ServiceDistributionCluster[] getCache() { |
| return cache; |
| } |
| } |