javax.naming.directory.DirContext Java Examples

The following examples show how to use javax.naming.directory.DirContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveMultiAttribute() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute abc = new BasicAttribute("abc");
	abc.add("123");
	abc.add("456");
	fixtureAttrs.put(abc);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();

	tested.setUpdateMode(true);
	tested.setAttributeValues("abc", new String[] {});

	ModificationItem[] mods = tested.getModificationItems();
	assertThat(mods.length).isEqualTo(1);
	assertThat(mods[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
	Attribute attr = mods[0].getAttribute();
	assertThat((String) attr.getID()).isEqualTo("abc");
	assertThat(attr.size()).isEqualTo(0);
}
 
Example #2
Source File: EtcdClientAutoConfiguration.java    From spring-boot-etcd with MIT License 6 votes vote down vote up
private List<String> discoverNodes(String serviceName) throws NamingException {
	List<String> locations = new ArrayList<>();

	Hashtable<String, String> env = new Hashtable<String, String>();
	env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
	env.put("java.naming.provider.url", "dns:");

	DirContext context = new InitialDirContext(env);
	Attributes attributes = context.getAttributes(serviceName, new String[] { "SRV" });
	for (NamingEnumeration<? extends Attribute> records = attributes.getAll(); records.hasMore();) {
		Attribute record = records.next();
		NamingEnumeration<String> values = (NamingEnumeration<String>) record.getAll();
		while (values.hasMore()) {
			String dns = values.next();
			String[] split = dns.split(" ");
			String host = split[3];
			if (host.endsWith(".")) {
				host = host.substring(0, host.length() - 1);
			}

			String location = "http://" + host + ":2379";
			locations.add(location);
		}
	}
	return locations;
}
 
Example #3
Source File: LdapSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
private String performOperationRead(String entryName, IPipeLineSession session, Map paramValueMap) throws SenderException, ParameterException {
	DirContext dirContext = null;
	try{
		dirContext = getDirContext(paramValueMap);
		return attributesToXml(dirContext.getAttributes(entryName, getAttributesReturnedParameter())).toXML();
	} catch(NamingException e) {
		// https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
		//   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
		// Sun:
		//   [LDAP: error code 32 - No Such Object...
		if(e.getMessage().startsWith("[LDAP: error code 32 - ") ) {
			if (log.isDebugEnabled()) log.debug("Operation [" + getOperation()+ "] found nothing - no such entryName: " + entryName);
			return DEFAULT_RESULT_READ;	
		} else {
			storeLdapException(e, session);
			throw new SenderException("Exception in operation [" + getOperation()+ "] entryName=["+entryName+"]", e);	
		}
	} finally {
		closeDirContext(dirContext);
	}
}
 
Example #4
Source File: LDAPUtil.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * @param ctx
 * @param ldapSearchBase
 * @param sid
 * @return
 * @throws NamingException
 */
public static String findGroupBySID(DirContext ctx, String ldapSearchBase, String sid,
                                    String userAttribute) throws NamingException {

    String searchFilter = "(&(objectClass=group)(objectSid=" + sid + "))";

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter,
            searchControls);

    if (results.hasMoreElements()) {
        SearchResult searchResult = (SearchResult) results.nextElement();

        // make sure there is not another item available, there should be only 1 match
        if (results.hasMoreElements()) {
            log.error("Matched multiple groups for the group with SID: " + sid);
            return null;
        } else {
            return (String) searchResult.getAttributes().get(userAttribute).get();
        }
    }
    return null;
}
 
Example #5
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public void search(final Name base, final String filter, final SearchControls controls,
		NameClassPairCallbackHandler handler) {

	// Create a SearchExecutor to perform the search.
	SearchExecutor se = new SearchExecutor() {
		public NamingEnumeration executeSearch(DirContext ctx) throws javax.naming.NamingException {
			return ctx.search(base, filter, controls);
		}
	};
	if (handler instanceof ContextMapperCallbackHandler) {
		assureReturnObjFlagSet(controls);
	}
	search(se, handler);
}
 
