List of usage examples for javax.naming.directory DirContext lookup
public Object lookup(Name name) throws NamingException;
From source file:org.archone.ad.domain.LdapActions.java
@RPCAction(name = "domain.create", required = { "domain", "userName", "password", "rootDn", "rootDnPassword" }) @RequiresRoles("SUPERUSER") public HashMap<String, Object> createDomain(OperationContext opContext) throws NamingException, NoSuchAlgorithmException, UnsupportedEncodingException { String domain = (String) opContext.getParams().get("domain"); String userName = (String) opContext.getParams().get("userName"); String password = (String) opContext.getParams().get("password"); String rootDn = (String) opContext.getParams().get("rootDn"); String rootDnPassword = (String) opContext.getParams().get("rootDnPassword"); DirContext dirContext = contextSource.getContext(rootDn, rootDnPassword); DirContextAdapter userRoot = (DirContextAdapter) dirContext .lookup("ds-cfg-backend-id=userRoot,cn=Backends,cn=config"); DomainDn domainDn = nameHelper.newDomainDnFromDomain(domain); //Declaring backend userRoot.addAttributeValue("ds-cfg-base-dn", domainDn.toString()); dirContext.modifyAttributes(userRoot.getNameInNamespace(), userRoot.getModificationItems()); //Creating backend DirContextAdapter adapter = new DirContextAdapter(); adapter.setAttributeValues("objectclass", new String[] { "top", "domain" }); adapter.setAttributeValue("dc", domain.split("\\.")[0]); dirContext.bind(domainDn.toString(), adapter, null); //Creating group node DirContextAdapter groupNode = new DirContextAdapter(); groupNode.setAttributeValue("objectclass", "organizationalUnit"); dirContext.bind(domainDn.getGroupNodeDn(), groupNode); //creating user node DirContextAdapter userNode = new DirContextAdapter(); userNode.setAttributeValue("objectclass", "organizationalUnit"); dirContext.bind(domainDn.getUserNodeDn(), userNode); //creating user DirContextAdapter userAccount = new DirContextAdapter(); userAccount.setAttributeValues("objectclass", ldapConfiguration.getUserObjectClassList().toArray()); userAccount.setAttributeValue("sn", userName); userAccount.setAttributeValue("cn", userName); UserDn userDn = nameHelper.newUserDn(userName, domainDn); userAccount.setAttributeValue("userPassword", password); dirContext.bind(userDn, userAccount); //creating admin group DirContextAdapter adminGroup = new DirContextAdapter(); adminGroup.setAttributeValues("objectclass", ldapConfiguration.getGroupObjectClassList().toArray()); adminGroup.setAttributeValue("uniqueMember", userDn.toString()); GroupDn groupDn = nameHelper.newGroupDn("administrator", domainDn); dirContext.bind(groupDn, adminGroup); HashMap<String, Object> response = new HashMap<String, Object>(); response.put("success", true); return response; }
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * return false if user or password is wrong * /*w ww . jav a2 s . c o m*/ * here we expand attributes: %u, %d, %s * if defined userSearch, retrieve user's DN and try to bind with it * @param username * @param password * @return */ private boolean ldapBind(String username, String password) { String userDN = null; try { TempParams t = new TempParams(); // if username is an email substitute %u e %d in baseDn: expandSearchAndBaseDn(username, t); // setup the default LdapInterface configured with bean data ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName()); ldapInterface.init(getLdapUrl(), getBaseDn(), getSearchBindDn(), getSearchBindPassword(), isFollowReferral(), isConnectionPooling(), null); // set the userDN when custom user search if (!StringUtils.isEmpty(getUserSearch())) { // customize the field used to search the user. SearchResult sr = ldapInterface.searchOneEntry(getUserSearch(), new String[] { "dn" }, SearchControls.SUBTREE_SCOPE); if (sr == null) { log.info("Username " + username + " not found"); return false; } userDN = sr.getNameInNamespace().trim(); log.info("binding with dn:" + userDN); } // on failure, set the user DN with append if (userDN == null) { userDN = "uid=" + username + "," + baseDn; } } catch (Exception e) { log.error("Can't instantiate LdapInterface: " + e.getMessage()); return false; } // Set up environment for creating 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, getLdapUrl()); // Authenticate as User and password env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userDN); env.put(Context.SECURITY_CREDENTIALS, password); try { DirContext ctx = new InitialDirContext(env); log.debug(ctx.lookup(userDN)); ctx.close(); } catch (AuthenticationException e) { log.info("User not authenticated: " + e.getMessage()); return false; } catch (NamingException e) { log.warn("User not authenticated: problem while accessing ldap " + e.getMessage()); e.printStackTrace(); return false; } return true; }
From source file:CreateJavaSchema.java
/** * Locates the Active Directory schema.// w w w.j av a 2 s . co m * @return A context for the root of the Active Directory schema. */ private DirContext getADSchema(DirContext rootCtx) throws NamingException { System.out.println(" [locating the schema]"); String snc = "schemaNamingContext"; // DSE attribute Attributes attrs = rootCtx.getAttributes("", new String[] { snc }); return (DirContext) rootCtx.lookup((String) attrs.get(snc).get()); }
From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java
@Override public boolean verifyPassword(String userName, String userPassword) { DirContext ctx = null; try {//from w w w. jav a 2s . c om LDAPUserCacheEntry userCacheEntry = getUserCacheEntry(userName, true); if (userCacheEntry.getExist()) { long l = System.currentTimeMillis(); ctx = contextSource.getContext(userCacheEntry.getDn(), userPassword); // Take care here - if a base was specified on the ContextSource // that needs to be removed from the user DN for the lookup to succeed. ctx.lookup(userCacheEntry.getDn()); logger.debug("Verify password for {} in {} ms", userName, System.currentTimeMillis() - l); return true; } } catch (Exception e) { // Context creation failed - authentication did not succeed //logger.error("Login failed", e); } finally { // It is imperative that the created DirContext instance is always closed LdapUtils.closeContext(ctx); } return false; }
From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java
/** * Determines the methods normally allowed for the resource. * * @param resources Description of the Parameter * @param req Description of the Parameter * @return Description of the Return Value *//*from w ww .ja v a2 s .com*/ private StringBuffer determineMethodsAllowed(DirContext resources, HttpServletRequest req) { StringBuffer methodsAllowed = new StringBuffer(); boolean exists = true; Object object = null; try { String path = getRelativePath(req); object = resources.lookup(path); } catch (NamingException e) { exists = false; } if (!exists) { methodsAllowed.append("OPTIONS, MKCOL, PUT, LOCK"); return methodsAllowed; } methodsAllowed.append("OPTIONS, GET, HEAD, POST, DELETE, TRACE"); methodsAllowed.append(", PROPPATCH, COPY, MOVE, LOCK, UNLOCK"); //if (listings) { methodsAllowed.append(", PROPFIND"); //} if (!(object instanceof DirContext)) { methodsAllowed.append(", PUT"); } return methodsAllowed; }
From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java
/** * Copy a collection.// w ww . j ava 2 s . c o m * * @param resources Resources implementation to be used * @param errorList Hashtable containing the list of errors which occurred * during the copy operation * @param source Path of the resource to be copied * @param dest Destination path * @return Description of the Return Value */ private boolean copyResource(DirContext resources, Hashtable errorList, String source, String dest) { if (debug > 1) { System.out.println("Copy: " + source + " To: " + dest); } Object object = null; try { object = resources.lookup(source); } catch (NamingException e) { } if (object instanceof DirContext) { try { resources.createSubcontext(dest); } catch (NamingException e) { errorList.put(dest, new Integer(WebdavStatus.SC_CONFLICT)); return false; } try { NamingEnumeration enum1 = resources.list(source); while (enum1.hasMoreElements()) { NameClassPair ncPair = (NameClassPair) enum1.nextElement(); String childDest = dest; if (!childDest.equals("/")) { childDest += "/"; } childDest += ncPair.getName(); String childSrc = source; if (!childSrc.equals("/")) { childSrc += "/"; } childSrc += ncPair.getName(); copyResource(resources, errorList, childSrc, childDest); } } catch (NamingException e) { errorList.put(dest, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return false; } } else { if (object instanceof Resource) { try { resources.bind(dest, object); } catch (NamingException e) { errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return false; } } else { errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return false; } } return true; }
From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java
/** * MKCOL Method.// w w w .ja v a 2s . c o m * * @param req Description of the Parameter * @param resp Description of the Parameter * @throws javax.servlet.ServletException Description of the Exception * @throws java.io.IOException Description of the Exception */ protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } // Retrieve the resources DirContext resources = getResources(); if (resources == null) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } // Can't create a collection if a resource already exists at the given // path if (exists) { // Get allowed methods StringBuffer methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } if (req.getInputStream().available() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource(req.getInputStream())); // TODO : Process this request body resp.sendError(WebdavStatus.SC_NOT_IMPLEMENTED); return; } catch (SAXException saxe) { // Parse error - assume invalid content resp.sendError(WebdavStatus.SC_BAD_REQUEST); return; } } boolean result = true; try { resources.createSubcontext(path); } catch (NamingException e) { result = false; } if (!result) { resp.sendError(WebdavStatus.SC_CONFLICT, WebdavStatus.getStatusText(WebdavStatus.SC_CONFLICT)); } else { resp.setStatus(WebdavStatus.SC_CREATED); // Removing any lock-null resource which would be present lockNullResources.remove(path); } }
From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java
/** * Delete a resource.// w w w.j a v a 2s . c o m * * @param path Path of the resource which is to be deleted * @param req Servlet request * @param resp Servlet response * @param setStatus Should the response status be set on * successful completion * @return Description of the Return Value * @throws javax.servlet.ServletException Description of the Exception * @throws java.io.IOException Description of the Exception */ private boolean deleteResource(String path, HttpServletRequest req, HttpServletResponse resp, boolean setStatus) throws ServletException, IOException { if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } String ifHeader = req.getHeader("If"); if (ifHeader == null) { ifHeader = ""; } String lockTokenHeader = req.getHeader("Lock-Token"); if (lockTokenHeader == null) { lockTokenHeader = ""; } if (isLocked(path, ifHeader + lockTokenHeader)) { resp.sendError(WebdavStatus.SC_LOCKED); return false; } // Retrieve the resources DirContext resources = getResources(); if (resources == null) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } boolean exists = true; Object object = null; try { object = resources.lookup(path); } catch (NamingException e) { exists = false; } if (!exists) { resp.sendError(WebdavStatus.SC_NOT_FOUND); return false; } boolean collection = (object instanceof DirContext); if (!collection) { try { resources.unbind(path); } catch (NamingException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); return false; } } else { Hashtable errorList = new Hashtable(); deleteCollection(req, resources, path, errorList); try { resources.unbind(path); } catch (NamingException e) { errorList.put(path, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } if (!errorList.isEmpty()) { sendReport(req, resp, errorList); return false; } } if (setStatus) { resp.setStatus(WebdavStatus.SC_NO_CONTENT); } return true; }
From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java
/** * Copy a resource.//from w w w . ja v a 2s . c o m * * @param req Servlet request * @param resp Servlet response * @return boolean true if the copy is successful * @throws javax.servlet.ServletException Description of the Exception * @throws java.io.IOException Description of the Exception */ private boolean copyResource(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Parsing destination header String destinationPath = req.getHeader("Destination"); if (destinationPath == null) { resp.sendError(WebdavStatus.SC_BAD_REQUEST); return false; } // Remove url encoding from destination destinationPath = RequestUtil.URLDecode(destinationPath, "UTF8"); int protocolIndex = destinationPath.indexOf("://"); if (protocolIndex >= 0) { // if the Destination URL contains the protocol, we can safely // trim everything upto the first "/" character after "://" int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4); if (firstSeparator < 0) { destinationPath = "/"; } else { destinationPath = destinationPath.substring(firstSeparator); } } else { String hostName = req.getServerName(); if ((hostName != null) && (destinationPath.startsWith(hostName))) { destinationPath = destinationPath.substring(hostName.length()); } int portIndex = destinationPath.indexOf(":"); if (portIndex >= 0) { destinationPath = destinationPath.substring(portIndex); } if (destinationPath.startsWith(":")) { int firstSeparator = destinationPath.indexOf("/"); if (firstSeparator < 0) { destinationPath = "/"; } else { destinationPath = destinationPath.substring(firstSeparator); } } } // Normalise destination path (remove '.' and '..') destinationPath = normalize(destinationPath); String contextPath = req.getContextPath(); if ((contextPath != null) && (destinationPath.startsWith(contextPath))) { destinationPath = destinationPath.substring(contextPath.length()); } String pathInfo = req.getPathInfo(); if (pathInfo != null) { String servletPath = req.getServletPath(); if ((servletPath != null) && (destinationPath.startsWith(servletPath))) { destinationPath = destinationPath.substring(servletPath.length()); } } if (debug > 0) { System.out.println("Dest path :" + destinationPath); } if ((destinationPath.toUpperCase().startsWith("/WEB-INF")) || (destinationPath.toUpperCase().startsWith("/META-INF"))) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } String path = getRelativePath(req); if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } if (destinationPath.equals(path)) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } // Parsing overwrite header boolean overwrite = true; String overwriteHeader = req.getHeader("Overwrite"); if (overwriteHeader != null) { if (overwriteHeader.equalsIgnoreCase("T")) { overwrite = true; } else { overwrite = false; } } // Overwriting the destination // Retrieve the resources DirContext resources = getResources(); if (resources == null) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } boolean exists = true; try { resources.lookup(destinationPath); } catch (NamingException e) { exists = false; } if (overwrite) { // Delete destination resource, if it exists if (exists) { if (!deleteResource(destinationPath, req, resp, true)) { return false; } } else { resp.setStatus(WebdavStatus.SC_CREATED); } } else { // If the destination exists, then it's a conflict if (exists) { resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return false; } } // Copying source to destination Hashtable errorList = new Hashtable(); boolean result = copyResource(resources, errorList, path, destinationPath); if ((!result) || (!errorList.isEmpty())) { sendReport(req, resp, errorList); return false; } // Removing any lock-null resource which would be present at // the destination path lockNullResources.remove(destinationPath); return true; }
From source file:com.zeroio.webdav.WebdavServlet.java
/** * Determines the methods normally allowed for the resource. * * @param resources Description of the Parameter * @param req Description of the Parameter * @return Description of the Return Value *//*ww w. jav a 2 s . c o m*/ private StringBuffer determineMethodsAllowed(DirContext resources, HttpServletRequest req) { StringBuffer methodsAllowed = new StringBuffer(); boolean exists = true; Object object = null; try { String path = getRelativePath(req); object = resources.lookup(path); } catch (NamingException e) { exists = false; } if (!exists) { methodsAllowed.append("OPTIONS, MKCOL, PUT, LOCK"); return methodsAllowed; } methodsAllowed.append("OPTIONS, GET, HEAD, POST, DELETE, TRACE"); methodsAllowed.append(", PROPPATCH, COPY, MOVE, LOCK, UNLOCK"); //if (listings) { methodsAllowed.append(", PROPFIND"); //} if (!(object instanceof DirContext)) { methodsAllowed.append(", PUT"); } return methodsAllowed; }