Showing posts with label OIM. Show all posts
Showing posts with label OIM. Show all posts

Friday, January 8, 2021

How to fetch ITReosurce Key based on applicationInstance?

 private String getITResourceKey(String applicationInstanceName) {

System.out.println(CLASS_NAME + " Start of getITResourceKey()");

                Connection connection = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

String itResourceKey = null;

try {

String query = "select itresource_key from app_instance where app_instance_display_name=?";

pstmt = connection.prepareStatement(query);

pstmt.setString(1, applicationInstanceName);

rs = pstmt.executeQuery();

if (rs.next()) {

itResourceKey = rs.getString("itresource_key");

}

                      } catch (Exception e) {

e.printStackTrace();

}finallly{

                       connection.close();

pstmt.close();

rs.close();

                }

return itResourceKey;

}


How to send email with attachment ?

 public static boolean sendMail(String[] emailto, String sFrom, InternetAddress[] iCC, InternetAddress[] iBCC,

String sSubject, String sMessage, String sAttachment, String host, String port) throws AddressException {


String methodName = "sendMail";

System.out.println(CLASS_NAME + methodName + "Inside : FileName : " + sAttachment);

LOGGER.debug(CLASS_NAME + methodName + "Inside : FileName : " + sAttachment);


// InternetAddress[] to = iAddr;

InternetAddress[] address = new InternetAddress[emailto.length];

int i;

for (i = 0; i < emailto.length; i++) {

address[i] = new InternetAddress(emailto[i]);

System.out.println("To " + address[i]);

}

// String subject = sSubject + "-" + falloutUserVOs.size();

String subject = sSubject;

String from = sFrom;


Properties properties = System.getProperties();

properties.setProperty("mail.smtp.host", host);

properties.setProperty("mail.smtp.port", port);

Session session = Session.getDefaultInstance(properties);

System.out.println(CLASS_NAME + methodName + "Property Added Successfully");

LOGGER.debug(CLASS_NAME + methodName + "Property Added Successfully");


try {

MimeMessage message = new MimeMessage(session);

message.setFrom(new InternetAddress(from));

message.setRecipients(Message.RecipientType.TO, (Address[]) address);

if (iCC != null) {

message.addRecipients(Message.RecipientType.CC, iCC);

}

if (iBCC != null) {

message.addRecipients(Message.RecipientType.BCC, iBCC);

}

message.setSubject(subject);

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

message.setContent(sMessage, "text/html");

} else {

System.out.println(CLASS_NAME + methodName + "Recipents Added Successfully");

LOGGER.debug(CLASS_NAME + methodName + "Recipents Added Successfully");

MimeBodyPart mimeBodyPart = new MimeBodyPart();

mimeBodyPart.setContent(sMessage, "text/html");


MimeMultipart mimeMultipart = new MimeMultipart();

mimeMultipart.addBodyPart(mimeBodyPart);


mimeBodyPart = new MimeBodyPart();

String filename = sAttachment;


DataSource source = new FileDataSource(filename);

mimeBodyPart.setDataHandler(new DataHandler(source));


String strPath = filename.substring(filename.lastIndexOf("/") + 1, filename.length());

mimeBodyPart.setFileName(strPath);

mimeMultipart.addBodyPart(mimeBodyPart);

// Send the complete message parts

message.setContent(mimeMultipart);

}

// Send message

Transport.send(message);

System.out.println(CLASS_NAME + methodName + "Sent message successfully....");

LOGGER.debug(CLASS_NAME + methodName + "Sent message successfully....");


} catch (MessagingException mex) {

System.out.println(CLASS_NAME + methodName + " ERROR : " + mex.getMessage());

LOGGER.error(CLASS_NAME + methodName + " ERROR : " + mex.getMessage());

return false;

}

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

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

return true;

}


-----------------------------------------------------------------------------------------------------------------------------

tcLookupOperationsIntf lookupOps = Platform.getService(tcLookupOperationsIntf.class);

String toEmails = lookupOps.getDecodedValueForEncodedValue("Lookup.Clarizen.WebService", "TO_EMAIL");

String[] to = toEmails.split(",");

boolean emailStatus1 = sendMail(to, lookupData.get("SENDER_EMAIL"), null, null,

lookupData.get("EMAIL_SUBJECT"), lookupData.get("MESSAGE"), fallout_userFilePath, lookupData.get("SMTP_PRIMARY_HOST"),

lookupData.get("SMTP_PORT"));