Example #6
Source File: LdapSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
private String performOperationChallenge(String principal, IPipeLineSession session, Map paramValueMap) throws SenderException, ParameterException {
	DirContext dirContext = null;
	try{
		// Use loopkupDirContext instead of getDirContext to prevent
		// NamingException (with error code 49) being converted to
		// SenderException.
		dirContext = loopkupDirContext(paramValueMap);
		attributesToXml(dirContext.getAttributes(principal, getAttributesReturnedParameter())).toXML();
		return DEFAULT_RESULT_CHALLENGE_OK;
	} catch(NamingException e) {
		// https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
		//   49 LDAP_INVALID_CREDENTIALS Indicates that during a bind operation one of the following occurred: The client passed either an incorrect DN or password, or the password is incorrect because it has expired, intruder detection has locked the account, or another similar reason. This is equivalent to AD error code 52e.
		if(e.getMessage().startsWith("[LDAP: error code 49 - ") ) {
			if (log.isDebugEnabled()) log.debug("Operation [" + getOperation()+ "] invalid credentials for: " + principal);
			return DEFAULT_RESULT_CHALLENGE_NOK;	
		} else {
			storeLdapException(e, session);
			throw new SenderException("Exception in operation [" + getOperation()+ "] principal=["+principal+"]", e);	
		}
	} finally {
		closeDirContext(dirContext);
	}
}
 
Example #7
Source File: ldapURLContextFactory.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
static ResolveResult getUsingURLIgnoreRootDN(String url, Hashtable<?,?> env)
        throws NamingException {
    LdapURL ldapUrl = new LdapURL(url);
    DirContext ctx = new LdapCtx("", ldapUrl.getHost(), ldapUrl.getPort(),
        env, ldapUrl.useSsl());
    String dn = (ldapUrl.getDN() != null ? ldapUrl.getDN() : "");

    // Represent DN as empty or single-component composite name.
    CompositeName remaining = new CompositeName();
    if (!"".equals(dn)) {
        // if nonempty, add component
        remaining.add(dn);
    }

    return new ResolveResult(ctx, remaining);
}
 
Example #8
Source File: ldapURLContextFactory.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
static ResolveResult getUsingURLIgnoreRootDN(String url, Hashtable<?,?> env)
        throws NamingException {
    LdapURL ldapUrl = new LdapURL(url);
    DirContext ctx = new LdapCtx("", ldapUrl.getHost(), ldapUrl.getPort(),
        env, ldapUrl.useSsl());
    String dn = (ldapUrl.getDN() != null ? ldapUrl.getDN() : "");

    // Represent DN as empty or single-component composite name.
    CompositeName remaining = new CompositeName();
    if (!"".equals(dn)) {
        // if nonempty, add component
        remaining.add(dn);
    }

    return new ResolveResult(ctx, remaining);
}
 
Example #9
Source File: JNDIRealm.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the credentials presented by the user match those
 * retrieved from the directory.
 *
 * @param context The directory context
 * @param info The User to be authenticated
 * @param credentials Authentication credentials
 *
 * @exception NamingException if a directory server error occurs
 */
protected boolean compareCredentials(DirContext context,
                                     User info,
                                     String credentials)
    throws NamingException {

    // Validate the credentials specified by the user
    if (containerLog.isTraceEnabled())
        containerLog.trace("  validating credentials");

    if (info == null || credentials == null)
        return (false);

    String password = info.getPassword();

    return compareCredentials(credentials, password);
}
 
Example #10
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public void search(final Name base, final String filter, final SearchControls controls,
		NameClassPairCallbackHandler handler, DirContextProcessor processor) {

	// Create a SearchExecutor to perform the search.
	SearchExecutor se = new SearchExecutor() {
		public NamingEnumeration executeSearch(DirContext ctx) throws javax.naming.NamingException {
			return ctx.search(base, filter, controls);
		}
	};
	if (handler instanceof ContextMapperCallbackHandler) {
		assureReturnObjFlagSet(controls);
	}
	search(se, handler, processor);
}
 
