Java Code Examples for javax.naming.NamingEnumeration

The following are top voted examples for showing how to use javax.naming.NamingEnumeration. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: apache-tomcat-7.0.73-with-comment   File: TestJNDIRealm.java   View source code 7 votes vote down vote up
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;
}
 
Example 2
Project: alfresco-repository   File: LDAPUserRegistry.java   View source code 6 votes vote down vote up
/**
 * 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: lazycat   File: NamingContext.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 4
Project: openjdk-jdk10   File: Rdn.java   View source code 6 votes vote down vote up
/**
 * 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
}
 
Example 5
Project: jerrydog   File: NamingContext.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 6
Project: OpenJSharp   File: Rdn.java   View source code 6 votes vote down vote up
/**
 * 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
}
 
Example 7
Project: apache-tomcat-7.0.73-with-comment   File: NamingContext.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 8
Project: premier-wherehows   File: AuthenticationManager.java   View source code 5 votes vote down vote up
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 9
Project: wherehowsX   File: AuthenticationManager.java   View source code 5 votes vote down vote up
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 10
Project: apache-tomcat-7.0.73-with-comment   File: BaseDirContext.java   View source code 5 votes vote down vote up
/**
 * 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));
}
 
Example 11
Project: tomcat7   File: JNDIRealm.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 12
Project: tomcat7   File: SelectorContext.java   View source code 5 votes vote down vote up
/**
 * 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));
}
 
Example 13
Project: unitimes   File: LocalContext.java   View source code 5 votes vote down vote up
@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");
}
 
Example 14
Project: tomcat7   File: BaseDirContext.java   View source code 5 votes vote down vote up
/**
 * 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));
}
 
Example 15
Project: jdk8u-jdk   File: BasicAttributes.java   View source code 5 votes vote down vote up
/**
 * 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: ChronoBike   File: LdapUtil.java   View source code 5 votes vote down vote up
/**
    * @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);
   }
 
Example 17
Project: openshift-ldapsync   File: LdapServer.java   View source code 5 votes vote down vote up
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;
}
 
Example 18
Project: sdirobot   File: CManagerMap.java   View source code 5 votes vote down vote up
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 19
Project: tomcat7   File: ResourceAttributes.java   View source code 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 20
Project: parabuild-ci   File: ManagerServlet.java   View source code 5 votes vote down vote up
/**
 * 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()));
  }

}
 
Example 21
Project: lazycat   File: ManagerServlet.java   View source code 5 votes vote down vote up
/**
 * 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 22
Project: openjdk-jdk10   File: ContinuationDirContext.java   View source code 5 votes vote down vote up
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);
}
 
Example 23
Project: apache-tomcat-7.0.73-with-comment   File: DirContextURLConnection.java   View source code 5 votes vote down vote up
/**
 * 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);

}
 
Example 24
Project: lazycat   File: ResourceAttributes.java   View source code 5 votes vote down vote up
/**
 * 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();
	}
}
 
Example 25
Project: monarch   File: MTableUtils.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 26
Project: OpenJSharp   File: ContinuationDirContext.java   View source code 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(Name name,
                            String filter,
                            SearchControls cons)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), filter, cons);
}
 
Example 27
Project: jdk8u-jdk   File: ContinuationDirContext.java   View source code 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes);
}
 
Example 28
Project: monarch   File: ContextJUnitTest.java   View source code 5 votes vote down vote up
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();
  }
}
 
Example 29
Project: lams   File: DirContextURLConnection.java   View source code 5 votes vote down vote up
/**
 * 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);

}
 
Example 30
Project: apache-tomcat-7.0.73-with-comment   File: ResourceAttributes.java   View source code 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 31
Project: jerrydog   File: GlobalResourcesLifecycleListener.java   View source code 5 votes vote down vote up
/**
 * 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);
            }
        }
    }

}
 
Example 32
Project: monarch   File: ContextJUnitTest.java   View source code 5 votes vote down vote up
/**
 * 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());
  }
}
 
Example 33
Project: hadoop-oss   File: LdapGroupsMapping.java   View source code 4 votes vote down vote up
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;
}
 
Example 34
Project: directory-ldap-api   File: AttributeUtils.java   View source code 4 votes vote down vote up
/**
 * 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;
    }
}
 
Example 35
Project: jdk8u-jdk   File: BasicAttributes.java   View source code 4 votes vote down vote up
public NamingEnumeration<String> getIDs() {
    return new IDEnumImpl();
}
 
Example 36
Project: JenkinsHue   File: LDAPManager.java   View source code 4 votes vote down vote up
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);
}
 
Example 37
Project: Android_Code_Arbiter   File: JndiLdapAdditionalSignature.java   View source code 4 votes vote down vote up
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);
}
 
Example 38
Project: apache-tomcat-7.0.73-with-comment   File: EmptyDirContext.java   View source code 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public NamingEnumeration<SearchResult> search(String name, String filterExpr,
        Object[] filterArgs, SearchControls cons) throws NamingException {
    return emptyEnum;
}
 
Example 39
Project: lazycat   File: EmptyDirContext.java   View source code 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes,
		String[] attributesToReturn) throws NamingException {
	return emptyEnum;
}
 
Example 40
Project: uavstack   File: GUISSOLdapClient.java   View source code 4 votes vote down vote up
@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;
}