How to fetch childData in OIM?

 public static HashMap<String, String> getChildData(String requestID) {

String methodName = "getChildData";

System.out.println(CLASS_NAME + "/" + methodName + "; Request ID = " + requestID);

HashMap functionRoleApplicationMap = new HashMap();

try {

Request request = getRequestObject(requestID);

List beneficiaryList = request.getBeneficiaries();

List reqBeneficiaryEntityList = ((Beneficiary) beneficiaryList.get(0)).getTargetEntities();

List<RequestBeneficiaryEntityAttribute> reqBeneficiaryEntityAttributeList = ((RequestBeneficiaryEntity) reqBeneficiaryEntityList

.get(0)).getEntityData();

for (RequestBeneficiaryEntityAttribute reqBeneficiaryEntityAttribute : reqBeneficiaryEntityAttributeList) {

if (reqBeneficiaryEntityAttribute.getName().equalsIgnoreCase("TABLE_NAME")) {

List<RequestBeneficiaryEntityAttribute> childAttributeList = reqBeneficiaryEntityAttribute

.getChildAttributes();


String fieldName = "";

String fieldValue = "";

for (RequestBeneficiaryEntityAttribute childAttribute : childAttributeList) {

if (childAttribute.getName().equalsIgnoreCase("Field Name")) {

fieldName = childAttribute.getValueHolder().toString();

}

if (childAttribute.getName().equalsIgnoreCase("Field Value")

&& null != childAttribute.getValueHolder()) {

fieldValue = childAttribute.getValueHolder().toString();

}

}

// System.out.println(fieldName + "==" + fieldValue);

functionRoleApplicationMap.put(fieldName, fieldValue);

}

}

} catch (Exception e) {

e.printStackTrace();

}

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

return functionRoleApplicationMap;

}


How to fetch parent form Data in OIM?

public static Map<String, String> getParentFormData(long processKey)

throws tcAPIException, tcInvalidLookupException, tcColumnNotFoundException, tcFormNotFoundException,

tcProcessNotFoundException, tcVersionNotFoundException, tcNotAtomicProcessException, LoginException {

String methodName = "getParentFormData";

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

tcFormInstanceOperationsIntf formInstOps = Platform.getService(tcFormInstanceOperationsIntf.class);

tcFormDefinitionOperationsIntf formDefOps = Platform.getService(tcFormDefinitionOperationsIntf.class);

tcResultSet tcresultset = formInstOps.getProcessFormData(processKey);

long l1 = formInstOps.getProcessFormDefinitionKey(processKey);

tcResultSet formFieldresultset = formDefOps.getFormFields(l1, formInstOps.getProcessFormVersion(processKey));

int formfieldCount = formFieldresultset.getRowCount();

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

for (int j1 = 0; j1 < formfieldCount; j1++) {

formFieldresultset.goToRow(j1);

String s4 = formFieldresultset.getStringValue(Structure Utility.Additional Columns.Field Label);

String val = tcresultset

.getStringValue(formFieldresultset.getStringValue(Structure Utility.Additional Columns.Name));

result.put(s4, val);

}

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

return result;

}                                        