Example #11
Source File: LdapDao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public List<T> findAll(final DirContext ctx, final String organizationalUnit) throws NamingException
{
  final LinkedList<T> list = new LinkedList<T>();
  NamingEnumeration< ? > results = null;
  final SearchControls controls = new SearchControls();
  controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  final String searchBase = getSearchBase(organizationalUnit);
  results = ctx.search(searchBase, "(objectclass=" + getObjectClass() + ")", controls);
  while (results.hasMore()) {
    final SearchResult searchResult = (SearchResult) results.next();
    final String dn = searchResult.getName();
    final Attributes attributes = searchResult.getAttributes();
    list.add(mapToObject(dn, searchBase, attributes));
  }
  return list;
}
 
Example #12
Source File: DirectoryManager.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
  * Creates a context in which to continue a <tt>DirContext</tt> operation.
  * Operates just like <tt>NamingManager.getContinuationContext()</tt>,
  * only the continuation context returned is a <tt>DirContext</tt>.
  *
  * @param cpe
  *         The non-null exception that triggered this continuation.
  * @return A non-null <tt>DirContext</tt> object for continuing the operation.
  * @exception NamingException If a naming exception occurred.
  *
  * @see NamingManager#getContinuationContext(CannotProceedException)
  */
@SuppressWarnings("unchecked")
public static DirContext getContinuationDirContext(
        CannotProceedException cpe) throws NamingException {

    Hashtable<Object,Object> env = (Hashtable<Object,Object>)cpe.getEnvironment();
    if (env == null) {
        env = new Hashtable<>(7);
    } else {
        // Make a (shallow) copy of the environment.
        env = (Hashtable<Object,Object>) env.clone();
    }
    env.put(CPE, cpe);

    return (new ContinuationDirContext(cpe, env));
}
 
Example #13
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testChangeMultiAttribute_RemoveValue() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("qwe");
	fixtureAttrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();
	assertThat(tested.isUpdateMode()).isTrue();
	tested.setAttributeValues("abc", new String[] { "123" });

	ModificationItem[] modificationItems = tested.getModificationItems();
	assertThat(modificationItems.length).isEqualTo(1);
    assertThat(modificationItems[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
	assertThat(modificationItems[0].getAttribute().get()).isEqualTo("qwe");
}
 
Example #14
Source File: SecureWebdavServlet.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * MOVE Method.
 */
protected void doMove(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    if (readOnly) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    // Check if operation allowed by OLAT VFS security callback
    DirContext resources = getResources(req);
    VFSDirContext vfsContext = (VFSDirContext) resources;
    String path = getRelativePath(req);
    if (!vfsContext.canRename(path)) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }

    if (copyResource(req, resp)) {
        deleteResource(path, req, resp);
    }
}
 
Example #15
Source File: LDAPAuthority.java    From athenz with Apache License 2.0 5 votes vote down vote up
DirContext getDirContext(String finalDN, String password) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerURL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, finalDN);
    env.put(Context.SECURITY_CREDENTIALS, password);
    return new InitialDirContext(env);
}
 
Example #16
Source File: MailValidation.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * verify if there is a mail server registered to the domain name. and return the email servers count
 */
public static int mailServersCount( String hostName ) throws NamingException {
  Hashtable<String, String> env = new Hashtable<String, String>();
  env.put( "java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory" );
  DirContext ictx = new InitialDirContext( env );
  Attributes attrs = ictx.getAttributes( hostName, new String[] { "MX" } );
  Attribute attr = attrs.get( "MX" );
  if ( attr == null ) {
    return ( 0 );
  }
  return ( attr.size() );
}
 
Example #17
Source File: RetryingDirContext.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void rebind(final Name name, final Object obj, final Attributes attrs)
        throws NamingException {
    new LoggingRetryHandler(DEFAULT_EXCEPTION_CLASSES, this, getSchedule(), getMaxRetries()) {

        @Override
        public Object operation() throws NamingException {
            ((DirContext) getDelegate()).rebind(name, obj, attrs);
            return null;
        }
    }.perform();
}
 
