Copy a Map Object in Java - java

I tried to follow the same way as in <How do I copy an object in Java?>.
But it does not work with Map object in the following codes. I want to copy the original map data to currMap. The current output is
0
1
2
3
null
null
null
I want it to be
0
1
2
3
0
2
3
What am I missing here?
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
class mapCopy{
private Map<Character, Queue<Integer>> map;
mapCopy(Map<Character, Queue<Integer>> map){
this.map=map;
}
mapCopy(mapCopy mapcopy){
this.map=mapcopy.map;
}
Map<Character, Queue<Integer>> getMap(){
return this.map;
}
}
public class Test {
static Map<Character, Queue<Integer>> BuildMap(){
String toMatch="able";
Map<Character, Queue<Integer>> map = new HashMap<>();
int i=0;
for(var c:toMatch.toCharArray()) {
Queue<Integer> q = map.get(c);
if(q==null)
q=new ArrayDeque<Integer>();
q.add(i);
map.put(c, q);
i++;
}
return map;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Character, Queue<Integer>> map = BuildMap();
List<String> dic = Arrays.asList("able", "ale");
for(var d:dic) {
var copy1 = new mapCopy(map);
var copy2 = new mapCopy(copy1);
var currMap = copy2.getMap();
for(var c:d.toCharArray()) {
System.out.println(currMap.get(c).poll());
}
}
}
}
Update 1:
iota's answer is what I look for. Here are the actually codes implemented by adding a copyMap function and adding it to currMap (var currMap = copyMap(map);)
class mapCopy is not needed.
static Map<Character, Queue<Integer>> copyMap(Map<Character, Queue<Integer>> mapcopy){
Map<Character, Queue<Integer>> map = new HashMap<>(mapcopy.size());
mapcopy.forEach((k,v)->{
map.put(k, new ArrayDeque<>(v));
});
return map;
}
Update 2:
Add complete codes
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
public class Test {
static Map<Character, Queue<Integer>> BuildMap(){
String toMatch="able";
Map<Character, Queue<Integer>> map = new HashMap<>();
int i=0;
for(var c:toMatch.toCharArray()) {
Queue<Integer> q = map.get(c);
if(q==null)
q=new ArrayDeque<Integer>();
q.add(i);
map.put(c, q);
i++;
}
return map;
}
static Map<Character, Queue<Integer>> copyMap(Map<Character, Queue<Integer>> mapcopy){
Map<Character, Queue<Integer>> map = new HashMap<>(mapcopy.size());
mapcopy.forEach((k,v)->{
map.put(k, new ArrayDeque<>(v));
});
return map;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Character, Queue<Integer>> map = BuildMap();
List<String> dic = Arrays.asList("able", "ale");
for(var d:dic) {
var currMap = copyMap(map);
for(var c:d.toCharArray()) {
System.out.println(currMap.get(c).poll());
}
}
}
}

You can iterate over the Map directly and copy each value into a new Map.
mapCopy(mapCopy mapcopy){
this.map = new HashMap<>(mapcopy.map.size());
mapcopy.map.forEach((k,v)->{
map.put(k, new ArrayDeque<>(v));
});
}

Related

Java map function

I want to use the map function (or stream function ?) to make this code this tighter.
var allObjectNames = new ArrayList<String>();
for (Object object : allObjects) {
allObjectNames.add(object.name);
}
I thought about:
var allObjectNames = new ArrayList<String>();
allObjectsNames.addAll(map(allObjects.name));
Or something like this.
Minimalistic Example:
package Mapping;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FunctionMapping {
public static void main(String[] args) {
var output1 = new Output("start");
var output2 = new Output("success");
var output3 = new Output("failure");
ArrayList<Output> rootOutput = new ArrayList<>();
rootOutput.add(output1);
rootOutput.add(output2);
rootOutput.add(output3);
var outputNames = rootOutput.stream().map(o -> o.outputName).collect(Collectors.toList());
}
static class Output {
String outputName;
Output (String name) {
this.outputName = name;
}
}
}
var allObjectNames = allObjects.stream().map(o -> o.name).collect(Collectors.toList());

Is there any logic to compare two word documents(docx) and catch the missing String, Special chars, space and all the stuff?

