Java 类javax.naming.NamingEnumeration 实例源码

项目:apache-tomcat-7.0.73-with-comment    文件:TestJNDIRealm.java   
private NamingEnumeration<SearchResult> mockSearchResults(String password)
        throws NamingException {
    @SuppressWarnings("unchecked")
    NamingEnumeration<SearchResult> searchResults =
    EasyMock.createNiceMock(NamingEnumeration.class);
    EasyMock.expect(Boolean.valueOf(searchResults.hasMore()))
            .andReturn(Boolean.TRUE)
            .andReturn(Boolean.FALSE)
            .andReturn(Boolean.TRUE)
            .andReturn(Boolean.FALSE);
    EasyMock.expect(searchResults.next())
            .andReturn(new SearchResult("ANY RESULT", "",
                    new BasicAttributes(USER_PASSWORD_ATTR, password)))
            .times(2);
    EasyMock.replay(searchResults);
    return searchResults;
}
项目:alfresco-repository    文件:LDAPUserRegistry.java   
/**
 * 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;
}
项目:lazycat    文件:NamingContext.java   
/**
 * Enumerates the names bound in the named context, along with the objects
 * bound to them. The contents of any subcontexts are not included.
 * <p>
 * If a binding is added to or removed from this context, its effect on an
 * enumeration previously returned is undefined.
 * 
 * @param name
 *            the name of the context to list
 * @return an enumeration of the bindings in this context. Each element of
 *         the enumeration is of type Binding.
 * @exception NamingException
 *                if a naming exception is encountered
 */
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
    // Removing empty parts
    while ((!name.isEmpty()) && (name.get(0).length() == 0))
        name = name.getSuffix(1);
    if (name.isEmpty()) {
        return new NamingContextBindingsEnumeration(bindings.values().iterator(), this);
    }

    NamingEntry entry = bindings.get(name.get(0));

    if (entry == null) {
        throw new NameNotFoundException(sm.getString("namingContext.nameNotBound", name, name.get(0)));
    }

    if (entry.type != NamingEntry.CONTEXT) {
        throw new NamingException(sm.getString("namingContext.contextExpected"));
    }
    return ((Context) entry.value).listBindings(name.getSuffix(1));
}
项目:openjdk-jdk10    文件:Rdn.java   
/**
 * 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
}
项目:jerrydog    文件:NamingContext.java   
/**
 * Enumerates the names bound in the named context, along with the class 
 * names of objects bound to them. The contents of any subcontexts are 
 * not included.
 * <p>
 * If a binding is added to or removed from this context, its effect on 
 * an enumeration previously returned is undefined.
 * 
 * @param name the name of the context to list
 * @return an enumeration of the names and class names of the bindings in 
 * this context. Each element of the enumeration is of type NameClassPair.
 * @exception NamingException if a naming exception is encountered
 */
public NamingEnumeration list(Name name)
    throws NamingException {
    // Removing empty parts
    while ((!name.isEmpty()) && (name.get(0).length() == 0))
        name = name.getSuffix(1);
    if (name.isEmpty()) {
        return new NamingContextEnumeration(bindings.elements());
    }

    NamingEntry entry = (NamingEntry) bindings.get(name.get(0));

    if (entry == null) {
        throw new NameNotFoundException
            (sm.getString("namingContext.nameNotBound", name.get(0)));
    }

    if (entry.type != NamingEntry.CONTEXT) {
        throw new NamingException
            (sm.getString("namingContext.contextExpected"));
    }
    return ((Context) entry.value).list(name.getSuffix(1));
}
项目:OpenJSharp    文件:Rdn.java   
/**
 * 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
}
项目:apache-tomcat-7.0.73-with-comment    文件:NamingContext.java   
/**
 * Enumerates the names bound in the named context, along with the 
 * objects bound to them. The contents of any subcontexts are not 
 * included.
 * <p>
 * If a binding is added to or removed from this context, its effect on 
 * an enumeration previously returned is undefined.
 * 
 * @param name the name of the context to list
 * @return an enumeration of the bindings in this context. 
 * Each element of the enumeration is of type Binding.
 * @exception NamingException if a naming exception is encountered
 */