Example #18
Source File: MailValidation.java    From hop with Apache License 2.0 5 votes vote down vote up
/**
 * verify if there is a mail server registered to the domain name. and return the email servers count
 */
public static int mailServersCount( String hostName ) throws NamingException {
  Hashtable<String, String> env = new Hashtable<String, String>();
  env.put( "java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory" );
  DirContext ictx = new InitialDirContext( env );
  Attributes attrs = ictx.getAttributes( hostName, new String[] { "MX" } );
  Attribute attr = attrs.get( "MX" );
  if ( attr == null ) {
    return ( 0 );
  }
  return ( attr.size() );
}
 
Example #19
Source File: LDAPOperationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Modifies the given {@link Attribute} instances using the given DN. This method performs a REPLACE_ATTRIBUTE
 * operation.
 * </p>
 *
 * @param dn
 * @param attributes
 */
public void modifyAttributes(String dn,  NamingEnumeration<Attribute> attributes) {
    try {
        List<ModificationItem> modItems = new ArrayList<ModificationItem>();
        while (attributes.hasMore()) {
            ModificationItem modItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attributes.next());
            modItems.add(modItem);
        }

        modifyAttributes(dn, modItems.toArray(new ModificationItem[] {}), null);
    } catch (NamingException ne) {
        throw new ModelException("Could not modify attributes on entry from DN [" + dn + "]", ne);
    }

}
 
