List of usage examples for javax.naming NamingEnumeration hasMore
public boolean hasMore() throws NamingException;
From source file:org.lsc.beans.LscBean.java
/** * Set a bean from an LDAP entry//from w w w .j av a 2s. 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. * //from w w w. j av a 2 s.co 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.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 *//*from w ww .j av a 2 s. c om*/ 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 {/* ww w . jav 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. *//*w w w . ja va2 s .co m*/ 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//from w w w . j av a 2s.c om * @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; }
From source file:org.springframework.security.ldap.SpringSecurityLdapTemplate.java
/** * Internal method extracted to avoid code duplication in AD search. */// www . jav a 2s .c o m 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<>(); 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.egt.core.util.Utils.java
public static void traceContext(Context c, String name) { NameClassPair ncp;/*from ww w .j av a2s. c o m*/ NamingEnumeration<NameClassPair> ncpenum; try { ncpenum = c.list(name); while (ncpenum.hasMore()) { ncp = ncpenum.next(); if (ncp.getClassName().endsWith("javaURLContext")) { traceContext(c, ncp.getName()); } else { Bitacora.logTrace(ncp.getName() + " = " + ncp.getClassName()); } } } catch (NamingException ex) { Bitacora.logFatal(ThrowableUtils.getString(ex)); } }
From source file:EnvEntry.java
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); try {/*from ww w. j a v a 2 s .c om*/ Context initCtx = new InitialContext(); NamingEnumeration e = initCtx.listBindings("java:comp/env"); while (e.hasMore()) { Binding binding = (Binding) e.next(); out.println("Name: " + binding.getName()); out.println("Type: " + binding.getClassName()); out.println("Value: " + binding.getObject()); out.println(); } } catch (NamingException e) { e.printStackTrace(out); } }
From source file:com.aes.touresbalon.touresbalonoms.utilities.ContactAttributeMapperJSON.java
@Override public Object mapFromAttributes(Attributes atrbts) throws NamingException { NamingEnumeration<String> ids = atrbts.getIDs(); JSONObject jo = new JSONObject(); while (ids.hasMore()) { String id = ids.next();/*w w w .j av a 2 s . c o m*/ jo.put(id, atrbts.get(id).get()); } return jo.toString(); }