@Override
public NamingEnumeration<Binding> listBindings(Name name)
    throws NamingException {
    // Removing empty parts
    while ((!name.isEmpty()) && (name.get(0).length() == 0))
        name = name.getSuffix(1);
    if (name.isEmpty()) {
        return new NamingContextBindingsEnumeration(bindings.values().iterator(), this);
    }

    NamingEntry entry = bindings.get(name.get(0));

    if (entry == null) {
        throw new NameNotFoundException
            (sm.getString("namingContext.nameNotBound", name, name.get(0)));
    }

    if (entry.type != NamingEntry.CONTEXT) {
        throw new NamingException
            (sm.getString("namingContext.contextExpected"));
    }
    return ((Context) entry.value).listBindings(name.getSuffix(1));
}
项目:premier-wherehows    文件:AuthenticationManager.java   
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;
}
项目:wherehowsX    文件:AuthenticationManager.java   
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;
}
项目:apache-tomcat-7.0.73-with-comment    文件:BaseDirContext.java   
/**
 * Enumerates the names bound in the named context, along with the 
 * objects bound to them.
 * 
 * @param name the name of the context to list
 * @return an enumeration of the bindings in this context. 
 * Each element of the enumeration is of type Binding.
 * @exception NamingException if a naming exception is encountered
 */
@Override
public final NamingEnumeration<Binding> listBindings(String name)
    throws NamingException {
    if (!aliases.isEmpty()) {
        AliasResult result = findAlias(name);
        if (result.dirContext != null) {
            return result.dirContext.listBindings(result.aliasName);
        }
    }

    // Next do a standard lookup
    List<NamingEntry> bindings = doListBindings(name);

    // Check the alternate locations
    List<NamingEntry> altBindings = null;

    String resourceName = "/META-INF/resources" + name;
    for (DirContext altDirContext : altDirContexts) {
        if (altDirContext instanceof BaseDirContext) {
            altBindings = ((BaseDirContext) altDirContext).doListBindings(resourceName);
        }
        if (altBindings != null) {
            if (bindings == null) {
                bindings = altBindings;
            } else {
                bindings.addAll(altBindings);
            }
        }
    }

    if (bindings != null) {
        return new NamingContextBindingsEnumeration(bindings.iterator(),
                this);
    }

    // Really not found
    throw new NameNotFoundException(
            sm.getString("resources.notFound", name));
}
项目:tomcat7    文件:JNDIRealm.java   
/**
 * Add values of a specified attribute to a list
 *
 * @param attrId Attribute name
 * @param attrs Attributes containing the new values
 * @param values ArrayList containing values found so far
 *
 * @exception NamingException if a directory server error occurs
 */
private ArrayList<String> addAttributeValues(String attrId,
                                     Attributes attrs,
                                     ArrayList<String> values)
    throws NamingException{

    if (containerLog.isTraceEnabled())
        containerLog.trace("  retrieving values for attribute " + attrId);
    if (attrId == null || attrs == null)
        return values;
    if (values == null)
        values = new ArrayList<String>();
    Attribute attr = attrs.get(attrId);
    if (attr == null)
        return values;
    NamingEnumeration<?> e = attr.getAll();
    try {
        while(e.hasMore()) {
            String value = (String)e.next();
            values.add(value);
        }
    } catch (PartialResultException ex) {
        if (!adCompat)
            throw ex;
    } finally {
        e.close();
    }
    return values;
}
项目:tomcat7    文件:SelectorContext.java   
/**
 * Enumerates the names bound in the named context, along with the class
 * names of objects bound to them.
 *
 * @param name the name of the context to list
 * @return an enumeration of the names and class names of the bindings in
 * this context. Each element of the enumeration is of type NameClassPair.
 * @exception NamingException if a naming exception is encountered
 */
