Folder structure from a string that has a parent child relationship - java

I have a scenario where I get a string output from a service that returns a folder structure as below
id=0c06c81c8052324b;name=Documentation;type=root;|id=0b06c81c80524a87;name=ABC;type=folder;parent=0c06c81c8052324b;|id=0b06c81c80524837;name=Admin;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052483d;name=Admin 2.0;type=folder;parent=0b06c81c80524837;|id=0b06c81c8052483a;name=Panel;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052484a;name=VCM;type=folder;parent=0b06c81c8052483a;|id=0c06c81c80269e63;name=Invoices;type=root;|id=0b06c81c8026a008;name=other;type=folder;parent=0c06c81c80269e63;|id=0b06c81c8027a600;name=Workflow;type=folder;parent=0b06c81c8026a008;|id=0b06c81c8027a601;name=Worksheet;type=folder;parent=0b06c81c8027a600;|id=0c06c81c8051c7d3;name=Receipts;type=root;|id=0b06c81c80545f32;name=VR_2;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f33;name=VR_3;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f30;name=VR_1;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c8053486d;name=VR;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f31;name=test2;type=folder;parent=0b06c81c8053486d;|id=0c06c81c8051c7d2;name=Source;type=root;|id=0b06c81c80524a8b;name=gem;type=folder;parent=0c06c81c8051c7d2;|id=0b06c81c80521681;name=Code;type=folder;parent=0b06c81c80524a8b;|id=0b06c81c8051cba7;name=pfm;type=folder;parent=0b06c81c80524a8b;
I was able to write a recursive logic to parse that string to come up with a structure as below:
Children of DCMGEN -> Documentation, ID: 0c06c81c8052324b
Children of DCMGEN -> Invoices, ID: 0c06c81c80269e63
Children of DCMGEN -> Source, ID: 0c06c81c8051c7d2
Children of DCMGEN -> Receipts, ID: 0c06c81c8051c7d3
Children of Documentation -> ABC, ID: 0b06c81c80524a87
Children of ABC -> Admin, ID: 0b06c81c80524837
Children of ABC -> Panel, ID: 0b06c81c8052483a
Children of Admin -> Admin 2.0, ID: 0b06c81c8052483d
Children of Panel -> VCM, ID: 0b06c81c8052484a
Children of Invoices -> other, ID: 0b06c81c8026a008
Children of other -> Workflow, ID: 0b06c81c8027a600
Children of Workflow -> Worksheet, ID: 0b06c81c8027a601
Children of Source -> gem, ID: 0b06c81c80524a8b
Children of gem -> Code, ID: 0b06c81c80521681
Children of gem -> pfm, ID: 0b06c81c8051cba7
Children of Receipts -> VR_2, ID: 0b06c81c80545f32
Children of Receipts -> VR_3, ID: 0b06c81c80545f33
Children of Receipts -> VR_1, ID: 0b06c81c80545f30
Children of Receipts -> VR, ID: 0b06c81c8053486d
Children of VR -> test2, ID: 0b06c81c80545f31
However, I want to create a folder structure from it on my local machine but am not able to create it recursively. Looking for some clues to solve this recursive problem. Can anyone please help ??
DCMGEN
Documentation
ABC
Admin
Admin 2.0
Panel
VCM
Invoices
other
Workflow
Worksheet
Source
gem
Code
pfm
Receipts
VR
test2
VR_1
VR_2
VR_3
Below is my code to get this far (with the help of some other thread on StackOverflow):
MegaMenuDTO.java
import java.util.ArrayList;
import java.util.List;
public class MegaMenuDTO {
private String Id;
private String name;
private String parentId;
private String type;
private List<MegaMenuDTO> childrenItems;
public MegaMenuDTO() {
this.Id = "";
this.name = "";
this.parentId = "";
this.childrenItems = new ArrayList<MegaMenuDTO>();
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public List<MegaMenuDTO> getChildrenItems() {
return childrenItems;
}
public void setChildrenItems(List<MegaMenuDTO> childrenItems) {
this.childrenItems = childrenItems;
}
public void addChildrenItem(MegaMenuDTO childrenItem){
if(!this.childrenItems.contains(childrenItem))
this.childrenItems.add(childrenItem);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
// return "MegaMenuDTO [Id=" + Id + ", name=" + name + ", parentId="
// + parentId + ", childrenItems=" + childrenItems + "]";
return "[name=" + name + ", childrenItems=" + childrenItems + "]";
}
}
MenuHelper.java
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MenuHelper {
private static final String TEMP_ROOT_FOLDER = "DCMGEN";
private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
private static final String FOLDERTREE_STR = "foldertree=";
private static final String RECORD_ELEMENT_DELIM = "[\\|]+";
private static final String SEPARATOR = System.getProperty("file.separator");
private static Map<String, List<MegaMenuDTO>> parentChildMap = new LinkedHashMap<String, List<MegaMenuDTO>>();
private static Map<String, String> idNameMap = new LinkedHashMap<String, String>();
//Test this helper class....
public static void main(String[] args) throws IOException {
final String FOLDER_STRUCTURE = "id=0c06c81c8052324b;name=Documentation;type=cabinet;|id=0b06c81c80524a87;name=ABC;type=folder;parent=0c06c81c8052324b;|id=0b06c81c80524837;name=Admin;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052483d;name=Admin 2.0;type=folder;parent=0b06c81c80524837;|id=0b06c81c8052483a;name=Panel;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052484a;name=VCM;type=folder;parent=0b06c81c8052483a;|id=0c06c81c80269e63;name=Invoices;type=cabinet;|id=0b06c81c8026a008;name=other;type=folder;parent=0c06c81c80269e63;|id=0b06c81c8027a600;name=Workflow;type=folder;parent=0b06c81c8026a008;|id=0b06c81c8027a601;name=Worksheet;type=folder;parent=0b06c81c8027a600;|id=0c06c81c8051c7d3;name=Receipts;type=cabinet;|id=0b06c81c80545f32;name=VR_2;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f33;name=VR_3;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f30;name=VR_1;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c8053486d;name=VR;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f31;name=test2;type=folder;parent=0b06c81c8053486d;|id=0c06c81c8051c7d2;name=Source;type=root;|id=0b06c81c80524a8b;name=gem;type=folder;parent=0c06c81c8051c7d2;|id=0b06c81c80521681;name=Code;type=folder;parent=0b06c81c80524a8b;|id=0b06c81c8051cba7;name=pfm;type=folder;parent=0b06c81c80524a8b;";
System.out.println("Temp folder : " + System.getProperty(JAVA_IO_TMPDIR));
List<FolderObj> folders = MenuHelper.parseResponseString(FOLDER_STRUCTURE);
if(folders != null) {
List<MegaMenuDTO> menuDTOList = MenuHelper.prepareMenu(folders);
List<File> rootDirs = new ArrayList<>();
File rootDir = new File(System.getProperty(JAVA_IO_TMPDIR) + SEPARATOR + TEMP_ROOT_FOLDER);
//Check and Delete the root folder, if present, before processing.
if(rootDir.exists()) {
rootDirs.add(rootDir);
for(File file : rootDirs) {
recursivelyDelete(file);
}
}
//Create a fresh root dir.
rootDirs.clear();
rootDir = createTempRootDir(TEMP_ROOT_FOLDER);
rootDirs.add(rootDir);
//System.out.println("Tree : " + menuDTOList);
for(MegaMenuDTO mmd: menuDTOList){
printMenu(mmd, "\t");
captureIdNameMap(mmd);
printPaths(mmd, TEMP_ROOT_FOLDER + SEPARATOR + mmd.getName());
}
for (Map.Entry<String, List<MegaMenuDTO>> entry : parentChildMap.entrySet()) {
String key = entry.getKey();
List<MegaMenuDTO> value = entry.getValue();
for(MegaMenuDTO dto : value) {
if(idNameMap.get(key) == null) {
System.out.println("Children of " + key + " -> " + dto.getName() + ", ID: " + dto.getId());
} else {
System.out.println("Children of " + idNameMap.get(key) + " -> " + dto.getName() + ", ID: " + dto.getId());
}
}
}
}
}
public static List<FolderObj> parseResponseString(final String input) {
if(input == null) {
return null;
}
List<FolderObj> menuList = new ArrayList<>();
String[] parsedValues = input.split(RECORD_ELEMENT_DELIM);
for(short i=0; i < parsedValues.length; i++) {
menuList.add(digest(filterValue(parsedValues[i])));
}
return menuList;
}
public static String filterValue(String input) {
if(input == null) {
return input;
}
if(input.contains(FOLDERTREE_STR)) {
input = input.substring(input.indexOf(FOLDERTREE_STR) + FOLDERTREE_STR.length());
}
return input;
}
public static FolderObj digest(String input) {
if(input == null) {
return null;
}
Map<String, String> holder = new HashMap<>();
String [] keyVals = input.split(";");
for(String keyVal : keyVals) {
String [] parts = keyVal.split("=");
holder.put(parts[0], parts[1]);
}
FolderObj folderObj = null;
String childId = null;
String name = null;
String type = null;
String parentId = null;
for(Map.Entry<String, String> entry : holder.entrySet()) {
String key = entry.getKey();
if(key.equals("id")) {
childId = entry.getValue();
} else if(key.equals("name")) {
name = entry.getValue();
} else if(key.equals("type")) {
type = entry.getValue();
} else if(key.equals("parent")) {
parentId = entry.getValue();
}
folderObj = new FolderObj(childId, parentId, name, type);
}
return folderObj;
}
public static List<MegaMenuDTO> prepareMenu(List<FolderObj> folderList) {
// Arrange String corresponds to the Id
Map<String, MegaMenuDTO> megaMenuMap = new HashMap<>();
// populate a Map
for(FolderObj folderObj: folderList){
// ----- Child -----
MegaMenuDTO mmdChild;
if(megaMenuMap.containsKey(folderObj.getChildId())){
mmdChild = megaMenuMap.get(folderObj.getChildId());
}
else{
mmdChild = new MegaMenuDTO();
megaMenuMap.put(folderObj.getChildId(),mmdChild);
}
mmdChild.setId(folderObj.getChildId());
mmdChild.setParentId(folderObj.getParentId());
mmdChild.setName(folderObj.getName());
mmdChild.setType(folderObj.getType());
// no need to set ChildrenItems list because the constructor created a new empty list
// ------ Parent ----
MegaMenuDTO mmdParent;
if(megaMenuMap.containsKey(folderObj.getParentId())){
mmdParent = megaMenuMap.get(folderObj.getParentId());
}
else{
mmdParent = new MegaMenuDTO();
megaMenuMap.put(folderObj.getParentId(),mmdParent);
}
mmdParent.setId(folderObj.getParentId());
// mmdParent.setParentId(null);
mmdParent.addChildrenItem(mmdChild);
}
// Get the root
List<MegaMenuDTO> menuList = new ArrayList<MegaMenuDTO>();
for(MegaMenuDTO megaMenuDTO : megaMenuMap.values()){
if(megaMenuDTO.getParentId() == null)
menuList.add(megaMenuDTO);
}
return menuList;
}
private static void printMenu(MegaMenuDTO dto, String tabValue) {
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
System.out.println(tabValue + childDTO.getName());
tabValue = "\t" + tabValue;
printMenu(childDTO, tabValue);
}
}
private static void captureIdNameMap(MegaMenuDTO dto) throws IOException {
idNameMap.put(dto.getId(), dto.getName());
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
idNameMap.put(childDTO.getId(), childDTO.getName());
captureIdNameMap(childDTO);
}
}
private static void printPaths(MegaMenuDTO dto, String name) throws IOException {
if(dto.getParentId() == null) {
if(parentChildMap.get("ROOT") == null) {
List<MegaMenuDTO> parentList = new ArrayList<MegaMenuDTO>();
parentList.add(dto);
parentChildMap.put("ROOT", parentList);
} else {
List<MegaMenuDTO> parentList = parentChildMap.get("ROOT");
parentList.add(dto);
parentChildMap.put("ROOT", parentList);
}
}
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
if (parentChildMap.get(childDTO.getParentId()) == null) {
List<MegaMenuDTO> parentList = new ArrayList<MegaMenuDTO>();
parentList.add(childDTO);
parentChildMap.put(childDTO.getParentId(), parentList);
} else {
List<MegaMenuDTO> parentList = parentChildMap.get(childDTO.getParentId());
parentList.add(childDTO);
parentChildMap.put(childDTO.getParentId(), parentList);
}
System.out.println(name + SEPARATOR + childDTO.getName() + ", ParentId : " + childDTO.getParentId());
createTempRootDir(name + SEPARATOR + childDTO.getName());
name = name + SEPARATOR + childDTO.getName();
printPaths(childDTO, name);
}
}
public static File createTempRootDir(String name) throws IOException {
final File sysTempDir = new File(System.getProperty(JAVA_IO_TMPDIR));
File newTempDir = new File(sysTempDir, name);
if (newTempDir.mkdirs()) {
return newTempDir;
} else {
throw new IOException("Failed to create temp dir named " + newTempDir.getAbsolutePath());
}
}
/**
* Recursively delete file or directory
*
* #param fileOrDir
* the file or dir to delete
* #return true iff all files are successfully deleted
*/
public static void recursivelyDelete(File fileOrDir) throws IOException {
Path directory = Paths.get(fileOrDir.getAbsolutePath());
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
}

