Java Code Examples for javax.naming.NamingEnumeration.hasMore()

The following are Jave code examples for showing how to use hasMore() of the javax.naming.NamingEnumeration class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: apache-tomcat-7.0.73-with-comment   File: TestNamingContext.java   Source Code and License Vote up 6 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        NamingEnumeration<Binding> enm =
            ctx.listBindings("java:comp/env/list");
        while (enm.hasMore()) {
            Binding b = enm.next();
            out.print(b.getObject().getClass().getName());
        }
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
 
Example 2
Project: alfresco-repository   File: LDAPUserRegistry.java   Source Code and License Vote up 6 votes
/**
 * Gets the values of a repeating attribute that may have range restriction options. If an attribute is range
 * restricted, it will appear in the attribute set with a ";range=i-j" option, where i and j indicate the start and
 * end index, and j is '*' if it is at the end.
 * 
 * @param attributes
 *            the attributes
 * @param attributeName
 *            the attribute name
 * @return the range restricted attribute
 * @throws NamingException
 *             the naming exception
 */
private Attribute getRangeRestrictedAttribute(Attributes attributes, String attributeName) throws NamingException
{
    Attribute unrestricted = attributes.get(attributeName);
    if (unrestricted != null)
    {
        return unrestricted;
    }
    NamingEnumeration<? extends Attribute> i = attributes.getAll();
    String searchString = attributeName.toLowerCase() + ';';
    while (i.hasMore())
    {
        Attribute attribute = i.next();
        if (attribute.getID().toLowerCase().startsWith(searchString))
        {
            return attribute;
        }
    }
    return null;
}
 
Example 3
Project: tomcat7   File: TestNamingContext.java   Source Code and License Vote up 6 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        NamingEnumeration<Binding> enm =
            ctx.listBindings("java:comp/env/list");
        while (enm.hasMore()) {
            Binding b = enm.next();
            out.print(b.getObject().getClass().getName());
        }
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
 
Example 4
Project: ChronoBike   File: LdapUtil.java   Source Code and License Vote up 6 votes
/**
    * @param dn
    * @return
    * @throws NamingException
    */
   public TreeMap getAllAttributesSorted(String dn) throws NamingException 
{
       NamingEnumeration enumAll = getAllAttributes(dn);
       TreeMap<String, Object> tree = new TreeMap<String, Object>();
       while (enumAll.hasMore()) 
       {
           Attribute a = (Attribute)enumAll.next();
           tree.put(new String(a.getID()), a.get());
       }
       for (Iterator it = tree.keySet().iterator(); it.hasNext();) 
       {
           String key = (String)it.next();
           Log.logDebug(key+" = "+tree.get(key));
       }
       return tree;
   }
 
Example 5
Project: premier-wherehows   File: AuthenticationManager.java   Source Code and License Vote up 5 votes
public static Map<String, String> getUserAttributes(DirContext ctx, String searchBase, String userName,
    String principalDomain, String... attributeNames)
    throws NamingException {
  if (StringUtils.isBlank(userName)) {
    throw new IllegalArgumentException("Username and password can not be blank.");
  }

  if (attributeNames.length == 0) {
    return Collections.emptyMap();
  }

  Attributes matchAttr = new BasicAttributes(true);
  BasicAttribute basicAttr = new BasicAttribute("userPrincipalName", userName + principalDomain);
  matchAttr.put(basicAttr);

  NamingEnumeration<? extends SearchResult> searchResult = ctx.search(searchBase, matchAttr, attributeNames);

  if (ctx != null) {
    ctx.close();
  }

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

  if (searchResult.hasMore()) {
    NamingEnumeration<? extends Attribute> attributes = searchResult.next().getAttributes().getAll();

    while (attributes.hasMore()) {
      Attribute attr = attributes.next();
      String attrId = attr.getID();
      String attrValue = (String) attr.get();

      result.put(attrId, attrValue);
    }
  }
  return result;
}
 
Example 6
Project: openjdk-jdk10   File: BasicAttributes.java   Source Code and License Vote up 5 votes
/**
 * Determines whether this {@code BasicAttributes} is equal to another
 * {@code Attributes}
 * Two {@code Attributes} are equal if they are both instances of
 * {@code Attributes},
 * treat the case of attribute IDs the same way, and contain the
 * same attributes. Each {@code Attribute} in this {@code BasicAttributes}
 * is checked for equality using {@code Object.equals()}, which may have
 * be overridden by implementations of {@code Attribute}).
 * If a subclass overrides {@code equals()},
 * it should override {@code hashCode()}
 * as well so that two {@code Attributes} instances that are equal
 * have the same hash code.
 * @param obj the possibly null object to compare against.
 *
 * @return true If obj is equal to this BasicAttributes.
 * @see #hashCode
 */