@Override
public NamingEnumeration<NameClassPair> list(String name)
    throws NamingException {

    if (log.isDebugEnabled()) {
        log.debug(sm.getString("selectorContext.methodUsingString", "list",
                name));
    }

    return getBoundContext().list(parseName(name));
}
项目:unitimes    文件:LocalContext.java   
@Override
public NamingEnumeration list(Name name) throws NamingException {
    if (name.isEmpty())
        return new ListOfNames(iBindings.keys());

    Object target = lookup(name);
    if (target instanceof Context)
        return ((Context) target).list("");


    throw new NotContextException(name + " cannot be listed");
}
项目:tomcat7    文件:BaseDirContext.java   
/**
 * Enumerates the names bound in the named context, along with the class 
 * names of objects bound to them.
 * 
 * @param name the name of the context to list
 * @return an enumeration of the names and class names of the bindings in 
 * this context. Each element of the enumeration is of type NameClassPair.
 * @exception NamingException if a naming exception is encountered
 */
@Override
public NamingEnumeration<NameClassPair> list(String name)
    throws NamingException {

    if (!aliases.isEmpty()) {
        AliasResult result = findAlias(name);
        if (result.dirContext != null) {
            return result.dirContext.list(result.aliasName);
        }
    }

    // Next do a standard lookup
    List<NamingEntry> bindings = doListBindings(name);

    // Check the alternate locations
    List<NamingEntry> altBindings = null;

    String resourceName = "/META-INF/resources" + name;
    for (DirContext altDirContext : altDirContexts) {
        if (altDirContext instanceof BaseDirContext) {
            altBindings = ((BaseDirContext) altDirContext).doListBindings(resourceName);
        }
        if (altBindings != null) {
            if (bindings == null) {
                bindings = altBindings;
            } else {
                bindings.addAll(altBindings);
            }
        }
    }

    if (bindings != null) {
        return new NamingContextEnumeration(bindings.iterator());
    }

    // Really not found
    throw new NameNotFoundException(
            sm.getString("resources.notFound", name));
}
项目:jdk8u-jdk    文件:BasicAttributes.java   
/**
 * 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;
}
项目:ChronoBike    文件:LdapUtil.java   
/**
    * @param dn
    * @param filter
    * @return
    * @throws NamingException
    */
   public NamingEnumeration searchChildren(String dn, String filter) throws NamingException 
{
       SearchControls constraints = new SearchControls();
       constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
       return m_ctx.search(dn, filter, constraints);
   }
项目:openshift-ldapsync    文件:LdapServer.java   
public NamingEnumeration<SearchResult> search(final String baseDN, final String filter) throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    LdapContext ctx = new InitialLdapContext(env, null);
    NamingEnumeration<SearchResult> result = ctx.search(baseDN, filter, searchControls);
    ctx.close();

    return result;
}
项目:sdirobot    文件:CManagerMap.java   
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();
}
项目:tomcat7    文件:ResourceAttributes.java   
/**
 * Get all attribute IDs.
 */
@Override
public NamingEnumeration<String> getIDs() {
    if (attributes == null) {
        Vector<String> attributeIDs = new Vector<String>();
        Date creationDate = getCreationDate();
        if (creationDate != null) {
            attributeIDs.addElement(CREATION_DATE);
            attributeIDs.addElement(ALTERNATE_CREATION_DATE);
        }
        Date lastModifiedDate = getLastModifiedDate();
        if (lastModifiedDate != null) {
            attributeIDs.addElement(LAST_MODIFIED);
            attributeIDs.addElement(ALTERNATE_LAST_MODIFIED);
        }
        if (getName() != null) {
            attributeIDs.addElement(NAME);
        }
        String resourceType = getResourceType();
        if (resourceType != null) {
            attributeIDs.addElement(TYPE);
            attributeIDs.addElement(ALTERNATE_TYPE);
        }
        long contentLength = getContentLength();
        if (contentLength >= 0) {
            attributeIDs.addElement(CONTENT_LENGTH);
            attributeIDs.addElement(ALTERNATE_CONTENT_LENGTH);
        }
        String etag = getETag();
        if (etag != null) {
            attributeIDs.addElement(ETAG);
            attributeIDs.addElement(ALTERNATE_ETAG);
        }
        return new RecyclableNamingEnumeration<String>(attributeIDs);
    } else {
        return attributes.getIDs();
    }
}
项目:parabuild-ci    文件:ManagerServlet.java   
/**
 * List the resources of the given context.
 */