I'm working on two word document comparison manually where i should not miss any Strings, Special chars, space and all the stuff and that document is around 150 pages or more. so its very headache to do comparison. Then I have written small java program to compare two documents but I'm not able to list the missing words.
Using Apche POI Library
Thanks in advance.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFooter;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
public class ReadDocFile {
private static XWPFDocument docx;
// private static String path = "C:\\States wise\\NH\\Assessment
// 2nd\\test.docx";
private static ArrayList<String> firstList = new ArrayList<String>(); // refers to first document list
private static ArrayList<String> secondList = new ArrayList<String>(); // refers to second document list
private static List<XWPFParagraph> paragraphList;
private static Map<String, String> map = null;
private static LinkedHashSet<String> firstMissedArray = new LinkedHashSet<String>(); // refers to first document Linked hash set
private static LinkedHashSet<String> secondMissedArray = new LinkedHashSet<String>(); // refers to second document Linked hash set
public static void getFilePath(String path) {
FileInputStream fis;
try {
fis = new FileInputStream(path);
docx = new XWPFDocument(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void get_First_Doc_Data() {
getFilePath("C:\\States wise\\NH\\Assessment 2nd\\test.docx");
paragraphList = docx.getParagraphs();
System.out.println("******************** first list Starts here ******************** ");
System.out.println();
for (int i = 0; i < paragraphList.size() - 1; i++) {
firstList.add(paragraphList.get(i).getText().toString());
System.out.println(firstList.get(i).toString());
}
System.out.println("*********** first list Ends here ********************");
}
public static void get_Second_Doc_Data() {
getFilePath("C:\\States wise\\NH\\Assessment 2nd\\test1.docx");
paragraphList = docx.getParagraphs();
System.out.println("******************** Second list Starts here ******************** ");
System.out.println();
for (int i = 0; i < paragraphList.size() - 1; i++) {
secondList.add(paragraphList.get(i).getText().toString());
System.out.println(secondList.get(i).toString());
}
System.out.println("*********** Second list Ends here ********************");
}
public static void main(String[] args) {
get_First_Doc_Data();
get_Second_Doc_Data();
//System.out.println("First Para: " + firstList.contains(secondList));
compare();
compare_Two_List();
}
private static void compare() {
String firstMiss = null;
//String secondMiss = null;
for (int i = 0; i < firstList.size(); i++) {
for (int j = 0; j < secondList.size(); j++) {
if (!firstList.get(i).toString().equals(secondList.get(i).toString())) {
firstMiss = firstList.get(i).toString();
//secondMiss = secondList.get(i).toString();
map = new HashMap<String, String>();
}
}
firstMissedArray.add(firstMiss);
//secondMissedArray.add(secondMiss);
// System.out.println(missedArray.get(i).toString());
}
}
private static void compare_Two_List() {
int num = 0;
map.clear();
Iterator<String> first = firstMissedArray.iterator();
//Iterator<String> second = secondMissedArray.iterator();
while (first.hasNext()) {
map.put(""+num, first.next());
num++;
}
System.out.println(firstMissedArray.size());
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
// it.remove(); // avoids a ConcurrentModificationException
}
}
}
I have taken liberty to modify your code to arrive at the solution for your problem. Please go through this.
This should pretty much solve your problem - put SYSO statements wherever you think is necessary and tweak the flow of the program to achieve desired checks as per you requirement. In my hurry, I may not have made use of coding standards of using try catch block for error handling and handling the negative scenarios, so please take care of that when implementing it live.
In case if the documents are not .DOCX but .PDF make use of the Apache PDFBox api.
Here is the Code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
public class Comapre_Docs {
private static final String FIRST_DOC_PATH = "E:\\Workspace_Luna\\assignments\\Expected.docx";
private static final String SECOND_DOC_PATH = "E:\\Workspace_Luna\\assignments\\Actual.docx";
private static XWPFDocument docx;
private static List<XWPFParagraph> paragraphList;
private static ArrayList<String> firstList = new ArrayList<String>();
private static ArrayList<String> secondList = new ArrayList<String>();
public static void get_Doc_Data(String filePath, ArrayList listName)
throws IOException {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
docx = new XWPFDocument(fis);
paragraphList = docx.getParagraphs();
for (int i = 0; i <= paragraphList.size() - 1; i++) {
listName.add(paragraphList.get(i).getText().toString());
}
fis.close();
}
public static void main(String[] args) throws IOException {
get_Doc_Data(FIRST_DOC_PATH, firstList);
get_Doc_Data(SECOND_DOC_PATH, secondList);
compare(firstList, secondList);
}
private static void compare(ArrayList<String> firstList_1,
ArrayList<String> secondList_1) {
simpleCheck(firstList_1, secondList_1);
int size = firstList_1.size();
for (int i = 0; i < size; i++) {
paragraphCheck(firstList_1.get(i).toString().split(" "),
secondList_1.get(i).toString().split(" "), i);
}
}
private static void paragraphCheck(String[] firstParaArray,
String[] secondParaArray, int paraNumber) {
System.out
.println("=============================================================");
System.out.println("Paragraph No." + (paraNumber + 1) + ": Started");
if (firstParaArray.length != secondParaArray.length) {
System.out.println("There is mismatch of "
+ Math.abs(firstParaArray.length - secondParaArray.length)
+ " words in this paragraph");
}
TreeMap<String, Integer> firstDocPara = getOccurence(firstParaArray);
TreeMap<String, Integer> secondDocPara = getOccurence(secondParaArray);
ArrayList<String> keyData = new ArrayList<String>(firstDocPara.keySet());
for (int i = 0; i < keyData.size(); i++) {
if (firstDocPara.get(keyData.get(i)) != secondDocPara.get(keyData
.get(i))) {
System.out
.println("The following word is missing in actual document : "
+ keyData.get(i));
}
}
System.out.println("Paragraph No." + (paraNumber + 1) + ": Done");
System.out
.println("=============================================================");
}
private static TreeMap<String, Integer> getOccurence(String[] paraArray) {
TreeMap<String, Integer> paragraphStringCountHolder = new TreeMap<String, Integer>();
paragraphStringCountHolder.clear();
for (String a : paraArray) {
int count = 1;
if (paragraphStringCountHolder.containsKey(a)) {
count = paragraphStringCountHolder.get(a) + 1;
paragraphStringCountHolder.put(a, count);
} else {
paragraphStringCountHolder.put(a, count);
}
}
return paragraphStringCountHolder;
}
private static boolean simpleCheck(ArrayList<String> firstList,
ArrayList<String> secondList) {
boolean flag = false;
if (firstList.size() > secondList.size()) {
System.out
.println("There are more paragraph in Expected document than in Actual document");
} else if (firstList.size() < secondList.size()) {
System.out
.println("There are more paragraph in Actual document than in Expected document");
} else if (firstList.size() == secondList.size()) {
System.out.println("The paragraph count in both documents match");
flag = true;
}
return flag;
}
}

Extract List<String> data to Match LinkedHashMap<Integer, List<String>>

I have a List<String> data which is like:
{"0":["passFrom","3/9/2018","3/9/2018","anotherMethod","but"],"1":["googleForAlongTIme","3/9/2018","3/9/2018","stillCannotConvert","theLinkHashMap"]}
I need to store to a linkeHashMap with the above data, so far I had try something like below.
ArrayList<String> listdata = new ArrayList<String>();
Map<Integer, List<String>> listMap = new LinkedHashMap<Integer, List<String>>();
if (jsonArray.getString(0).trim()!= null && !jsonArray.getString(0).isEmpty()) {
for (int i = 0; i < jsonArray.length(); i++){
listdata.add(jsonArray.getString(i)); // here is the data which shown above
//trying to use split at here but find out `**["passFrom","3/9/2018","3/9/2018","anotherMethod","but"],"1"**` is not the correct data
/*List<String> bothList= Arrays.asList(listdata.get(i).toString().split(":"));
for (String string : bothList) {
List<String> tempData=Arrays.asList(bothList.toString());
listMap.put(i, tempData);
System.out.println("TeST: " + string);
}*/
}
}
Need some hints and help here, as my final aim is to get the 0,1 integer and below data to store inside the listMap
"passFrom","3/9/2018","3/9/2018","anotherMethod","but"
"googleForAlongTIme","3/9/2018","3/9/2018","stillCannotConvert","theLinkHashMap"
Try this:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class ParseJson {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
final String jsonStr = "{\"0\":[\"passFrom\",\"3/9/2018\",\"3/9/2018\",\"anotherMethod\",\"but\"],\"1\":[\"googleForAlongTIme\",\"3/9/2018\",\"3/9/2018\",\"stillCannotConvert\",\"theLinkHashMap\"]}";
Map<Integer, List<String>> map = objectMapper.readValue(jsonStr, new TypeReference<LinkedHashMap<Integer, List<String>>>(){});
for (Map.Entry<Integer, List<String>> entry : map.entrySet()) {
System.out.printf("For item \"%d\", values are:\n", entry.getKey());
for (String value : entry.getValue()) {
System.out.printf("\t[%s]\n", value);
}
}
}
}
Outputs:
For item "0", values are:
[passFrom]
[3/9/2018]
[3/9/2018]
[anotherMethod]
[but]
For item "1", values are:
[googleForAlongTIme]
[3/9/2018]
[3/9/2018]
[stillCannotConvert]
[theLinkHashMap]

Array contains null values

I was trying to read some words from a text file and then arrange them into descending array.
I reached the point where I read the words successfully,stored the words in a array, and when I went ahead to arrange it into descending form I noticed that my array also contained some null values.
When I tried to remove the null values using (complete code below)
Arrays.stream(w.words).filter(x->x != null).toArray(); , it still didn't worked.
After trying for quite some time now I think I need some help here.
Code,text file and output at this stage is as follows:
`
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
public class Practise {
private Scanner fp;
private Scanner scanLine;
private String[] words = new String[6] ;
int count;
String temp;
String [][] samewords;
int size;
String[] words_sorted;
public Practise() {
openFile();
readFile();
printa();
}
private void openFile() {
try {
fp = new Scanner(new File ("D:\\workspace\\file.txt"));
}
catch (Exception e) {
System.out.println("File does not exist");
}
}
private void readFile() {
try {
count = 0;
while (fp.hasNextLine()) {
String strLine = fp.nextLine();
scanLine = new Scanner(strLine);
words[count] = scanLine.next();
System.out.println("Here2"+words[count]);
System.out.println();
count++;
}
}
catch (Exception e) {
System.err.print("Error: " + e.getMessage());
}
}
private void printa() {
try (BufferedReader br = new BufferedReader(new FileReader("D:\\workspace\\file.txt"))) {
size = findLongestWords();
samewords = new String[size][size];
String line;
int i = 0;
String [] temp;
while ((line = br.readLine()) != null) {
temp = line.split(",");
for (int j = 0; j < samewords[i].length; j++) {
samewords[i][j] = temp[j];
System.out.println(samewords[i][j]);
}
i++;
}
//System.out.println(answers[1][2]);
} catch (IOException e) {
e.printStackTrace();
}
}
public int findLongestWords() throws FileNotFoundException {
int longest_word = 0;
int current;
BufferedReader sc = new BufferedReader(new FileReader("D:\\workspace\\file.txt"));
String li;
String[] tr;
try {
while ((li = sc.readLine())!= null ) {
tr = li.split(",");
current = tr.length;
if (current > longest_word) {
longest_word = current;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\n"+longest_word+"\n");
return longest_word;
}
private String[] sort(String[] string) {
/*Local variables*/
Map<String, Integer> map=new LinkedHashMap<String, Integer>();
Map<String, Integer> mapCopy=new LinkedHashMap<String, Integer>();
int [] lengthsArray=new int[string.length];
String [] sortedStrings=new String[string.length];
int counter1=0;
int counter2=0;
/* Store all the pairs <key,value>
* i.e <string[i],string[i].length>
*/
for(String s:string) {
System.out.println(s);
map.put((String) s, s.length());
lengthsArray[counter1]= s.length();//store all the lengths
counter1++;
}
mapCopy=new LinkedHashMap<String, Integer>(map);//make a copy of map
Arrays.sort(lengthsArray);//sort the array of lengths
/*
* Sort array according to the array of lengths
* by finding the matching value from the map
* then add it to the final string array,and then remove it from the map
*/
for(int item:lengthsArray) {
for(Map.Entry<String, Integer> e:map.entrySet()) {
if(item==e.getValue()) {
sortedStrings[counter2]=e.getKey();
counter2++;
map.remove(e.getKey());
break;
}
}
}
map=mapCopy;
System.out.println(map);//print map
return sortedStrings;
}
public static void main(String[] args) {
Practise w = new Practise();
System.out.println(Arrays.toString(w.words));
w.sort(w.words);
}
}
`
file.txt is:
ACT,CAT,AT,RAT,PAT,TAT
output is:
Here2ACT,CAT,AT,RAT,PAT,TAT
6
ACT
CAT
AT
RAT
PAT
TAT
[ACT,CAT,AT,RAT,PAT,TAT, null, null, null, null, null]
ACT,CAT,AT,RAT,PAT,TAT
null
Exception in thread "main" java.lang.NullPointerException
at Practise.sort(Practise.java:190)
at Practise.main(Practise.java:239)
null is because of the word array which you have declared ( predefined size ). Probably you can change that and use ArrayList (as it can be of dynamic size) instead of an String array, which can help you resolve. Just to help you, follow below changes:
private List<String> words = new ArrayList<>();
/*update below line in readFile() instead of words[count] = scanLine.next();*/
words.add(scanLine.next());
Change method signature sort(List<String> string)
//also update below declarations
int[] lengthsArray = new int[string.size()];
String[] sortedStrings = new String[string.size()];
change Arrays.toString(w.words) to just w.words in print statement
Hope this helps. Everything looks good.

Java equivalent of Python's format()

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)

Categories