public boolean equals(Object obj) {
    if ((obj != null) && (obj instanceof Attributes)) {
        Attributes target = (Attributes)obj;

        // Check case first
        if (ignoreCase != target.isCaseIgnored()) {
            return false;
        }

        if (size() == target.size()) {
            Attribute their, mine;
            try {
                NamingEnumeration<?> theirs = target.getAll();
                while (theirs.hasMore()) {
                    their = (Attribute)theirs.next();
                    mine = get(their.getID());
                    if (!their.equals(mine)) {
                        return false;
                    }
                }
            } catch (NamingException e) {
                return false;
            }
            return true;
        }
    }
    return false;
}
 
Example 7
Project: lazycat   File: ManagerServlet.java   Source Code and License Vote up 5 votes
/**
 * List the resources of the given context.
 */
protected void printResources(PrintWriter writer, String prefix, javax.naming.Context namingContext, String type,
		Class<?> clazz, StringManager smClient) {

	try {
		NamingEnumeration<Binding> items = namingContext.listBindings("");
		while (items.hasMore()) {
			Binding item = items.next();
			if (item.getObject() instanceof javax.naming.Context) {
				printResources(writer, prefix + item.getName() + "/", (javax.naming.Context) item.getObject(), type,
						clazz, smClient);
			} else {
				if ((clazz != null) && (!(clazz.isInstance(item.getObject())))) {
					continue;
				}
				writer.print(prefix + item.getName());
				writer.print(':');
				writer.print(item.getClassName());
				// Do we want a description if available?
				writer.println();
			}
		}
	} catch (Throwable t) {
		ExceptionUtils.handleThrowable(t);
		log("ManagerServlet.resources[" + type + "]", t);
		writer.println(smClient.getString("managerServlet.exception", t.toString()));
	}

}
 
Example 8
Project: centraldogma   File: SearchFirstActiveDirectoryRealm.java   Source Code and License Vote up 5 votes
/**
 * Finds a distinguished name(DN) of a user by querying the active directory LDAP context for the
 * specified username.
 */
protected String findUserDn(LdapContextFactory ldapContextFactory, String username) throws NamingException {
    LdapContext ctx = null;
    try {
        // Binds using the system username and password.
        ctx = ldapContextFactory.getSystemLdapContext();

        final SearchControls ctrl = new SearchControls();
        ctrl.setCountLimit(1);
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setTimeLimit(searchTimeoutMillis);

        final String filter =
                searchFilter != null ? USERNAME_PLACEHOLDER.matcher(searchFilter)
                                                           .replaceAll(username)
                                     : username;
        final NamingEnumeration<SearchResult> result = ctx.search(searchBase, filter, ctrl);
        try {
            if (!result.hasMore()) {
                throw new AuthenticationException("No username: " + username);
            }
            return result.next().getNameInNamespace();
        } finally {
            result.close();
        }
    } finally {
        LdapUtils.closeContext(ctx);
    }
}
 
Example 9
Project: tomcat7   File: ManagerServlet.java   Source Code and License Vote up 5 votes
/**
 * List the resources of the given context.
 */
protected void printResources(PrintWriter writer, String prefix,
                              javax.naming.Context namingContext,
                              String type, Class<?> clazz,
                              StringManager smClient) {

    try {
        NamingEnumeration<Binding> items = namingContext.listBindings("");
        while (items.hasMore()) {
            Binding item = items.next();
            if (item.getObject() instanceof javax.naming.Context) {
                printResources
                    (writer, prefix + item.getName() + "/",
                     (javax.naming.Context) item.getObject(), type, clazz,
                     smClient);
            } else {
                if ((clazz != null) &&
                    (!(clazz.isInstance(item.getObject())))) {
                    continue;
                }
                writer.print(prefix + item.getName());
                writer.print(':');
                writer.print(item.getClassName());
                // Do we want a description if available?
                writer.println();
            }
        }
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        log("ManagerServlet.resources[" + type + "]", t);
        writer.println(smClient.getString("managerServlet.exception",
                t.toString()));
    }

}
 
Example 10
Project: ChronoBike   File: LdapUtil.java   Source Code and License Vote up 5 votes
/**
    * @param dn
    * @param attributeNames
    * @return
    * @throws NamingException
    */
   public NamingEnumeration getSomeAttributes(String dn, String[] attributeNames) throws NamingException 
{
       Attributes attrs = m_ctx.getAttributes(dn, attributeNames);
       NamingEnumeration enumSome = attrs.getAll();
       while (enumSome.hasMore()) 
       {
           Attribute a = (Attribute)enumSome.next();
           Log.logDebug(a.getID()+" = "+a.get());
       }
       return enumSome;
   }
 
Example 11
Project: lams   File: DirContextURLConnection.java   Source Code and License Vote up 5 votes
/**
 * Returns the name of the specified header field.
 */
