Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, July 3, 2024

Read a CSV file, copy the CSV file data, concatenate two columns from original file and write it to another csv file

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CSVModifier {
public static void main(String[] args) {
String line;
String inputFilePath = "F:\\DOCS\\test_03072024.csv";
String outputFilePath = "F:\\DOCS\\updated_test_03072024.csv";

try  {

BufferedReader br = new BufferedReader(new FileReader(inputFilePath));
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFilePath));

// Read the header
String header = br.readLine();
if (header != null) {
String[] headers = header.split(",");
int appIndex = -1;
int roleNameIndex = -1;

// Find the indices of "app" and "Role Name"
for (int i = 0; i < headers.length; i++) {
if (headers[i].trim().equalsIgnoreCase("app")) {
appIndex = i;
} else if (headers[i].trim().equalsIgnoreCase("Role Name")) {
roleNameIndex = i;
}
}

// Check if both columns were found
if (appIndex == -1 || roleNameIndex == -1) {
throw new IllegalArgumentException(
"Input CSV does not contain required columns 'Service' and 'Role Name'");
}

// Add the new column to the header
header += ",app|RoleName";
bw.write(header);
bw.newLine();

// Read and process each line
while ((line = br.readLine()) != null) {
String[] columns = line.split(",");
String app = columns[appIndex];
String roleName = columns[roleNameIndex];
// Concatenate "app" and "Role Name"
String newColumn = app + "|" + roleName;
// Add the new column to the line
line += "," + newColumn;
bw.write(line);
bw.newLine();
}
}
bw.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}

Friday, May 3, 2024

Trim the String

public static String getNotNullString(String value){

String returnValue = "";

if (value != null) {

 str = value.trim();

 }

 return returnValue ;

}

Saturday, February 17, 2024

Map inside Map

HashMap primasRoleIdMap = new HashMap();

primasRoleIdMap.put("roleId", "");

primasRoleIdMap.put("roleType", "");

HashMap<String, HashMap> primasRoleMap = new HashMap();

primasRoleMap.put("roleIds", primasRoleIdMap);


Tuesday, February 6, 2024

Adv Policy Java

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

