List of usage examples for javax.naming.directory InitialDirContext InitialDirContext
public InitialDirContext(Hashtable<?, ?> environment) throws NamingException
From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java
/** * Updates the profile of the user on the external provider. * * @param user the profile to be updated (it is assumed username is never changed) * @throws PortalServiceException for any errors encountered *///from w w w. j a va 2s. co m public void updateUser(CMSUser user) throws PortalServiceException { DirContext ctx = null; try { ctx = new InitialDirContext(env); List<ModificationItem> mods = new ArrayList<ModificationItem>(); List<Attribute> profile = mapAttributes(user); for (Attribute attribute : profile) { mods.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute)); } ctx.modifyAttributes(MessageFormat.format(userDNPattern, user.getUsername()), mods.toArray(new ModificationItem[0])); synchRoles(user.getUsername(), user.getRole()); } catch (NamingException e) { throw new PortalServiceConfigurationException("Unable to save user.", e); } finally { closeContext(ctx); } }
From source file:org.kitodo.services.data.LdapServerService.java
/** * create new user in LDAP-directory.// w w w .j a v a 2s . co m * * @param user * User object * @param password * String */ public void createNewUser(User user, String password) throws NamingException, NoSuchAlgorithmException, IOException { if (!user.getLdapGroup().getLdapServer().isReadOnly()) { Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings( user.getLdapGroup().getLdapServer()); LdapUser ldapUser = new LdapUser(); ldapUser.configure(user, password, getNextUidNumber(user.getLdapGroup().getLdapServer())); DirContext ctx = new InitialDirContext(ldapEnvironment); ctx.bind(buildUserDN(user), ldapUser); ctx.close(); setNextUidNumber(user.getLdapGroup().getLdapServer()); Helper.setMessage( Helper.getTranslation("ldapWritten") + " " + serviceManager.getUserService().getFullName(user)); /* * check if HomeDir exists, else create it */ logger.debug("HomeVerzeichnis pruefen"); URI homePath = getUserHomeDirectory(user); if (!new File(homePath).exists()) { logger.debug("HomeVerzeichnis existiert noch nicht"); serviceManager.getFileService().createDirectoryForUser(homePath, user.getLogin()); logger.debug("HomeVerzeichnis angelegt"); } else { logger.debug("HomeVerzeichnis existiert schon"); } } else { Helper.setMessage("ldapIsReadOnly"); } }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Test to make sure anonymous binds are disabled when going through * the wire protocol./* ww w . j a v a2 s . com*/ * * @throws Exception if anything goes wrong */ @Test public void testDisableAnonymousBinds() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(false); // Use the SUN JNDI provider to hit server port and bind as anonymous final Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/ou=system"); env.put(Context.SECURITY_AUTHENTICATION, "none"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); try { new InitialDirContext(env); fail(); } catch (Exception e) { // We should get here } try { // Use the netscape API as JNDI cannot be used to do a search without // first binding. LDAPUrl url = new LDAPUrl(Network.LOOPBACK_HOSTNAME, getLdapServer().getPort(), "ou=system", new String[] { "vendorName" }, 0, "(ObjectClass=*)"); LDAPConnection.search(url); fail(); } catch (LDAPException e) { // Expected result } }
From source file:org.talend.dataquality.email.checkerImpl.CallbackMailServerCheckerImpl.java
public void init() { // Prepare naming directory context. Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); //$NON-NLS-1$ //$NON-NLS-2$ // if the user add the paramter for: java.naming.provider.url, if has then add it to env // Added TDQ-6918 Allow user add parameter: java.naming.provider.url String dnsUrl = dns;/*from ww w . j a v a 2 s. com*/ if (dnsUrl != null) { env.put(Context.PROVIDER_URL, dnsUrl); } // ~ try { ictx = new InitialDirContext(env); } catch (NamingException e) { LOG.error("Invalid DNS: " + e); //$NON-NLS-1$ } }
From source file:CreateJavaSchema.java
/** * Signs on to directory server using parameters supplied to program. * @return The initial context to the server. *//* www.j a v a 2s. co m*/ private DirContext signOn() throws NamingException { if (dn != null && auth == null) { auth = "simple"; // use simple for Netscape } Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.REFERRAL, "follow"); if (auth != null) { env.put(Context.SECURITY_AUTHENTICATION, auth); env.put(Context.SECURITY_PRINCIPAL, dn); env.put(Context.SECURITY_CREDENTIALS, passwd); } // Workaround for Netscape schema bugs if (netscapebug) { env.put("com.sun.naming.netscape.schemaBugs", "true"); } // LDAP protocol tracing if (traceLdap) { env.put("com.sun.jndi.ldap.trace.ber", System.err); } return new InitialDirContext(env); }
From source file:ldap.LdapClient.java
public LdapClient() throws Exception { try {//from w w w . j a v a2s.co m resources = ResourceBundle.getBundle("ldap/LdapClient", SessionManager.getSession().getLocale()); } catch (MissingResourceException e) { throw new ServletException("resource bundle not found", e); } frame = new SFrame("LDAP Client"); SContainer contentPane = frame.getContentPane(); tabbedPane = new STabbedPane(); contentPane.setLayout(null); settingsForm = new SForm(new SGridLayout(2)); tabbedPane.add(settingsForm, resources.getString("provider")); urlTextField = new STextField(); urlTextField.setColumns(columns); urlTextField.setText((String) SessionManager.getSession().getProperty("java.naming.provider.url")); settingsForm.add(new SLabel(resources.getString("provider.url"))); settingsForm.add(urlTextField); basednTextField = new STextField(); basednTextField.setColumns(columns); basednTextField.setText((String) SessionManager.getSession().getProperty("java.naming.provider.basedn")); settingsForm.add(new SLabel(resources.getString("provider.basedn"))); settingsForm.add(basednTextField); binddnTextField = new STextField(); binddnTextField.setColumns(columns); binddnTextField.setText((String) SessionManager.getSession().getProperty("java.naming.security.principal")); settingsForm.add(new SLabel(resources.getString("provider.binddn"))); settingsForm.add(binddnTextField); passwordTextField = new SPasswordField(); passwordTextField.setColumns(columns); passwordTextField .setText((String) SessionManager.getSession().getProperty("java.naming.security.credentials")); settingsForm.add(new SLabel(resources.getString("provider.password"))); settingsForm.add(passwordTextField); connectButton = new SButton(resources.getString("provider.connect")); disconnectButton = new SButton(resources.getString("provider.disconnect")); disconnectButton.setVisible(false); settingsForm.add(connectButton); settingsForm.add(disconnectButton); mainPanel = new SPanel(); try { mainPanel.setLayout(new STemplateLayout(getClass().getResource("ldapclientlayout.html"))); } catch (Exception e) { logger.warn("no template", e); mainPanel.setLayout(new SFlowLayout()); } tabbedPane.add(mainPanel, resources.getString("browser")); createTreeModel(null); tree = new STree(treeModel); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addTreeSelectionListener(this); SessionManager.getSession().setProperty("tree", tree); editPanel = new EditObjectPanel(); mainPanel.add(tree, "tree"); mainPanel.add(editPanel, "editor"); addPanel = new AddObjectPanel(); tabbedPane.add(addPanel, resources.getString("add")); contentPane.add(tabbedPane); connectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Session session = SessionManager.getSession(); String url = urlTextField.getText(); if (url != null && url.length() > 0) session.setProperty("java.naming.provider.url", url); String basedn = basednTextField.getText(); if (basedn != null && basedn.length() > 0) session.setProperty("java.naming.provider.basedn", basedn); String binddn = binddnTextField.getText(); if (binddn != null && binddn.length() > 0) session.setProperty("java.naming.security.principal", binddn); String password = passwordTextField.getText(); if (password != null && password.length() > 0) session.setProperty("java.naming.security.credentials", password); try { context = new InitialDirContext(new Hashtable(session.getProperties())); createTreeModel(context); tree.setModel(treeModel); tabbedPane.setSelectedIndex(1); urlTextField.setVisible(true); basednTextField.setVisible(true); binddnTextField.setVisible(true); passwordTextField.setVisible(true); connectButton.setVisible(true); disconnectButton.setVisible(false); passwordTextField.setText(null); } catch (NamingException e) { passwordTextField.setText(null); logger.warn("no initial context", e); } } }); disconnectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { createTreeModel(null); tree.setModel(treeModel); urlTextField.setVisible(false); basednTextField.setVisible(false); binddnTextField.setVisible(false); passwordTextField.setVisible(false); connectButton.setVisible(false); disconnectButton.setVisible(true); passwordTextField.setText(null); } }); frame.show(); }
From source file:com.aurel.track.util.LdapUtil.java
public static boolean authenticate(TSiteBean siteBean, String loginName, String ppassword) throws NamingException { boolean userIsOK = false; ArrayList<String> trace = new ArrayList<String>(); trace.add("Ldap trying to authenticate user with loginname >" + loginName + "<"); if (siteBean.getLdapServerURL().startsWith("ldaps:")) { System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE); }/*from w ww .ja va 2s.c o m*/ // get the CN String keyDn = getCn(siteBean, loginName); try { if (keyDn != null) { trace.add("Using keyDn >" + keyDn + "<"); // Set up the environment for creating the initial context Hashtable<String, String> env = new Hashtable<String, String>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, siteBean.getLdapServerURL()); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, keyDn); env.put(Context.SECURITY_CREDENTIALS, ppassword); // Create initial context DirContext itest = new InitialDirContext(env); itest.close(); // user was validated userIsOK = true; } return userIsOK; } catch (NamingException e) { for (String msg : trace) { LOGGER.warn(msg); } throw e; } }
From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java
public DirContext getContext() throws UserStoreException { DirContext context = null;//from ww w . java2s. c o m //if dcMap is not populated, it is not DNS case if (dcMap == null) { try { context = new InitialDirContext(environment); } catch (NamingException e) { log.error("Error obtaining connection. " + e.getMessage(), e); log.error("Trying again to get connection."); try { context = new InitialDirContext(environment); } catch (Exception e1) { log.error("Error obtaining connection for the second time" + e.getMessage(), e); throw new UserStoreException("Error obtaining connection. " + e.getMessage(), e); } } } else if (dcMap != null && dcMap.size() != 0) { try { //first try the first entry in dcMap, if it fails, try iteratively Integer firstKey = dcMap.firstKey(); SRVRecord firstRecord = dcMap.get(firstKey); //compose the connection URL environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(firstRecord)); context = new InitialDirContext(environment); } catch (NamingException e) { log.error("Error obtaining connection to first Domain Controller." + e.getMessage(), e); log.info("Trying to connect with other Domain Controllers"); for (Integer integer : dcMap.keySet()) { try { SRVRecord srv = dcMap.get(integer); environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(srv)); context = new InitialDirContext(environment); break; } catch (NamingException e1) { if (integer == (dcMap.lastKey())) { log.error("Error obtaining connection for all " + integer + " Domain Controllers." + e.getMessage(), e); throw new UserStoreException("Error obtaining connection. " + e.getMessage(), e); } } } } } return (context); }
From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java
protected boolean userExists(String id) { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_CREDENTIALS, "secret"); try {// w ww.jav a 2 s. com DirContext ctx = new InitialDirContext(env); /* * Setup subtree scope to tell LDAP to recursively descend directory structure during searches. */ SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); /* * Setup the directory entry attributes we want to search for. In this case it is the user's ID. */ String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(id) + "))"; /* Execute the search, starting at the directory level of Users */ NamingEnumeration hits = ctx.search(getBasePath(), filter, searchControls); /* All we need to know is if there were any hits at all. */ if (hits.hasMore()) { hits.close(); ctx.close(); return true; } else { hits.close(); ctx.close(); return false; } } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:org.kitodo.production.services.data.LdapServerService.java
/** * create new user in LDAP-directory.// w w w .ja va2s. c o m * * @param user * User object * @param password * String */ public void createNewUser(User user, String password) throws NamingException, NoSuchAlgorithmException, IOException { if (!user.getLdapGroup().getLdapServer().isReadOnly()) { Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings( user.getLdapGroup().getLdapServer()); LdapUser ldapUser = new LdapUser(); ldapUser.configure(user, password, getNextUidNumber(user.getLdapGroup().getLdapServer())); DirContext ctx = new InitialDirContext(ldapEnvironment); ctx.bind(buildUserDN(user), ldapUser); ctx.close(); setNextUidNumber(user.getLdapGroup().getLdapServer()); Helper.setMessage( Helper.getTranslation("ldapWritten") + " " + ServiceManager.getUserService().getFullName(user)); /* * check if HomeDir exists, else create it */ logger.debug("HomeVerzeichnis pruefen"); URI homePath = getUserHomeDirectory(user); if (!new File(homePath).exists()) { logger.debug("HomeVerzeichnis existiert noch nicht"); ServiceManager.getFileService().createDirectoryForUser(homePath, user.getLogin()); logger.debug("HomeVerzeichnis angelegt"); } else { logger.debug("HomeVerzeichnis existiert schon"); } } else { Helper.setMessage("ldapIsReadOnly"); } }