List of usage examples for javax.naming.directory Attribute getID
String getID();
From source file:ca.tnt.ldaputils.impl.LdapEntry.java
/** * Runs the batch modifications requested through the {@link * ILdapEntry#modifyBatchAttribute(int, String, Object)} *//* ww w . j av a2 s .c o m*/ public void modifyBatchAttributes(final String bindDN, final String bindPassword) { // BEGIN modifyBatchAttributes() DirContext ldapContext = null; if (modificationItems.size() == 0) { throw new IllegalStateException("No modification items for batch"); } try { final Object[] tempModItems; final ModificationItem[] modItems; tempModItems = modificationItems.values().toArray(); modItems = new ModificationItem[tempModItems.length]; for (int index = 0; index < tempModItems.length; index++) { // convert to ModificationItem array modItems[index] = (ModificationItem) tempModItems[index]; } ldapContext = manager.getConnection(bindDN, bindPassword); ldapContext.modifyAttributes(getDn(), modItems); /** * Update the attributes in memory */ for (final ModificationItem modItem : modItems) { final Attribute attribute; attribute = modItem.getAttribute(); updateAttribute(attribute.getID()); } // manager.reloadAttributes(this); } catch (NamingException namingException) { throw new LdapNamingException(namingException); } catch (Exception exception) { throw new LdapNamingException("error modifying attributes", exception); } finally { try { if (ldapContext != null) { ldapContext.close(); } } catch (NamingException namingException) { manager.logNamingException(namingException); } // recreate empty batch list modificationItems = new LinkedHashMap(); } }
From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java
/** * Loads attributes for the argument subject. * @param subject //from ww w . java2 s . c om * @return the map */ protected Map loadAttributes(SubjectImpl subject) { Map<String, Set<String>> attributes1 = new HashMap<String, Set<String>>(); Search search = getSearch("searchSubject"); if (search == null) { log.error("searchType: \"search\" not defined."); return attributes1; } //setting attributeNames to null will cause all attributes for a subject to be returned String[] attributeNames = null; Set attributeNameSet = this.getAttributes(); if (attributeNameSet.size() == 0) { attributeNames = null; } else { attributeNames = new String[attributeNameSet.size()]; int i = 0; for (Iterator it = attributeNameSet.iterator(); it.hasNext(); attributeNames[i++] = (String) it.next()) ; } try { Attributes ldapAttributes = getLdapUnique(search, subject.getId(), attributeNames); for (NamingEnumeration e = ldapAttributes.getAll(); e.hasMore();) { Attribute attr = (Attribute) e.next(); String name1 = attr.getID(); Set<String> values = new HashSet<String>(); for (NamingEnumeration en = attr.getAll(); en.hasMore();) { Object value = en.next(); values.add(value.toString()); } attributes1.put(name1, values); } subject.setAttributes(attributes1); } catch (SubjectNotFoundException ex) { log.error("SubjectNotFound: " + subject.getId() + " " + ex.getMessage(), ex); } catch (SubjectNotUniqueException ex) { log.error("SubjectNotUnique: " + subject.getId() + " " + ex.getMessage(), ex); } catch (NamingException ex) { log.error("LDAP Naming Except: " + ex.getMessage(), ex); } return attributes1; }
From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java
/** * Gathers attributes from JNDI storage to the supplied attributes object. * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes) *//*from w ww . j a v a2s . com*/ public void process(String sUserId, IAttributes oAttributes) throws AttributeException { DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); if (_listGather.size() > 0) { String[] saAttributes = _listGather.toArray(new String[0]); oScope.setReturningAttributes(saAttributes); } String searchFilter = resolveSearchQuery(sUserId); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes for id: "); sbFailed.append(sUserId); _logger.error(sbFailed.toString(), e); throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.debug("User unknown: " + sUserId); return; } if (oNamingEnumeration.hasMore()) { SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oSearchedAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oSearchedAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); String sMappedName = _htMapper.get(sAttributeName); if (sMappedName != null) sAttributeName = sMappedName; if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); oAttributes.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; oAttributes.put(sAttributeName, oValue); } } } } catch (AttributeException e) { throw e; } catch (NamingException e) { _logger.debug("Failed to fetch attributes for user: " + sUserId, e); } catch (Exception e) { _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e); throw new AttributeException(SystemErrors.ERROR_INTERNAL); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e); } } } }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the values of the specified fields for the supplied id. * @see IExternalStorage#getFields(java.lang.String, java.util.List) *//*from w ww . jav a 2s . c o m*/ public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException { Hashtable<String, Object> htReturn = new Hashtable<String, Object>(); DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] saFields = fields.toArray(new String[0]); oScope.setReturningAttributes(saFields); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes '"); sbFailed.append(fields); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); htReturn.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; htReturn.put(sAttributeName, oValue); } } } catch (UserException e) { throw e; } catch (Exception e) { _logger.fatal("Could not retrieve fields: " + fields, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return htReturn; }
From source file:org.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java
/** * {@inheritDoc}// w w w . ja va 2 s. com */ public void logSearchResultEntry(Connection connection, StudioSearchResult studioSearchResult, long requestNum, NamingException ex) { if (!isSearchResultEntryLogEnabled()) { return; } try { String formattedString; if (studioSearchResult != null) { String dn = studioSearchResult.getNameInNamespace(); Attributes attributes = studioSearchResult.getAttributes(); LdifContentRecord record = new LdifContentRecord(LdifDnLine.create(dn)); NamingEnumeration<? extends Attribute> attributeEnumeration = attributes.getAll(); while (attributeEnumeration.hasMore()) { Attribute attribute = attributeEnumeration.next(); String attributeName = attribute.getID(); NamingEnumeration<?> valueEnumeration = attribute.getAll(); while (valueEnumeration.hasMore()) { Object o = valueEnumeration.next(); if (o instanceof String) { record.addAttrVal(LdifAttrValLine.create(attributeName, (String) o)); } if (o instanceof byte[]) { record.addAttrVal(LdifAttrValLine.create(attributeName, (byte[]) o)); } } } record.finish(LdifSepLine.create()); formattedString = record.toFormattedString(LdifFormatParameters.DEFAULT); } else { formattedString = LdifFormatParameters.DEFAULT.getLineSeparator(); } log(formattedString, "SEARCH RESULT ENTRY (" + requestNum + ")", ex, connection); //$NON-NLS-1$ //$NON-NLS-2$ } catch (NamingException e) { } }
From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java
protected Attributes getLdapUnique(Search search, String searchValue, String[] attributeNames) throws SubjectNotFoundException, SubjectNotUniqueException { Attributes attributes = null; Iterator<SearchResult> results = getLdapResults(search, searchValue, attributeNames); if (results == null || !results.hasNext()) { String errMsg = "No results: " + search.getSearchType() + " filter:" + search.getParam("filter") + " searchValue: " + searchValue; throw new SubjectNotFoundException(errMsg); }/*from www .j a v a 2s. com*/ SearchResult si = (SearchResult) results.next(); attributes = si.getAttributes(); if (results.hasNext()) { si = (SearchResult) results.next(); if (!multipleResults) { String errMsg = "Search is not unique:" + si.getName() + "\n"; throw new SubjectNotUniqueException(errMsg); } Attributes attr = si.getAttributes(); NamingEnumeration<? extends Attribute> n = attr.getAll(); try { while (n.hasMore()) { Attribute a = n.next(); log.debug("checking attribute " + a.getID()); if (attributes.get(a.getID()) == null) { log.debug("adding " + a.getID()); attributes.put(a); } } } catch (NamingException e) { log.error("ldap excp: " + e); } } return attributes; }
From source file:org.pepstock.jem.gwt.server.security.ExtendedJndiLdapRealm.java
/** * Load all LDAP attributes in principal attributes and stores all in a list. * //from w ww.java2s. c o m * @param attributes LDAP attributes * @return list of principal attribtues */ @SuppressWarnings("rawtypes") private List<PrincipalAttribute> loadAttributes(String id, Attributes attributes) { // creates a list List<PrincipalAttribute> list = new ArrayList<PrincipalAttribute>(); if (attributes != null) { try { // scans LDAP attributes for (NamingEnumeration attrEnum = attributes.getAll(); attrEnum.hasMore();) { Attribute attribute = (Attribute) attrEnum.next(); // creates all principal attributes for (NamingEnumeration valueEnum = attribute.getAll(); valueEnum.hasMore();) { PrincipalAttribute attr = new PrincipalAttribute(); attr.setName(attribute.getID()); attr.setValue(valueEnum.next()); list.add(attr); } } } catch (NamingException e) { LogAppl.getInstance().emit(UserInterfaceMessage.JEMG031E, e, id); } } return list; }
From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java
/** * Try to get more attributes for the argument subject. (from name) *//* w ww . j a v a 2s. co m*/ protected Map getAllAttributes(LdapSubject subject) { Map attributes = new HashMap(); log.debug("getAllAttributes for " + subject.getName()); Search search = getSearch("searchSubjectAttributes"); if (search == null) { log.error("searchType: \"searchSubjectAttributes\" not defined."); return attributes; } try { Attributes ldapAttributes = getLdapUnique(search, subject.getName(), allAttributeNames); for (NamingEnumeration e = ldapAttributes.getAll(); e.hasMore();) { Attribute attr = (Attribute) e.next(); String attrName = attr.getID(); // special case the basic ones if (attrName.equals(subjectIDAttributeName)) continue; // already have if (attrName.equals(nameAttributeName)) continue; // already have if (attrName.equals(descriptionAttributeName)) { subject.setDescription((String) attr.get()); continue; } Set values = new HashSet(); for (NamingEnumeration en = attr.getAll(); en.hasMore();) { Object value = en.next(); values.add(value.toString()); } attributes.put(attrName, values); } subject.setAttributes(attributes); } catch (SubjectNotFoundException ex) { log.error("SubjectNotFound: " + subject.getId() + " " + ex.getMessage(), ex); } catch (SubjectNotUniqueException ex) { log.error("SubjectNotUnique: " + subject.getId() + " " + ex.getMessage(), ex); } catch (NamingException ex) { log.error("LDAP Naming Except: " + ex.getMessage(), ex); } return attributes; }
From source file:org.lsc.beans.LscBean.java
/** * Set an attribute. API CHANGE: Do nothing if attribute is empty * //from w w w. ja v a 2 s .c o m * @param attr * the attribute to set */ public final void setAttribute(final Attribute attr) { if (attr != null && attr.size() > 0) { // convert the Attribute into a Set of values try { setAttribute(attr.getID(), SetUtils.attributeToSet(attr)); } catch (NamingException e) { LOGGER.error("Error storing the attribute {}: {}", attr.getID(), e.toString()); LOGGER.debug(e.toString(), e); } } }
From source file:fr.cls.atoll.motu.web.services.MotuOGCFrontController.java
/** * Method that returns an adapted version of the servlet config returned by the super method. Thus, the * {@link ServletContext#getRealPath(String)} is overriden to allow a nice resolution of a file among * external directories./*from w ww . j a v a 2 s .c o m*/ * * @return the servlet context instance of this servlet. */ private ServletConfig wrapServletConfig(final ServletConfig sc) { return new ServletConfigAdapter(sc) { private ServletContextAdapter ctx = null; @Override public ServletContext getServletContext() { if (ctx == null) { ctx = new ServletContextAdapter(super.getServletContext()) { /** * First try to resolve the given location as a resource (using classpath extensions * if necessary). If this try fails, then let the process go on. */ @Override public String getRealPath(String name) { try { // try the classpath URL url = ConfigLoader.getInstance().get(name); if (url != null) { return url.toString(); } // try the current context naming // TODO: try to see if we can keep independence with the container ApplicationContext appCtx = null; if (ctx.getRootContext() instanceof ApplicationContextFacade) { Field privateStringField = ApplicationContextFacade.class .getDeclaredField("context"); privateStringField.setAccessible(true); Object context = privateStringField.get(ctx.getRootContext()); if ((context != null) && context instanceof ApplicationContext) { DirContext dc = ((ApplicationContext) context).getResources(); Attributes atts = dc.getAttributes(name); for (NamingEnumeration e = atts.getAll(); e.hasMore();) { final Attribute a = (Attribute) e.next(); if ("canonicalPath".equals(a.getID())) { String s = a.get().toString(); File f = new File(s); if (f.exists()) { return f.getAbsolutePath(); } } } } } throw new IllegalStateException("name " + name + " not resolved on classpath. Try default (servlet) resolution."); } catch (Exception e) { return super.getRealPath(name); } } }; } return ctx; } }; }