public class Policy{

Map<String, String> identityRoles = new HashMap<>();

Map<String, String> requestRoles = new HashMap<>();

Map<String, Integer> tempMap = new HashMap<>();

List<String> duplicateReq = new ArrayList<>();

Map<String, String> customOrg = new HashMap<>();


public void validationInProcess() {

customOrg.put("orgO1", "Organization One DName");

customOrg.put("orgO2", "Organization two DName");


identityRoles.put("BR1", "orgO1");

identityRoles.put("BR2", "orgO2");

identityRoles.put("BR9", "orgO3");

identityRoles.put("BR12", "orgO4");


requestRoles.put("BR2", "orgO1");

requestRoles.put("BR1", "orgO2");

requestRoles.put("BR10", "orgO4");

requestRoles.put("BR11", "orgO5");


if (!requestRoles.isEmpty() && identityRoles.isEmpty()) {

if (requestRoles.size() == 1) {

System.out.println("Requested one role and no assigned roles found. Processing request. ");

} else {

System.out.println("Requested multiple Roles. Undergoing Organization duplicate valdiation.");

List<String> listOfReqRoles = new ArrayList<>(requestRoles.values());

List<String> duplicateReq = validateDuplicateOrg(listOfReqRoles);

processRequest(duplicateReq);

}

} else if (!identityRoles.isEmpty() && requestRoles.isEmpty()) {

if (requestRoles.size() == 1) {

System.out.println("Requested one role and no assigned roles found. Processing request. ");

} else {

System.out.println("Requested multiple Roles. Undergoing Organization duplicate valdiation.");

List<String> listOfDetRoles = new ArrayList<>(identityRoles.values());

List<String> duplicateDet = validateDuplicateOrg(listOfDetRoles);

processRequest(duplicateDet);

}

} else if (!identityRoles.isEmpty() && !requestRoles.isEmpty()) {

if (requestRoles.size() == 1) {

System.out.println("Requested One Role");

validateRoleCount(identityRoles, requestRoles);

} else {

List<String> listOfReqRoles = new ArrayList<>(requestRoles.values());

List<String> duplicateReq = validateDuplicateOrg(listOfReqRoles);

if (processRequest(duplicateReq)) {

validateRoleCount(identityRoles, requestRoles);

}

}

}

}

public List<String> validateDuplicateOrg(List<String> listOfRoles) {

List<String> duplicate = new ArrayList<>();

System.out.println("Validating Duplication. Requested Role's Organization : " + listOfRoles.toString());

for (int i = 0; i < listOfRoles.size(); i++) {

for (int j = i + 1; j < listOfRoles.size(); j++) {

if (listOfRoles.get(i).equalsIgnoreCase(listOfRoles.get(j))) {

duplicate.add(listOfRoles.get(i));

}

}

}

return duplicate;

}

public boolean processRequest(List<String> processList) {

boolean flag = false;

if (!processList.isEmpty()) {

for (int i = 0; i < processList.size(); i++) {

if (customOrg.containsKey(processList.get(i))) {

System.out.println("Requested Roles found Duplicate Org : " + processList.get(i));

flag = false;

} else {

System.out.println("Requeste role not found in Org . Processing Request");

flag = true;

}

}

} else {

System.out.println("No duplicate found. Processing request.");

flag = true;

}

return flag;

}

public Map<String, Integer> validateRoleCount(Map<String, String> identityRoles, Map<String, String> requestRoles) {

int OrgCount = 0;

for (Map.Entry<String, String> identityRole : identityRoles.entrySet()) {

for (Map.Entry<String, String> requestRole : requestRoles.entrySet()) {

if (customOrg.containsKey(identityRole.getValue()) && customOrg.containsKey(requestRole.getValue())) {

if (identityRole.getValue().equalsIgnoreCase(requestRole.getValue())) {

OrgCount++;

}

}

}

if (OrgCount >= 1) {

for (Map.Entry<String, String> customRole : customOrg.entrySet()) {

if (customRole.getKey().equalsIgnoreCase(identityRole.getValue())) {

OrgCount += 1;

tempMap.put(customRole.getKey(), OrgCount);

}

}

}

OrgCount = 0; }

for (Map.Entry<String, Integer> entry : tempMap.entrySet())

System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

return tempMap;

}

public static void main(String[] args) {

new Policy().validationInProcess();

}

}


Thursday, February 1, 2024

Finding Duplicate Organization Names

import java.util.HashMap;

import java.util.Map;

public class OrgRole {

Map<String,String> custom=new HashMap<>();

Map<String,String> identityRoles=new HashMap<>();

Map<String,Integer> tempMap=new HashMap<>();

void ValidatingRole(){

custom.put("OrgR1", "OR1");

custom.put("OrgR2", "OR2");

custom.put("OrgR3", "OR3");

custom.put("OrgR4", "OR4");

identityRoles.put("OrgKey1", "OR4");

identityRoles.put("OrgKey2", "OR4");

identityRoles.put("OrgKey3", "OR4");

identityRoles.put("OrgKey4", "OR2");

identityRoles.put("OrgKey5", "OR2");

int OrgCount = 0;

for (Map.Entry<String,String> orgRole : custom.entrySet()) {

for (Map.Entry<String,String> identityRole : identityRoles.entrySet()) {

if(orgRole.getValue().equalsIgnoreCase(identityRole.getValue())) {

OrgCount++;

}

}

if(OrgCount >= 2){

tempMap.put(orgRole.getValue(), OrgCount);

}

OrgCount=0;

}

for (Map.Entry<String,Integer> entry : tempMap.entrySet())  

            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 

}

public static void main(String[] args) {

new OrgRole().ValidatingRole();

}

}

====================================================================================================================================================

HashMap hashMap = null;

Custom custom = context.getObjectByName(Custom.class, "Container - SODRoles Custom Object");

attributes = custom.getAttributes();

List SODRolekeys = attributes.getKeys();

for (String containerRolekey : SODRolekeys) {

hashMap.put(containerRolekey, custom.get(containerRolekey));

}

====================================================================================================================================================

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

