I have written a method which takes map entity and location as parameters, using Jackson object mapper
public class EntityGenerator {
private static void generatePartiallySearchableEntity(Map<String, Set<String>> synMap, String root_dir_loc) throws Exception {
Set < String > namedEntitySet = null;
synMap.put("severity", namedEntitySet);
ObjectMapper mapperobj = new ObjectMapper();
mapperobj.writeValue(new File(root_dir_loc), synMap);
System.out.println("Test.json file created");
}
public static void main(String args[]) throws Exception {
Map < String, Set < String >> sysMap = new HashMap<String, Set<String>>();
Set < String > severityEntitySet = new HashSet<String>();
severityEntitySet.add("Critical");
severityEntitySet.add("Error ");
severityEntitySet.add("Warning ");
severityEntitySet.add("Information ");
sysMap.put("Severity", severityEntitySet);
Set < String > impactEntitySet = new HashSet<String>();
impactEntitySet.add("Inciden");
impactEntitySet.add("Risk");
impactEntitySet.add("Event");
sysMap.put("Imapct", impactEntitySet);
String root_dir_loc = "C:\\Users\\rakshitm\\Documents\\test.json";
generatePartiallySearchableEntity(sysMap, root_dir_loc);
}
I'm getting JSON output like this, like different what I expected from
{"severity":null,"Severity":["Error ","Information ","Critical","Warning "],"Imapct":["Inciden","Risk","Event"]}
I need JSON output of this type
[
{
"value": "event",
"synonyms": [
"event"
]
},
{
"value": "impact",
"synonyms": [
"impact"
]
},
{
"value": "severity",
"synonyms": [
"severity"
]
},
{
"value": "notes",
"synonyms": [
"notes"
]
}
]
See the code below:
package com.abhi.learning.stackoverflow;
import java.util.List;
public class Example {
private String value;
private List<String> synonyms = null;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<String> getSynonyms() {
return synonyms;
}
public void setSynonyms(List<String> synonyms) {
this.synonyms = synonyms;
}
}
Main Class:
package com.abhi.learning.stackoverflow;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
Example emp = new Example();
ArrayList<String> al = new ArrayList<String>();
al.add("Critical");
al.add("Error ");
al.add("Warning ");
emp.setSynonyms(al);
emp.setValue("Severity");
Example emp1 = new Example();
ArrayList<String> al1 = new ArrayList<String>();
al1.add("Inciden");
al1.add("Risk");
al1.add("Event");
emp1.setSynonyms(al1);
emp1.setValue("Imapct");
List<Example> lstEx = new ArrayList<Example>();
lstEx.add(emp1);
lstEx.add(emp);
try {
objectMapper.writeValue(new File("target/employee.json"), lstEx);
} catch ( IOException e) {
e.printStackTrace();
}
}
}
This is the json i got :
[
{
"value":"Imapct",
"synonyms":[
"Inciden",
"Risk",
"Event"
]
},
{
"value":"Severity",
"synonyms":[
"Critical",
"Error ",
"Warning "
]
}
]
You can add more Example objects for "events" & "Notes"
You need a Pojo of following specification.
class Event {
private String value;
private List<String> synonyms;
}
Then you make a list of this class and that would parse your Json correctly.
List<Event> events = new ArrayList<>();
Related
I am trying to write a test case in which the condition is I have to read a json file then if valuesdata is true then it must have values attribute and when it is false then it should have sql attribute
{
"data": [
{
"valuesdata": true,
"values": [
{
"id": "1"
}
]
},
{
"valuesdata": false,
"sql": "select * from data"
}
]
}
This is what I was trying to write , any help is appreciated
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class Test{
#Test
#DisplayName("If Json valuesdata is true it should have values attribute")
public void dropdownJsonValueIsStaticTrue() throws Exception {
String content = new String(Files.readAllBytes(Paths.get(input_file_path)));
JSONObject jsonObjects = new JSONObject(content);
jsonObjects.getJSONArray("data").getJSONObject(0).getBoolean("valuesdata");
}
}
You can consider that :
#Test
public void dropdownJsonValueIsStaticTrue() throws Exception {
String content = new String(Files.readAllBytes(Paths.get(input_file_path)));
JSONObject jsonObjects = new JSONObject(content);
JSONArray datas = jsonObjects.getJSONArray("data");
for (int i = 0 ; i < datas.length(); i++) {
JSONObject data = datas.getJSONObject(i);
boolean valuesdata = data.getBoolean("valuesdata");
if(valuesdata) {
assertTrue(data.getJSONArray("values") != null);
} else {
assertTrue(data.getString("sql") != null);
}
}
}
I have a JSON file (myjsonfile.json) which stores the folder structure along with file contents as a JSON. It is as follows:
{
"name":"folder1",
"type":"directory",
"children":[
{"name":"info",
"type":"directory",
"children": [
{
"name":"info1.txt",
"type":"file",
"content": ["abcd", "efgh", "ijk"]
}]
},
{"name":"data",
"type":"directory",
"children": [{
"name":"data1.txt",
"type":"file",
"content": ["abcd", "xyz"]
}]
}
]
}
What I want to do is access the content of either of the two text files (info1.txt or data1.txt) dynamically and store them as a List of Strings. By dynamically I mean that the filename i.e., the key (info1.txt or data1.txt) will be provided by the user.
I was able to parse and get the value in a static way by using org.json library like this:
File file = new File(myfilepath/myjsonfile.json);
String jsonContent = null;
try {
content = FileUtils.readFileToString(file, "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
// Convert JSON string to JSONObject
JSONObject jsonObj = new JSONObject(jsonContent);
JSONArray children = jsonObj.getJSONArray("children");
System.out.println(children.toString());
JSONObject child0 = children.getJSONObject(0);
System.out.println(child0.toString());
// and so on...
However, I can't figure out how to make this dynamic and store the file contents as a List of Strings based on the user input of the filename.
Can someone please help me out?
EDIT: Clarified the question. myfilepath here refers to the file path of the JSON file (myjsonfile.json).
You need to loop through each object and see if name has the file you are looking for. I would recommend you use a more verbose JSON processing library such as Jackson or Gson to make things easier. However, given your current implementation, you want to do something along the lines of:
if(jsonObj.has("children")) {
JSONArray mainChild = jsonObj.getJSONArray("children");
for(int i=0; i < mainChild.length(); i++) {
if(((JSONObject)mainChild.get(i)).has("children")) {
JSONArray child = ((JSONObject)mainChild.get(i)).getJSONArray("children");
for(int j=0; j < child.length(); j++) {
JSONObject obj = child.getJSONObject(j);
if(obj.has("name")
&& fileNameToLookFor.equals(obj.getString("name"))) {
if(obj.has("content")) {
return obj.getJSONArray("content");
}
return null;
}
}
}
}
return null;
}
Implement your own tree-node-walker:
class NodeWalker {
private final JSONObject object;
public NodeWalker(JSONObject object) {
this.object = object;
}
public List<String> findContentFor(String name) {
LinkedList<JSONObject> queue = new LinkedList<>();
queue.add(object);
while (queue.size() > 0) {
JSONObject next = queue.pop();
Object fileName = next.get("name");
final String contentName = "content";
if (fileName != null && fileName.equals(name) && next.has(contentName)) {
JSONArray content = next.getJSONArray(contentName);
if (content == null) {
return Collections.emptyList();
}
List<String> result = new ArrayList<>();
IntStream.range(0, content.length()).forEach(i -> result.add(content.getString(i)));
return result;
}
final String childrenName = "children";
if (next.has(childrenName)) {
JSONArray array = next.getJSONArray(childrenName);
IntStream.range(0, array.length()).forEach(i -> queue.add(array.getJSONObject(i)));
}
}
return Collections.emptyList();
}
}
Simple usage:
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.IntStream;
public class ProfileApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
List<String> strings = Files.readAllLines(jsonFile.toPath());
String json = String.join("", strings);
JSONObject jsonObj = new JSONObject(json);
NodeWalker nodeWalker = new NodeWalker(jsonObj);
String[] files = {"info1.txt", "data1.txt", "data2.txt"};
for (String file : files) {
System.out.println(file + " contents -> " + nodeWalker.findContentFor(file));
}
}
}
prints:
info1.txt contents -> [abcd, efgh, ijk]
data1.txt contents -> [abcd, xyz]
data2.txt contents -> []
Gson
Much easier to use Gson library and class model of your JSON payload. Let's create a class:
class FileNode {
private String name;
private String type;
private List<FileNode> children;
private List<String> content;
public List<String> findContent(String name) {
LinkedList<FileNode> queue = new LinkedList<>();
queue.add(this);
while (queue.size() > 0) {
FileNode next = queue.pop();
if (next.name.equals(name)) {
return next.content;
}
if (next.children != null) {
queue.addAll(next.children);
}
}
return Collections.emptyList();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<FileNode> getChildren() {
return children;
}
public void setChildren(List<FileNode> children) {
this.children = children;
}
public List<String> getContent() {
return content;
}
public void setContent(List<String> content) {
this.content = content;
}
#Override
public String toString() {
return "FileNode{" +
"name='" + name + '\'' +
", type='" + type + '\'' +
", children=" + children +
", content=" + content +
'}';
}
}
Which we can use as below:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.FileReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class GsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
FileNode root = gson.fromJson(new FileReader(jsonFile), FileNode.class);
String[] files = {"info1.txt", "data1.txt", "data2.txt"};
for (String file : files) {
System.out.println(file + " contents -> " + root.findContent(file));
}
}
}
Above code prints:
info1.txt contents -> [abcd, efgh, ijk]
data1.txt contents -> [abcd, xyz]
data2.txt contents -> []
I have a simple RDF file and want to convert it to nice nested JSON.
_:b0 a <http://schema.org/Book> ;
<http://schema.org/name> "Semantic Web Primer (First Edition)" ;
<http://schema.org/offers> _:b1 ;
<http://schema.org/publisher> "Linked Data Tools" .
_:b1 a <http://schema.org/Offer> ;
<http://schema.org/price> "2.95" ;
<http://schema.org/priceCurrency> "USD" .
should become
{
"type" : "Book",
"name" : "Semantic Web Primer (First Edition)",
"offers" : {
"type" : "Offer",
"price" : "2.95",
"priceCurrency" : "USD"
},
"publisher" : "Linked Data Tools"
}
Use framing
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.RDFWriter;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.StatementCollector;
import org.junit.Test;
import com.github.jsonldjava.core.JsonLdOptions;
import com.github.jsonldjava.core.JsonLdProcessor;
import com.github.jsonldjava.utils.JsonUtils;
import com.google.common.base.Charsets;
public class HowToConvertRdfToJson {
#Test
public void convertRdfToPrettyJson(){
try(InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("book.ttl")){
System.out.println(getPrettyJsonLdString(in,RDFFormat.TURTLE));
}catch(Exception e){
throw new RuntimeException(e);
}
}
/**
* #param in Input stream with rdf data
* #param format format of the rdf data
* #return a pretty JSON document as String
*/
public static String getPrettyJsonLdString(InputStream in, RDFFormat format) {
return getPrettyJsonLdString(
readRdfToString(in, format, RDFFormat.JSONLD, ""));
}
/**
* #param statements rdf statements collected
* #return a pretty JSON document as String
*/
public static String getPrettyJsonLdString(Collection<Statement> statements) {
return getPrettyJsonLdString(
graphToString(statements, RDFFormat.JSONLD));
}
private static String getPrettyJsonLdString(String rdfGraphAsJson) {
try {
//#formatter:off
return JsonUtils
.toPrettyString(
removeGraphArray(
getFramedJson(
createJsonObject(
rdfGraphAsJson))));
//#formatter:on
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static Map<String, Object> removeGraphArray(Map<String, Object> framedJson) {
List<Map<String,Object>> graph = (List<Map<String, Object>>) framedJson.get("#graph");
return graph.get(0);
}
private static Map<String, Object> getFramedJson(Object json) {
try {
return JsonLdProcessor.frame(json, getFrame(), new JsonLdOptions());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static Map<String, Object> getFrame() {
Map<String, Object> context = new HashMap<>();
context.put("#context", "http://schema.org/");
// if this does not work use the direct address as follows
// context.put("#context","https://schema.org/docs/jsonldcontext.jsonld");
return context;
}
private static Object createJsonObject(String ld) {
try (InputStream inputStream =
new ByteArrayInputStream(ld.getBytes(Charsets.UTF_8))) {
Object jsonObject = JsonUtils.fromInputStream(inputStream);
return jsonObject;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Collection<Statement> readRdfToGraph(
final InputStream inputStream, final RDFFormat inf,
final String baseUrl) {
try {
final RDFParser rdfParser = Rio.createParser(inf);
final StatementCollector collector = new StatementCollector();
rdfParser.setRDFHandler(collector);
rdfParser.parse(inputStream, baseUrl);
return collector.getStatements();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public static String readRdfToString(InputStream in, RDFFormat inf,
RDFFormat outf, String baseUrl) {
Collection<Statement> myGraph = null;
myGraph = readRdfToGraph(in, inf, baseUrl);
return graphToString(myGraph, outf);
}
public static String graphToString(Collection<Statement> myGraph,
RDFFormat outf) {
StringWriter out = new StringWriter();
RDFWriter writer = Rio.createWriter(outf, out);
try {
writer.startRDF();
for (Statement st : myGraph) {
writer.handleStatement(st);
}
writer.endRDF();
} catch (RDFHandlerException e) {
throw new RuntimeException(e);
}
return out.getBuffer().toString();
}
}
Prints
{
"id" : "_:b0",
"type" : "Book",
"name" : "Semantic Web Primer (First Edition)",
"offers" : {
"id" : "_:b1",
"type" : "Offer",
"price" : "2.95",
"priceCurrency" : "USD"
},
"publisher" : "Linked Data Tools"
}
With pom
<dependency>
<groupId>org.eclipse.rdf4j</groupId>
<artifactId>rdf4j-runtime</artifactId>
<version>2.2</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.github.jsonld-java</groupId>
<artifactId>jsonld-java</artifactId>
<version>0.10.0</version>
</dependency>
I am using org.json for this.
This is my application for generating a JSON structure
package com;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) throws JSONException {
Test testJson = new Test();
Map<String, LinkedList<String>> categoryitemslistMap = new LinkedHashMap<String, LinkedList<String>>();
JSONObject leafobj = new JSONObject();
JSONArray T2Array = new JSONArray();
JSONArray T3Array = new JSONArray();
JSONArray T4Array = new JSONArray();
JSONObject T3JsonObj = new JSONObject();
JSONObject T2JsonObj = new JSONObject();
LinkedList<String> T3ValuesList = new LinkedList<String>();
T3ValuesList.add("Bottled");
T3ValuesList.add("Fountain");
categoryitemslistMap.put("Soft Drinks", T3ValuesList);
String t2consildated_Data = "Lemon,Orange";
for (Map.Entry<String, LinkedList<String>> entry : categoryitemslistMap.entrySet()) {
String t1data = entry.getKey();
if (t1data.equalsIgnoreCase("Soft Drinks")) {
LinkedList<String> t1ChildList = entry.getValue();
for (String t2Data : t1ChildList) {
if (t2consildated_Data != null&& !t2consildated_Data.isEmpty()) {
StringTokenizer stt = new StringTokenizer(t2consildated_Data, ",");
while (stt.hasMoreTokens()) {
String t3data = stt.nextToken();
JSONArray jsonarray = testJson.createLeaf();
leafobj.put("leaf", jsonarray);
T4Array.put(leafobj);
}
}
}
} // end of processing values of categoryitemslistMap(Linked List)
} // end of processing categoryitemslistMap
T3JsonObj.put("T3",T4Array);
System.out.println(T3JsonObj);
} // end of main method
public JSONArray createLeaf() throws JSONException {
JSONArray ja = new JSONArray();
for(int i=0;i<2;i++)
{
if(i==0)
{
JSONObject jo = new JSONObject();
jo.put("name", "500 ML");
ja.put(jo);
}
else if(i==1)
{
JSONObject jo = new JSONObject();
jo.put("name", "1 Litre");
ja.put(jo);
}
}
return ja;
}
}
With this the output is being genrated as
{"T3":[{"leaf":[{"name":"500 ML"},{"name":"1 Litre"}]},{"leaf":[{"name":"500 ML"},{"name":"1 Litre"}]},{"leaf":[{"name":"500 ML"},{"name":"1 Litre"}]},{"leaf":[{"name":"500 ML"},{"name":"1 Litre"}]}]}
Could anybody please tell me how can i generate the following JSON Structure ?
{
"Soft Drinks": {
"T2": [
{
"name": "Bottled",
"T3": [
{
"name": "Lemon",
"leaf": [
{
"name": "500 ML"
}
]
},
{
"name": "Orange",
"leaf": [
{
"name": "500 ML"
}
]
}
]
},
{
"name": "Fountain",
"T3": [
{
"name": "Lemon",
"leaf": [
{
"name": "500 ML"
}
]
},
{
"name": "Orange",
"leaf": [
{
"name": "500 ML"
}
]
}
]
}
]
}
}
From the Javadocs:
So just replace System.out.println(T3JsonObj); with System.out.println(T3JsonObj.toString(4));
Here's two ways of doing string substitution:
name = "Tshepang"
"my name is {}".format(name)
"my name is " + name
How do I do something similar to the first method, using Java?
name = "PaĆlo";
MessageFormat f = new MessageFormat("my name is {0}");
f.format(new Object[]{name});
Or shorter:
MessageFormat.format("my name is {0}", name);
String s = String.format("something %s","name");
Underscore-java has a format() static method. Live example
import com.github.underscore.Underscore;
public class Main {
public static void main(String[] args) {
String name = "Tshepang";
String formatted = Underscore.format("my name is {}", name);
// my name is Tshepang
}
}
You can try this
package template.fstyle;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import static java.util.Objects.nonNull;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
#Slf4j
#NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FStyleFinal {
private static final String PLACEHOLDERS_KEY = "placeholders";
private static final String VARIABLE_NAMES_KEY = "variableNames";
private static final String PLACEHOLDER_PREFIX = "{{";
private static final String PLACEHOLDER_SUFFIX = "}}";
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{\\s*([\\S]+)\\s*}}");
private static Map<String, List<String>> toPlaceholdersAndVariableNames(String rawTemplate) {
List<String> placeholders = newArrayList();
List<String> variableNames = newArrayList();
Matcher matcher = PLACEHOLDER_PATTERN.matcher(rawTemplate);
while (matcher.find()) {
for (int j = 0; j <= matcher.groupCount(); j++) {
String s = matcher.group(j);
if (StringUtils.startsWith(s, PLACEHOLDER_PREFIX) && StringUtils.endsWith(s, PLACEHOLDER_SUFFIX)) {
placeholders.add(s);
} else if (!StringUtils.startsWith(s, PLACEHOLDER_PREFIX) && !StringUtils.endsWith(s, PLACEHOLDER_SUFFIX)) {
variableNames.add(s);
}
}
}
checkArgument(CollectionUtils.size(placeholders) == CollectionUtils.size(variableNames), "template engine error");
Map<String, List<String>> map = newHashMap();
map.put(PLACEHOLDERS_KEY, placeholders);
map.put(VARIABLE_NAMES_KEY, variableNames);
return map;
}
private static String toJavaTemplate(String rawTemplate, List<String> placeholders) {
String javaTemplate = rawTemplate;
for (String placeholder : placeholders) {
javaTemplate = StringUtils.replaceOnce(javaTemplate, placeholder, "%s");
}
return javaTemplate;
}
private static Object[] toJavaTemplateRenderValues(Map<String, String> context, List<String> variableNames, boolean allowNull) {
return variableNames.stream().map(name -> {
String value = context.get(name);
if (!allowNull) {
checkArgument(nonNull(value), name + " should not be null");
}
return value;
}).toArray();
}
private static Map<String, String> fromBeanToMap(Object bean, List<String> variableNames) {
return variableNames.stream().distinct().map(name -> {
String value = null;
try {
value = BeanUtils.getProperty(bean, name);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
log.debug("fromBeanToMap error", e);
}
return Pair.of(name, value);
}).filter(p -> nonNull(p.getRight())).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
}
public static String render(String rawTemplate, Map<String, String> context, boolean allowNull) {
Map<String, List<String>> templateMeta = toPlaceholdersAndVariableNames(rawTemplate);
List<String> placeholders = templateMeta.get(PLACEHOLDERS_KEY);
List<String> variableNames = templateMeta.get(VARIABLE_NAMES_KEY);
// transform template to java style template
String javaTemplate = toJavaTemplate(rawTemplate, placeholders);
Object[] renderValues = toJavaTemplateRenderValues(context, variableNames, allowNull);
return String.format(javaTemplate, renderValues);
}
public static String render(String rawTemplate, Object bean, boolean allowNull) {
Map<String, List<String>> templateMeta = toPlaceholdersAndVariableNames(rawTemplate);
List<String> variableNames = templateMeta.get(VARIABLE_NAMES_KEY);
Map<String, String> mapContext = fromBeanToMap(bean, variableNames);
return render(rawTemplate, mapContext, allowNull);
}
public static void main(String[] args) {
String template = "hello, my name is {{ name }}, and I am {{age}} years old, a null value {{ not_exists }}";
Map<String, String> context = newHashMap();
context.put("name", "felix");
context.put("age", "18");
String s = render(template, context, true);
log.info("{}", s);
try {
render(template, context, false);
} catch (IllegalArgumentException e) {
log.error("error", e);
}
}
}
Sample output:
[main] INFO template.fstyle.FStyleFinal - hello, my name is felix, and I am 18 years old, a null value null
[main] ERROR template.fstyle.FStyleFinal - error
java.lang.IllegalArgumentException: not_exists should not be null
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:142)
at template.fstyle.FStyleFinal.lambda$toJavaTemplateRenderValues$0(FStyleFinal.java:69)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:545)
at java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
at java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:438)
at java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:444)
at template.fstyle.FStyleFinal.toJavaTemplateRenderValues(FStyleFinal.java:72)
at template.fstyle.FStyleFinal.render(FStyleFinal.java:93)
at template.fstyle.FStyleFinal.main(FStyleFinal.java:113)