public String getHeaderField(String name) {

    if (!connected) {
        // Try to connect (silently)
        try {
            connect();
        } catch (IOException e) {
        }
    }
    
    if (attributes == null)
        return (null);

    NamingEnumeration attributeEnum = attributes.getIDs();
    try {
        while (attributeEnum.hasMore()) {
            String attributeID = (String)attributeEnum.next();
            if (attributeID.equalsIgnoreCase(name)) {
                Attribute attribute = attributes.get(attributeID);
                if (attribute == null) return null;
                return getHeaderValueAsString(attribute.get(attribute.size()-1));
            }
        }
    } catch (NamingException ne) {
        // Shouldn't happen
    }

    return (null);
    
}
 
Example 12
Project: sdirobot   File: CManagerMap.java   Source Code and License Vote up 5 votes
public static boolean enumerate(Context _ctx, NamingEnumeration e, String string,String __dbtype) throws NamingException {
    while (e.hasMore()) {
        Binding binding = (Binding) e.next();
        Common.debugingLine2D("DataSource binding Name: " + binding.getName());
        // System.out.println("Type: " + binding.getClassName());
        //  System.out.println("Value: " + binding.getObject());

        if(binding.getName().endsWith(__dbtype))
        {
        DataSource _ds1 = (DataSource) _ctx.lookup("jdbc/" + binding.getName());
        addDs(binding.getName(), _ds1);
        }
    }
    return !_m_conn.isEmpty();
}
 
Example 13
Project: oscm   File: LdapAccessServiceBean.java   Source Code and License Vote up 5 votes
private boolean hasMoreEnum(NamingEnumeration<SearchResult> namingEnum)
        throws NamingException {
    boolean hasMore = true;
    try {
        if (!namingEnum.hasMore()) {
            hasMore = false;
        }
    } catch (PartialResultException e) {
        hasMore = false;
        logger.logWarn(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.WARN_LDAP_PARTIAL_EXCEPTION);
    }
    return hasMore;
}
 
Example 14
Project: Equella   File: LDAP.java   Source Code and License Vote up 5 votes
/**
 * @return null if there are zero results
 */
private NamingEnumeration<SearchResult> search(DirContext ctx, Name base, String[] returnAttributes, Filter filter,
	boolean recurse)
{
	SearchControls ctls = new SearchControls();
	ctls.setCountLimit(filter.getLimit());
	ctls.setReturningAttributes(returnAttributes);
	ctls.setSearchScope(recurse ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);

	try
	{
		// Search for objects using the filter
		String query = filter.toFilter();
		if( LOGGER.isDebugEnabled() )
		{
			LOGGER.debug("Query:" + query + " Base:" + base);
		}
		NamingEnumeration<SearchResult> ne = ctx.search(base, query, ctls);
		if( ne.hasMore() )
		{
			return ne;
		}
	}
	catch( PartialResultException pre )
	{
		LOGGER.info(pre);
	}
	catch( SizeLimitExceededException slee )
	{
		LOGGER.info(slee);
	}
	catch( Exception e )
	{
		LOGGER.warn(e);
	}

	return null;
}
 
Example 15
Project: jdk8u-jdk   File: BasicAttributes.java   Source Code and License Vote up 5 votes
/**
 * Determines whether this <tt>BasicAttributes</tt> is equal to another
 * <tt>Attributes</tt>
 * Two <tt>Attributes</tt> are equal if they are both instances of
 * <tt>Attributes</tt>,
 * treat the case of attribute IDs the same way, and contain the
 * same attributes. Each <tt>Attribute</tt> in this <tt>BasicAttributes</tt>
 * is checked for equality using <tt>Object.equals()</tt>, which may have
 * be overridden by implementations of <tt>Attribute</tt>).
 * If a subclass overrides <tt>equals()</tt>,
 * it should override <tt>hashCode()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 * @param obj the possibly null object to compare against.
 *
 * @return true If obj is equal to this BasicAttributes.
 * @see #hashCode
 */
public boolean equals(Object obj) {
    if ((obj != null) && (obj instanceof Attributes)) {
        Attributes target = (Attributes)obj;

        // Check case first
        if (ignoreCase != target.isCaseIgnored()) {
            return false;
        }

        if (size() == target.size()) {
            Attribute their, mine;
            try {
                NamingEnumeration<?> theirs = target.getAll();
                while (theirs.hasMore()) {
                    their = (Attribute)theirs.next();
                    mine = get(their.getID());
                    if (!their.equals(mine)) {
                        return false;
                    }
                }
            } catch (NamingException e) {
                return false;
            }
            return true;
        }
    }
    return false;
}
 