public class AdvPolicyViolation {

List<String> duplicateReq = new ArrayList<>();

Map<String, String> customOrg = new HashMap<>();

Map<String, String> identityRoles = new HashMap<>();

Map<String, String> requestRoles = new HashMap<>();

Map<String, Integer> tempMap = new HashMap<>();

void ValidatingRole() {

customOrg.put("orgO1", "Organization One DName");

customOrg.put("orgO2", "Organization two DName");

identityRoles.put("BR1", "orgO1");

identityRoles.put("BR5", "orgO2");

identityRoles.put("BR9", "orgO3");

identityRoles.put("BR12", "orgO4");

requestRoles.put("BR2", "orgO1");

requestRoles.put("BR5", "orgO2");

requestRoles.put("BR10", "orgO4");

requestRoles.put("BR11", "orgO5");

if (requestRoles.size() == 1) {

System.out.println("One request role found");

validateRoleCount(identityRoles, requestRoles);

} else {

System.out.println("Multiple request roles are found");

List<String> listOfReqRoles = new ArrayList<>(requestRoles.values());

for (int i = 0; i < requestRoles.size(); i++) {

for (int j = i + 1; j < listOfReqRoles.size(); j++) {

if (listOfReqRoles.get(i).equalsIgnoreCase(listOfReqRoles.get(j))) {

duplicateReq.add(listOfReqRoles.get(i));

}

}

}

if (!duplicateReq.isEmpty()) {

for (int i = 0; i < duplicateReq.size(); i++) {

if (customOrg.containsKey(duplicateReq.get(i))) {

System.out.println("Requested Roles found Duplicate Org " + duplicateReq.get(i));

// return duplicates found

} else {

System.out.println("Requeste role not found in Org . Processing Request");

// process request

}

}

} else {

System.out.println("No duplicate found. Processing request.");

validateRoleCount(identityRoles, requestRoles);

}

}

}

public Map<String, Integer> validateRoleCount(Map<String, String> identityRoles, Map<String, String> requestRoles) {

int orgCount = 0;

for (Map.Entry<String, String> identityRole : identityRoles.entrySet()) {

for (Map.Entry<String, String> requestRole : requestRoles.entrySet()) {

if (customOrg.containsKey(identityRole.getValue()) && customOrg.containsKey(requestRole.getValue())) {

if (identityRole.getValue().equalsIgnoreCase(requestRole.getValue())) {

orgCount++;

}

}

}

if (orgCount >= 1) {

for (Map.Entry<String, String> customRole : customOrg.entrySet()) {

if (customRole.getKey().equalsIgnoreCase(identityRole.getValue())) {

orgCount += 1;

tempMap.put(customRole.getKey(), orgCount);

}

}

}

orgCount = 0;

}

for (Map.Entry<String, Integer> entry : tempMap.entrySet())

System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

return tempMap;

}

public static void main(String[] args) {

new AdvPolicyViolation().ValidatingRole();

}

}

Wednesday, April 13, 2022

LDAPConnection suing Java Code

import java.util.Hashtable;

import javax.naming.Context;

import javax.naming.NamingException;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;


public class LdapConnection {

     public static void main(String[] args) {

          Hashtable env = new Hashtable();

          env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");

          env.put(Context.PROVIDER_URL,"ldap://localhost:389");

          try {

               LdapContext ctx = new InitialLdapContext(env,null);

               System.out.println("LDAP Connection Successful");

               System.exit(0);

          } catch (NamingException e) {

               System.err.println("LDAP Notifications failure. " + e.getMessage());

               System.exit(1);

          }

      }

}

Monday, January 25, 2021

How to fetch file from SFTP (Server)?

File inputFileorDirectory = new File(inputMap.get("Input File Path").toString());

LOGGER.debug("Input file or Directory is : " + inputFileorDirectory.getName());

System.out.println("Input file or Directory is : " + inputFileorDirectory.getName());


