下面列出了javax.naming.NamingException#getMessage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Constructs an Rdn from the given attribute set. See
* {@link javax.naming.directory.Attributes Attributes}.
* <p>
* The string attribute values are not interpreted as
* <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
* formatted RDN strings. That is, the values are used
* literally (not parsed) and assumed to be unescaped.
*
* @param attrSet The non-null and non-empty attributes containing
* type/value mappings.
* @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
* be used to construct a valid RDN.
*/
public Rdn(Attributes attrSet) throws InvalidNameException {
if (attrSet.size() == 0) {
throw new InvalidNameException("Attributes cannot be empty");
}
entries = new ArrayList<>(attrSet.size());
NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
try {
for (int nEntries = 0; attrs.hasMore(); nEntries++) {
RdnEntry entry = new RdnEntry();
Attribute attr = attrs.next();
entry.type = attr.getID();
entry.value = attr.get();
entries.add(nEntries, entry);
}
} catch (NamingException e) {
InvalidNameException e2 = new InvalidNameException(
e.getMessage());
e2.initCause(e);
throw e2;
}
sort(); // arrange entries for comparison
}
/**
* Constructs an Rdn from the given attribute set. See
* {@link javax.naming.directory.Attributes Attributes}.
* <p>
* The string attribute values are not interpreted as
* <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
* formatted RDN strings. That is, the values are used
* literally (not parsed) and assumed to be unescaped.
*
* @param attrSet The non-null and non-empty attributes containing
* type/value mappings.
* @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
* be used to construct a valid RDN.
*/
public Rdn(Attributes attrSet) throws InvalidNameException {
if (attrSet.size() == 0) {
throw new InvalidNameException("Attributes cannot be empty");
}
entries = new ArrayList<>(attrSet.size());
NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
try {
for (int nEntries = 0; attrs.hasMore(); nEntries++) {
RdnEntry entry = new RdnEntry();
Attribute attr = attrs.next();
entry.type = attr.getID();
entry.value = attr.get();
entries.add(nEntries, entry);
}
} catch (NamingException e) {
InvalidNameException e2 = new InvalidNameException(
e.getMessage());
e2.initCause(e);
throw e2;
}
sort(); // arrange entries for comparison
}
/**
* Constructs an Rdn from the given attribute set. See
* {@link javax.naming.directory.Attributes Attributes}.
* <p>
* The string attribute values are not interpreted as
* <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
* formatted RDN strings. That is, the values are used
* literally (not parsed) and assumed to be unescaped.
*
* @param attrSet The non-null and non-empty attributes containing
* type/value mappings.
* @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
* be used to construct a valid RDN.
*/
public Rdn(Attributes attrSet) throws InvalidNameException {
if (attrSet.size() == 0) {
throw new InvalidNameException("Attributes cannot be empty");
}
entries = new ArrayList<>(attrSet.size());
NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
try {
for (int nEntries = 0; attrs.hasMore(); nEntries++) {
RdnEntry entry = new RdnEntry();
Attribute attr = attrs.next();
entry.type = attr.getID();
entry.value = attr.get();
entries.add(nEntries, entry);
}
} catch (NamingException e) {
InvalidNameException e2 = new InvalidNameException(
e.getMessage());
e2.initCause(e);
throw e2;
}
sort(); // arrange entries for comparison
}
/**
* Constructs an Rdn from the given attribute set. See
* {@link javax.naming.directory.Attributes Attributes}.
* <p>
* The string attribute values are not interpreted as
* <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
* formatted RDN strings. That is, the values are used
* literally (not parsed) and assumed to be unescaped.
*
* @param attrSet The non-null and non-empty attributes containing
* type/value mappings.
* @throws InvalidNameException If contents of {@code attrSet} cannot
* be used to construct a valid RDN.
*/
public Rdn(Attributes attrSet) throws InvalidNameException {
if (attrSet.size() == 0) {
throw new InvalidNameException("Attributes cannot be empty");
}
entries = new ArrayList<>(attrSet.size());
NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
try {
for (int nEntries = 0; attrs.hasMore(); nEntries++) {
RdnEntry entry = new RdnEntry();
Attribute attr = attrs.next();
entry.type = attr.getID();
entry.value = attr.get();
entries.add(nEntries, entry);
}
} catch (NamingException e) {
InvalidNameException e2 = new InvalidNameException(
e.getMessage());
e2.initCause(e);
throw e2;
}
sort(); // arrange entries for comparison
}
/**
* Constructs an Rdn from the given attribute set. See
* {@link javax.naming.directory.Attributes Attributes}.
* <p>
* The string attribute values are not interpreted as
* <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
* formatted RDN strings. That is, the values are used
* literally (not parsed) and assumed to be unescaped.
*
* @param attrSet The non-null and non-empty attributes containing
* type/value mappings.
* @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
* be used to construct a valid RDN.
*/
public Rdn(Attributes attrSet) throws InvalidNameException {
if (attrSet.size() == 0) {
throw new InvalidNameException("Attributes cannot be empty");
}
entries = new ArrayList<>(attrSet.size());
NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
try {
for (int nEntries = 0; attrs.hasMore(); nEntries++) {
RdnEntry entry = new RdnEntry();
Attribute attr = attrs.next();
entry.type = attr.getID();
entry.value = attr.get();
entries.add(nEntries, entry);
}
} catch (NamingException e) {
InvalidNameException e2 = new InvalidNameException(
e.getMessage());
e2.initCause(e);
throw e2;
}
sort(); // arrange entries for comparison
}
/**
* Constructs an Rdn from the given attribute set. See
* {@link javax.naming.directory.Attributes Attributes}.
* <p>
* The string attribute values are not interpreted as
* <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
* formatted RDN strings. That is, the values are used
* literally (not parsed) and assumed to be unescaped.
*
* @param attrSet The non-null and non-empty attributes containing
* type/value mappings.
* @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
* be used to construct a valid RDN.
*/
public Rdn(Attributes attrSet) throws InvalidNameException {
if (attrSet.size() == 0) {
throw new InvalidNameException("Attributes cannot be empty");
}
entries = new ArrayList<>(attrSet.size());
NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
try {
for (int nEntries = 0; attrs.hasMore(); nEntries++) {
RdnEntry entry = new RdnEntry();
Attribute attr = attrs.next();
entry.type = attr.getID();
entry.value = attr.get();
entries.add(nEntries, entry);
}
} catch (NamingException e) {
InvalidNameException e2 = new InvalidNameException(
e.getMessage());
e2.initCause(e);
throw e2;
}
sort(); // arrange entries for comparison
}
@Override
public Binding nextElement() {
try {
return nextElementInternal();
} catch (NamingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
Object readResolve() throws ObjectStreamException {
try {
return SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext().lookup(jndiName);
} catch (final NamingException e) {
throw new InvalidObjectException(e.getMessage());
}
}
public Destination resolveDestinationName(Session session, String destinationName, boolean pubSubDomain)
throws JMSException {
if (jndiTemplate != null) {
try {
return jndiTemplate.lookup(destinationName, Destination.class);
} catch (NamingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
if (pubSubDomain) {
return session.createTopic(destinationName);
}
return session.createQueue(destinationName);
}
/**
* Performs Dns query.
*
* @param <T> the generic type
* @param cls DnsRecord Type
* @param domain the domain
* @param dnsServerAddress IPAddress of DNS server to use (may be null)
* @return DnsRecord The DNS record list (never null but may be empty)
* @throws DnsException the dns exception
*/
public static <T extends DnsRecord> List<T> dnsQuery(Class<T> cls, String domain, String dnsServerAddress) throws
DnsException {
List<T> dnsRecordList = new ArrayList<T>();
try {
// Create initial context
DirContext ictx = new InitialDirContext(getEnv(dnsServerAddress));
// Retrieve SRV record context attribute for the specified domain
Attributes contextAttributes = ictx.getAttributes(domain,
new String[] {EWSConstants.SRVRECORD});
if (contextAttributes != null) {
NamingEnumeration<?> attributes = contextAttributes.getAll();
if (attributes != null) {
while (attributes.hasMore()) {
Attribute attr = (Attribute) attributes.next();
NamingEnumeration<?> srvValues = attr.getAll();
if (srvValues != null) {
while (srvValues.hasMore()) {
T dnsRecord = cls.newInstance();
// Loads the DNS SRV record
dnsRecord.load((String) srvValues.next());
dnsRecordList.add(dnsRecord);
}
}
}
}
}
} catch (NamingException ne) {
throw new DnsException(ne.getMessage());
} catch (Exception e) {
throw new DnsException(e.getMessage());
}
return dnsRecordList;
}
EntityNamePrincipalName.Builder mapBuilderFromContext(DirContextOperations context) {
final EntityNamePrincipalName.Builder person = EntityNamePrincipalName.Builder.create();
try {
person.setDefaultName((EntityName.Builder) getDefaultNameMapper().mapFromContext(context));
} catch (NamingException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
person.setPrincipalName(context.getStringAttribute(getConstants().getKimLdapNameProperty()));
return person;
}
/**
* Creates object without parameter
*/
protected BaseTableDAO(String configPath) throws SQLException {
logger = Logger.getLogger(configPath, this.getClass());
try {
setConnection(DBConnectionFactory.singleton().getConnection(
configPath));
} catch (NamingException namingException) {
throw new SQLException(namingException.getMessage());
}
connCreated = true;
}
@Override
public X509Certificate findByIssuerSerial(String issuer, String serial) {
if (issuer == null || serial == null) {
throw new IllegalArgumentException("Issuer and serial applications are expected in request");
}
String filter = String.format(filterIssuerSerialTemplate, issuer, serial);
try {
Attribute attr = ldapSearch.findAttribute(rootDN, filter, ldapConfig.getAttrCrtBinary());
return getCert(attr);
} catch (NamingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public void initialize() {
try {
this.workManager = (WorkManager) new InitialContext().lookup(workManagerName);
} catch (NamingException e) {
throw new IllegalStateException("Could not locate WorkManager: " + e.getMessage(), e);
}
}
@Override
public Set<LDAPCapabilityRepresentation> queryServerCapabilities() {
Set<LDAPCapabilityRepresentation> result = new LinkedHashSet<>();
try {
List<String> attrs = new ArrayList<>();
attrs.add("supportedControl");
attrs.add("supportedExtension");
attrs.add("supportedFeatures");
List<SearchResult> searchResults = operationManager
.search("", "(objectClass=*)", Collections.unmodifiableCollection(attrs), SearchControls.OBJECT_SCOPE);
if (searchResults.size() != 1) {
throw new ModelException("Could not query root DSE: unexpected result size");
}
SearchResult rootDse = searchResults.get(0);
Attributes attributes = rootDse.getAttributes();
for (String attr: attrs) {
Attribute attribute = attributes.get(attr);
if (null != attribute) {
CapabilityType capabilityType = CapabilityType.fromRootDseAttributeName(attr);
NamingEnumeration<?> values = attribute.getAll();
while (values.hasMoreElements()) {
Object o = values.nextElement();
LDAPCapabilityRepresentation capability = new LDAPCapabilityRepresentation(o, capabilityType);
logger.info("rootDSE query: " + capability);
result.add(capability);
}
}
}
return result;
} catch (NamingException e) {
throw new ModelException("Failed to query root DSE: " + e.getMessage(), e);
}
}
private void convertNamingException( final NamingException e )
throws ChaiOperationException, ChaiUnavailableException
{
// important safety tip: naming exceptions sometimes come with null messages....
final StringBuilder errorMsg = new StringBuilder();
errorMsg.append( e.getClass().getName() );
if ( e.getMessage() != null )
{
errorMsg.append( ": " ).append( e.getMessage() );
}
Throwable cause = e.getCause();
int safetyCounter = 0;
while ( cause != null && safetyCounter < 10 )
{
safetyCounter++;
errorMsg.append( ", cause:" ).append( cause.getClass().getName() );
if ( cause.getMessage() != null )
{
errorMsg.append( ": " ).append( cause.getMessage() );
}
cause = cause.getCause();
}
if ( errorIsRetryable( e ) )
{
throw new ChaiUnavailableException( errorMsg.toString(), ChaiError.COMMUNICATION, false, false );
}
throw ChaiOperationException.forErrorMessage( errorMsg.toString() );
}
/**
* Get user name list from DN list.
*
* @param userListFromSearch
* @return
* @throws UserStoreException
*/
private List<String> getUserNamesFromDNList(List<String> userListFromSearch) throws UserStoreException {
List<String> userNameList = new ArrayList<>();
DirContext dirContext = this.connectionSource.getContext();
String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
String displayNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.DISPLAY_NAME_ATTRIBUTE);
String[] requiredAttributes = {userNameProperty, displayNameAttribute};
for (String user : userListFromSearch) {
try {
String displayName = null;
String userName = null;
Attributes userAttributes = dirContext.getAttributes(escapeDNForSearch(user), requiredAttributes);
if (userAttributes != null) {
Attribute userNameAttribute = userAttributes.get(userNameProperty);
if (userNameAttribute != null) {
userName = (String) userNameAttribute.get();
}
if (StringUtils.isNotEmpty(displayNameAttribute)) {
Attribute displayAttribute = userAttributes.get(displayNameAttribute);
if (displayAttribute != null) {
displayName = (String) displayAttribute.get();
}
}
}
String domainName =
realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
/* Username will be null in the special case where the username attribute has changed to another
and having different userNameProperty than the current user-mgt.xml. */
if (userName != null) {
user = UserCoreUtil.getCombinedName(domainName, userName, displayName);
userNameList.add(user);
} else {
// Skip listing users which are not applicable to current user-mgt.xml
if (log.isDebugEnabled()) {
log.debug(String.format("User %s doesn't have the user name property %s", user,
userNameProperty));
}
}
} catch (NamingException e) {
log.error(String.format("Error in reading user information in the user store for the user %s, %s",
user, e.getMessage()));
throw new UserStoreException(e.getMessage(), e);
}
}
return userNameList;
}
/**
* Parse the search result of non group filtering and get the user list.
*
* @param answer
* @param returnedAttributes
* @return
* @throws UserStoreException
*/
private List<String> getUserListFromNonGroupFilterResult(NamingEnumeration<SearchResult> answer,
List<String> returnedAttributes)
throws UserStoreException {
List<String> finalUserList = new ArrayList<>();
String userAttributeSeparator = ",";
NamingEnumeration<?> attrs = null;
try {
while (answer.hasMoreElements()) {
SearchResult searchResult = answer.next();
Attributes attributes = searchResult.getAttributes();
if (attributes == null) {
continue;
}
Attribute attribute = attributes.get(returnedAttributes.get(0));
if (attribute == null) {
continue;
}
StringBuffer attrBuffer = new StringBuffer();
for (attrs = attribute.getAll(); attrs.hasMore(); ) {
String attr = (String) attrs.next();
if (StringUtils.isNotEmpty(attr.trim())) {
String attrSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
if (StringUtils.isNotEmpty(attrSeparator.trim())) {
userAttributeSeparator = attrSeparator;
}
attrBuffer.append(attr + userAttributeSeparator);
if (log.isDebugEnabled()) {
log.debug(returnedAttributes.get(0) + " : " + attr);
}
}
}
String propertyValue = attrBuffer.toString();
Attribute serviceNameObject = attributes.get(returnedAttributes.get(1));
String serviceNameAttributeValue = null;
if (serviceNameObject != null) {
serviceNameAttributeValue = (String) serviceNameObject.get();
}
/* Length needs to be more than userAttributeSeparator.length() for a valid attribute,
since we attach userAttributeSeparator. */
if (propertyValue.trim().length() > userAttributeSeparator.length()) {
if (LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE.equals(serviceNameAttributeValue)) {
continue;
}
propertyValue = propertyValue.substring(0, propertyValue.length() -
userAttributeSeparator.length());
finalUserList.add(propertyValue);
}
}
} catch (NamingException e) {
log.error(String.format("Error occurred while getting user list from non group filter %s", e.getMessage()));
throw new UserStoreException(e.getMessage(), e);
} finally {
// Close the naming enumeration and free up resources
JNDIUtil.closeNamingEnumeration(attrs);
}
return finalUserList;
}
@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 {
// 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;
}
}
private AccessContext signInLDAP(IdentityName idName, byte[] password)
throws SignInException
{
AccessContext signInContext = null;
Hashtable<String, String> ldapEnv = new Hashtable<>();
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, ctrlCfg.getLdapUri());
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
String ldapDN = ctrlCfg.getLdapDn().replaceAll("\\{user}", idName.displayValue);
ldapEnv.put(Context.SECURITY_PRINCIPAL, ldapDN);
ldapEnv.put(Context.SECURITY_CREDENTIALS, new String(password, StandardCharsets.UTF_8));
try
{
DirContext ctx = new InitialDirContext(ldapEnv);
if (!ctrlCfg.getLdapSearchFilter().isEmpty())
{
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
final String searchFilter = ctrlCfg.getLdapSearchFilter().replaceAll("\\{user}", idName.displayValue);
NamingEnumeration result = ctx.search(ctrlCfg.getLdapSearchFilter(), searchFilter, searchControls);
if (!result.hasMore())
{
result.close();
throw new InvalidCredentialsException(
"Sign-in failed: LDAP search filter didn't find a match.",
// Description
"Sign-in failed",
// Cause
"Search filter expression didn't match any item.",
// Correction
"Adapt LDAP search_base,search_filter or add user to searched group.",
// No error details
null
);
}
result.close();
}
signInContext = publicCtx;
errorLog.logInfo("LDAP User %s successfully authenticated.", idName.displayValue);
}
catch (NamingException nExc)
{
throw new InvalidCredentialsException(
"Sign-in failed: Invalid sign in credentials",
// Description
"Sign-in failed",
// Cause
"The credentials for the sign-in are not valid or LDAP access not correctly configured.",
// Correction
"The name of a valid identity and a matching password must be provided " +
"to sign in to the system or LDAP access correctly configured.",
nExc.getMessage(),
nExc
);
}
return signInContext;
}