protected void printResources(final PrintWriter writer, final String prefix,
                              final javax.naming.Context namingContext,
                              final String type, final Class clazz) {

  try {
    final NamingEnumeration items = namingContext.listBindings("");
    while (items.hasMore()) {
      final Binding item = (Binding) items.next();
      if (item.getObject() instanceof javax.naming.Context) {
        printResources
                (writer, prefix + item.getName() + '/',
                        (javax.naming.Context) item.getObject(), type, clazz);
      } 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) {
    log("ManagerServlet.resources[" + type + ']', t);
    writer.println(sm.getString("managerServlet.exception",
            t.toString()));
  }

}
项目:lazycat    文件:ManagerServlet.java   
/**
 * 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()));
    }

}
项目:openjdk-jdk10    文件:ContinuationDirContext.java   
public NamingEnumeration<SearchResult> search(String name,
                            String filterExpr,
                            Object[] args,
                            SearchControls cons)
throws NamingException {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(), filterExpr, args,
                                     cons);
}
项目:apache-tomcat-7.0.73-with-comment    文件:DirContextURLConnection.java   
/**
 * Returns the name of the specified header field.
 */
@Override
public String getHeaderField(String name) {

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

    if (attributes == null)
        return (null);

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

    return (null);

}
项目:lazycat    文件:ResourceAttributes.java   
/**
 * Get all attribute IDs.
 */
@Override
public NamingEnumeration<String> getIDs() {
    if (attributes == null) {
        Vector<String> attributeIDs = new Vector<String>();
        Date creationDate = getCreationDate();
        if (creationDate != null) {
            attributeIDs.addElement(CREATION_DATE);
            attributeIDs.addElement(ALTERNATE_CREATION_DATE);
        }
        Date lastModifiedDate = getLastModifiedDate();
        if (lastModifiedDate != null) {
            attributeIDs.addElement(LAST_MODIFIED);
            attributeIDs.addElement(ALTERNATE_LAST_MODIFIED);
        }
        if (getName() != null) {
            attributeIDs.addElement(NAME);
        }
        String resourceType = getResourceType();
        if (resourceType != null) {
            attributeIDs.addElement(TYPE);
            attributeIDs.addElement(ALTERNATE_TYPE);
        }
        long contentLength = getContentLength();
        if (contentLength >= 0) {
            attributeIDs.addElement(CONTENT_LENGTH);
            attributeIDs.addElement(ALTERNATE_CONTENT_LENGTH);
        }
        String etag = getETag();
        if (etag != null) {
            attributeIDs.addElement(ETAG);
            attributeIDs.addElement(ALTERNATE_ETAG);
        }
        return new RecyclableNamingEnumeration<String>(attributeIDs);
    } else {
        return attributes.getIDs();
    }
}
项目:monarch    文件:MTableUtils.java   
/**
 * This method uses JNDI to look up an address in DNS and return its name
 * 
 * @return the host name associated with the address or null if lookup isn't possible or there is
 *         no host name for this address
 */
private static String reverseDNS(InetAddress addr) {
  byte[] addrBytes = addr.getAddress();
  // reverse the address suitable for reverse lookup

  StringBuilder sb = new StringBuilder();
  for (int index = addrBytes.length - 1; index >= 0; index--) {
    // lookup = lookup + (addrBytes[index] & 0xff) + '.';
    sb.append((addrBytes[index] & 0xff)).append('.');
  }
  sb.append("in-addr.arpa");
  String lookup = sb.toString();

  try {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
    DirContext ctx = new InitialDirContext(env);
    Attributes attrs = ctx.getAttributes(lookup, new String[] {"PTR"});
    for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();) {
      Attribute attr = (Attribute) ae.next();
      for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
        Object elem = vals.nextElement();
        if ("PTR".equals(attr.getID()) && elem != null) {
          return elem.toString();
        }
      }
    }
    ctx.close();
  } catch (Exception e) {
    // ignored
  }
  return null;
}
项目:OpenJSharp    文件:ContinuationDirContext.java   
public NamingEnumeration<SearchResult> search(Name name,
                            String filter,
                            SearchControls cons)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), filter, cons);
}
项目:jdk8u-jdk    文件:ContinuationDirContext.java   
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes);
}
项目:monarch    文件:ContextJUnitTest.java   
private void verifyListBindings(Context c, String name, Object obj1, Object obj2)
    throws NamingException {
  boolean datasourceFoundFlg = false;
  boolean o2FoundFlg = false;
  boolean datasourceO1FoundFlg = false;
  boolean datasourceNullFoundFlg = false;

  // List bindings for the specified context
  for (NamingEnumeration en = c.listBindings(name); en.hasMore();) {
    Binding b = (Binding) en.next();
    if (b.getName().equals("datasource")) {
      assertEquals(b.getObject(), dataSourceContext);
      datasourceFoundFlg = true;

      Context nextCon = (Context) b.getObject();
      for (NamingEnumeration en1 = nextCon.listBindings(""); en1.hasMore();) {
        Binding b1 = (Binding) en1.next();
        if (b1.getName().equals("sub41")) {
          assertEquals(b1.getObject(), obj1);
          datasourceO1FoundFlg = true;
        } else if (b1.getName().equals("sub43")) {
          // check for null object
          assertNull(b1.getObject());
          datasourceNullFoundFlg = true;
        }
      }
    } else if (b.getName().equals("sub42")) {
      assertEquals(b.getObject(), obj2);
      o2FoundFlg = true;
    }
  }
  if (!(datasourceFoundFlg && o2FoundFlg && datasourceO1FoundFlg && datasourceNullFoundFlg)) {
    fail();
  }
}
项目:lams    文件:DirContextURLConnection.java   
/**
 * Returns an unmodifiable Map of the header fields.
 */