How to fetch Old Manager Login and New Manager Login in Post Process EventHandler

 public class UserManagerEventHandler implements PostProcessHandler {

private static final Logger LOGGER = Logger.getLogger(UserManagerEventHandler.class.getName());

private static final String CLASS_NAME = UserManagerEventHandler.class.getName();

@Override

public boolean cancel(long arg0, long arg1, AbstractGenericOrchestration arg2) {

return false;

}

@Override

public void compensate(long arg0, long arg1, AbstractGenericOrchestration arg2) {

}

@Override

public BulkEventResult execute(long arg0, long arg1, BulkOrchestration arg2) {

return null;

}

/**

* @param processId    

*            OIM.ORCHEVENTS.ProcessId

* @param eventId      

*            OIM.ORCHEVENTS.ID

* @param orchestration

*            Holds useful data

*/

@Override

public EventResult execute(long processId, long eventId, Orchestration orchestration) {

String methodName = "execute";

System.out.println(CLASS_NAME + "/" + methodName + "; processId = " + processId + "; eventId = " + eventId

+ "; orchestration = " + orchestration);

LOGGER.debug(CLASS_NAME + "/" + methodName + "; processId = " + processId + "; eventId = " + eventId

+ "; orchestration = " + orchestration);

try {

// contains only the new values

HashMap<String, Serializable> newParameters = orchestration.getParameters();

// contains old and new

HashMap<String, Serializable> interParameters = orchestration.getInterEventData();

// values of user

System.out.println(String.format("Inter Parameters: %s ", interParameters));

System.out.println(String.format("New Parameters: %s ", newParameters));


User currentUserState = (User) interParameters.get("CURRENT_USER");


Long oldManagerKey = currentUserState.getAttribute("usr_manager_key") instanceof ContextAware

? (Long) ((ContextAware) currentUserState.getAttribute("usr_manager_key")).getObjectValue()

: (Long) currentUserState.getAttribute("usr_manager_key");


Long newManagerKey = getParamaterStringValue(newParameters, "usr_manager_key");


Long newMangerID = newParameters.get(AttributeName.MANAGER_KEY.getId()) instanceof ContextAware

? (Long) ((ContextAware) newParameters.get(AttributeName.MANAGER_KEY.getId())).getObjectValue()

: (Long) newParameters.get(AttributeName.MANAGER_KEY.getId());


Long oldManagerID = null;

oldManagerID = (Long) currentUserState.getAttribute(AttributeName.MANAGER_KEY.getId());


LOGGER.debug(CLASS_NAME + "newMangerID:\t" + newMangerID);

LOGGER.debug(CLASS_NAME + "newManagerKey:\t" + newManagerKey);

LOGGER.debug(CLASS_NAME + "oldManagerID" + oldManagerID);

LOGGER.debug(CLASS_NAME + "oldManagerKey" + oldManagerKey);


LOGGER.debug(CLASS_NAME + "User Login:\t" + currentUserState.getLogin());


String userLogin = currentUserState.getLogin().toUpperCase();

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

LOGGER.debug("userLogin : " + userLogin);


String newMGRKey = String.valueOf(newManagerKey);

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

LOGGER.debug("newMGRKey : " + newMGRKey);


String newManagerUserLogin = "";

String oldManagerUserLogin = "";

UserManager usrMgr = Platform.getService(UserManager.class);


// Check existence of manager key

if (newMGRKey != null) {

User newmanagerUser = usrMgr.getDetails(newMGRKey, new HashSet<String>(), false);

newManagerUserLogin = newmanagerUser.getLogin().toUpperCase();

LOGGER.debug("New Manager Login : " + newManagerUserLogin);

System.out.println("New Manager Login : " + newManagerUserLogin);

}

String oldMGRKey = String.valueOf(oldManagerKey);

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

LOGGER.debug("oldMGRKey : " + oldMGRKey);


// Check existence of manager key

if (oldMGRKey != null) {

User oldManagerUser = usrMgr.getDetails(oldMGRKey, new HashSet<String>(), false);

oldManagerUserLogin = oldManagerUser.getLogin().toUpperCase();

LOGGER.debug("Old Manager Login : " + oldManagerUserLogin);

System.out.println("Old Manager Login : " + oldManagerUserLogin);

}

if (oldManagerID != null && newMangerID != null && newMangerID != oldManagerID) {

System.out.println("Manager update is invoking :");

LOGGER.debug("Manager update is invoking :");


String managerUpdateStatus = ManagerChange.managerChange(userLogin, oldManagerUserLogin, newManagerUserLogin);

}

}

catch (Exception ex) {

LOGGER.error(CLASS_NAME + "Error occured in Process Evenet Handler");

System.out.println(CLASS_NAME + "/" + " Exception : " + ex.getMessage());

ex.printStackTrace();

}

return new EventResult();

}

/**

* ContextAware object is obtained when the actor is a regular user. If the

* actor is an administrator, the exact value of the attribute is obtained.

* @param parameters   

*            parameters from the orchestration object

* @param key  

*            name of User Attribute in OIM Profile or column in USR table

* @return value of the corresponding key in parameters

*/

private Long getParamaterStringValue(HashMap<String, Serializable> parameters, String key) {

Long value = parameters.get(key) instanceof ContextAware

? (Long) ((ContextAware) parameters.get(key)).getObjectValue() : (Long) parameters.get(key);

return value;

}

@Override

public void initialize(HashMap<String, String> arg0) {

}

}

Friday, December 18, 2020

Change / Update the end date for XELSYSADM user

update USR 

set usr_pwd_warn_date=null, usr_pwd_expire_date=null, usr_pwd_never_expires='1'  

where usr_login='XELSYSADM';

commit;

                                                                    (OR)

update USR 

set usr_pwd_warn_date=null, usr_pwd_expire_date='01-04-21', usr_pwd_never_expires='1'  

