package net.curisit.securis; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import net.curisit.securis.beans.RequestBean; import net.curisit.securis.utils.HWInfo; import net.curisit.securis.utils.JsonUtils; import net.curisit.securis.utils.LicUtils; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class ReqGenerator { private static final Logger LOG = LogManager.getLogger(ReqGenerator.class); private static ReqGenerator singleton = new ReqGenerator(); private ReqGenerator() { } public static ReqGenerator getInstance() { return singleton; } public RequestBean createRequest(String licTypeCode, String customerCode, String packCode) throws SeCurisException { RequestBean req = new RequestBean(); req.setLicenseTypeCode(licTypeCode); req.setCustomerCode(customerCode); req.setPackCode(packCode); req.setArch(HWInfo.getArch()); req.setCrcLogo(getCrcLogo()); req.setMacAddresses(HWInfo.getMACAddress()); req.setOsName(HWInfo.getOsName()); return req; } public RequestBean loadRequest(File requestFile) throws SeCurisException { try { String json = new String(Files.readAllBytes(Paths.get(requestFile.toURI())), "utf-8"); RequestBean req = JsonUtils.json2object(json, RequestBean.class); return req; } catch (IOException e) { LOG.error("Request file {} was not found or is not accesible"); throw new SeCurisException("ERROR accesing request file: " + requestFile.getAbsolutePath(), e); } } /** * Generate a request file using a {@link RequestBean} * * @param req * @param file * @throws SeCurisException */ public void save(RequestBean req, File file) throws SeCurisException { byte[] json; try { json = JsonUtils.toPrettyJSON(req).getBytes("utf-8"); Files.write(Paths.get(file.toURI()), json, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (UnsupportedEncodingException e) { LOG.error("Error creating json doc from request: " + req, e); throw new SeCurisException("Error creating json doc from request: " + req, e); } catch (IOException e) { LOG.error("Error creating request file: " + file, e); throw new SeCurisException("Error creating request file: " + file, e); } LOG.debug("License saved in {}", file); } private String getCrcLogo() { String logResource = "images/logo_customer.png"; InputStream is = getClass().getClassLoader().getResourceAsStream(logResource); if (is == null) return null; try { String shaLogo = LicUtils.sha256(IOUtils.toByteArray(is), LicenseValidator.LOGO_SECRET); return shaLogo; } catch (IOException e) { LOG.error("Customer logo was not found in classpath in " + logResource, e); return null; } } }