Finally got it to work after reading up more on recursion. Below is the new updated code for anyone trying to do something similar. Not claiming that this is the most efficient or shortest code possible but the best I could come up with. If someone has an improved version, I would be very happy to see that.
MenuHelper.java
public class MenuHelper {
private static final String TEMP_ROOT_FOLDER = "DCMGEN";
private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
private static final String FOLDERTREE_STR = "foldertree=";
private static final String RECORD_ELEMENT_DELIM = "[\\|]+";
private static final String SEPARATOR = System.getProperty("file.separator");
private static Map<String, List<MegaMenuDTO>> parentChildMap = new LinkedHashMap<String, List<MegaMenuDTO>>();
private static Map<String, String> idNameMap = new LinkedHashMap<String, String>();
//Test this helper class....
public static void main(String[] args) throws IOException {
final String FOLDER_STRUCTURE = "id=0c06c81c8052324b;name=Documentation;type=cabinet;|id=0b06c81c80524a87;name=ABC;type=folder;parent=0c06c81c8052324b;|id=0b06c81c80524837;name=Admin;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052483d;name=Admin 2.0;type=folder;parent=0b06c81c80524837;|id=0b06c81c8052483a;name=Panel;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052484a;name=VCM;type=folder;parent=0b06c81c8052483a;|id=0c06c81c80269e63;name=Invoices;type=cabinet;|id=0b06c81c8026a008;name=other;type=folder;parent=0c06c81c80269e63;|id=0b06c81c8027a600;name=Workflow;type=folder;parent=0b06c81c8026a008;|id=0b06c81c8027a601;name=Worksheet;type=folder;parent=0b06c81c8027a600;|id=0c06c81c8051c7d3;name=Receipts;type=cabinet;|id=0b06c81c80545f32;name=VR_2;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f33;name=VR_3;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f30;name=VR_1;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c8053486d;name=VR;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f31;name=test2;type=folder;parent=0b06c81c8053486d;|id=0c06c81c8051c7d2;name=Source;type=root;|id=0b06c81c80524a8b;name=gem;type=folder;parent=0c06c81c8051c7d2;|id=0b06c81c80521681;name=Code;type=folder;parent=0b06c81c80524a8b;|id=0b06c81c8051cba7;name=pfm;type=folder;parent=0b06c81c80524a8b;";
System.out.println("Temp folder : " + System.getProperty(JAVA_IO_TMPDIR));
List<FolderObj> folders = MenuHelper.parseResponseString(FOLDER_STRUCTURE);
if(folders != null) {
List<MegaMenuDTO> menuDTOList = MenuHelper.prepareMenu(folders);
List<File> rootDirs = new ArrayList<>();
File rootDir = new File(System.getProperty(JAVA_IO_TMPDIR) + SEPARATOR + TEMP_ROOT_FOLDER);
//Check and Delete the root folder, if present, before processing.
if(rootDir.exists()) {
rootDirs.add(rootDir);
for(File file : rootDirs) {
recursivelyDelete(file);
}
}
//Create a fresh root dir.
rootDirs.clear();
rootDir = createTempRootDir(TEMP_ROOT_FOLDER);
rootDirs.add(rootDir);
//System.out.println("Tree : " + menuDTOList);
for(MegaMenuDTO mmd: menuDTOList){
printMenu(mmd, "\t");
captureIdNameMap(mmd);
printPaths(mmd, TEMP_ROOT_FOLDER + SEPARATOR + mmd.getName());
}
for (Map.Entry<String, List<MegaMenuDTO>> entry : parentChildMap.entrySet()) {
String key = entry.getKey();
List<MegaMenuDTO> value = entry.getValue();
for(MegaMenuDTO dto : value) {
if(idNameMap.get(key) == null) {
System.out.println("Children of " + key + " -> " + dto.getName() + ", ID: " + dto.getId());
} else {
System.out.println("Children of " + idNameMap.get(key) + " -> " + dto.getName() + ", ID: " + dto.getId());
}
}
}
System.out.println("--------------------------------------\n");
for (Map.Entry<String, List<MegaMenuDTO>> entry : parentChildMap.entrySet()) {
String key = entry.getKey();
List<MegaMenuDTO> value = entry.getValue();
if(key.equals("ROOT")) {
for(MegaMenuDTO dto : value) {
System.out.println("Root Folder is : " + dto.getName());
//createTempRootDir(TEMP_ROOT_FOLDER + SEPARATOR + dto.getName());
System.out.println(TEMP_ROOT_FOLDER + SEPARATOR + dto.getName());
printFoldersRecursively(parentChildMap.get(dto.getId()), TEMP_ROOT_FOLDER + SEPARATOR + dto.getName());
}
}
}
}
}
public static void printFoldersRecursively(List<MegaMenuDTO> value, String rootPath) throws IOException {
for (MegaMenuDTO inDTO1 : value) {
System.out.println(rootPath + SEPARATOR + inDTO1.getName());
for(MegaMenuDTO childItem : inDTO1.getChildrenItems()) {
System.out.println(rootPath + SEPARATOR + inDTO1.getName() + SEPARATOR + childItem.getName());
printFoldersRecursively(childItem.getChildrenItems(), rootPath + SEPARATOR + inDTO1.getName() + SEPARATOR + childItem.getName());
}
}
}
public static List<FolderObj> parseResponseString(final String input) {
if(input == null) {
return null;
}
List<FolderObj> menuList = new ArrayList<>();
String[] parsedValues = input.split(RECORD_ELEMENT_DELIM);
for(short i=0; i < parsedValues.length; i++) {
menuList.add(digest(filterValue(parsedValues[i])));
}
return menuList;
}
public static String filterValue(String input) {
if(input == null) {
return input;
}
if(input.contains(FOLDERTREE_STR)) {
input = input.substring(input.indexOf(FOLDERTREE_STR) + FOLDERTREE_STR.length());
}
return input;
}
public static FolderObj digest(String input) {
if(input == null) {
return null;
}
Map<String, String> holder = new HashMap<>();
String [] keyVals = input.split(";");
for(String keyVal : keyVals) {
String [] parts = keyVal.split("=");
holder.put(parts[0], parts[1]);
}
FolderObj folderObj = null;
String childId = null;
String name = null;
String type = null;
String parentId = null;
for(Map.Entry<String, String> entry : holder.entrySet()) {
String key = entry.getKey();
if(key.equals("id")) {
childId = entry.getValue();
} else if(key.equals("name")) {
name = entry.getValue();
} else if(key.equals("type")) {
type = entry.getValue();
} else if(key.equals("parent")) {
parentId = entry.getValue();
}
folderObj = new FolderObj(childId, parentId, name, type);
}
return folderObj;
}
public static List<MegaMenuDTO> prepareMenu(List<FolderObj> folderList) {
// Arrange String corresponds to the Id
Map<String, MegaMenuDTO> megaMenuMap = new HashMap<>();
// populate a Map
for(FolderObj folderObj: folderList){
MegaMenuDTO mmdChild;
if(megaMenuMap.containsKey(folderObj.getChildId())){
mmdChild = megaMenuMap.get(folderObj.getChildId());
} else{
mmdChild = new MegaMenuDTO();
megaMenuMap.put(folderObj.getChildId(),mmdChild);
}
mmdChild.setId(folderObj.getChildId());
mmdChild.setParentId(folderObj.getParentId());
mmdChild.setName(folderObj.getName());
mmdChild.setType(folderObj.getType());
// ------ Parent ----
MegaMenuDTO mmdParent;
if(megaMenuMap.containsKey(folderObj.getParentId())){
mmdParent = megaMenuMap.get(folderObj.getParentId());
} else{
mmdParent = new MegaMenuDTO();
megaMenuMap.put(folderObj.getParentId(),mmdParent);
}
mmdParent.setId(folderObj.getParentId());
mmdParent.addChildrenItem(mmdChild);
}
// Get the root
List<MegaMenuDTO> menuList = new ArrayList<MegaMenuDTO>();
for(MegaMenuDTO megaMenuDTO : megaMenuMap.values()){
if(megaMenuDTO.getParentId() == null)
menuList.add(megaMenuDTO);
}
return menuList;
}
private static void printMenu(MegaMenuDTO dto, String tabValue) {
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
System.out.println(tabValue + childDTO.getName());
tabValue = "\t" + tabValue;
printMenu(childDTO, tabValue);
}
}
private static void captureIdNameMap(MegaMenuDTO dto) throws IOException {
idNameMap.put(dto.getId(), dto.getName());
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
idNameMap.put(childDTO.getId(), childDTO.getName());
captureIdNameMap(childDTO);
}
}
private static void printPaths(MegaMenuDTO dto, String name) throws IOException {
if(dto.getParentId() == null) {
if(parentChildMap.get("ROOT") == null) {
List<MegaMenuDTO> parentList = new ArrayList<MegaMenuDTO>();
parentList.add(dto);
parentChildMap.put("ROOT", parentList);
} else {
List<MegaMenuDTO> parentList = parentChildMap.get("ROOT");
parentList.add(dto);
parentChildMap.put("ROOT", parentList);
}
}
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
if (parentChildMap.get(childDTO.getParentId()) == null) {
List<MegaMenuDTO> parentList = new ArrayList<MegaMenuDTO>();
parentList.add(childDTO);
parentChildMap.put(childDTO.getParentId(), parentList);
} else {
List<MegaMenuDTO> parentList = parentChildMap.get(childDTO.getParentId());
parentList.add(childDTO);
parentChildMap.put(childDTO.getParentId(), parentList);
}
System.out.println(name + SEPARATOR + childDTO.getName() + ", ParentId : " + childDTO.getParentId());
createTempRootDir(name + SEPARATOR + childDTO.getName());
name = name + SEPARATOR + childDTO.getName();
printPaths(childDTO, name);
}
}
public static File createTempRootDir(String name) throws IOException {
final File sysTempDir = new File(System.getProperty(JAVA_IO_TMPDIR));
File newTempDir = new File(sysTempDir, name);
if (newTempDir.mkdirs()) {
return newTempDir;
} else {
throw new IOException("Failed to create temp dir named " + newTempDir.getAbsolutePath());
}
}
/**
* Recursively delete file or directory
*
* #param fileOrDir
* the file or dir to delete
* #return true iff all files are successfully deleted
*/
public static void recursivelyDelete(File fileOrDir) throws IOException {
Path directory = Paths.get(fileOrDir.getAbsolutePath());
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
}