if (inputFileorDirectory.isDirectory()) {

LOGGER.debug("Input is a Directory : " + inputFileorDirectory.getName());

System.out.println("Input is a Directory : " + inputFileorDirectory.getName());


FilenameFilter fileNameFilter = new FilenameFilter() {

@Override

public boolean accept(File dir, String name) {

if (name.endsWith("csv")) {

return true;

} else {

return false;

}

}

};

String[] inputFileNames = inputFileorDirectory.list(fileNameFilter);

if (inputFileNames == null || inputFileNames.length == 0) {

LOGGER.error("No Files present inside the directory");

System.out.println("No Files present inside the directory");

throw new Exception("No Files present inside the directory");

}

for (String inputFileName : inputFileNames) {

// Process Records

String data = readData(inputFileorDirectory.getAbsolutePath() + File.separator + inputFileName);

System.out.println("Data : " + data);

LOGGER.debug("Data : " + data);

}

}

 

Friday, January 8, 2021

How to fetch session of JSON Object?

 public static String getSessionIdJSONObject(String userName, String password, HashMap<String, String> lookupData) {

String methodName = "getSessionIdJSONObject";

LOGGER.debug(CLASS_NAME + "/" + methodName + "; userName = " + userName + "; password = " + password);

System.out.println(CLASS_NAME + "/" + methodName + "; userName = " + userName + "; password = " + password);


String WS_URL = null;

URL url = null;

String retVal = "SUCCESS";

StringBuffer response = null;

OutputStream os = null;

BufferedReader in = null;

try {

String webServiceParams = "{\"UserName\":\"" + userName + "\"" + " , \"Password\":\"" + password + "\"}";

System.out.println("webServiceParams : " + webServiceParams);


WS_URL = lookupData.get("SessionIdURL");

System.out.println("WebService URL :" + WS_URL);


url = new URL(WS_URL);

                        //url = new URL(null, WS_URL, new sun.net.www.protocol.https.Handler());

HttpsURLConnection postConnection = (HttpsURLConnection) url.openConnection();

postConnection.setRequestMethod("POST");

postConnection.setRequestProperty("Content-Type", "application/json");

postConnection.setDoOutput(true);

os = postConnection.getOutputStream();

os.write(webServiceParams.getBytes());


int responseCode = postConnection.getResponseCode();

System.out.println("POST Response Code :  " + responseCode);

System.out.println("POST Response Message : " + postConnection.getResponseMessage());


if (responseCode == 200) { // success

in = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));

String inputLine;

response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

}

// print result

System.out.println("JSON object is : " + response.toString());

LOGGER.debug("JSON object is : " + response.toString());


} else {

retVal = "FAIL";

System.out.println("Return value is : " + retVal);

System.out.println("POST NOT WORKED");

LOGGER.debug("Return value is : " + retVal);

LOGGER.debug("POST NOT WORKED");

}

}


catch (Exception e) {

System.out.println("Exception is : " + e.getMessage());

LOGGER.error("Exception is : " + e.getMessage());

e.printStackTrace();

} // End of Catch block

finally {

closeIOFile(os, in);

}

System.out.println("Return value is : " + retVal);

LOGGER.debug("Return value is : " + retVal);

System.out.println("Exiting from the method : " + methodName);

LOGGER.debug("Exiting from the method : " + methodName);

return response.toString();

}


NOTE :  

Ex: SessionIdURL = "https://oimsailpointpedia.blogspot.com/search/label/Java";

How to fetch user status of JOSN Object?

 public static String extractUserState(String jsonObject)

throws ParseException, JsonParseException, JsonMappingException, IOException {

String methodName = "extractUserState";

LOGGER.debug(CLASS_NAME + "/" + methodName + "; jsonObject = " + jsonObject);

System.out.println(CLASS_NAME + "/" + methodName + "; jsonObject = " + jsonObject);


String userStatus = null;

String id = null;

State state = new State();

ObjectMapper objectMapper = new ObjectMapper();

Entities entities = objectMapper.readValue(jsonObject, Entities.class);

System.out.println("Entities lenght  : " + entities.getEntities().length);

if (entities.getEntities().length != 0) {

for (User user : entities.getEntities()) {

state = user.getState();

id = state.getId();

userStatus = id.substring(7);

System.out.println(id.substring(7));

}

}

System.out.println("Exiting from the method : " + methodName);

LOGGER.debug("Exiting from the method : " + methodName);

return userStatus;

}

How to fetch User Id / External Id of JSON Object?

 // fetch external user Id

public static String extractUserId(String jsonObject)

