BrightSide Workbench Full Report + Source Code
JsonVisualConstraints.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2023 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.visual;
20 
21 import java.io.File;
22 import java.io.IOException;
23 import java.util.HashMap;
24 import java.util.function.Consumer;
25 import org.turro.elephant.context.ElephantContext;
26 import org.turro.file.CachedFileContent;
27 import org.turro.file.Document;
28 import org.turro.log.WebLoggers;
29 import org.turro.reflection.JSONSerializer;
30 
35 public class JsonVisualConstraints extends HashMap<String, JsonVisualConstraint> {
36 
37  /* Load */
38 
39  private static CachedFileContent<JsonVisualConstraints> CACHED = CachedFileContent.<JsonVisualConstraints>instance();
40 
41  public static JsonVisualConstraints load(String visualFile, Consumer<JsonVisualConstraints> defaults) {
42  File file = Document.from(convert(visualFile)).document();
43  return CACHED.constructor(() -> {
45  defaults.accept(lvc);
46  save(visualFile, lvc);
47  return lvc;
48  }).loader(f -> {
49  try {
50  JSONSerializer ser = new JSONSerializer(true);
51  return ser.fromJson(Document.from(f).content(), JsonVisualConstraints.class);
52  } catch (IOException ex) {
54  return null;
55  }
56  }).load(visualFile, file);
57  }
58 
59  private static void save(String visualFile, JsonVisualConstraints jvc) {
60  try {
61  JSONSerializer ser = new JSONSerializer(jvc, true);
62  Document.from(convert(visualFile)).content(ser.toJson());
63  } catch (IOException ex) {
64  WebLoggers.info(JsonVisualConstraints.class).exception(ex).log();
65  }
66  }
67 
68  private static String convert(String visualFile) {
69  if(!visualFile.contains("/")) {
70  visualFile = "/WEB-INF/elephant/conf/visuals/json-" + visualFile + "-visual.json";
71  }
72  return ElephantContext.getRealPath(visualFile);
73  }
74 
75 }
static WebLoggers severe(Object entity)
Definition: WebLoggers.java:51
WebLoggers exception(Throwable throwable)
Definition: WebLoggers.java:29
static JsonVisualConstraints load(String visualFile, Consumer< JsonVisualConstraints > defaults)