where usr_login='XELSYSADM';

commit;


NOTE : 

Date :   dd/MM/yy

Monday, November 16, 2020

How to fetch childData(Roles or Entitlements ) in OIM?

 public static HashMap<String, String> getChildData(Account resourceAccount) {

String methodName = "getChildData";

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

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

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

String childFormName = "UD_PEDIA_PC";

        String fieldName = "";

String fieldValue = "";

Map<String, ArrayList<ChildTableRecord>> childData = resourceAccount.getAccountData().getChildData();

Iterator iter = childData.entrySet().iterator();

while (true) {

String currentChildFormName;

ArrayList childFormData;

do {

if (!iter.hasNext()) {

return childDataMap;

}

Entry pairs = (Entry) iter.next();

currentChildFormName = (String) pairs.getKey();

childFormData = (ArrayList) pairs.getValue();

} while (!currentChildFormName.equals(childFormName));

Iterator var10 = childFormData.iterator();

while (var10.hasNext()) {

ChildTableRecord record = (ChildTableRecord) var10.next();

Map<String, Object> childRecordData = record.getChildData();

fieldName = (String) childRecordData.get("UD_PEDIA_PC_FIELDNAME");

fieldValue = (String) childRecordData.get("UD_PEDIA_PC_VALUE");

childDataMap.put(fieldName, fieldValue);

}

}

}

How to fetch user key and user status by using UserLogin in OIM?

 public static HashMap<String, String> getUserDetails(String userLogin) {

String methodName = "getUserDetails";

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

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

String userKey = "";

String userStatus = "";

String query = "SELECT * FROM USR WHERE usr_login ='" + userLogin + "' AND                            usr_status = 'Active'";

HashMap<String, String> hashMap = null;

Connection connection = null;

PreparedStatement preparedStatement = null;

ResultSet rs = null;

try {

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

connection = Platform.getOperationalDS().getConnection();

preparedStatement = connection.prepareStatement(query);

rs = preparedStatement.executeQuery(query);

while (rs.next()) {

userKey = rs.getString("USR_KEY");

userStatus = rs.getString("USR_STATUS");

hashMap.put("User Key", userKey);

hashMap.put("User Status", userStatus);

}

} catch (SQLException e) {

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

LOGGER.error("SQLException : " + e.getMessage());

e.printStackTrace();

} finally {

closeDatabaseConnections(connection, preparedStatement, rs);

}

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

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

return hashMap;

}

Saturday, September 19, 2020

How to fetch users from group or entitlement

private String[] fetchUsersFromGroup(String groupName){

String[] userIds = null;

RoleManager roleMgr = Platform.getService(RoleManager.class);

try{

Role role = roleMgr.getDetails(RoleManagerConstants.ROLE_NAME, groupName, null);

String roleKey = role.getEntityId();

List userList = roleMge.getMembers(roleKey, true);

int userListSize = userList.size();

userIds = new String[userListSize];

for(int i = 0; i < userListSize; i++){

User user = (User) userList.get(i);

String userLogin = user.getLogin();

userIds[i] = userLogin;

}

} catch(Exception e){

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

}

return userIds;

}


Monday, August 31, 2020

Custom Target Reconciliation

import Thor.API.Exceptions.tcAPIException;

import Thor.API.Operations.tcProvisioningOperationsIntf;

import Thor.API.Operations.tcUserOperationsIntf;

import com.bea.security.providers.xacml.entitlement.parser.Roles;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.Hashtable;

import java.util.Map;

import javax.security.auth.login.LoginException;

import oracle.iam.platform.OIMClient;

import oracle.iam.reconciliation.api.BatchAttributes;

import oracle.iam.reconciliation.api.EventAttributes;

import oracle.iam.reconciliation.api.InputData;

import oracle.iam.reconciliation.api.ReconOperationsService;

import oracle.iam.reconciliation.api.ReconciliationResult;

import oracle.iam.scheduler.vo.TaskSupport;


