Example usage for javax.naming Context PROVIDER_URL

List of usage examples for javax.naming Context PROVIDER_URL

Introduction

In this page you can find the example usage for javax.naming Context PROVIDER_URL.

Prototype

String PROVIDER_URL

To view the source code for javax.naming Context PROVIDER_URL.

Click Source Link

Document

Constant that holds the name of the environment property for specifying configuration information for the service provider to use.

Usage

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided
 * username and credential./*w w w . j a v  a 2  s. c  o m*/
 *
 * @return the Initial Ldap Context to be used to perform searches, etc.
 * @throws NamingException LDAP binding error.
 */
protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential)
        throws NamingException {

    Properties env = new Properties();

    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication());
    env.setProperty(Context.PROVIDER_URL, getProviderUrl());
    env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol()));

    // Set defaults for key values if they are missing

    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
    }

    String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
    if (authType == null)
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");

    String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
    String providerURL = getProviderUrl();
    // Use localhost if providerUrl not set
    if (providerURL == null) {
        //providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
        if (protocol != null && protocol.equals("ssl")) {
            // We should use Start TLS extension?
            providerURL = "ldaps://localhost:636";
        } else {
            providerURL = "ldap://localhost:389";
        }
    }

    env.setProperty(Context.PROVIDER_URL, providerURL);
    env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredential);

    // always follow referrals transparently
    env.put(Context.REFERRAL, "follow");

    // Logon into LDAP server
    if (logger.isDebugEnabled())
        logger.debug("Logging into LDAP server, env=" + env);

    InitialLdapContext ctx = new InitialLdapContext(env, null);

    if (logger.isDebugEnabled())
        logger.debug("Logged into LDAP server, " + ctx);

    return ctx;
}

From source file:org.oscm.identityservice.bean.IdentityServiceBean.java

@Override
@Interceptors({ ServiceProviderInterceptor.class })
public List<VOUserDetails> searchLdapUsers(final String userIdPattern) throws ValidationException {

    ArgumentValidator.notNull("userIdPattern", userIdPattern);

    Organization organization = dm.getCurrentUser().getOrganization();

    LdapConnector connector = getLdapConnectionForOrganization(organization);
    Properties dirProperties = connector.getDirProperties();
    Map<SettingType, String> attrMap = connector.getAttrMap();
    String baseDN = connector.getBaseDN();

    List<SettingType> attrList = new ArrayList<>(attrMap.keySet());
    ILdapResultMapper<VOUserDetails> mapper = new LdapVOUserDetailsMapper(null, attrMap);
    try {/*from w ww  .j  av a  2  s .co  m*/
        // read user from LDAP
        List<VOUserDetails> voUserList = ldapAccess.search(dirProperties, baseDN,
                getLdapSearchFilter(attrMap, userIdPattern), mapper, false);

        int size = voUserList.size();
        for (int i = 0; i < size; i++) {
            VOUserDetails voUser = voUserList.get(i);
            PlatformUser user = getPlatformUserByOrgAndReamUserId(organization, voUser.getRealmUserId());
            if (null != user) {
                // update the domain object with possibly changed LDAP
                // attributes and return a complete value object
                UserDataAssembler.updatePlatformUser(voUser, attrList, user);
                voUserList.set(i, UserDataAssembler.toVOUserDetails(user));
            } else {
                // set some mandatory attributes
                voUser.setOrganizationId(organization.getOrganizationId());
                String locale = voUser.getLocale();
                if (locale == null || locale.trim().length() == 0) {
                    voUser.setLocale(organization.getLocale());
                }
            }
        }
        return voUserList;
    } catch (NamingException e) {
        Object[] params = new Object[] { dirProperties.get(Context.PROVIDER_URL), e.getMessage() };
        ValidationException vf = new ValidationException(ReasonEnum.LDAP_CONNECTION_REFUSED, null, params);
        logger.logError(Log4jLogger.SYSTEM_LOG, vf, LogMessageIdentifier.ERROR_LDAP_SYSTEM_CONNECTION_REFUSED);
        throw vf;
    }
}

From source file:org.oscm.identityservice.bean.IdentityServiceBean.java

@Override
@Interceptors({ ServiceProviderInterceptor.class })
public boolean searchLdapUsersOverLimit(final String userIdPattern) throws ValidationException {
    ArgumentValidator.notNull("userIdPattern", userIdPattern);

    Organization organization = dm.getCurrentUser().getOrganization();

    LdapConnector connector = getLdapConnectionForOrganization(organization);
    Properties dirProperties = connector.getDirProperties();
    Map<SettingType, String> attrMap = connector.getAttrMap();
    String baseDN = connector.getBaseDN();
    ILdapResultMapper<VOUserDetails> mapper = new LdapVOUserDetailsMapper(null, attrMap);
    try {/*from w  w w .jav a  2s  .  c  o  m*/
        return ldapAccess.searchOverLimit(dirProperties, baseDN, getLdapSearchFilter(attrMap, userIdPattern),
                mapper, false);
    } catch (NamingException e) {
        Object[] params = new Object[] { dirProperties.get(Context.PROVIDER_URL), e.getMessage() };
        ValidationException vf = new ValidationException(ReasonEnum.LDAP_CONNECTION_REFUSED, null, params);
        logger.logError(Log4jLogger.SYSTEM_LOG, vf, LogMessageIdentifier.ERROR_LDAP_SYSTEM_CONNECTION_REFUSED);
        throw vf;
    }
}

