Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package fileoperations; import loggerapi.CustomLogger; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import main.MainClass; /** * * @author harsha-1916 */ public class FileOperations { private static final CustomLogger loggerProperties = new CustomLogger(); private static Logger loggerObj; private static final String URLPARAMS = "urlparams"; private static final String SEARCHPARAMS = "searchparams"; private static final String COLUMNS = "columns"; private static final String AUTHTOKEN = "authtoken"; private static final String PORTAL = "portal"; private static final String DEPARTMENT = "department"; static { initializeLoggerParams(); } private static void initializeLoggerParams() { boolean isValidLogger = loggerProperties.setLoggerProperties("FileOperations", "./Logs/FileOperations.%u.%g.txt"); if (isValidLogger) { loggerObj = loggerProperties.getLogger(); //loggerObj.setUseParentHandlers(false); } } public static boolean writeObjectToFile(Object ObjectToWrite, String fileToWrite) { loggerObj.log(Level.INFO, "inside writeObjectToFile method"); BufferedWriter bw = null; loggerObj.log(Level.INFO, "File to write the object is:" + fileToWrite); File file = new File(fileToWrite); try { if (!file.exists()) { file.createNewFile(); loggerObj.log(Level.INFO, "File did not exist before: so created new one with the name: " + fileToWrite); } FileWriter fw = new FileWriter(file, true); bw = new BufferedWriter(fw); bw.write(ObjectToWrite.toString()); } catch (IOException ex) { loggerObj.log(Level.SEVERE, "Error in writing to the file:" + fileToWrite + "\n Exception is " + ex.toString()); return false; } catch (Exception ex) { loggerObj.log(Level.SEVERE, "Error in writing to the file:" + fileToWrite + "\n Exception is " + ex.toString()); return false; } finally { try { if (bw != null) { bw.close(); } } catch (IOException ex) { loggerObj.log(Level.SEVERE, "Error in closing the file:" + fileToWrite + " after reading"); return false; } } loggerObj.log(Level.INFO, "Successfully written the object to: " + fileToWrite); return true; } public static boolean writeCollectionToFile(Collection<String> objToWrite, String delimiter, String fileToWrite) { loggerObj.log(Level.INFO, "inside writeObjectToFile method"); BufferedWriter bw = null; loggerObj.log(Level.INFO, "File to write the object is:" + fileToWrite); File file = new File(fileToWrite); try { if (file.exists()) { file.delete(); } if (!file.exists()) { file.createNewFile(); loggerObj.log(Level.INFO, "File did not exist before: so created new one with the name: " + fileToWrite); } FileWriter fw = new FileWriter(file, true); bw = new BufferedWriter(fw); for (String i : objToWrite) { bw.write(i.toString() + ","); } } catch (IOException ex) { loggerObj.log(Level.SEVERE, "Error in writing to the file:" + fileToWrite + "\n Exception is " + ex.toString()); return false; } catch (Exception ex) { loggerObj.log(Level.SEVERE, "Error in writing to the file:" + fileToWrite + "\n Exception is " + ex.toString()); return false; } finally { try { if (bw != null) { bw.close(); } } catch (IOException ex) { loggerObj.log(Level.SEVERE, "Error in closing the file:" + fileToWrite + " after reading"); return false; } } loggerObj.log(Level.INFO, "Successfully written the object to: " + fileToWrite); return true; } public static Object readFromJSONFile(String fileToReadFrom) { loggerObj.log(Level.INFO, "Inside readFromJSONFile method"); JSONParser parser = new JSONParser(); FileReader fileReader = null; try { loggerObj.log(Level.INFO, "file to read from is:" + fileToReadFrom); fileReader = new FileReader(fileToReadFrom); Object obj = parser.parse(fileReader); loggerObj.log(Level.INFO, "JSON Object is validated successfully from" + fileToReadFrom); fileReader.close(); return obj; } catch (IOException ex) { try { loggerObj.log(Level.SEVERE, "Error in reading the JSON from the file " + fileToReadFrom + "\n Exception is: " + ex.toString()); if (fileReader != null) { fileReader.close(); } } catch (IOException ex1) { loggerObj.log(Level.SEVERE, "Error in closing the file after problem in reading the JSON from the file " + fileToReadFrom); } return null; } catch (ParseException ex) { try { loggerObj.log(Level.SEVERE, "Error in validating the JSON from the file" + fileToReadFrom + "Exception " + ex.toString()); if (fileReader != null) { fileReader.close(); } } catch (IOException ex1) { loggerObj.log(Level.SEVERE, "Error in closing the file after problem in parsing the JSON from the file " + fileToReadFrom); } return null; } } public static JSONObject CSVToJSONObject(String CSVFileName) { BufferedReader fileReader = null; final String DELIMITER = ","; JSONObject ModuleVsOwners = new JSONObject(); try { String line = ""; //Create the file reader fileReader = new BufferedReader(new FileReader(CSVFileName)); //Read the file line by line while ((line = fileReader.readLine()) != null) { //Get all tokens available in line String[] tokens = line.split(DELIMITER); if (!tokens[0].equals("Module")) { ModuleVsOwners.put(tokens[0], tokens[1]); } } return ModuleVsOwners; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } public static List<String> readStringArrFromCSVFile(String CSVFileName) { BufferedReader fileReader = null; final String DELIMITER = ","; try { String result = ""; String line = ""; //Create the file reader fileReader = new BufferedReader(new FileReader(CSVFileName)); //Read the file line by line while ((line = fileReader.readLine()) != null) { //Get all tokens available in line result += line; } List<String> items = Arrays.asList(result.split("\\s*" + DELIMITER + "\\s*")); return items; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } public static JSONObject supPropsToJSONObj(String fileName) { loggerObj.log(Level.INFO, "Inside supPropsToJSONObj method"); BufferedReader fileReader = null; final String VALUEDELIMITER = "="; JSONObject supDetails = new JSONObject(); JSONObject urlParams = new JSONObject(); try { String line = ""; //Create the file reader fileReader = new BufferedReader(new FileReader(fileName)); //Read the file line by line while ((line = fileReader.readLine()) != null) { //Get all tokens available in line String[] tokens = line.split(VALUEDELIMITER); if (tokens.length == 0) { continue; } if (tokens[0].trim().contains("authtoken")) { urlParams.put(AUTHTOKEN, tokens[1].trim()); } else if (tokens[0].contains("portal")) { urlParams.put(PORTAL, tokens[1].trim()); } else if (tokens[0].contains("department")) { urlParams.put(DEPARTMENT, tokens[1].trim()); } else if (tokens[0].contains("columns")) { String columnsStr = tokens[1].trim(); String[] columnsArr = columnsStr.split(","); supDetails.put(COLUMNS, columnsArr); } else if ((tokens[0].contains("searchParams"))) { String searchStr = tokens[1].trim(); String[] searchParams = searchStr.split(","); supDetails.put(SEARCHPARAMS, searchParams); } } supDetails.put(URLPARAMS, urlParams); } catch (Exception e) { loggerObj.log(Level.SEVERE, "Exception while parsing the file " + fileName + "\n Exception is: ", e); return null; } finally { try { fileReader.close(); } catch (IOException e) { loggerObj.log(Level.SEVERE, "Exception while Closing the file " + fileName + "\n Exception is: ", e); return null; } } return supDetails; } /* This returns the JSONObject with the following format {<department name(String)>:conf file location(String)>,<department name(String)>:{conf file location(String)>} example: {MDM Plus: ./Files/MEDC_WOESummGen/conf/MDM Plus/connectionConfig.props , Desktop Central: ./Files/MEDC_WOESummGen/conf/Desktop Central/connectionConfig.props } */ public static JSONObject MEDC_WOE_DeptDetails(String fileName) { BufferedReader fileReader = null; final String DELIMITER = ","; final String VALUEDELIMITER = "="; JSONObject deptToConfFile = new JSONObject(); try { String line = ""; //Create the file reader fileReader = new BufferedReader(new FileReader(fileName)); //Read the file line by line while ((line = fileReader.readLine()) != null) { //Get all tokens available in line String[] tokens = line.split(DELIMITER); if (tokens.length < 2) { continue; } String department = null; String confFile = null; if (tokens[0].trim().contains(DEPARTMENT)) { String departmentArr[] = tokens[0].split(VALUEDELIMITER); if (departmentArr.length == 2) { department = departmentArr[1].trim(); } //System.out.println("Dept1: "+ department); } if (tokens[1].trim().contains("conf_file_location")) { String confFileArr[] = tokens[1].split(VALUEDELIMITER); if (confFileArr.length == 2) { confFile = confFileArr[1].trim(); } //System.out.println("ConfFile1: "+ confFile); } //System.out.println("Dept2: "+ department + " confFile2: "+ confFile); deptToConfFile.put(department, confFile); } } catch (Exception e) { loggerObj.log(Level.SEVERE, "Exception while parsing the file " + fileName + "\n Exception is: " + e); return null; } finally { try { fileReader.close(); } catch (IOException e) { loggerObj.log(Level.SEVERE, "Exception while Closing the file " + fileName + "\n Exception is: " + e); return null; } } return deptToConfFile; } public static ArrayList<String> getFilesLocForSupToRepSync(String masterFileLoc) { BufferedReader fileReader = null; final String DELIMITER = ":"; final String comment = "#"; ArrayList<String> fileLocations = new ArrayList<String>(); try { String line = ""; //Create the file reader fileReader = new BufferedReader(new FileReader(masterFileLoc)); //Read the file line by line while ((line = fileReader.readLine()) != null) { //Get all tokens available in line if (!line.startsWith(comment)) { String[] tokens = line.split(DELIMITER); if (tokens.length < 2) { continue; } fileLocations.add(tokens[1].trim()); } } } catch (Exception e) { loggerObj.log(Level.SEVERE, "Exception while parsing the file " + masterFileLoc + "\n Exception is: " + e); return null; } finally { try { fileReader.close(); } catch (IOException e) { loggerObj.log(Level.SEVERE, "Exception while Closing the file " + masterFileLoc + "\n Exception is: " + e); return null; } } return fileLocations; } public static JSONObject mailSettingsToJO(String fileName) { BufferedReader fileReader = null; final String VALUEDELIMITER = "="; final String comment = "#"; JSONObject mailSettings = new JSONObject(); try { String line = ""; //Create the file reader fileReader = new BufferedReader(new FileReader(fileName)); //Read the file line by line while ((line = fileReader.readLine()) != null) { System.out.println("Line:" + line); //Get all tokens available in line if (!line.startsWith(comment)) { String[] tokens = line.split(VALUEDELIMITER); if (tokens.length < 2) { continue; } if (tokens[0].trim().toLowerCase().equals("senderemailaddress")) { //System.out.println("SenderEmailaddress: " + tokens[1].trim()); mailSettings.put("Senderemailaddress", tokens[1].trim()); } } } } catch (Exception e) { loggerObj.log(Level.SEVERE, "Exception while parsing the file " + fileName + "\n Exception is: " + e); return null; } finally { try { fileReader.close(); } catch (IOException e) { loggerObj.log(Level.SEVERE, "Exception while Closing the file " + fileName + "\n Exception is: " + e); return null; } } return mailSettings; } public static JSONObject SupToReportsPropsToJSObj(String fileName) { BufferedReader fileReader = null; final String DELIMITER = ":"; final String VALUEDELIMITER = "="; JSONObject SupToReportsPropsJSObj = new JSONObject(); JSONObject urlparams = new JSONObject(); JSONObject supDetails = new JSONObject(); JSONObject repDetails = new JSONObject(); supDetails.put(URLPARAMS, urlparams); SupToReportsPropsJSObj.put("supDetails", supDetails); SupToReportsPropsJSObj.put("repDetails", repDetails); try { String line = ""; //Create the file reader fileReader = new BufferedReader(new FileReader(fileName)); //Read the file line by line while ((line = fileReader.readLine()) != null) { //Get all tokens available in line String[] tokens = line.split(DELIMITER); if (tokens.length == 0) { continue; } if (tokens[0].equals("sup")) { if (tokens[1].contains("authtoken")) { urlparams.put(AUTHTOKEN, tokens[1].split(VALUEDELIMITER)[1].trim()); } else if (tokens[1].contains("portal")) { urlparams.put(PORTAL, tokens[1].split(VALUEDELIMITER)[1].trim()); } else if (tokens[1].contains("department")) { urlparams.put(DEPARTMENT, tokens[1].split(VALUEDELIMITER)[1].trim()); } else if (tokens[1].contains("columns")) { String columnsStr = tokens[1].split(VALUEDELIMITER)[1].trim(); String[] columnsArr = columnsStr.split(","); supDetails.put(COLUMNS, columnsArr); } else if (tokens[1].contains("SearchCriteria")) { String searchCriteria = tokens[1].split(VALUEDELIMITER)[1].trim(); String[] searchParams = searchCriteria.split("@"); supDetails.put(SEARCHPARAMS, searchParams); } } else if (tokens[0].equals("rep")) { if (tokens[1].contains("URLEmail")) { repDetails.put("URLEmail", tokens[1].split(VALUEDELIMITER)[1].trim()); } else if (tokens[1].contains("DBName")) { repDetails.put("DBName", tokens[1].split(VALUEDELIMITER)[1].trim()); } else if (tokens[1].contains("TableName")) { repDetails.put("TableName", tokens[1].split(VALUEDELIMITER)[1].trim()); } else if (tokens[1].contains("authToken")) { repDetails.put(AUTHTOKEN, tokens[1].split(VALUEDELIMITER)[1].trim()); } if (tokens[1].contains("ZOHO_IMPORT_TYPE")) { repDetails.put("ZOHO_IMPORT_TYPE", tokens[1].split(VALUEDELIMITER)[1].trim()); } else if (tokens[1].contains("ZOHO_ON_IMPORT_ERROR")) { repDetails.put("ZOHO_ON_IMPORT_ERROR", tokens[1].split(VALUEDELIMITER)[1].trim()); } else if (tokens[1].contains("ZOHO_MATCHING_COLUMNS")) { repDetails.put("ZOHO_MATCHING_COLUMNS", tokens[1].split(VALUEDELIMITER)[1].trim()); } else if (tokens[1].contains("ZOHO_DATE_FORMAT")) { repDetails.put("ZOHO_DATE_FORMAT", tokens[1].split(VALUEDELIMITER)[1].trim()); } else if (tokens[1].contains("ZOHO_SELECTED_COLUMNS")) { // repDetails.put("ZOHO_DATE_FORMAT",tokens[1].split(VALUEDELIMITER)[1].trim()); repDetails.put("ZOHO_SELECTED_COLUMNS", tokens[1].split(VALUEDELIMITER)[1].trim()); } } else if (tokens[0].equals("sup_rep")) { String Sup_rep_Columns = tokens[1].trim(); if (Sup_rep_Columns != null && !Sup_rep_Columns.equals("")) { repDetails.put("supTorepColumnHeader", Sup_rep_Columns); } } else if (tokens[0].equals("rep_extra")) { String extraColumns = tokens[1].trim(); if (extraColumns != null && !extraColumns.equals("")) { repDetails.put("newColumnHeader", extraColumns); } } } } catch (Exception e) { loggerObj.log(Level.SEVERE, "Exception while parsing the file " + fileName + "\n Exception is: ", e); return null; } finally { try { fileReader.close(); } catch (IOException e) { loggerObj.log(Level.SEVERE, "Exception while Closing the file " + fileName + "\n Exception is: ", e); return null; } } return SupToReportsPropsJSObj; } }