public class TestRecon extends TaskSupport {


static OIMClient client = null;

private tcUserOperationsIntf userOperation = null;

private tcProvisioningOperationsIntf provisionOperation = null;

private ReconOperationsService reconOperation;

private String fileName;

private String ItResource;

private String resourceObjName;


public OIMClient oimConnection() {


oracle.iam.platform.OIMClient oimClient = null;

try {

Hashtable<Object, Object> env = new Hashtable<Object, Object>();

env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, weblogic.jndi.WLInitialContextFactory");

env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, "t3://:14000");

System.setProperty("java.security.auth.login.config", "");

System.setProperty("OIM.AppServerType", "wls");

System.setProperty("APPSERVER_TYPE", "wls");

oimClient = new oracle.iam.platform.OIMClient(env);

oimClient.login("xelsysadm", "Welcome123".toCharArray());

} catch (LoginException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

System.out.print("Successfully Connected with OIM ");

return oimClient;

}


public static void login() throws LoginException {


System.out.println("inside oim login....");

String ctxFactory = "weblogic.jndi.WLInitialContextFactory";

String serverURL = "t3://localhost:14000/identity";

System.setProperty("java.security.auth.login.config", "C:\\Users\\bprasad\\Desktop\\designconsole\\config\\authwl.conf");

System.setProperty("APPSERVER_TYPE", "wls");

String username = "XELSYSADM";

char[] password = "Welcome123".toCharArray();

Hashtable env = new Hashtable();

env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, ctxFactory);

env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, serverURL);

client = new OIMClient(env);

try {

System.out.println("Logging in");

client.login(username, password);

System.out.println("Login successful..");

} catch (Exception e) {

e.printStackTrace();

System.out.println("Login failed");

}

}

public TestRecon() {

}

public static void main(String[] args) throws LoginException {


// String fileName = "C:\\Users\\Downloads\\OIM\\projects\\workday\\sampleIn.csv";

String itresourceName = "FlatFileTrusted";

String resourceObj = "FlatFileTrusted User";

HashMap<String, String> map = null;

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

map.put("File Name", fileName);

map.put("ITResource Name", itresourceName);

map.put("Resource Object Name", resourceObj);

TestRecon dummyRecon = new TestRecon();

login();

dummyRecon.execute(map);

}


public void execute(HashMap hashMap) {


fileName = hashMap.get("File Name").toString();

ItResource = hashMap.get("ITResource Name").toString();

this.resourceObjName = hashMap.get("Resource Object Name").toString();

initialize();

// getReconData();

triggerRecon();

}

private void initialize() {


this.userOperation = ((tcUserOperationsIntf) client.getService(tcUserOperationsIntf.class));

this.provisionOperation = ((tcProvisioningOperationsIntf) client

.getService(tcProvisioningOperationsIntf.class));

reconOperation = ((ReconOperationsService) client.getService(ReconOperationsService.class));

}

public HashMap getAttributes() {

return null;

}

public void setAttributes() {

}

private void getReconData() {

String file = this.fileName;

BufferedReader reader = null;

try {

reader = new BufferedReader(new FileReader(file));

int headerFieldCount = 0;

String line = "";

while ((line = reader.readLine()) != null) {

this.data.add(line.split("\\,"));

}

} catch (Exception e) {

e.printStackTrace();

try {

reader.close();

} catch (IOException ioe) {

ioe.printStackTrace();

} catch (Exception e1) {

e1.printStackTrace();

}

} finally {

try {

reader.close();

} catch (IOException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

}

}

private void triggerRecon() {


EventAttributes ea = new EventAttributes();

Map reconMap = new HashMap();

reconMap.put("User Login", "Magnus6142");

reconMap.put("First Name", "MagnusF");

reconMap.put("Last Name", "MagnusL");

reconMap.put("Organization", "Skillopedia");

reconMap.put("User Type ", "Employee");

reconMap.put("CPI", "112211");

reconMap.put("Employee Number", "2855");

reconMap.put("WorkdayStatus", "Active");

reconMap.put("status", "Active");

reconMap.put("Role", "EMP");

ea.setEventFinished(true);

ea.setActionDate(null);

long eventKey = reconOperation.createReconciliationEvent(this.resourceObjName, reconMap, ea);

try {

reconOperation.processReconciliationEvent(eventKey);

} catch (tcAPIException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

}

}

How to fetch users from group?

private String[] getUsersFromGroup(String groupName){

String[] userLogins = null;

Set retAttrs = new HashSet();

RoleManager roleManager = null;

Role role = null;

try {

roleManager = Platfomr.getService(RoleManager.class);

role = roleManager.getDetails(RoleManagerConstants.ROLE_NAME, groupName, retAttrs);

String roleKey = role.getEntityId();

List <User> listOfUsers = roleManager.getRoleMembers(roleKey, true);

int size = listOfUsers.size();

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

User user =  listOfUsers.get(i);

String userLogin = user.getLogin();

userLogins = userLogin;

}

}catch(Exception e) {

e.printStackTrace();

}

return userLogins;

}

