blob: 2802645e0b41f8bad6d91d2bd335491347c658ff [file] [log] [blame]
/**
******************************************************************************
* Copyright © 2018 PTA GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*
******************************************************************************
*/
package org.eclipse.openK.core.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.openK.api.ServiceDistributionCluster;
import org.eclipse.openK.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;
}
}