Related

I need help for java.util.PriorityQueue, java.io.BufferedReader and java.io.PrintWriter to read and write to JSON file

First of all, i'm completely noob in Java... and i need help to modify a piece of code.
The current code, write data to a CSV file and i need to modify it to save to JSON format, but using java.util.PriorityQueue, java.io.BufferedReader and java.io.PrintWriter. Can anyone help me to achieve this ?
Here is the code:
Route.java file:
import Exceptions.FailedCheckException;
import java.time.ZonedDateTime;
public class Route implements Comparable<Route> {
private Integer id;
private String name;
private Coordinates coordinates;
private java.time.ZonedDateTime creationDate;
private Location from;
private Location to;
private Long distance;
java.time.ZonedDateTime getCreationDate() {
return creationDate;
}
#Override
public String toString() {
return "Route{" +
"id=" + id +
", name='" + name + '\'' +
", coordinates=" + coordinates +
", creationDate=" + creationDate +
", from=" + from +
", to=" + to +
", distance=" + distance +
'}';
}
public String toCSVfile() {
String CSV = id + "," + name + "," + coordinates.getX() + "," + coordinates.getY() + "," + creationDate + ",";
if (from != null)
CSV += from.getX() + "," + from.getY() + "," + from.getZ() + "," + from.getName() + ",";
else
CSV += "null,,,,";
CSV += to.getX() + "," + to.getY() + "," + to.getZ() + "," + to.getName() + ",";
CSV += distance != null ? distance : "null";
return CSV;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getDistance() {
return distance;
}
public void setCreationDate(ZonedDateTime creationDate) {
this.creationDate = creationDate;
}
public void setFrom(Location from) {
this.from = from;
}
public void setTo(Location to) {
this.to = to;
}
public void setDistance(Long distance) {
this.distance = distance;
}
public static Checker<Long> distanceCheck = (Long L) -> {
if (L == null) return null;
else if (L > 1) return L;
throw new FailedCheckException();
};
public static Checker<Integer> idCheck = (Integer I) -> {
if (I != null && I > 0) return I;
else throw new FailedCheckException();
};
public static Checker<String> nameCheck = (String S) -> {
if (S != null && S.length() != 0) return S;
else throw new FailedCheckException();
};
#Override
public int compareTo(Route route) {
int result = getName().compareTo(route.getName());
if (result == 0 && getDistance() != null && route.getDistance() != null) {
result = getDistance().compareTo(route.getDistance());
}
return result;
}
}
And here is the SaveManagement.java file:
import Exceptions.FailedCheckException;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.Collections;
import java.util.Scanner;
/**
* Class operating with files
*/
public class SaveManagement {
private static File file;
public static void setFile(File file) {
SaveManagement.file = file;
}
/**
* file saving in CSV format
*/
public static void saveToFile(Collection c) {
if (file == null)
file = new File("save.csv");
try (FileWriter fileWriter = new FileWriter(file)) {
for (Route r : c.list) {
fileWriter.write(r.toCSVfile() + "\n");
}
} catch (IOException e) {
System.out.println("File Access Error");
}
}
/**
* Returns a collection from a saved file
*/
#NotNull
public static Collection listFromSave() {
Collection collection = new Collection();
try (Scanner scan = new Scanner(file)) {
String[] args;
for (int lineNum = 1; scan.hasNext(); lineNum++) {
try {
String line = scan.nextLine();
args = line.split(",", 14);
Route route = new Route();
int id = Route.idCheck.checker(Integer.parseInt(args[0]));
if (collection.searchById(id) == null)
route.setId(id);
else {
System.out.println("Invalid id received");
throw new FailedCheckException();
}
route.setName(Route.nameCheck.checker(args[1]));
int cx = Coordinates.xCheck.checker(Integer.parseInt(args[2]));
Long cy = Coordinates.yCheck.checker(Long.parseLong(args[3]));
route.setCoordinates(new Coordinates(cx, cy));
ZonedDateTime dateTime = ZonedDateTime.parse(args[4]);
route.setCreationDate(dateTime);
if (!args[5].equals("null")) {
Long fromX = Location.xyzCheck.checker(Long.parseLong(args[5]));
Long fromY = Location.xyzCheck.checker(Long.parseLong(args[6]));
long fromZ = Location.xyzCheck.checker(Long.parseLong(args[7]));
route.setFrom(new Location(fromX, fromY, fromZ, args[8]));
}
Long toX = Location.xyzCheck.checker(Long.parseLong(args[9]));
Long toY = Location.xyzCheck.checker(Long.parseLong(args[10]));
long toZ = Location.xyzCheck.checker(Long.parseLong(args[11]));
route.setTo(new Location(toX, toY, toZ, args[12]));
if (!args[13].equals("null")) {
Long dis = Route.distanceCheck.checker(Long.parseLong(args[13]));
route.setDistance(dis);
}
collection.list.add(route);
} catch (ArrayIndexOutOfBoundsException | DateTimeParseException | NumberFormatException | FailedCheckException e) {
System.out.println("\u001B[31m" + "Error reading file, line: " + "\u001B[0m" + lineNum);
}
}
} catch (FileNotFoundException e) {
System.out.println("\u001B[31m" + "File Access Error" + "\u001B[0m");
}
Collections.sort(collection.list);
return collection;
}
}
FileWriter should be changed to PrintWriter, Scanner with BufferedReader and i don't know how to implement java.util.PriorityQueue.
Thank you!
Edit:
Should i import java.util.PriorityQueue on Route.java and change
public String toCSVfile() {
to
public String toJSONfile() {

Searching a string in a text file and learning which line is it

I have a text file like down below:
jack; 488;22;98
kylie; 541;72;81
jenna; 995;66;17 .
.
The list is formatted as follows:
On every line, the first number after the name is the student's code and the numbers following it are scores.
I want to pass the student's code (as a String) as the input to the program and it should return the student's second score to me.
I have tried bufferedreader ,but I can just write all text files as output, but I can't search for the code and the other things.
Thanks
BufferedReader br = new BufferedReader(new FileReader("filePath"));
String contentLine = br.readLine();
while (contentLine != null) {
String[] result=contentLine.split(";");
String studentCode =result[1].trim();
// apply your logic for studentCode here
contentLine = br.readLine();
}
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FilterCsv {
private class Student {
private String name;
private String code;
private String score;
private String score2;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getScore2() {
return score2;
}
public void setScore2(String score2) {
this.score2 = score2;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", code='" + code + '\'' +
", score='" + score + '\'' +
", score2='" + score2 + '\'' +
'}';
}
}
private Function<String, Student> mapToItem = (line) -> {
System.out.println(line);
String[] p = line.split(";");
Student student = new Student();
student.setName(p[0]);
if (p[1] != null && p[1].trim().length() > 0) {
student.setCode(p[1]);
}
if (p[2] != null && p[2].trim().length() > 0) {
student.setScore(p[2]);
}
if (p[3] != null && p[3].trim().length() > 0) {
student.setScore2(p[3]);
}
return student;
};
private List<Student> processInputFile(String inputFilePath, String name) {
List<Student> inputList = new ArrayList<>();
try {
File inputF = new File(inputFilePath);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
// skip the header of the csv
inputList = br.lines().map(mapToItem).collect(Collectors.toList());
br.close();
String secondScore = inputList
.stream()
.peek(System.out::println)
.filter((s -> s.getName().equals(name)))
.findFirst()
.get().getScore2();
System.out.println("Score 2 for " + name + " is: " + secondScore);
} catch (IOException e) {
System.out.println(e);
}
return inputList;
}
public static void main(String[] args) {
new FilterCsv().processInputFile("your filepath, "studentsName");
}
}
add some error checking and stuff...
Cheers

Create Node tree from list of paths

I have this list of paths:
private static final List<String> paths = Arrays.asList(
"assets/css/custom.css",
"assets/css/default.css",
"assets/js/main.js",
"assets/js/old/main-old.js",
"fonts/poppins.woff",
"favicon.ico",
"index.html"
);
That I need to create a searchable tree, like this:
and here's what I have now:
public void testCreateTree() {
Node root = new Node("ROOT", null, Node.NODE_TYPE.ROOT);
paths.forEach(path -> {
final Node[] currentNode = {root};
if(!path.contains("/")) { // root files
currentNode[0].addChild(new Node(path, currentNode[0], Node.NODE_TYPE.FILE));
} else {
String folders = DirectoryRegex.matchFolders(path); // e.g. matches/returns "root/"
String fileName = DirectoryRegex.matchFile(path); // e.g. matches/returns index.html
String[] folderArrays = folders.split("/");
Arrays.asList(folderArrays).forEach(folder -> {
Node node = new Node("ROOT", null, Node.NODE_TYPE.ROOT);
node.setNodeName(folder);
node.setNodeType(Node.NODE_TYPE.FOLDER);
node.setParent(currentNode[0]);
// check if child exists
Node existingNode = currentNode[0].getChild(folder, Node.NODE_TYPE.FOLDER);
if(existingNode == null) {
existingNode = node;
currentNode[0].addChild(node);
}
currentNode[0] = existingNode;
});
currentNode[0].addChild(new Node(fileName, currentNode[0], Node.NODE_TYPE.FILE));
}
});
String print = root.printNodeJSON().toString();
Console.log(print);
}
The Node.java class is this:
public class Node {
public NODE_TYPE getNodeType() {
return nodeType;
}
public void setNodeType(NODE_TYPE nodeType) {
this.nodeType = nodeType;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public List<Node> getChildren() {
if(children == null) {
children = new LinkedList<>();
}
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public void addChild(Node child) {
getChildren().add(child);
}
public Node getChild(String nodeName, NODE_TYPE nodeType) {
final Node[] child = {null};
getChildren().forEach(node -> {
if(node.getNodeName().equals(nodeName) && node.getNodeType().equals(nodeType)) {
child[0] = node;
}
});
return child[0];
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
private Node() {}
public Node(String nodeName, Node parent, NODE_TYPE nodeType) {
setNodeName(nodeName);
setNodeType(nodeType);
setParent(parent);
}
public enum NODE_TYPE { FILE, FOLDER, ROOT }
private NODE_TYPE nodeType;
private Node parent;
private List<Node> children;
private String nodeName;
public String printNode() {
final String[] s = {"["};
s[0] = s[0] + "Node name: " + nodeName + ",";
if(nodeType != null) {
s[0] = s[0] + "Node type: " + nodeType.toString() + ",";
}
if(getParent() != null) {
s[0] = s[0] + "Node Parent: [ name = " + getParent().getNodeName() + ", type = " + getParent().getNodeType() + " ]";
}
s[0] = s[0] + "Node children: [";
getChildren().forEach(child -> {
s[0] = "[" + s[0] + child.printNode() + "]";
});
s[0] = s[0] + "]";
s[0] = s[0] + "]";
return s[0];
}
public JSONObject printNodeJSON() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("nodeName", nodeName);
jsonObject.put("nodeType", nodeType != null ? nodeType.toString() : null);
jsonObject.put("parent", getParent() != null ? getParent().printNodeJSONWithoutChildren() : null);
JSONArray children = new JSONArray();
getChildren().forEach(child -> {
children.put(child.printNodeJSON());
});
jsonObject.put("children", children);
return jsonObject;
}
public JSONObject printNodeJSONWithoutChildren() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("nodeName", nodeName);
jsonObject.put("nodeType", nodeType != null ? nodeType.toString() : null);
jsonObject.put("parent", getParent() != null ? getParent().printNodeJSONWithoutChildren() : null);
// JSONArray children = new JSONArray();
// getChildren().forEach(child -> {
// children.put(child.printNodeJSON());
// });
// jsonObject.put("children", children);
return jsonObject;
}
}
The code works fine but I want to know the most efficient way to do this.

How to solve the runtime exception while converting csv to bean using opencsv for blank csv file

Requirement:
I have two csv file input.csv and output.csv
The goal is to read the data rows from input.csv, then do some processing on it and if the processing fails then write the failed row of csv to output.csv
Initially input.csv have some data and output.csv is blank.
Here is the main class file:
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class UploadDocUsingCsv {
private static final String INPUT_CSV_FILE_PATH = "resources/input.csv";
private static final String OUTPUT_CSV_FILE_PATH = "resources/output.csv"; // this file only contain data whose upload is failed
public static void main(String args[]) {
try (
Reader reader4Input = Files.newBufferedReader(Paths.get(INPUT_CSV_FILE_PATH));
Reader reader4Output = Files.newBufferedReader(Paths.get(OUTPUT_CSV_FILE_PATH))
) {
// Read Input File
CsvToBean csvToBean4Input;
CsvToBeanBuilder csvToBeanBuilder4Input = new CsvToBeanBuilder(reader4Input);
csvToBeanBuilder4Input.withType(DocumentDetail.class);
csvToBeanBuilder4Input.withIgnoreLeadingWhiteSpace(true);
csvToBeanBuilder4Input.withSkipLines(0);
csvToBean4Input = csvToBeanBuilder4Input.build();
// Read Output File
CsvToBean csvToBean4Output;
CsvToBeanBuilder csvToBeanBuilder4Output= new CsvToBeanBuilder(reader4Output);
csvToBeanBuilder4Output.withType(DocumentDetail.class);
csvToBeanBuilder4Output.withIgnoreLeadingWhiteSpace(true);
csvToBeanBuilder4Output.withSkipLines(1); // skip header
csvToBean4Output = csvToBeanBuilder4Output.build();
// Declare Set to contain DocumentDetail object whose data could not be sent
HashSet<DocumentDetail> documentDetailsNotSent = new HashSet<DocumentDetail>();
// Call method to upload the document from input file
Iterator<DocumentDetail> csvDocumentDetailIterator = csvToBean4Input.iterator();
DocumentDetail csvHeader = csvDocumentDetailIterator.next(); // skip the header
// documentDetailsNotSent.add(csvHeader);
while (csvDocumentDetailIterator.hasNext()) {
DocumentDetail documentDetail = csvDocumentDetailIterator.next();
System.out.println(documentDetail);
documentDetailsNotSent.add(documentDetail);
}
// Call method to upload the document from output file
csvDocumentDetailIterator = csvToBean4Output.iterator(); // java.lang.RuntimeException: Error capturing CSV header!
while (csvDocumentDetailIterator.hasNext()) {
DocumentDetail documentDetail = csvDocumentDetailIterator.next();
System.out.println(documentDetail);
documentDetailsNotSent.add(documentDetail);
}
Writer writer4Output = Files.newBufferedWriter(Paths.get(OUTPUT_CSV_FILE_PATH));
// write the documentDetail objects that are not uploaded to output file
ArrayList<DocumentDetail> documentDetailNotSetList = new ArrayList<DocumentDetail>(documentDetailsNotSent);
documentDetailNotSetList.add(0, csvHeader);
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(DocumentDetail.class);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer4Output)
.withMappingStrategy(mappingStrategy)
.build();
beanToCsv.write(documentDetailNotSetList);
writer4Output.close();
} catch (Exception e){
System.out.println(e);
}
}
}
DocumentDetail class used as Bean is here:
import com.opencsv.bean.CsvBindByPosition;
import java.util.Objects;
public class DocumentDetail {
#CsvBindByPosition(position = 0)
private String contractId;
#CsvBindByPosition(position = 1)
private String partyId;
#CsvBindByPosition(position = 2)
private String contractBranch;
#CsvBindByPosition(position = 3)
private String customerName;
#CsvBindByPosition(position = 4)
private String vertical;
#CsvBindByPosition(position = 5)
private String referenceContractId;
#CsvBindByPosition(position = 6)
private String bankFlowNo;
#CsvBindByPosition(position = 7)
private String payoutCategory;
#CsvBindByPosition(position = 8)
private String camNo;
#CsvBindByPosition(position = 9)
private String camStatus;
#CsvBindByPosition(position = 10)
private String folderName;
#CsvBindByPosition(position = 11)
private String documentName;
#CsvBindByPosition(position = 12)
private String pdfName;
public String getContractId() {
return contractId;
}
public void setContractId(String contractId) {
this.contractId = contractId;
}
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
public String getContractBranch() {
return contractBranch;
}
public void setContractBranch(String contractBranch) {
this.contractBranch = contractBranch;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getVertical() {
return vertical;
}
public void setVertical(String vertical) {
this.vertical = vertical;
}
public String getReferenceContractId() {
return referenceContractId;
}
public void setReferenceContractId(String referenceContractId) {
this.referenceContractId = referenceContractId;
}
public String getBankFlowNo() {
return bankFlowNo;
}
public void setBankFlowNo(String bankFlowNo) {
this.bankFlowNo = bankFlowNo;
}
public String getPayoutCategory() {
return payoutCategory;
}
public void setPayoutCategory(String payoutCategory) {
this.payoutCategory = payoutCategory;
}
public String getCamNo() {
return camNo;
}
public void setCamNo(String camNo) {
this.camNo = camNo;
}
public String getCamStatus() {
return camStatus;
}
public void setCamStatus(String camStatus) {
this.camStatus = camStatus;
}
public String getFolderName() {
return folderName;
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
public String getDocumentName() {
return documentName;
}
public void setDocumentName(String documentName) {
this.documentName = documentName;
}
public String getPdfName() {
return pdfName;
}
public void setPdfName(String pdfName) {
this.pdfName = pdfName;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DocumentDetail that = (DocumentDetail) o;
return contractId.equals(that.contractId) &&
partyId.equals(that.partyId) &&
contractBranch.equals(that.contractBranch) &&
customerName.equals(that.customerName) &&
vertical.equals(that.vertical) &&
referenceContractId.equals(that.referenceContractId) &&
bankFlowNo.equals(that.bankFlowNo) &&
payoutCategory.equals(that.payoutCategory) &&
camNo.equals(that.camNo) &&
camStatus.equals(that.camStatus) &&
folderName.equals(that.folderName) &&
documentName.equals(that.documentName) &&
pdfName.equals(that.pdfName);
}
#Override
public int hashCode() {
return Objects.hash(contractId, partyId, contractBranch, customerName, vertical, referenceContractId,
bankFlowNo, payoutCategory, camNo, camStatus, folderName, documentName, pdfName);
}
#Override
public String toString() {
return "DocumentDetail{" +
"contractId='" + contractId + '\'' +
", partyId='" + partyId + '\'' +
", contractBranch='" + contractBranch + '\'' +
", customerName='" + customerName + '\'' +
", vertical='" + vertical + '\'' +
", referenceContractId='" + referenceContractId + '\'' +
", bankFlowNo='" + bankFlowNo + '\'' +
", payoutCategory='" + payoutCategory + '\'' +
", camNo='" + camNo + '\'' +
", camStatus='" + camStatus + '\'' +
", folderName='" + folderName + '\'' +
", documentName='" + documentName + '\'' +
", pdfName='" + pdfName + '\'' +
'}';
}
}
Input.csv is here
CONTRACT _ID,PARTY_ID ,CONTRACT_BRANCH ,CUSTOMER_NAME,VERTICAL ,REFERENCE_CONTRACT_ID ,BANK FLOW NO,PAYOUT CATEGORY,CAM_NO,CAM_STATUS ,FOLDER _NAME ,Document Name,PDF_NAME
133336,362177,xyz,qwe fghfg,fgh,NG233112344,958875934,Purchase Invoice,NA,APPROVED,dfgdfg Construction_dfg,PAYMENT VOUCHER,9588759.pdf
The question is how to solve the java.lang.RuntimeException: Error capturing CSV header! while calling csvToBean4Output.iterator();
I have solved the problem by checking for the output.csv is empty or not.
Here is the code:
boolean empty = (new File(OUTPUT_CSV_FILE_PATH)).length() == 0;
if(!empty){
csvDocumentDetailIterator = csvToBean4Output.iterator();
while (csvDocumentDetailIterator.hasNext()) {
DocumentDetail documentDetail = csvDocumentDetailIterator.next();
logger.info(documentDetail);
boolean isSent = commonMethods.uploadDoc(documentDetail);
logger.info("isSent: " + isSent);
if(!isSent){
documentDetailsNotSent.add(documentDetail);
}
}
}

Read from JSON file and map the objects

So I've got this huge JSON file available from which I need to extract data. The JSON format goes something like this:
{
"enabled":true,
"contentMetadataPartial":
{
"customTags":
{
"tag1":"value1"
}
},
"simulatedChanges":
[
3000,
2500,
400
],
"simulatedUpdateMetadata":
[
{
"customTags":
{
"tag1":"value1",
},
"assetName":"asset1234",
},
{
"duration":1111,
"encodedRate":3333,
}
]
}
To read it I was trying to create a class to the map the keys and objects. Something like this, similar to this question:
public class ConfigData
{
private Boolean enabled;
private class ContentMetadataPartial
{
private class CustomTags
{
String tag1;
}
}
int[] simulatedChanges = new int[3];
//problem here
}
But I'm getting stuck at the array, which contains more objects not just simple basic data types.
The JSON file is huge and has similar type of items all over it. I'm fairly new with this and may be doing some mistake. Any help towards right direction is appreciated. Thanks!
You need a classes structure, not all in one:
ConfigData:
package com.example.gson;
import java.util.List;
public class ConfigData {
private Boolean enabled;
private ContentMetadataPartial contentMetadataPartial;
private List<Integer> simulatedChanges = null;
private List<SimulatedUpdateMetadatum> simulatedUpdateMetadata = null;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public ContentMetadataPartial getContentMetadataPartial() {
return contentMetadataPartial;
}
public void setContentMetadataPartial(ContentMetadataPartial contentMetadataPartial) {
this.contentMetadataPartial = contentMetadataPartial;
}
public List<Integer> getSimulatedChanges() {
return simulatedChanges;
}
public void setSimulatedChanges(List<Integer> simulatedChanges) {
this.simulatedChanges = simulatedChanges;
}
public List<SimulatedUpdateMetadatum> getSimulatedUpdateMetadata() {
return simulatedUpdateMetadata;
}
public void setSimulatedUpdateMetadata(List<SimulatedUpdateMetadatum> simulatedUpdateMetadata) {
this.simulatedUpdateMetadata = simulatedUpdateMetadata;
}
#Override
public String toString() {
return "ConfigData [enabled=" + enabled + ", contentMetadataPartial=" + contentMetadataPartial
+ ", simulatedChanges=" + simulatedChanges + ", simulatedUpdateMetadata=" + simulatedUpdateMetadata
+ "]";
}
}
ContentMetadataPartial:
package com.example.gson;
public class ContentMetadataPartial {
private CustomTags customTags;
public CustomTags getCustomTags() {
return customTags;
}
public void setCustomTags(CustomTags customTags) {
this.customTags = customTags;
}
}
CustomTags:
package com.example.gson;
public class CustomTags {
private String tag1;
public String getTag1() {
return tag1;
}
public void setTag1(String tag1) {
this.tag1 = tag1;
}
}
SimulatedUpdateMetadatum:
package com.example.gson;
public class SimulatedUpdateMetadatum {
private CustomTags customTags;
private String assetName;
private Integer duration;
private Integer encodedRate;
public CustomTags getCustomTags() {
return customTags;
}
public void setCustomTags(CustomTags customTags) {
this.customTags = customTags;
}
public String getAssetName() {
return assetName;
}
public void setAssetName(String assetName) {
this.assetName = assetName;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public Integer getEncodedRate() {
return encodedRate;
}
public void setEncodedRate(Integer encodedRate) {
this.encodedRate = encodedRate;
}
}
GsonMain:
package com.example.gson;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.example.gson.ConfigData;
import com.google.gson.Gson;
public class GsonMain {
private static final String jsonFile = "files/input.json";
public static void main(String[] args) {
String content = readFile(jsonFile);
ConfigData conf = new Gson().fromJson(content, ConfigData.class);
System.out.println(conf);
}
private static String readFile(String filename) {
BufferedReader br = null;
FileReader fr = null;
StringBuilder content = new StringBuilder();
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
content.append(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return content.toString();
}
}
And your Json well formed:
{
"enabled":true,
"contentMetadataPartial":
{
"customTags":
{
"tag1":"value1"
}
},
"simulatedChanges":
[
3000,
2500,
400
],
"simulatedUpdateMetadata":
[
{
"customTags":
{
"tag1":"value1"
},
"assetName":"asset1234"
},
{
"duration":1111,
"encodedRate":3333
}
]
}
I have used this web to generate the classes.
package com.webom.practice;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Sample {
public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
public static void main(String[]args) {
String Jsondata="{\r\n" +
" \"enabled\":true,\r\n" +
" \"contentMetadataPartial\":\r\n" +
" {\r\n" +
" \"customTags\":\r\n" +
" {\r\n" +
" \"tag1\":\"value1\"\r\n" +
" }\r\n" +
" },\r\n" +
" \"simulatedChanges\":\r\n" +
" [\r\n" +
" 3000,\r\n" +
" 2500,\r\n" +
" 400\r\n" +
" ],\r\n" +
" \"simulatedUpdateMetadata\":\r\n" +
" [\r\n" +
" {\r\n" +
" \"customTags\":\r\n" +
" {\r\n" +
" \"tag1\":\"value1\",\r\n" +
" },\r\n" +
" \"assetName\":\"asset1234\",\r\n" +
" },\r\n" +
" {\r\n" +
" \"duration\":1111,\r\n" +
" \"encodedRate\":3333,\r\n" +
" }\r\n" +
" ]\r\n" +
"}\r\n" ;
JSONObject json = new JSONObject(Jsondata);
System.out.println(json);
Map<String,Object> dataConversion=Sample.jsonToMap(json);
System.out.println(dataConversion);
}
}

Categories