From source file:org.oscm.identityservice.bean.IdentityServiceBean.java

@Override
@Interceptors({ ServiceProviderInterceptor.class })
public void importLdapUsers(List<VOUserDetails> users, String marketplaceId)
        throws NonUniqueBusinessKeyException, ValidationException, MailOperationException {

    ArgumentValidator.notNull("users", users);

    Organization organization = dm.getCurrentUser().getOrganization();

    LdapConnector connector = getLdapConnectionForOrganization(organization);
    Properties dirProperties = connector.getDirProperties();
    Map<SettingType, String> attrMap = connector.getAttrMap();
    String baseDN = connector.getBaseDN();

    Marketplace marketplace = getMarketplace(marketplaceId);
    for (VOUserDetails user : users) {
        try {// w  w  w.j a v a 2 s  .co m
            ILdapResultMapper<VOUserDetails> mapper = new LdapVOUserDetailsMapper(user, attrMap);
            List<VOUserDetails> list = ldapAccess.search(dirProperties, baseDN,
                    getLdapSearchFilter(attrMap, user.getRealmUserId()), mapper, false);
            int size = list.size();
            if (size == 1) {
                user = list.get(0);
                if (GenericValidator.isBlankOrNull(user.getLocale())) {
                    user.setLocale(organization.getLocale());
                }
                try {
                    addPlatformUser(user, organization, null, UserAccountStatus.ACTIVE, true, false,
                            marketplace, false);
                } catch (UserRoleAssignmentException e) {
                    sessionCtx.setRollbackOnly();
                    ValidationException vf = new ValidationException(e.getMessage());
                    logger.logError(Log4jLogger.SYSTEM_LOG, vf,
                            LogMessageIdentifier.ERROR_VALIDATION_PARAMETER_LDAP_FOUND_ERROR, "User");
                    throw vf;
                }

            } else if (size == 0) {
                sessionCtx.setRollbackOnly();
                ValidationException vf = new ValidationException(ReasonEnum.LDAP_USER_NOT_FOUND, null,
                        new Object[] { user.getRealmUserId() });
                logger.logError(Log4jLogger.SYSTEM_LOG, vf,
                        LogMessageIdentifier.ERROR_VALIDATION_PARAMETER_LDAP_FOUND_ERROR, "User");
                throw vf;
            } else {
                sessionCtx.setRollbackOnly();
                ValidationException vf = new ValidationException(ReasonEnum.LDAP_USER_NOT_UNIQUE, null,
                        new Object[] { user.getRealmUserId() });
                logger.logError(Log4jLogger.SYSTEM_LOG, vf,
                        LogMessageIdentifier.ERROR_VALIDATION_PARAMETER_LDAP_FOUND_ERROR, "User");
                throw vf;
            }
        } catch (NamingException e) {
            Object[] params = new Object[] { dirProperties.get(Context.PROVIDER_URL), e.getMessage() };
            ValidationException vf = new ValidationException(ReasonEnum.LDAP_CONNECTION_REFUSED, null, params);
            logger.logError(Log4jLogger.SYSTEM_LOG, vf,
                    LogMessageIdentifier.ERROR_LDAP_SYSTEM_CONNECTION_REFUSED);
            throw vf;
        }
    }
}

From source file:org.akaza.openclinica.controller.SystemController.java

public HashMap<String, Object> getLdapModule(StudyBean studyBean) {
    String enabled = CoreResources.getField("ldap.enabled");
    String ldapHost = CoreResources.getField("ldap.host");
    String username = CoreResources.getField("ldap.userDn");
    String password = CoreResources.getField("ldap.password");

    String result = "";
    Properties env = new Properties();

    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapHost);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, username); // replace with user DN
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = null;//from w  ww  . j a  va  2s  . c  o m
    try {
        ctx = new InitialDirContext(env);
        result = "ACTIVE";
    } catch (Exception e) {
        result = "INACTIVE";
    }

    HashMap<String, String> mapMetadata = new HashMap<>();
    mapMetadata.put("ldap.host", ldapHost);

    HashMap<String, Object> mapWebService = new HashMap<>();
    mapWebService.put("enabled", enabled.equalsIgnoreCase("true") ? "True" : "False");
    mapWebService.put("status", result);
    mapWebService.put("metadata", mapMetadata);

    HashMap<String, Object> mapModule = new HashMap<>();
    mapModule.put("Ldap", mapWebService);

    return mapModule;
}