How to read values from lookup?

private HashMap<String, String> readLookupEntries(String lookupName){

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

tcLookupOperationsIntf  lookupOperationsIntf = Platform.getService(tcLookupOperationsIntf.class);

try {

tcResultSet resultSet =  lookupOperationsIntf.getLookupValues(lookupName);

for(int i = 0; resultSet.getRowCount(); i++){

resultSet.goToRow(i);

lookupEntryMap.put(resultSet.getStringValue("Lookup Definition.Lookup Code Information.Code Key"), resultSet.getStringValue("Lookup Definition.Lookup Code Information.Decode") );

}

catch(Exception e){

e.printStackTrace();

}

finally{

lookupOperationsIntf.close();

}

return lookupEntryMap;




How to get userLogin by using email?

Public String getUserLoginByEmail(String email){

Connection connection = null;

PreparedStatement pstatement = null;

ResultSet resultSet = null; 

String sql = "select * from usr where usr_mail = ? AND usr_status = 'Active' ";

try {

connection = Platform.getOperationalDS.getConnection();

pstatement = connection.prepareStatement(sql);

prepareStatement.setString(1,email);

resultSet = prepareStatement.executeQuery();

if (resultSet.next()){

String userLogin = resultSet.getString("user_Login");

}

catch(Exception ex){

ex.printStackTrace();

}

finally{

try{

if(connection != null) {

connection.close();

}

if(pStatement != null) {

pStatement.close();

}

if(resultSet != null) {

resultSet.close();

}

}

catch(Exception ex2) {

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

}

return userLogin;

}





Friday, July 24, 2020

Adding Entitlements to Account

Adding Entitlements to Account

import java.util.*;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import Thor.API.tcResultSet;
import Thor.API.Exceptions.tcAPIException;
import Thor.API.Exceptions.tcColumnNotFoundException;
import Thor.API.Exceptions.tcITResourceNotFoundException;
import Thor.API.Operations.tcITResourceInstanceOperationsIntf;
import Thor.API.Operations.tcLookupOperationsIntf;
import oracle.core.ojdl.logging.ODLLogger;
import oracle.iam.identity.exception.NoSuchUserException;
import oracle.iam.identity.exception.UserLookupException;
import oracle.iam.identity.usermgmt.api.UserManager;
import oracle.iam.platform.Platform;
import oracle.iam.provisioning.api.EntitlementService;
import oracle.iam.provisioning.api.ProvisioningService;
import oracle.iam.provisioning.exception.GenericProvisioningException;
import oracle.iam.provisioning.exception.UserNotFoundException;


public class EntitlementsOfServiceAccount {

private static final ODLLogger logger = ODLLogger.getODLLogger(EntitlementsOfServiceAccount.class.getName());
private final String adGroupNames = "Lookup.XYZ.ServiceAccounts.ADGroups";
private final String adGroupCongifuration = "Lookup.XYZ.ServiceAccounts.Configuration";

String userDN = null;
String groupDN = null;
LdapContext adConnection = null;
Map<String, String> AD_IT_RESOURSE_PARAMETERS = null;
HashMap<String, String> adGroups = new HashMap<String, String>();
HashMap<String, String> adConfigurations = new HashMap<String, String>();

    // OIM API's
 UserManager userManager = Platform.getService(UserManager.class);
 ProvisioningService provisioningService = Platform.getService(ProvisioningService.class);
 EntitlementService entitlementService = Platform.getService(EntitlementService.class);

// taking input from adapter as user i.e., common name
public void addEntitlementsToUser(String user) {

adGroups = getLookupEntries(adGroupNames);
adConfigurations = getLookupEntries(adGroupCongifuration);
userDN = adConfigurations.get("GroupDN");
groupDN = adConfigurations.get("UserDN");

for (String key : adGroups.keySet()) {
provisionEntitlementsToServiceAccount(user, key, adConnection);
    }

}

// Getting AD connection and IT Resource details
public void addADGroupsToSeriveAccounts(String itReourceName) throws NamingException, NoSuchUserException,
UserLookupException, UserNotFoundException, GenericProvisioningException {

AD_IT_RESOURSE_PARAMETERS = getITResourcesProperties(itReourceName);
adConnection = getADConnection(itReourceName, AD_IT_RESOURSE_PARAMETERS);
addEntitlementsToUser("SRC-ACCTEST");

}

// Testing purpose passing IT Resource from main method
public static void main(String[] args) throws Exception {

String itResourceName = "Active Directory";
EntitlementsOfServiceAccount eOfServiceAccount = new EntitlementsOfServiceAccount();
eOfServiceAccount.addADGroupsToSeriveAccounts(itResourceName);
}

// AD Connection
private LdapContext getADConnection(final String itResource, Map<String, String> TEST_AD_IT_RESOURSE_PARAMETERS) {

logger.info("Entering into getADConnection method : ");

String adminName = null;
String adminPassword = null;
String hostName = null;
String userName = null;
String containerDN = null;
InitialLdapContext ctx = null;
TEST_AD_IT_RESOURSE_PARAMETERS = getITResourcesProperties(itResource);

if (null != TEST_AD_IT_RESOURSE_PARAMETERS && !TEST_AD_IT_RESOURSE_PARAMETERS.isEmpty()) {
hostName = TEST_AD_IT_RESOURSE_PARAMETERS.get("LDAPHostName");
userName = TEST_AD_IT_RESOURSE_PARAMETERS.get("DirectoryAdminName");
containerDN = TEST_AD_IT_RESOURSE_PARAMETERS.get("Container");

if (userName.contains("\\")) {
userName = userName.substring(userName.indexOf("\\") + 1);
userName = "cn=" + userName + ",cn=users," + containerDN;
}
adminName = userName;
adminPassword = TEST_AD_IT_RESOURSE_PARAMETERS.get("DirectoryAdminPassword");
}
if (adminPassword.equals("Null Password")) {
System.out.println("Null Password: Connection Failed");
return null;
}
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.security.authentication", "simple");
env.put("java.naming.security.principal", adminName);
env.put("java.naming.security.credentials", adminPassword);
env.put("java.naming.provider.url", "ldap://" + hostName + ":389");

try {
ctx = new InitialLdapContext(env, null);
} catch (NamingException e) {
System.out.println("Error while getting the connection :  " + e.getMessage());
e.printStackTrace();
}
System.out.println("AD connection is success :  ");
return ctx;
}

// fetch Entitlements, userDN and groupDN from lookup
public HashMap<String, String> getLookupEntries(String lookupName) {

// tcLookupOperationsIntf lookupOperationsIntf = Platform.getService(tcLookupOperationsIntf.class);
logger.info("Entering into getLookupEntries method : ");
HashMap<String, String> lookupEntryMap = new HashMap<String, String>();

try {
tcResultSet result = lookupOperationsIntf.getLookupValues(lookupName);
for (int i = 0; i < result.getRowCount(); i++) {
result.goToRow(i);
lookupEntryMap.put(result.getStringValue("Lookup Definition.Lookup Code Information.Code Key"),
result.getStringValue("Lookup Definition.Lookup Code Information.Decode"));
}
} catch (Exception e) {
e.printStackTrace();
}
return lookupEntryMap;
}

// IT Resource
private Map<String, String> getITResourcesProperties(String itResourceName) {

System.out.println("Entering into the getITResourcesProperties method : ");
tcITResourceInstanceOperationsIntf resourceFactory = null;
long vdResourceKey = 0L;
Map<String, String> result = new HashMap<String, String>();

try {
resourceFactory = (tcITResourceInstanceOperationsIntf) Platform.getService(tcITResourceInstanceOperationsIntf.class);

Map<String, String> filter = new HashMap<String, String>();
filter.put("IT Resource.Name", itResourceName);
tcResultSet resources = resourceFactory.findITResourceInstances(filter);
vdResourceKey = resources.getLongValue("IT Resource.Key");
tcResultSet params = resourceFactory.getITResourceInstanceParameters(vdResourceKey);
int j = 0;
for (int objectRowCount = params.getRowCount(); j < objectRowCount; j++) {
params.goToRow(j);
result.put(params.getStringValue("IT Resources Type Parameter.Name"),
params.getStringValue("IT Resource.Parameter.Value"));
}
} catch (tcAPIException e) {
e.printStackTrace();
} catch (tcColumnNotFoundException e) {
e.printStackTrace();
} catch (tcITResourceNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}


// add enetitlements to servieaccount
private String provisionEntitlementsToServiceAccount(String userID, String groupName, LdapContext context) {

System.out.println("Entering into the provisionUserToAD");
try {

String groupDN = adConfigurations.get("GroupDN");
String userDngroup = adConfigurations.get("UserDN");
String groupNameFullName = "CN=" + groupName + "," + groupDN;

String userDN = "CN=" + userID.toLowerCase() + "," + userDngroup;
ModificationItem[] modItem = new ModificationItem[1];
modItem[0] = new ModificationItem(1, new BasicAttribute("member", userDN));
context.modifyAttributes(groupNameFullName, modItem);
System.out.println("Addition completed");

} catch (Exception e) {
System.out.println("Error Message" + e.getMessage());
return "Failed";
}
return "Success";
}
}

Thursday, July 23, 2020

DataSource Connection

public class DataSourceConnection {

public Connection getOIMDBConnection(String t3url) {
       
                Connection connection = null;
DataSource ds = null;       
                try {
Hashtable env = new Hashtable();                     
env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, "weblogic.jndi.WLInitialContextFactory");
env.put(OIMClient.JAVA_NAMING_PROVIDER_URL,t3url);
                       
Context context = new InitialContext(env);
ds = (DataSource) context.lookup("jdbc/operationsDB");
System.out.println( "Successfully looked up OIM datasource : ");
           
if (ds != null) {
                                    conn = ds.getConnection();
    System.out.println("Successfully obtained OIM database connection : ");
}
} catch (Exception e) {
                            System.out.println("Exception while getting DB connection : "+e.getMessage());
                        }         
                        return connection;
}

Wednesday, July 22, 2020

DatabaseConnection

public class DBConnection {

            public static Connection getJDBConnection(String dbUrl, String userName, String password){  

                              Connection connection = null;                

try {                           

                              Class.forName("oracle.jdbc.driver.OracleDriver");

                              connection = DriverManager.getConnection(dbUrl,userName,password);

                              System.out.println("Database connection is successful : ");

               

                              catch (Exception e) {

                              System.out.println("Error in Database Connection : "+e.getMessage());

               }                 

finally{

if(connection != null){

connection.close();

}        

}  

        return connection;

    }    


               Note : Servicename = /OIMDEV, SID = :OIMDEV

                         String dbUrl = "jdbc:oracle:thin:@HOSTNAME:1521/OIMDEV";

                         String userName = "dev_oim";

                         String password = "Welcome123";

 


OIMConnection

public class OIMConnection {  
   
 public static OIMclient getOIMConnection(String userName, String password, String t3URL, String authLoc){

 Hashtable env = new Hashtable();                     env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, "weblogic.jndi.WLInitialContextFactory");
 env.put(OIMClient.JAVA_NAMING_PROVIDER_URL,t3URL);

            // Set system properties
      
            System.setProperty("java.security.auth.login.config", authLoc);
            System.setProperty("OIM.AppServerType", "wls");
            System.setProperty("APPSERVER_TYPE", "wls");
   
           OIMClient client = null;
            try {
                    client  = new OIMClient(env);
                    client.login(userName, password.toCharArray());
                    System.out.println("OIM Connection is successful : ");

            } catch (Exception e) {
                System.out.println("Error  in gettting connection : "e.getMessage());
            }
        return client;
 }

Environmental Variables for Plugin Registration


export APP_SERVER=weblogic
export ANT_HOME=/app/bpr/Oracle/Middleware/modules/org.apche.ant_1.7.1/
export MW_HOME=/app/bpr/Oracle/Middleware/
export WL_HOME=/app/bpr/Oracle/Middleware/wlserver_10.3/
export OIM_ORACLE_HOME=/app/bpr/Oracle/Middleware/Oracle_IDM1/
export OIM_HOME=/app/bpr/Oracle/Middleware/Oracle_IDM1/server/
export DOMAIN_HOME=/app/bpr/Oracle/Middleware/user_projects/domains/base_domain/
export ORACLE_COMMON=/app/bpr/Oracle/Middleware/oracle_common/
export PATH=$ANT_HOME/bin:$JAVA_HOME/bin:$PATH

Default Schedulers in PS3


List of default Schedulers :-

1. Application Instance Post Delete Processing Job

2. Bulk Load Archival Job

3. Bulk Load Post Process

4. Catalog Synchronization Job

5. Entitlement List

6. Entitlement Assignments

7. Evaluate User Policies

8. Password Expiration Task

9. Password Warning Task

10. Retry Failed Orchestrations

11. Retry Failed Reconciliation Events

12. Retry Reconciliation Batch Job

13. User Operations              

etc......

IAM, IGA & Identity Security

IAM sets up the employee's account so they can log in and access the application with their credentials. IGA makes sure that access requ...

Featured Articles