Example 16
Project: Equella   File: MemberOfGroupSearch.java   Source Code and License Vote up 5 votes
private Collection<Name> getLDAPGroupNames(DirContext ctx, Attributes useratt)
{
	Set<Name> foundGroups = new HashSet<Name>();
	if( !Check.isEmpty(memberOfField) )
	{
		Attribute attribute = useratt.get(memberOfField);
		try
		{
			NameParser parser = ctx.getNameParser(""); //$NON-NLS-1$
			if( attribute != null )
			{
				NamingEnumeration<?> enumeration = attribute.getAll();
				while( enumeration != null && enumeration.hasMore() )
				{
					String role = (String) enumeration.next();
					Name compound = parser.parse(role);
					foundGroups.add(compound);
				}
			}
		}
		catch( NamingException e )
		{
			throw new RuntimeException("Couldn't get memberField", e);
		}
	}
	return foundGroups;
}
 
Example 17
Project: apache-tomcat-7.0.73-with-comment   File: DirContextURLConnection.java   Source Code and License Vote up 4 votes
/**
 * Returns an unmodifiable Map of the header fields.
 */
@Override
public Map<String,List<String>> getHeaderFields() {

  if (!connected) {
      // Try to connect (silently)
      try {
          connect();
      } catch (IOException e) {
          //Ignore
      }
  }

  if (attributes == null)
      return (Collections.emptyMap());

  HashMap<String,List<String>> headerFields =
      new HashMap<String,List<String>>(attributes.size());
  NamingEnumeration<String> attributeEnum = attributes.getIDs();
  try {
      while (attributeEnum.hasMore()) {
          String attributeID = attributeEnum.next();
          Attribute attribute = attributes.get(attributeID);
          if (attribute == null) continue;
          ArrayList<String> attributeValueList =
              new ArrayList<String>(attribute.size());
          NamingEnumeration<?> attributeValues = attribute.getAll();
          while (attributeValues.hasMore()) {
              Object attrValue = attributeValues.next();
              attributeValueList.add(getHeaderValueAsString(attrValue));
          }
          attributeValueList.trimToSize(); // should be a no-op if attribute.size() didn't lie
          headerFields.put(attributeID, Collections.unmodifiableList(attributeValueList));
      }
  } catch (NamingException ne) {
        // Shouldn't happen
  }

  return Collections.unmodifiableMap(headerFields);

}
 
Example 18
Project: openjdk-jdk10   File: BasicAttributes.java   Source Code and License Vote up 3 votes
/**
 * Calculates the hash code of this BasicAttributes.
 *<p>
 * The hash code is computed by adding the hash code of
 * the attributes of this object. If this BasicAttributes
 * ignores case of its attribute IDs, one is added to the hash code.
 * If a subclass overrides {@code hashCode()},
 * it should override {@code equals()}
 * as well so that two {@code Attributes} instances that are equal
 * have the same hash code.
 *
 * @return an int representing the hash code of this BasicAttributes instance.
 * @see #equals
 */
public int hashCode() {
    int hash = (ignoreCase ? 1 : 0);
    try {
        NamingEnumeration<?> all = getAll();
        while (all.hasMore()) {
            hash += all.next().hashCode();
        }
    } catch (NamingException e) {}
    return hash;
}
 
Example 19
Project: OpenJSharp   File: BasicAttributes.java   Source Code and License Vote up 3 votes
/**
 * Calculates the hash code of this BasicAttributes.
 *<p>
 * The hash code is computed by adding the hash code of
 * the attributes of this object. If this BasicAttributes
 * ignores case of its attribute IDs, one is added to the hash code.
 * If a subclass overrides <tt>hashCode()</tt>,
 * it should override <tt>equals()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 *
 * @return an int representing the hash code of this BasicAttributes instance.
 * @see #equals
 */
public int hashCode() {
    int hash = (ignoreCase ? 1 : 0);
    try {
        NamingEnumeration<?> all = getAll();
        while (all.hasMore()) {
            hash += all.next().hashCode();
        }
    } catch (NamingException e) {}
    return hash;
}
 
Example 20
Project: jdk8u-jdk   File: BasicAttributes.java   Source Code and License Vote up 3 votes
/**
 * Calculates the hash code of this BasicAttributes.
 *<p>
 * The hash code is computed by adding the hash code of
 * the attributes of this object. If this BasicAttributes
 * ignores case of its attribute IDs, one is added to the hash code.
 * If a subclass overrides <tt>hashCode()</tt>,
 * it should override <tt>equals()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 *
 * @return an int representing the hash code of this BasicAttributes instance.
 * @see #equals
 */
public int hashCode() {
    int hash = (ignoreCase ? 1 : 0);
    try {
        NamingEnumeration<?> all = getAll();
        while (all.hasMore()) {
            hash += all.next().hashCode();
        }
    } catch (NamingException e) {}
    return hash;
}