Example #20
Source File: LdapDao.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Calls {@link #create(Object)} if the object isn't part of the given set, otherwise {@link #update(Object)}.
 * @param setOfAllLdapObjects List generated before via {@link #getSetOfAllObjects()}.
 * @param obj
 * @throws NamingException
 */
public void createOrUpdate(final DirContext ctx, final SetOfAllLdapObjects setOfAllLdapObjects, final String ouBase, final T obj,
    final Object... args) throws NamingException
    {
  if (setOfAllLdapObjects.contains(obj, buildDn(ouBase, obj)) == true) {
    update(ctx, ouBase, obj, args);
  } else {
    create(ctx, ouBase, obj, args);
  }
    }
 
Example #21
Source File: LdapTestUtils.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Load an Ldif file into an LDAP server.
 *
 * @param contextSource ContextSource to use for getting a DirContext to
 *                      interact with the LDAP server.
 * @param ldifFile      a Resource representing a valid LDIF file.
 * @throws IOException if the Resource cannot be read.
 */
public static void loadLdif(ContextSource contextSource, Resource ldifFile) throws IOException {
    DirContext context = contextSource.getReadWriteContext();
    try {
        loadLdif(context, ldifFile);
    } finally {
        try {
            context.close();
        } catch (Exception e) {
            // This is not the exception we are interested in.
        }
    }
}
 
Example #22
Source File: BaseDirContext.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves selected attributes associated with a named object.
 * 
 * @return the requested attributes; never null
 * @param name the name of the object from which to retrieve attributes
 * @param attrIds the identifiers of the attributes to retrieve. null 
 * indicates that all attributes should be retrieved; an empty array 
 * indicates that none should be retrieved
 * @exception NamingException if a naming exception is encountered
 */
@Override
public final Attributes getAttributes(String name, String[] attrIds)
    throws NamingException {
    
    // First check for aliases
    if (!aliases.isEmpty()) {
        AliasResult result = findAlias(name);
        if (result.dirContext != null) {
            return result.dirContext.getAttributes(
                    result.aliasName, attrIds);
        }
    }
    
    // Next do a standard lookup
    Attributes attrs = doGetAttributes(name, attrIds);

    if (attrs != null)
        return attrs;

    String resourceName = "/META-INF/resources" + name;
    // Check the alternate locations
    for (DirContext altDirContext : altDirContexts) {
        if (altDirContext instanceof BaseDirContext)
            attrs = ((BaseDirContext) altDirContext).doGetAttributes(resourceName, attrIds);
        else {
            try {
                attrs = altDirContext.getAttributes(name, attrIds);
            } catch (NamingException ne) {
                // Ignore
            }
        }
        if (attrs != null)
            return attrs;
    }
    
    // Really not found
    throw new NameNotFoundException(
            sm.getString("resources.notFound", name));
}
 
Example #23
Source File: RetryingDirContext.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public DirContext getSchema(final String name) throws NamingException {
    final Context context = getDelegate();
    return new RetryingDirContext(getSchedule(), getMaxRetries()) {

        @Override
        public DirContext newDelegate() throws NamingException {
            return ((DirContext) context).getSchema(name);
        }
    };
}
 
Example #24
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public void modifyAttributes(final String dn, final ModificationItem[] mods) {
	executeReadWrite(new ContextExecutor() {
		public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
			ctx.modifyAttributes(dn, mods);
			return null;
		}
	});
}
 
Example #25
Source File: ContinuationDirContext.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
protected DirContextNamePair getTargetContext(Name name)
        throws NamingException {

    if (cpe.getResolvedObj() == null)
        throw (NamingException)cpe.fillInStackTrace();

    Context ctx = NamingManager.getContext(cpe.getResolvedObj(),
                                           cpe.getAltName(),
                                           cpe.getAltNameCtx(),
                                           env);
    if (ctx == null)
        throw (NamingException)cpe.fillInStackTrace();

    if (ctx instanceof DirContext)
        return new DirContextNamePair((DirContext)ctx, name);

    if (ctx instanceof Resolver) {
        Resolver res = (Resolver)ctx;
        ResolveResult rr = res.resolveToClass(name, DirContext.class);

        // Reached a DirContext; return result.
        DirContext dctx = (DirContext)rr.getResolvedObj();
        return (new DirContextNamePair(dctx, rr.getRemainingName()));
    }

    // Resolve all the way using lookup().  This may allow the operation
    // to succeed if it doesn't require the penultimate context.
    Object ultimate = ctx.lookup(name);
    if (ultimate instanceof DirContext) {
        return (new DirContextNamePair((DirContext)ultimate,
                                      new CompositeName()));
    }

    throw (NamingException)cpe.fillInStackTrace();
}
 
Example #26
Source File: SingleContextSource.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
private DirContext getNonClosingDirContextProxy(DirContext context) {
    return (DirContext) Proxy.newProxyInstance(DirContextProxy.class
            .getClassLoader(), new Class<?>[]{
            LdapUtils.getActualTargetClass(context),
            DirContextProxy.class},
            new SingleContextSource.NonClosingDirContextInvocationHandler(
                    context));

}
 
Example #27
Source File: LdapSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
/** 
 * Return xml element containing all of the subcontexts of the parent context with their attributes. 
 * @return tree xml.
 */ 
private XmlBuilder getTree(DirContext parentContext, String context, IPipeLineSession session, Map paramValueMap)
{
	XmlBuilder contextElem = new XmlBuilder("context");
	contextElem.addAttribute("name", context);
	
	String[] subCtxList = getSubContextList(parentContext, context, session);
	try	{
		if (subCtxList.length == 0) {
			XmlBuilder attrs = attributesToXml(parentContext.getAttributes(context, getAttributesReturnedParameter()));
			contextElem.addSubElement(attrs);
		}
		else {
			for (int i = 0; i < subCtxList.length; i++)
			{
				contextElem.addSubElement( getTree((DirContext)parentContext.lookup(context), subCtxList[i], session, paramValueMap) );
			}
			contextElem.addSubElement( attributesToXml(parentContext.getAttributes(context, getAttributesReturnedParameter())));
		}

	} catch (NamingException e) {
		storeLdapException(e, session);
		log.error("Exception in operation [" + getOperation()+ "]: ", e);
	}

	return contextElem;
}
 
Example #28
Source File: JNDIProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
@LdapOperation
@ModifyOperation
public final void writeStringAttribute( final String entryDN, final String attributeName, final Set<String> values, final boolean overwrite )
        throws ChaiUnavailableException, ChaiOperationException
{
    activityPreCheck();
    getInputValidator().writeStringAttribute( entryDN, attributeName, values, overwrite );


    // Create the ModificationItem
    final ModificationItem[] modificationItem = new ModificationItem[values.size()];

    int loopCounter = 0;
    for ( final String value : values )
    {
        // Create a BasicAttribute for the object.
        final BasicAttribute attributeToReplace = new BasicAttribute( attributeName, value );

        // Determine the modification type, if replace, only replace on the first attribute, the rest just get added.
        final int modType = ( loopCounter == 0 && overwrite ) ? DirContext.REPLACE_ATTRIBUTE : DirContext.ADD_ATTRIBUTE;

        // Populate the ModificationItem object with the flag & the attribute to replace.
        modificationItem[loopCounter] = new ModificationItem( modType, attributeToReplace );
        loopCounter++;
    }

    // get ldap connection
    final LdapContext ldapConnection = getLdapConnection();

    // Modify the Attributes.
    try
    {
        ldapConnection.modifyAttributes( addJndiEscape( entryDN ), modificationItem );
    }
    catch ( NamingException e )
    {
        LOGGER.trace( "error during write of attribute '" + attributeName + "', error: " + e.getMessage() );
        convertNamingException( e );
    }
}
 
Example #29
Source File: ContinuationDirContext.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
protected DirContextNamePair getTargetContext(Name name)
        throws NamingException {

    if (cpe.getResolvedObj() == null)
        throw (NamingException)cpe.fillInStackTrace();

    Context ctx = NamingManager.getContext(cpe.getResolvedObj(),
                                           cpe.getAltName(),
                                           cpe.getAltNameCtx(),
                                           env);
    if (ctx == null)
        throw (NamingException)cpe.fillInStackTrace();

    if (ctx instanceof DirContext)
        return new DirContextNamePair((DirContext)ctx, name);

    if (ctx instanceof Resolver) {
        Resolver res = (Resolver)ctx;
        ResolveResult rr = res.resolveToClass(name, DirContext.class);

        // Reached a DirContext; return result.
        DirContext dctx = (DirContext)rr.getResolvedObj();
        return (new DirContextNamePair(dctx, rr.getRemainingName()));
    }

    // Resolve all the way using lookup().  This may allow the operation
    // to succeed if it doesn't require the penultimate context.
    Object ultimate = ctx.lookup(name);
    if (ultimate instanceof DirContext) {
        return (new DirContextNamePair((DirContext)ultimate,
                                      new CompositeName()));
    }

    throw (NamingException)cpe.fillInStackTrace();
}
 
Example #30
Source File: DNS.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the hostname associated with the specified IP address by the
 * provided nameserver.
 *
 * Loopback addresses 
 * @param hostIp The address to reverse lookup
 * @param ns The host name of a reachable DNS server
 * @return The host name associated with the provided IP
 * @throws NamingException If a NamingException is encountered
 */
public static String reverseDns(InetAddress hostIp, String ns)
  throws NamingException {
  //
  // Builds the reverse IP lookup form
  // This is formed by reversing the IP numbers and appending in-addr.arpa
  //
  String[] parts = hostIp.getHostAddress().split("\\.");
  String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "."
    + parts[0] + ".in-addr.arpa";

  DirContext ictx = new InitialDirContext();
  Attributes attribute;
  try {
    attribute = ictx.getAttributes("dns://"               // Use "dns:///" if the default
                       + ((ns == null) ? "" : ns) +
                       // nameserver is to be used
                       "/" + reverseIP, new String[] { "PTR" });
  } finally {
    ictx.close();
  }

  String hostname = attribute.get("PTR").get().toString();
  int hostnameLength = hostname.length();
  if (hostname.charAt(hostnameLength - 1) == '.') {
    hostname = hostname.substring(0, hostnameLength - 1);
  }
  return hostname;
}