throws ParseException, JsonParseException, JsonMappingException, IOException {

String methodName = "extractUserId";

LOGGER.debug(CLASS_NAME + "/" + methodName);

System.out.println(CLASS_NAME + "/" + methodName);

String externalUserIDValue = null;

ObjectMapper objectMapper = new ObjectMapper();

Entities entities = objectMapper.readValue(jsonObject, Entities.class);

System.out.println("Entities lenght  : " + entities.getEntities().length);

if (entities.getEntities().length != 0) {

for (User user : entities.getEntities()) {

externalUserIDValue = user.getExternalId();

}

}

System.out.println("Exiting from the method : " + methodName);

LOGGER.debug("Exiting from the method : " + methodName);

return externalUserIDValue;

}


How to fetch Session Id of JSONObject?

public static String extractSessionIDFromGetSessionId(String jsonObject) throws ParseException {

String methodName = "extractSessionIDFromGetSessionId";

LOGGER.debug(CLASS_NAME + "/" + methodName + "; jsonObject = " + jsonObject);

System.out.println(CLASS_NAME + "/" + methodName + "; jsonObject = " + jsonObject);


JSONParser parser = new JSONParser();

String sessionId = "";

System.out.println("JSON object is :" + jsonObject);

LOGGER.debug("JSON object is :" + jsonObject);


Object obj = parser.parse(jsonObject);

JSONObject jo = (JSONObject) obj;

sessionId = jo.get("sessionId").toString();

System.out.println("SessionId is : " + sessionId);


System.out.println("Exiting from the method : " + methodName);

LOGGER.debug("Exiting from the method : " + methodName);

return sessionId;

}

NOTE: JSON Jar is required


Tuesday, July 28, 2020

Reading data from CSV file (by using CSVReader - CSV-2.5 jar is required)

String filePath = "D:\IDM\Sailpoint\sailpoint7.3\AuthEMP.csv"
File file = new File(filePath);
FileReader fileReader = new FileReader(file);
CSVReader csvReader = new CSVReader(fileReader);
List<String> inValidRecords = new ArrayList<String>());

List<String> headersList = new ArrayList<String>(Arrays.asList(csvReader.readNext()));
List<String[]> listOfRecords = csvReader.readAll();

for(Strin[] record : listOfRecords){

    if(record != null){
        boolean isValid = updateMethod(record[headersList.indexOf("userLogin")],record[headersList.indexOf("employeeNumber")],record[headersList.indexOf("justification")],record[headersList.indexOf("endDate")]);

if(!isValid){
System.ou.println("Adding record to invalid List :  UserLogin = "+record[headersList.indexOf("userLogin")] +", UPI= "+  record[headersList.indexOf("employeeNumber")]);

inValidRecords.add(record);
        }
    }
}

String to Date to String to Date Conversion code

// Fetch current date :

Calender calender = Calender.getInstance();
Date currentDate = calender.getTime();

// Printing  current date in terminal :

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
System.setProperty("current_time", dateFormat.format(new Date()));

// Converting String to Date to String to Date

String endDate = "20200728";
Date date1 = new SimpleDateFormat("yyyyMMdd").parse(endDate);
SimpleDateFormat newFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
String str = newFormat.format(date1);
Date date2 = newFormat(str);

Java String to Date Example :

String sDate1="10/03/1994";  
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);  
System.out.println(sDate1+"\t"+date1);

Java Date to String Example :

Date date = Calendar.getInstance().getTime();  
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");  
String strDate = dateFormat.format(date);  
System.out.println("Before conversion of date into String: " + date); 
System.out.println("After conversion of date into String: " + strDate); 

// Inserting user data into EMP table

Connection connection = Platform.getConnection();
PreparedStatement pstmt = connection.prepareStatement("insert into EMP(userLogin,employeeNumber,reason,end_Date) values(?,?,?,?)");

pstmt.setString(1, userLogin);
pstmt.setString(2, upi);
pstmt.setString(3, reason);
pstmt.setDate(4, new java.sql.Date(date2.getTime));
pstmt.exceuteUpdate();
connection.commit();


VA Installation & Configuration

Definition : A VA is a Linux-based virtual machine that connects to your sources and apps using SailPoint APIs, connectors, and integrations...

Featured Articles