List of usage examples for javax.naming NamingException getMessage
public String getMessage()
From source file:org.wso2.carbon.appfactory.ext.datasource.ApplicationAwareDataSourceRepository.java
private void checkAndCreateJNDISubContexts(Context context, String jndiName) throws DataSourceException { String[] tokens = jndiName.split("/"); Context tmpCtx;// w w w. j a v a 2 s . c om String token; for (int i = 0; i < tokens.length - 1; i++) { token = tokens[i]; tmpCtx = this.lookupJNDISubContext(context, token); if (tmpCtx == null) { try { tmpCtx = context.createSubcontext(token); } catch (NamingException e) { throw new DataSourceException( "Error in creating JNDI subcontext '" + context + "/" + token + ": " + e.getMessage(), e); } } context = tmpCtx; } }
From source file:org.openiam.spml2.spi.ldap.LdapConnectorImpl.java
public ResponseType setPassword(SetPasswordRequestType reqType) { log.debug("setPassword request called.."); ConnectionMgr conMgr = null;// www.j av a 2s . co m String requestID = reqType.getRequestID(); /* PSO - Provisioning Service Object - * - ID must uniquely specify an object on the target or in the target's namespace * - Try to make the PSO ID immutable so that there is consistency across changes. */ PSOIdentifierType psoID = reqType.getPsoID(); /* targetID - */ String targetID = psoID.getTargetID(); /* ContainerID - May specify the container in which this object should be created * ie. ou=Development, org=Example */ PSOIdentifierType containerID = psoID.getContainerID(); /* A) Use the targetID to look up the connection information under managed systems */ ManagedSys managedSys = managedSysService.getManagedSys(targetID); try { log.debug("managedSys found for targetID=" + targetID + " " + " Name=" + managedSys.getName()); conMgr = ConnectionFactory.create(ConnectionManagerConstant.LDAP_CONNECTION); LdapContext ldapctx = conMgr.connect(managedSys); log.debug("Ldapcontext = " + ldapctx); String ldapName = psoID.getID(); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", reqType.getPassword())); ldapctx.modifyAttributes(ldapName, mods); // check if the request contains additional attributes List<ExtensibleObject> extObjList = reqType.getAny(); if (extObjList != null && extObjList.size() > 0) { ExtensibleObject obj = extObjList.get(0); if (obj != null) { List<ExtensibleAttribute> attrList = obj.getAttributes(); if (attrList != null && attrList.size() > 0) { mods = new ModificationItem[attrList.size()]; for (ExtensibleAttribute a : attrList) { mods[0] = new ModificationItem(a.getOperation(), new BasicAttribute(a.getName(), a.getValue())); } ldapctx.modifyAttributes(ldapName, mods); } } } } catch (NamingException ne) { log.error(ne.getMessage(), ne); ResponseType resp = new ResponseType(); resp.setStatus(StatusCodeType.FAILURE); resp.setError(ErrorCode.NO_SUCH_IDENTIFIER); return resp; } catch (Exception ne) { log.error(ne.getMessage(), ne); ResponseType resp = new ResponseType(); resp.setStatus(StatusCodeType.FAILURE); resp.setError(ErrorCode.OTHER_ERROR); resp.addErrorMessage(ne.toString()); return resp; } finally { /* close the connection to the directory */ try { if (conMgr != null) { conMgr.close(); } } catch (NamingException n) { log.error(n); } } ResponseType respType = new ResponseType(); respType.setStatus(StatusCodeType.SUCCESS); return respType; }
From source file:com.icesoft.net.messaging.jms.JMSAdapter.java
private void initialize() throws NamingException { Properties _environmentProperties = new Properties(); String _initialContextFactory; for (int i = 0; i < jmsProviderConfigurations.length; i++) { _initialContextFactory = jmsProviderConfigurations[i].getInitialContextFactory(); if (_initialContextFactory != null) { _environmentProperties.setProperty(JMSProviderConfiguration.INITIAL_CONTEXT_FACTORY, _initialContextFactory); }/*from w w w. ja va 2 s . c o m*/ String _providerUrl = jmsProviderConfigurations[i].getProviderURL(); if (_providerUrl != null) { _environmentProperties.setProperty(JMSProviderConfiguration.PROVIDER_URL, _providerUrl); } String _urlPackagePrefixes = jmsProviderConfigurations[i].getURLPackagePrefixes(); if (_urlPackagePrefixes != null) { _environmentProperties.setProperty(JMSProviderConfiguration.URL_PACKAGE_PREFIXES, _urlPackagePrefixes); } if (LOG.isDebugEnabled()) { StringBuffer _environment = new StringBuffer(); _environment.append("Trying JMS Environment:\r\n"); Iterator _properties = _environmentProperties.entrySet().iterator(); while (_properties.hasNext()) { Map.Entry _property = (Map.Entry) _properties.next(); _environment.append(" "); _environment.append(_property.getKey()); _environment.append(" = "); _environment.append(_property.getValue()); _environment.append("\r\n"); } LOG.debug(_environment.toString()); } try { // throws NamingException. initialContext = new InitialContext(_environmentProperties); // throws NamingException. topicConnectionFactory = (TopicConnectionFactory) initialContext .lookup(jmsProviderConfigurations[i].getTopicConnectionFactoryName()); index = i; if (LOG.isDebugEnabled()) { StringBuffer _environment = new StringBuffer(); _environment.append("Using JMS Environment:\r\n"); Iterator _properties = _environmentProperties.entrySet().iterator(); while (_properties.hasNext()) { Map.Entry _property = (Map.Entry) _properties.next(); _environment.append(" "); _environment.append(_property.getKey()); _environment.append(" = "); _environment.append(_property.getValue()); _environment.append("\r\n"); } LOG.debug(_environment.toString()); } break; } catch (NamingException exception) { if (LOG.isDebugEnabled()) { LOG.debug("Failed JMS Environment: " + exception.getMessage()); } if (initialContext != null) { try { initialContext.close(); } catch (NamingException e) { // ignoring this one. } } if ((i + 1) == jmsProviderConfigurations.length) { throw exception; } } } }
From source file:com.idega.slide.webdavservlet.DomainConfig.java
public String getSlideBasePathFromJNDI() { try {/*w w w .j av a 2s . c o m*/ String path = (String) getEnvContext().lookup("properties/" + SLIDE_BASEPATH_PROPERTY); return path; } catch (NamingException e) { // TODO Auto-generated catch block //e.printStackTrace(); System.err.println("Error looking up from JNDI: " + e.getMessage()); } return null; }
From source file:ru.efo.security.ADUserDetailsService.java
private ADUserDetails loadUserByUsername(DirContext context, String username, String password) throws UsernameNotFoundException { try {// w w w . ja va 2 s.c om SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); // search for username NamingEnumeration<SearchResult> renum = context.search(userSearchBase, "(&(objectClass=user)(sAMAccountName={0}))", new Object[] { username }, controls); if (!renum.hasMoreElements()) { throw new UsernameNotFoundException("User '" + username + "' is not exist"); } SearchResult result = renum.next(); final Attributes attributes = result.getAttributes(); // User's display name String displayName = null; Attribute attr = attributes.get(displayNameAttribute); if (attr != null) { displayName = attr.get().toString(); } if (!StringUtils.hasText(displayName)) displayName = username; logger.log(Level.FINE, "Display name: " + displayName); // User's email String email = null; attr = attributes.get(emailAttribute); if (attr != null) { email = attr.get().toString(); } logger.log(Level.FINE, "E-mail: " + email); // User's phone number String phone = null; attr = attributes.get(phoneAttribute); if (attr != null) { phone = attr.get().toString(); } logger.log(Level.FINE, "Phone: " + phone); // Is user blocked boolean blocked = false; attr = attributes.get("userAccountControl"); if (attr != null) { blocked = (Long.parseLong(attr.get().toString()) & 2) != 0; } logger.log(Level.FINE, "Blocked: " + blocked); // describe roles and groups final Set<String> roles = new TreeSet<>(); final Set<String> groups = new TreeSet<>(); Attribute memberOf = attributes.get("memberOf"); describeRoles(context, memberOf, groups, roles); // Describe user primary role Attribute attrPrimaryGroupId = attributes.get("primaryGroupId"); Attribute attrObjectSid = attributes.get("objectSid"); if (attrPrimaryGroupId != null && attrObjectSid != null) { int primaryGroupId = Integer.parseInt(attrPrimaryGroupId.get().toString()); byte[] objectSid = (byte[]) attrObjectSid.get(); // add primary group RID for (int i = 0; i < 4; i++) { objectSid[objectSid.length - 4 + i] = (byte) (primaryGroupId & 0xFF); primaryGroupId >>= 8; } StringBuilder tmp = new StringBuilder(); for (int i = 2; i <= 7; i++) { tmp.append(Integer.toHexString(objectSid[i] & 0xFF)); } // convert objectSid to String StringBuilder sidBuilder = new StringBuilder("S-").append(objectSid[0]).append("-") .append(Long.parseLong(tmp.toString(), 16)); // the sub authorities count int count = objectSid[1]; // add authorities for (int i = 0; i < count; i++) { tmp.setLength(0); int offset = i * 4; tmp.append(String.format("%02X%02X%02X%02X", (objectSid[11 + offset] & 0xFF), (objectSid[10 + offset] & 0xFF), (objectSid[9 + offset] & 0xFF), (objectSid[8 + offset] & 0xFF))); sidBuilder.append('-').append(Long.parseLong(tmp.toString(), 16)); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); renum = context.search(userSearchBase, "(&(objectClass=group)(objectSid={0}))", new Object[] { sidBuilder.toString() }, searchControls); if (renum.hasMoreElements()) { result = renum.next(); attr = result.getAttributes().get("distinguishedName"); describeRoles(context, attr, groups, roles); } } return new ADUserDetails(username, password, displayName, email, phone, blocked, groups, roles); } catch (NamingException ex) { logger.log(Level.SEVERE, "Could not find user '" + username + "'", ex); throw new UsernameNotFoundException(ex.getMessage()); } }
From source file:org.josso.jb32.agent.JBossCatalinaNativeRealm.java
/** * Return the Principal associated with the specified username and * credentials, if there is one; otherwise return null. * * The method was completely rewritten since the overriden operation, * on succesfull authentication, sets as the authenticated Principal * a SimplePrincipal instantiated using the provided username. * The problem is that in JOSSO the username is a SSO Session Id, not * a username. So we need to set the SSOUser returned by the Gateway * as the authenticatd Principal.// w w w . ja v a2 s.co m * Since the JaasSecurityManager caches the authenticated user using the * Principal referring to a JOSSO Session Id, we will need to map, for * example when roles are checked against the realm, a user Principal * back to its JOSSO Session Identifier Principal. This way the the user * and its roles can be retrieved correctly by the JaasSecurityManager. * * @param username Username of the Principal to look up * @param credentials Password or other credentials to use in * authenticating this username */ public Principal authenticate(String username, String credentials) { logger.debug("Begin authenticate, username=" + username); Principal principal = null; SSOUser ssoUser = null; Principal caller = (Principal) SecurityAssociationValve.userPrincipal.get(); if (caller == null && username == null && credentials == null) return null; try { Context securityCtx = null; securityCtx = prepareENC(); if (securityCtx == null) { logger.error("No security context for authenticate(String, String)"); return null; } // Get the JBoss security manager from the ENC context SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr"); if (!isSSODomain(securityMgr.getSecurityDomain())) { // This is not a SSO Security domain, let JBoss realm handle this ... return super.authenticate(username, credentials); } principal = new SimplePrincipal(username); char[] passwordChars = null; if (credentials != null) passwordChars = credentials.toCharArray(); SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager(); String requester = ""; // Check for nulls ? SSOAgentRequest request = AbstractSSOAgent._currentRequest.get(); if (request != null) requester = request.getRequester(); else logger.warn("No SSO Agent request found in thread local variable, can't identify requester"); ssoUser = im.findUserInSession(requester, username); if (ssoUser != null) { logger.debug("User: " + username + " is authenticated"); Subject subject = new Subject(); subject.getPrincipals().add(ssoUser); logger.warn("WARN Cannot identify requester!"); SSORole[] ssoRolePrincipals = im.findRolesBySSOSessionId(requester, username); Group targetGrp = new BaseRoleImpl("Roles"); for (int i = 0; i < ssoRolePrincipals.length; i++) { subject.getPrincipals().add(ssoRolePrincipals[i]); targetGrp.addMember(ssoRolePrincipals[i]); // Add user role to "Roles" group } // Add the "Roles" group to the Subject so that JBoss can fetch user roles. subject.getPrincipals().add(targetGrp); logger.debug("Authenticated Subject: " + subject); // Make the cache aware of the user-session association so that // it can handle correctly cache entry lookups. //_cachePolicy.attachSessionToUser(principal, ssoUser); // Instead of associating the Principal used for authenticating (which is a // session id), sets the authenticated principal to the SSOUser part of the // Subject returned by the Gateway. JBossSecurityAssociationActions.setPrincipalInfo(ssoUser, passwordChars, subject); // Get the CallerPrincipal mapping RealmMapping rm = (RealmMapping) securityCtx.lookup("realmMapping"); Principal oldPrincipal = ssoUser; principal = rm.getPrincipal(oldPrincipal); logger.debug("Mapped from input principal: " + oldPrincipal + " to: " + principal); if (!principal.equals(oldPrincipal)) { _userPrincipalMap.put(principal, oldPrincipal); } } else { principal = null; logger.debug("User: " + username + " is NOT authenticated"); } } catch (NamingException e) { principal = null; logger.error("Error during authenticate", e); } catch (SSOIdentityException e) { // Ignore this ... (user does not exist for this session) if (logger.isDebugEnabled()) { logger.debug(e.getMessage()); } principal = null; } catch (Exception e) { logger.error("Session authentication failed : " + username, e); throw new RuntimeException("Fatal error authenticating session : " + e); } logger.debug("End authenticate, principal=" + ssoUser); return ssoUser; }
From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java
/** * Removes an existing principal in a previously configured KDC * <p/>/*w ww. ja v a2s.co m*/ * The implementation is specific to a particular type of KDC. * * @param principal a String containing the principal to remove * @return true if the principal was successfully removed; otherwise false * @throws KerberosOperationException */ @Override public boolean removePrincipal(String principal) throws KerberosOperationException { if (!isOpen()) { throw new KerberosOperationException("This operation handler has not been opened"); } if (principal == null) { throw new KerberosOperationException("principal is null"); } DeconstructedPrincipal deconstructPrincipal = createDeconstructPrincipal(principal); try { String dn = findPrincipalDN(deconstructPrincipal.getNormalizedPrincipal()); if (dn != null) { ldapContext.destroySubcontext(dn); } } catch (NamingException e) { throw new KerberosOperationException( String.format("Can not remove principal %s: %s", principal, e.getMessage()), e); } return true; }
From source file:org.josso.jb4.agent.JBossCatalinaNativeRealm.java
/** * Return the Principal associated with the specified username and * credentials, if there is one; otherwise return null. * * The method was completely rewritten since the overriden operation, * on succesfull authentication, sets as the authenticated Principal * a SimplePrincipal instantiated using the provided username. * The problem is that in JOSSO the username is a SSO Session Id, not * a username. So we need to set the SSOUser returned by the Gateway * as the authenticatd Principal./*from www . j a va 2s .c om*/ * Since the JaasSecurityManager caches the authenticated user using the * Principal referring to a JOSSO Session Id, we will need to map, for * example when roles are checked against the realm, a user Principal * back to its JOSSO Session Identifier Principal. This way the the user * and its roles can be retrieved correctly by the JaasSecurityManager. * * @param username Username of the Principal to look up * @param credentials Password or other credentials to use in * authenticating this username */ public Principal authenticate(String username, String credentials) { logger.debug("Begin authenticate, username=" + username); Principal principal = null; SSOUser ssoUser = null; Principal caller = (Principal) SecurityAssociationValve.userPrincipal.get(); if (caller == null && username == null && credentials == null) return null; try { Context securityCtx = null; securityCtx = prepareENC(); if (securityCtx == null) { logger.error("No security context for authenticate(String, String)"); return null; } // Get the JBoss security manager from the ENC context SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr"); if (!isSSODomain(securityMgr.getSecurityDomain())) { // This is not a SSO Security domain, let JBoss realm handle this ... return super.authenticate(username, credentials); } principal = new SimplePrincipal(username); char[] passwordChars = null; if (credentials != null) passwordChars = credentials.toCharArray(); SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager(); String requester = ""; // Check for nulls ? SSOAgentRequest request = AbstractSSOAgent._currentRequest.get(); if (request != null) requester = request.getRequester(); else logger.warn("No SSO Agent request found in thread local variable, can't identify requester"); ssoUser = im.findUserInSession(requester, username); if (ssoUser != null) { logger.debug("User: " + username + " is authenticated"); Subject subject = new Subject(); subject.getPrincipals().add(ssoUser); logger.warn("WARN Cannot identify requester!"); SSORole[] ssoRolePrincipals = im.findRolesBySSOSessionId(requester, username); Group targetGrp = new BaseRoleImpl("Roles"); for (int i = 0; i < ssoRolePrincipals.length; i++) { subject.getPrincipals().add(ssoRolePrincipals[i]); targetGrp.addMember(ssoRolePrincipals[i]); // Add user role to "Roles" group } // Add the "Roles" group to the Subject so that JBoss can fetch user roles. subject.getPrincipals().add(targetGrp); Group callerPrincipal = new BaseRoleImpl("CallerPrincipal"); callerPrincipal.addMember(ssoUser); // Add the "CallerPrincipal" group to the Subject so that JBoss can fetch user. subject.getPrincipals().add(callerPrincipal); logger.debug("Authenticated Subject: " + subject); // Make the cache aware of the user-session association so that // it can handle correctly cache entry lookups. //_cachePolicy.attachSessionToUser(principal, ssoUser); // Instead of associating the Principal used for authenticating (which is a // session id), sets the authenticated principal to the SSOUser part of the // Subject returned by the Gateway. JBossSecurityAssociationActions.setPrincipalInfo(ssoUser, passwordChars, subject); // Get the CallerPrincipal mapping RealmMapping rm = (RealmMapping) securityCtx.lookup("realmMapping"); Principal oldPrincipal = ssoUser; principal = rm.getPrincipal(oldPrincipal); logger.debug("Mapped from input principal: " + oldPrincipal + " to: " + principal); // Get the caching principal principal = getCachingPrincpal(rm, oldPrincipal, principal, credentials, subject); } else { principal = null; logger.debug("User: " + username + " is NOT authenticated"); } } catch (NamingException e) { principal = null; logger.error("Error during authenticate", e); } catch (SSOIdentityException e) { // Ignore this ... (user does not exist for this session) if (logger.isDebugEnabled()) { logger.debug(e.getMessage()); } principal = null; } catch (Exception e) { logger.error("Session authentication failed : " + username, e); throw new RuntimeException("Fatal error authenticating session : " + e); } logger.debug("End authenticate, principal=" + ssoUser); return ssoUser; }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
private void close(NamingEnumeration namingEnumeration) { if (namingEnumeration != null) { try {//ww w . j a v a 2s.co m namingEnumeration.close(); } catch (NamingException e) { log.warn("fail to close namingEnumeration: {}", e.getMessage()); } } }
From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java
/** * Updates the password for an existing principal in a previously configured KDC * <p/>/*from w w w . j a va 2s .c om*/ * The implementation is specific to a particular type of KDC. * * @param principal a String containing the principal to update * @param password a String containing the password to set * @return an Integer declaring the new key number * @throws KerberosOperationException */ @Override public Integer setPrincipalPassword(String principal, String password) throws KerberosOperationException { if (!isOpen()) { throw new KerberosOperationException("This operation handler has not been opened"); } if (principal == null) { throw new KerberosOperationException("principal is null"); } if (password == null) { throw new KerberosOperationException("principal password is null"); } DeconstructedPrincipal deconstructPrincipal = createDeconstructPrincipal(principal); try { String dn = findPrincipalDN(deconstructPrincipal.getNormalizedPrincipal()); if (dn != null) { ldapContext.modifyAttributes(escapeDNCharacters(dn), new ModificationItem[] { new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", String.format("\"%s\"", password).getBytes("UTF-16LE"))) }); } else { throw new KerberosOperationException( String.format("Can not set password for principal %s: Not Found", principal)); } } catch (NamingException e) { throw new KerberosOperationException( String.format("Can not set password for principal %s: %s", principal, e.getMessage()), e); } catch (UnsupportedEncodingException e) { throw new KerberosOperationException("Unsupported encoding UTF-16LE", e); } return 0; }