List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:com.ironiacorp.persistence.datasource.HibernateConfigurationUtil.java
/** * Retrieve the data sources registered at JNDI in the given context. * /*from w w w. j a va2 s . c o m*/ * @param namingContext * Start point context. * * @return A collection of the data sources found within the context. */ private static Collection<String> getAvailableDataSources(Context namingContext) { Collection<String> datasources = new ArrayList<String>(); Class<?> type = null; // Acquire global JNDI resources if available try { type = Class.forName("xyz"); } catch (ClassNotFoundException e) { } try { NamingEnumeration<Binding> items = namingContext.listBindings(""); while (items.hasMore()) { Binding item = (Binding) items.next(); if (item.getObject() instanceof Context) { datasources.addAll(getAvailableDataSources((Context) item.getObject())); } else { if (type.isInstance(item.getObject())) { datasources.add(item.getName()); } } } } catch (Throwable t) { } return datasources; }
From source file:org.zanata.ZanataInit.java
private static void list(Context ctx, String indent, StringBuffer buffer, boolean verbose) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); try {/*from w ww . j av a 2s . com*/ NamingEnumeration<NameClassPair> ne = ctx.list(""); while (ne.hasMore()) { NameClassPair pair = ne.next(); String name = pair.getName(); String className = pair.getClassName(); boolean recursive = false; boolean isLinkRef = false; boolean isProxy = false; Class<?> c = null; try { c = loader.loadClass(className); if (Context.class.isAssignableFrom(c)) { recursive = true; } if (LinkRef.class.isAssignableFrom(c)) { isLinkRef = true; } isProxy = Proxy.isProxyClass(c); } catch (ClassNotFoundException cnfe) { // If this is a $Proxy* class its a proxy if (className.startsWith("$Proxy")) { isProxy = true; // We have to get the class from the binding try { Object p = ctx.lookup(name); c = p.getClass(); } catch (NamingException e) { Throwable t = e.getRootCause(); if (t instanceof ClassNotFoundException) { // Get the class name from the exception msg String msg = t.getMessage(); if (msg != null) { // Reset the class name to the CNFE class className = msg; } } } } } buffer.append(indent).append(" +- ").append(name); // Display reference targets if (isLinkRef) { // Get the try { Object obj = ctx.lookupLink(name); LinkRef link = (LinkRef) obj; buffer.append("[link -> "); buffer.append(link.getLinkName()); buffer.append(']'); } catch (Throwable t) { buffer.append("invalid]"); } } // Display proxy interfaces if (isProxy) { buffer.append(" (proxy: ").append(pair.getClassName()); if (c != null) { Class<?>[] ifaces = c.getInterfaces(); buffer.append(" implements "); for (Class<?> iface : ifaces) { buffer.append(iface); buffer.append(','); } buffer.setCharAt(buffer.length() - 1, ')'); } else { buffer.append(" implements ").append(className).append(")"); } } else if (verbose) { buffer.append(" (class: ").append(pair.getClassName()).append(")"); } buffer.append('\n'); if (recursive) { try { Object value = ctx.lookup(name); if (value instanceof Context) { Context subctx = (Context) value; list(subctx, indent + " | ", buffer, verbose); } else { buffer.append(indent).append(" | NonContext: ").append(value); buffer.append('\n'); } } catch (Throwable t) { buffer.append("Failed to lookup: ").append(name).append(", errmsg=").append(t.getMessage()); buffer.append('\n'); } } } ne.close(); } catch (NamingException ne) { buffer.append("error while listing context ").append(ctx.toString()).append(": ") .append(ne.toString(true)); } }
From source file:org.jkcsoft.java.util.JndiHelper.java
public static Map getUserInfo(BehavioralContext ctx, String userName) throws NamingException { Map infoMap = null;// w w w. j a va 2 s . co m Configuration cfg = ctx.getConfig(); // String searchRelativeDc = cfg.getString(Constants.KEY_AD_USER_NODE_DN); String theFilter = LDAP_USER_SAMACCOUNTNAME + "=" + userName; List theAttrsList = new Vector(Arrays.asList(ldapUserAttrs)); theAttrsList.addAll(Arrays.asList(ldapTopAttrs)); int countLimit = 1000; int timeLimitMillis = 30000; boolean returnObject = false; boolean derefObj = true; SearchControls scs = new SearchControls(SearchControls.SUBTREE_SCOPE, countLimit, timeLimitMillis, (String[]) theAttrsList.toArray(new String[0]), returnObject, derefObj); DirContext rootCtx = getTsessAccountContext(ctx); try { log.debug("Search params name[" + searchRelativeDc + "] " + "filter[" + theFilter + "] controls[" + scs + "]"); NamingEnumeration results = rootCtx.search(searchRelativeDc, theFilter, scs); if (results == null || !results.hasMore()) throw new NamingException("User LDAP entry not found"); SearchResult searchResult = ((SearchResult) results.next()); if (searchResult == null) throw new NamingException("User LDAP entry not found"); if (log.isTraceEnabled()) { logLdap(log, 0, 0, searchResult); } Attributes userLdapAttrs = searchResult.getAttributes(); infoMap = new HashMap(); for (Iterator attrIter = theAttrsList.iterator(); attrIter.hasNext();) { loadMap(infoMap, userLdapAttrs, (String) attrIter.next()); } } finally { safeClose(rootCtx); } return infoMap; }
From source file:org.lsc.beans.LscBean.java
/** * Set a bean from an LDAP entry//from ww w . ja v a2 s . co m * * @param entry * the LDAP entry * @param baseDn * the base Dn used to set the right Dn * @param c * class to instantiate * @return the bean * @throws NamingException * thrown if a directory exception is encountered while looking * at the entry */ public static LscBean getInstance(final SearchResult entry, final String baseDn, final Class<?> c) throws NamingException { try { if (entry != null) { LscBean ab = (LscBean) c.newInstance(); String dn = entry.getName(); if ((dn.length() > 0) && (dn.charAt(0) == '"') && (dn.charAt(dn.length() - 1) == '"')) { dn = dn.substring(1, dn.length() - 1); } if (dn.startsWith("ldap://")) { ab.setDistinguishName(entry.getNameInNamespace()); } else { // Manually concat baseDn because getNameInNamespace returns // a differently escaped DN, causing LSC to detect a MODRDN if ((baseDn != null) && (baseDn.length() > 0)) { if (dn.length() > 0) { ab.setDistinguishName(dn + "," + baseDn); } else { ab.setDistinguishName(baseDn); } } else { ab.setDistinguishName(dn); } } NamingEnumeration<?> ne = entry.getAttributes().getAll(); while (ne.hasMore()) { ab.setAttribute((Attribute) ne.next()); } return ab; } else { return null; } } catch (InstantiationException ie) { LOGGER.error(ie.toString()); LOGGER.debug(ie.toString(), ie); } catch (IllegalAccessException iae) { LOGGER.error(iae.toString()); LOGGER.debug(iae.toString(), iae); } return null; }
From source file:org.pepstock.jem.jppf.ExecuteManager.java
/** * Create a JPPF job that can be submitted for execution. * // w ww .j a v a2 s.c o m * @param runnable Class name of Runnable or JPPFTask to execute * @param parallelTaskNumber Number of parallel task to submit * @param xmlContext InitialContext, serialized in XML string * @return an instance of the {@link org.jppf.client.JPPFJob JPPFJob} class. * @throws NamingException * @throws IOException * @throws JPPFException * @throws JPFFException * if an error occurs while creating the job or adding tasks. */ private static JPPFJob createJob(String xmlContext) throws JPPFMessageException, NamingException, IOException, JPPFException { XStream xstream = new XStream(); // reads all properties String jobName = JPPFConfiguration.getProperties().getProperty(Keys.JEM_JOB_NAME); String taskName = JPPFConfiguration.getProperties().getProperty(Keys.JEM_TASK_NAME); String runnable = JPPFConfiguration.getProperties().getProperty(Keys.JEM_RUNNABLE); int parallelTaskNumber = JPPFConfiguration.getProperties().getInt(Keys.JEM_TASK_NUMBER); // creates a data provider to pass initial context and number of parallel task MemoryMapDataProvider provider = new MemoryMapDataProvider(); provider.setValue(Keys.JEM_CONTEXT, xmlContext); provider.setValue(Keys.JEM_TASK_NUMBER, String.valueOf(parallelTaskNumber)); // checks if CHUNK is set if (JPPFConfiguration.getProperties().containsKey(Keys.JEM_CHUNKABLE_DATA_DESCRIPTION)) { // gets data description String dataDescription = JPPFConfiguration.getProperties() .getProperty(Keys.JEM_CHUNKABLE_DATA_DESCRIPTION); File file = null; InitialContext ic = ContextUtils.getContext(); // lookup for JNDI reference // needs file name because chunk is based on RandomFileAccess // that wants a FILE and not inputstream // so gets data description implementation object // to get REAL FILE NamingEnumeration<NameClassPair> list = ic.list(dataDescription); while (list.hasMore()) { NameClassPair pair = list.next(); // checks if is datastream // only datastreams are searched if (pair.getName().equalsIgnoreCase(dataDescription) && pair instanceof DataStreamNameClassPair) { DataStreamNameClassPair dsPair = (DataStreamNameClassPair) pair; DataStreamReference prevReference = (DataStreamReference) dsPair.getObject(); // gets data description XML definition StringRefAddr sra = (StringRefAddr) prevReference.get(StringRefAddrKeys.DATASTREAMS_KEY); // creates datadescription implementatio to get file DataDescriptionImpl ddImpl = (DataDescriptionImpl) xstream.fromXML(sra.getContent().toString()); file = ddImpl.getDatasets().iterator().next().getRealFile(); // leaves while break; } } // if file is null // data description is not found if (file == null) { throw new JPPFMessageException(JPPFMessage.JEMJ019E, dataDescription); } // calculated buffersize long bufferSize = file.length() / parallelTaskNumber; // using delimiter, creates chunk list List<ChunkDefinition> chunks = null; String delimiter = JPPFConfiguration.getProperties().getProperty(Keys.JEM_DELIMITER); String delimiterString = JPPFConfiguration.getProperties().getProperty(Keys.JEM_DELIMITER_STRING); if (delimiter != null) { // delimiter default LF char splitter = CharUtils.LF; // if delimiter is defined in BYTE mode // calculate char if (delimiter.toLowerCase().startsWith("0x")) { delimiter = StringUtils.substringAfter(delimiter.toLowerCase(), "0x"); splitter = (char) Integer.parseInt(delimiter, 16); } else { // if uses a escape java char splitter = StringEscapeUtils.unescapeJava(delimiter).charAt(0); } String displayDelimiter = Integer.toHexString((byte) splitter) + "(" + splitter + ")"; LogAppl.getInstance().emit(JPPFMessage.JEMJ020I, displayDelimiter); // calculates chunks chunks = ChunksFactory.getChunksByDelimiter(file, bufferSize, splitter); provider.setValue(Keys.JEM_DELIMITER, splitter); } else if (delimiterString != null) { LogAppl.getInstance().emit(JPPFMessage.JEMJ020I, delimiterString); // calculates chunks chunks = ChunksFactory.getChunksByDelimiter(file, bufferSize, delimiterString); provider.setValue(Keys.JEM_DELIMITER, delimiterString); } else { // if delimiter and delimiterString are missing, uses default delimiter (System.getProperty("line.separator") chunks = ChunksFactory.getChunksByDelimiter(file, bufferSize); } // changes parallel task // because chunk calculation tries to maintain the same // number of task but usually there are less after // chunk list creation parallelTaskNumber = chunks.size(); LogAppl.getInstance().emit(JPPFMessage.JEMJ021I, chunks); // serializes and saves on data provider all necessary data provider.setValue(Keys.JEM_TASK_NUMBER, String.valueOf(parallelTaskNumber)); provider.setValue(Keys.JEM_CHUNKABLE_DATA_DESCRIPTION, dataDescription); provider.setValue(Keys.JEM_CHUNKS, xstream.toXML(chunks)); } LogAppl.getInstance().emit(JPPFMessage.JEMJ023I, parallelTaskNumber); // checks if merged data decritpion is an argument if (JPPFConfiguration.getProperties().containsKey(Keys.JEM_MERGED_DATA_DESCRIPTION)) { // loads a list with all temporary files for tasks // to use to write partial output for (int i = 0; i < parallelTaskNumber; i++) { File temp = File.createTempFile("task[" + i + "]-merge", ".jemjppf"); temp.deleteOnExit(); TEMPORARY_FILES.add(temp); LogAppl.getInstance().emit(JPPFMessage.JEMJ022I, temp.getAbsolutePath(), i); } // sets data provider provider.setValue(Keys.JEM_MERGED_DATA_DESCRIPTION, JPPFConfiguration.getProperties().getProperty(Keys.JEM_MERGED_DATA_DESCRIPTION)); provider.setValue(Keys.JEM_TEMPORARY_FILES, xstream.toXML(TEMPORARY_FILES)); } // create a JPPF job JPPFJob job = new JPPFJob(provider); // give this job a readable unique id that we can use to monitor and // manage it. job.setName(jobName + "." + taskName); // Checks what instance has been past to distribute on grid try { Object clazz = Class.forName(runnable).newInstance(); if (clazz instanceof JPPFTask) { for (int i = 0; i < parallelTaskNumber; i++) { JPPFTask t = new WrapperJPPFTask((JPPFTask) clazz); // add a task to the job. job.addTask(t); } } else if (clazz instanceof Runnable) { for (int i = 0; i < parallelTaskNumber; i++) { JPPFTask t = new RunnableTask((Runnable) clazz); // add a task to the job. job.addTask(t); } } else { throw new JPPFMessageException(JPPFMessage.JEMJ002E, runnable, Runnable.class.getName(), JPPFTask.class.getName()); } } catch (InstantiationException e) { throw new JPPFMessageException(JPPFMessage.JEMJ002E, e, runnable, Runnable.class.getName(), JPPFTask.class.getName()); } catch (IllegalAccessException e) { throw new JPPFMessageException(JPPFMessage.JEMJ002E, e, runnable, Runnable.class.getName(), JPPFTask.class.getName()); } catch (ClassNotFoundException e) { throw new JPPFMessageException(JPPFMessage.JEMJ002E, e, runnable, Runnable.class.getName(), JPPFTask.class.getName()); } // there is no guarantee on the order of execution of the tasks, // however the results are guaranteed to be returned in the same order // as the tasks. return job; }
From source file:org.ballerinalang.stdlib.ldap.nativeimpl.GetLdapScopesOfUser.java
private static List<String> getListOfNames(List<String> searchBases, String searchFilter, SearchControls searchCtls, String property, DirContext ldapConnectionContext) throws NamingException { if (LOG.isDebugEnabled()) { LOG.debug("Result for searchBase: " + searchBases + " searchFilter: " + searchFilter + " property:" + property + " appendDN: false"); }/*w ww .ja v a 2s .c o m*/ List<String> names = new ArrayList<>(); NamingEnumeration<SearchResult> answer = null; try { // handle multiple search bases for (String searchBase : searchBases) { answer = ldapConnectionContext.search(LdapUtils.escapeDNForSearch(searchBase), searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult searchResult = answer.next(); if (searchResult.getAttributes() == null) { continue; } Attribute attr = searchResult.getAttributes().get(property); if (attr == null) { continue; } for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { String name = (String) vals.nextElement(); if (LOG.isDebugEnabled()) { LOG.debug("Found user: " + name); } names.add(name); } } if (LOG.isDebugEnabled()) { for (String name : names) { LOG.debug("Result : " + name); } } } } finally { LdapUtils.closeNamingEnumeration(answer); } return names; }
From source file:org.ballerinalang.auth.ldap.util.LdapUtils.java
/** * Searches the corresponding name for a given username from LDAP. * * @param userName Given username * @param searchBase LDAP search base * @param searchFilter LDAP search filter * @param dirContext Directory naming context * @return Associated name for the given username * @throws UserStoreException if there is any exception occurs during the process * @throws NamingException if there is any exception occurs during the process *//*ww w . j av a 2 s. c o m*/ public static String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter, DirContext dirContext) throws UserStoreException, NamingException { if (userName == null) { throw new UserStoreException("userName value is null."); } String userDN = null; NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] searchBases = searchBase.split("#"); for (String base : searchBases) { answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls); if (!(answer.hasMore())) { continue; } SearchResult userObj = answer.next(); if (userObj != null) { //no need to decode since , if decoded the whole string, can't be encoded again //eg CN=Hello\,Ok=test\,test, OU=Industry userDN = userObj.getNameInNamespace(); break; } } if (LOG.isDebugEnabled()) { LOG.debug("Name in space for " + userName + " is " + userDN); } } finally { LdapUtils.closeNamingEnumeration(answer); } return userDN; }
From source file:fr.iphc.grid.jobmonitor.CeList.java
static public ArrayList<URL> AvailableLdapCe() throws Exception { ArrayList<URL> CeList = new ArrayList<URL>(); Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://cclcgtopbdii01.in2p3.fr:2170"); env.put("java.naming.ldap.attributes.binary", "objectSID"); try {/*from w w w . ja v a2 s . c o m*/ // Create initial context DirContext ctx = new InitialDirContext(env); SearchControls contraints = new SearchControls(); contraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attributIDs = { "GlueCEUniqueID" }; contraints.setReturningAttributes(attributIDs); String BASE_SEARCH = "Mds-Vo-name=local,o=grid"; String filter = "(&(objectClass=GlueCE)(GlueCEImplementationName=CREAM)(GlueCEAccessControlBaseRule=VO:biomed))"; NamingEnumeration<SearchResult> answer = ctx.search(BASE_SEARCH, filter, contraints); // int index = 0; Random rand = new Random(); while (answer.hasMore()) { // index++; SearchResult result = answer.next(); // Attributes attrs = result.getAttributes(); // NamingEnumeration f = attrs.getAll(); // Attribute attr = (Attribute) f.next(); String line = "cream://" + result.getAttributes().get("GlueCEUniqueID").get() + "?delegationId=" + rand.nextLong(); URL serviceURL = URLFactory.createURL(line); CeList.add(serviceURL); } // Close the context when we're done ctx.close(); } catch (Exception e) { e.printStackTrace(); } ; return CeList; }
From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java
/** * Internal method extracted to avoid code duplication in AD search. */// www. j av a 2 s . c om public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls, String base, String filter, Object[] params) throws NamingException { final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace()); final DistinguishedName searchBaseDn = new DistinguishedName(base); final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params, buildControls(searchControls)); if (logger.isDebugEnabled()) { logger.debug("Searching for entry under DN '" + ctxBaseDn + "', base = '" + searchBaseDn + "', filter = '" + filter + "'"); } Set<DirContextOperations> results = new HashSet<DirContextOperations>(); try { while (resultsEnum.hasMore()) { SearchResult searchResult = resultsEnum.next(); DirContextAdapter dca = (DirContextAdapter) searchResult.getObject(); Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured"); if (logger.isDebugEnabled()) { logger.debug("Found DN: " + dca.getDn()); } results.add(dca); } } catch (PartialResultException e) { LdapUtils.closeEnumeration(resultsEnum); logger.info("Ignoring PartialResultException"); } if (results.size() == 0) { throw new IncorrectResultSizeDataAccessException(1, 0); } if (results.size() > 1) { throw new IncorrectResultSizeDataAccessException(1, results.size()); } return results.iterator().next(); }
From source file:com.flexive.shared.EJBLookup.java
/** * Discover which lookup strategy works for the given class * * @param appName EJB application name * @param environment properties passed to the initial context * @param type the class/*ww w . j a v a 2s.c o m*/ * @return appName (may have changed) */ private static <T> String discoverStrategy(String appName, final Hashtable<String, String> environment, Class<T> type) { InitialContext ctx = null; for (STRATEGY strat : STRATEGY.values()) { if (strat == STRATEGY.UNKNOWN) continue; used_strategy = strat; try { final Hashtable<String, String> env = environment != null ? new Hashtable<String, String>(environment) : new Hashtable<String, String>(); prepareEnvironment(strat, env); ctx = new InitialContext(env); ctx.lookup(buildName(appName, type)); if (used_strategy == STRATEGY.EJB31_MODULE) { // we need to resolve all interfaces required by non-web components (stream server, scheduler), // since they run outside the module context resolveKnownInterfaces(); } return appName; } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Strategy " + strat + " failed: " + e.getMessage(), e); } //ignore and try next } } //houston, we have a problem - try locale and remote with appname again iterating through all "root" ctx bindings //this can happen if the ear is not named flexive.ear try { if (ctx == null) ctx = new InitialContext(environment); NamingEnumeration<NameClassPair> ncpe = ctx.list(""); while (ncpe.hasMore()) { NameClassPair ncp = ncpe.next(); if (ncp.getClassName().endsWith("NamingContext")) { appName = ncp.getName(); try { used_strategy = STRATEGY.APP_SIMPLENAME_LOCAL; ctx.lookup(buildName(ncp.getName(), type)); APPNAME = ncp.getName(); LOG.info("Using application name [" + appName + "] for lookups!"); return APPNAME; } catch (Exception e) { //ignore and try remote } try { used_strategy = STRATEGY.APP_SIMPLENAME_REMOTE; ctx.lookup(buildName(ncp.getName(), type)); APPNAME = ncp.getName(); LOG.info("Using application name [" + appName + "] for lookups!"); return APPNAME; } catch (Exception e) { //ignore and try remote } } } } catch (Exception e) { LOG.warn(e); } used_strategy = null; return appName; }