public Map getHeaderFields() {

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

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

  HashMap headerFields = new HashMap(attributes.size());
  NamingEnumeration attributeEnum = attributes.getIDs();
  try {
      while (attributeEnum.hasMore()) {
          String attributeID = (String)attributeEnum.next();
          Attribute attribute = attributes.get(attributeID);
          if (attribute == null) continue;
          ArrayList attributeValueList = new ArrayList(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);

}
项目:apache-tomcat-7.0.73-with-comment    文件:ResourceAttributes.java   
/**
 * Get all attribute IDs.
 */
@Override
public NamingEnumeration<String> getIDs() {
    if (attributes == null) {
        Vector<String> attributeIDs = new Vector<String>();
        Date creationDate = getCreationDate();
        if (creationDate != null) {
            attributeIDs.addElement(CREATION_DATE);
            attributeIDs.addElement(ALTERNATE_CREATION_DATE);
        }
        Date lastModifiedDate = getLastModifiedDate();
        if (lastModifiedDate != null) {
            attributeIDs.addElement(LAST_MODIFIED);
            attributeIDs.addElement(ALTERNATE_LAST_MODIFIED);
        }
        if (getName() != null) {
            attributeIDs.addElement(NAME);
        }
        String resourceType = getResourceType();
        if (resourceType != null) {
            attributeIDs.addElement(TYPE);
            attributeIDs.addElement(ALTERNATE_TYPE);
        }
        long contentLength = getContentLength();
        if (contentLength >= 0) {
            attributeIDs.addElement(CONTENT_LENGTH);
            attributeIDs.addElement(ALTERNATE_CONTENT_LENGTH);
        }
        String etag = getETag();
        if (etag != null) {
            attributeIDs.addElement(ETAG);
            attributeIDs.addElement(ALTERNATE_ETAG);
        }
        return new RecyclableNamingEnumeration<String>(attributeIDs);
    } else {
        return attributes.getIDs();
    }
}
项目:jerrydog    文件:GlobalResourcesLifecycleListener.java   
/**
 * Create the MBeans for the interesting global JNDI resources in
 * the specified naming context.
 *
 * @param prefix Prefix for complete object name paths
 * @param context Context to be scanned
 *
 * @exception NamingException if a JNDI exception occurs
 */
protected void createMBeans(String prefix, Context context)
    throws NamingException {

    if (debug >= 1) {
        log("Creating MBeans for Global JNDI Resources in Context '" +
            prefix + "'");
    }

    NamingEnumeration bindings = context.listBindings("");
    while (bindings.hasMore()) {
        Binding binding = (Binding) bindings.next();
        String name = prefix + binding.getName();
        Object value = context.lookup(binding.getName());
        if (debug >= 2) {
            log("Checking resource " + name);
        }
        if (value instanceof Context) {
            createMBeans(name + "/", (Context) value);
        } else if (value instanceof UserDatabase) {
            try {
                createMBeans(name, (UserDatabase) value);
            } catch (Exception e) {
                log("Exception creating UserDatabase MBeans for " + name,
                    e);
            }
        }
    }

}
项目:monarch    文件:ContextJUnitTest.java   
/**
 * Removes all entries from the specified context, including subcontexts.
 * 
 * @param context context to clear
 */
private void clearContext(Context context) throws NamingException {
  for (NamingEnumeration e = context.listBindings(""); e.hasMoreElements();) {
    Binding binding = (Binding) e.nextElement();
    if (binding.getObject() instanceof Context) {
      clearContext((Context) binding.getObject());
    }
    context.unbind(binding.getName());
  }
}
项目:hadoop-oss    文件:LdapGroupsMapping.java   
List<String> doGetGroups(String user) throws NamingException {
  List<String> groups = new ArrayList<String>();

  DirContext ctx = getDirContext();

  // Search for the user. We'll only ever need to look at the first result
  NamingEnumeration<SearchResult> results = ctx.search(baseDN,
      userSearchFilter,
      new Object[]{user},
      SEARCH_CONTROLS);
  if (results.hasMoreElements()) {
    SearchResult result = results.nextElement();
    String userDn = result.getNameInNamespace();

    NamingEnumeration<SearchResult> groupResults = null;

    if (isPosix) {
      String gidNumber = null;
      String uidNumber = null;
      Attribute gidAttribute = result.getAttributes().get(posixGidAttr);
      Attribute uidAttribute = result.getAttributes().get(posixUidAttr);
      if (gidAttribute != null) {
        gidNumber = gidAttribute.get().toString();
      }
      if (uidAttribute != null) {
        uidNumber = uidAttribute.get().toString();
      }
      if (uidNumber != null && gidNumber != null) {
        groupResults =
            ctx.search(baseDN,
                "(&"+ groupSearchFilter + "(|(" + posixGidAttr + "={0})" +
                    "(" + groupMemberAttr + "={1})))",
                new Object[] { gidNumber, uidNumber },
                SEARCH_CONTROLS);
      }
    } else {
      groupResults =
          ctx.search(baseDN,
              "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
              new Object[]{userDn},
              SEARCH_CONTROLS);
    }
    if (groupResults != null) {
      while (groupResults.hasMoreElements()) {
        SearchResult groupResult = groupResults.nextElement();
        Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
        groups.add(groupName.get().toString());
      }
    }
  }

  return groups;
}
项目:directory-ldap-api    文件:AttributeUtils.java   
/**
 * Check if the attributes is a BasicAttributes, and if so, switch
 * the case sensitivity to false to avoid tricky problems in the server.
 * (Ldap attributeTypes are *always* case insensitive)
 * 
 * @param attributes The Attributes to check
 * @return The modified Attributes
 */
public static Attributes toCaseInsensitive( Attributes attributes )
{
    if ( attributes == null )
    {
        return attributes;
    }

    if ( attributes instanceof BasicAttributes )
    {
        if ( attributes.isCaseIgnored() )
        {
            // Just do nothing if the Attributes is already case insensitive
            return attributes;
        }
        else
        {
            // Ok, bad news : we have to create a new BasicAttributes
            // which will be case insensitive
            Attributes newAttrs = new BasicAttributes( true );

            NamingEnumeration<?> attrs = attributes.getAll();

            if ( attrs != null )
            {
                // Iterate through the attributes now
                while ( attrs.hasMoreElements() )
                {
                    newAttrs.put( ( javax.naming.directory.Attribute ) attrs.nextElement() );
                }
            }

            return newAttrs;
        }
    }
    else
    {
        // we can safely return the attributes if it's not a BasicAttributes
        return attributes;
    }
}
项目:jdk8u-jdk    文件:BasicAttributes.java   
public NamingEnumeration<String> getIDs() {
    return new IDEnumImpl();
}
项目:JenkinsHue    文件:LDAPManager.java   
private NamingEnumeration<SearchResult> getLDAPInformation(InitialDirContext context, String login) throws NamingException {
    SearchControls cons = new SearchControls();
    cons.setSearchScope(SearchControls.SUBTREE_SCOPE);
    cons.setDerefLinkFlag(false);
    return context.search(ldapValue.getUserSearchBase(), MessageFormat.format(ldapValue.getUserSearchFilter(), login), cons);
}
项目:Android_Code_Arbiter    文件:JndiLdapAdditionalSignature.java   
public static void moreLdapInjections(String input) throws NamingException {
    //Stub instances
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, "ldap://ldap.example.com");
    props.put(Context.REFERRAL, "ignore");

    SearchControls ctrls = new SearchControls();
    ctrls.setReturningAttributes(new String[]{"givenName", "sn"});
    ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    //Various context instance store in various type (class or interface)
    DirContext         context1 = new InitialDirContext(props);
    InitialDirContext  context2 = new InitialDirContext(props);
    InitialLdapContext context3 = new InitialLdapContext();
    LdapContext        context4 = new InitialLdapContext();

    NamingEnumeration<SearchResult> answers;
    answers = context1.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context1.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context1.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context1.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);

    answers = context2.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context2.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context2.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context2.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);

    answers = context3.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context3.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context3.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context3.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);

    answers = context4.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context4.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context4.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context4.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);


    //False positive
    answers = context1.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=bob)", ctrls);
    answers = context1.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=bob)", new Object[0], ctrls);
    answers = context1.search("dc=People,dc=example,dc=com", "(uid=bob)", ctrls);
    answers = context1.search("dc=People,dc=example,dc=com", "(uid=bob)", new Object[0], ctrls);
}
项目:apache-tomcat-7.0.73-with-comment    文件:EmptyDirContext.java   
@Override
@SuppressWarnings("unchecked")
public NamingEnumeration<SearchResult> search(String name, String filterExpr,
        Object[] filterArgs, SearchControls cons) throws NamingException {
    return emptyEnum;
}
项目:lazycat    文件:EmptyDirContext.java   
@Override
@SuppressWarnings("unchecked")
public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes,
        String[] attributesToReturn) throws NamingException {
    return emptyEnum;
}
项目:uavstack    文件:GUISSOLdapClient.java   
@SuppressWarnings("rawtypes")
private String formatEmailInfo(Attribute attr) {

    if (null == attr) {
        return "";
    }

    StringBuilder values = new StringBuilder();
    boolean isFormat = false;
    try {

        String formatS = "=";
        String attrId = attr.getID();
        String groupKey = ldapConfig.get("groupKey");
        String groupTag = ldapConfig.get("groupTag");
        for (NamingEnumeration vals = attr.getAll(); vals.hasMore();) {
            String strValue = vals.next().toString();
            if (groupKey.equals(attrId) && strValue.indexOf(groupTag) >= 0) {

                values.append(",");
                isFormat = true;

                if (strValue.indexOf(formatS) == -1) {
                    values.append(strValue);
                    continue;
                }

                int begin = strValue.indexOf(formatS) + formatS.length();
                int end = strValue.indexOf(",");
                values.append(strValue.substring(begin, end));

            }
        }
    }
    catch (Exception e) {
        loggerError("formatEmailInfo 555", "", e);
        throw new ApphubException(e);
    }
    /**
     * 去除第一个逗号
     */
    String result = "";
    if (isFormat) {
        result = values.toString().substring(1);
    }
    return result;
}