Example usage for javax.naming.directory Attributes size

List of usage examples for javax.naming.directory Attributes size

Introduction

In this page you can find the example usage for javax.naming.directory Attributes size.

Prototype

int size();

Source Link

Document

Retrieves the number of attributes in the attribute set.

Usage

From source file:de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationUpdate.java

private void updateOrg() throws NameNotFoundException, AASUnauthorizedException, AttributeModificationException,
        ExecutionException {/*from  ww  w  .  j  a  v a  2s  .c  om*/
    boolean vChange = false;
    InitialLdapContext vCtx = null;
    try {

        if (this._oldOrganisation == null) {
            LOG.log(Level.WARNING, "No such organization ''{0}'' with oid: ''{1}''.",
                    new Object[] { this._organisation.getDisplayName(), this._organisation.getOIDs() });
            throw new NameNotFoundException("No such organization '" + this._organisation.getDisplayName()
                    + "' with oid: '" + this._organisation.getOIDs() + "'.");
        }

        GeoAdresse vGeoAdresse;
        String vLocalDispalyName = null;
        if (_submit != null) { // hier ist "GeoLocationDisplayName" breits ausgefhrt
            try {
                vGeoAdresse = _submit.get(10, TimeUnit.SECONDS);
                if (vGeoAdresse.getRequestStatus() == GeoRequestStatus.OK) {
                    this._organisation.getAddress().setLatitude(vGeoAdresse.getLatitude());
                    this._organisation.getAddress().setLongitude(vGeoAdresse.getLongitude());
                    this._organisation.getAddress()
                            .setLocationDisplayName(vGeoAdresse.getLocationDisplayName());
                } else {
                    LOG.log(Level.WARNING, "GeoRequestStatus: {0}, (organization id: {1})",
                            new Object[] { vGeoAdresse.getRequestStatus(), this._organisation.getOIDs() });
                }
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._organisation.getOIDs(), ex);
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._organisation.getOIDs(), ex);
            }
        } else if (_submitGeoLocDisplayName != null) {
            try {
                vLocalDispalyName = _submitGeoLocDisplayName.get(5, TimeUnit.SECONDS);
                this._organisation.getAddress().setLocationDisplayName(vLocalDispalyName);
                //LOG.info("LocalDisplayName='" + vLocalDispalyName + "'" + vLocalDispalyName + "'");
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            } catch (ExecutionException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            }

        }

        LOG.info("newOIDs: '" + this._organisation.getOIDs() + "'");
        LOG.info("oldOIDs: '" + this._oldOrganisation.getOIDs() + "'");

        if (this._organisation.getOrgRDN() == null) {
            // -- Ansonsten eine nicht gesetzte RDN kann zum Knall fhren...
            this._organisation.setOrgRDN(this._oldOrganisation.getOrgRDN());
        } else if (!this._organisation.getOrgRDN().equals(this._oldOrganisation.getOrgRDN())) {
            // -- Hier ist etwas faul...
            LOG.log(Level.WARNING,
                    "The organization ''{0}'' has RDN: ''{1}'', but there exist an organization ''{0}'' with RDN: ''{2}''!",
                    new Object[] { this._organisation.getId(), this._organisation.getOrgRDN(),
                            this._oldOrganisation.getOrgRDN() });
            throw new NameNotFoundException("No such organization '" + this._organisation.getDisplayName()
                    + "' with oid: '" + this._organisation.getOIDs() + "'.");
        }

        if (this.isPrivilegesUpdate()) {
            Set<PrivilegeEnum> removePrivileges = this.privilegeDiff(this._organisation.getPrivilegesSet(),
                    this._oldOrganisation.getPrivilegesSet());
            Set<PrivilegeEnum> addPrivileges = this.privilegeDiff(this._oldOrganisation.getPrivilegesSet(),
                    this._organisation.getPrivilegesSet());
            if (!removePrivileges.isEmpty() || !addPrivileges.isEmpty()) {
                vChange = true;
                for (PrivilegeEnum p : removePrivileges) {
                    ThreadSinglePrivilegeDelete threadSinglePrivilegeDelete = new ThreadSinglePrivilegeDelete(p,
                            this._organisation, this._performer);
                    threadSinglePrivilegeDelete.call();
                }
                for (PrivilegeEnum p : addPrivileges) {
                    ThreadSinglePrivilegeCreate threadSinglePrivilegeCreate = new ThreadSinglePrivilegeCreate(p,
                            this._organisation, this._performer);
                    threadSinglePrivilegeCreate.call();
                }
            }
        }

        Attributes orgAttributes = new BasicAttributes(true);
        Attributes orgRemoveAttributes = new BasicAttributes(true);

        if (vChange = this.convertOrganizationToLdapOrgAttrsForUpdate(this._organisation, this._oldOrganisation,
                orgAttributes, orgRemoveAttributes, getPerformer())) {

            // -- If any changes, the status is set to 'revised'
            //    but not if status will be explicitly changed or by a update operation on Licenses directory
            if (!isChangeOfStatus() && !isUpdatingOfLicensedOrgs()) {
                if ((ConstEnumOrgStatus.approved.equals(this._organisation.getStatus()))) {
                    // -- ...then go retrospectively into "revised" status:
                    this._organisation.setStatus(ConstEnumOrgStatus.revised);

                    orgAttributes.put(Constants.ldap_ddbOrg_Status,
                            String.valueOf(this._organisation.getStatus().name()));
                }
            }
        }
        // ---------------------------------------------------------------------
        if (vChange) {

            // -- Save changes to the corresponding directory:
            StringBuilder vOrgEntryDN = (isUpdatingOfLicensedOrgs()
                    ? this.getLicensedOrgsDN(this._organisation.getOIDs())
                    : this.getOrgDN(this._organisation.getOIDs()));
            LOG.log(Level.INFO, "DEBUG-Info: destination OrgEntryDN = '" + vOrgEntryDN + "'");

            vCtx = LDAPConnector.getSingletonInstance().takeCtx();
            if (orgRemoveAttributes.size() > 0) {
                vCtx.modifyAttributes(vOrgEntryDN.toString(), DirContext.REMOVE_ATTRIBUTE, orgRemoveAttributes);
            }
            vCtx.modifyAttributes(vOrgEntryDN.toString(), DirContext.REPLACE_ATTRIBUTE, orgAttributes);
        } else {
            throw new AttributeModificationException(
                    "Not modified: oid = '" + this._organisation.getOIDs() + "'");
        }

    } catch (RejectedExecutionException ex) {
        LOG.log(Level.SEVERE, "RejectedExecutionException\n{0}", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error\n{0}", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NameNotFoundException ex) {
        LOG.log(Level.WARNING, null, ex);
        throw ex;
    } catch (AttributeModificationException ex) {
        LOG.log(Level.WARNING, "AttributeModificationException\n{0}", ex.getMessage());
        // !!!!AttributeModificationException extends NamingExeption:
        //throw ex;
        throw new AttributeModificationException(ex.getMessage());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "NamingException\n{0}", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (vCtx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(vCtx);
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "Exception", ex);
            }
        }
    }

}

From source file:net.spfbl.core.Reverse.java

public static ArrayList<String> getMXSet(String host) throws NamingException {
    TreeMap<Integer, TreeSet<String>> mxMap = new TreeMap<Integer, TreeSet<String>>();
    Attributes atributes = Server.getAttributesDNS(host, new String[] { "MX" });
    if (atributes == null || atributes.size() == 0) {
        atributes = Server.getAttributesDNS(host, new String[] { "CNAME" });
        Attribute attribute = atributes.get("CNAME");
        if (attribute != null) {
            String cname = (String) attribute.get(0);
            return getMXSet(cname);
        }//from   w  w w  . j a  v  a 2s .co m
    } else {
        Attribute attribute = atributes.get("MX");
        if (attribute != null) {
            for (int index = 0; index < attribute.size(); index++) {
                try {
                    String mx = (String) attribute.get(index);
                    int space = mx.indexOf(' ');
                    String value = mx.substring(0, space);
                    int priority = Integer.parseInt(value);
                    mx = mx.substring(space + 1);
                    int last = mx.length() - 1;
                    TreeSet<String> mxSet = mxMap.get(priority);
                    if (mxSet == null) {
                        mxSet = new TreeSet<String>();
                        mxMap.put(priority, mxSet);
                    }
                    if (Subnet.isValidIP(mx.substring(0, last))) {
                        mxSet.add(Subnet.normalizeIP(mx.substring(0, last)));
                    } else if (Domain.isHostname(mx)) {
                        mxSet.add(Domain.normalizeHostname(mx, true));
                    }
                } catch (NumberFormatException ex) {
                }
            }
        }
    }
    ArrayList<String> mxList = new ArrayList<String>();
    if (mxMap.isEmpty()) {
        // https://tools.ietf.org/html/rfc5321#section-5
        mxList.add(Domain.normalizeHostname(host, true));
    } else {
        for (int priority : mxMap.keySet()) {
            TreeSet<String> mxSet = mxMap.get(priority);
            for (String mx : mxSet) {
                if (!mxList.contains(mx)) {
                    mxList.add(mx);
                }
            }
        }
    }
    return mxList;
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

private void writeSearchResult(final SearchResult sr, final XMLBuffer xmlb) throws NamingException {
    final Attributes attrs = sr.getAttributes();
    final int size = attrs.size();
    final ArrayList<Attribute> sortedAttrs = new ArrayList<>(size);

    xmlb.openTag("searchresult"); // $NON-NLS-1$
    xmlb.tag("dn", sr.getName()); // $NON-NLS-1$
    xmlb.tag("returnedattr", Integer.toString(size)); // $NON-NLS-1$
    xmlb.openTag("attributes"); // $NON-NLS-1$

    try {//w  w  w .j  av  a 2 s.com
        for (NamingEnumeration<? extends Attribute> en = attrs.getAll(); en.hasMore();) {
            final Attribute attr = en.next();
            sortedAttrs.add(attr);
        }
        sortAttributes(sortedAttrs);
        for (final Attribute attr : sortedAttrs) {
            StringBuilder sb = new StringBuilder();
            if (attr.size() == 1) {
                sb.append(getWriteValue(attr.get()));
            } else {
                final ArrayList<String> sortedVals = new ArrayList<>(attr.size());
                boolean first = true;

                for (NamingEnumeration<?> ven = attr.getAll(); ven.hasMore();) {
                    final Object value = getWriteValue(ven.next());
                    sortedVals.add(value.toString());
                }

                Collections.sort(sortedVals);

                for (final String value : sortedVals) {
                    if (first) {
                        first = false;
                    } else {
                        sb.append(", "); // $NON-NLS-1$
                    }
                    sb.append(value);
                }
            }
            xmlb.tag(attr.getID(), sb);
        }
    } finally {
        xmlb.closeTag("attributes"); // $NON-NLS-1$
        xmlb.closeTag("searchresult"); // $NON-NLS-1$
    }
}

From source file:org.apache.nifi.processors.enrich.QueryDNS.java

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    if (!initialized.get()) {
        initializeResolver(context);/*from  w ww . ja  v  a 2 s  .c o  m*/
        getLogger().warn("Resolver was initialized at onTrigger instead of onScheduled");

    }

    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final String queryType = context.getProperty(DNS_QUERY_TYPE).getValue();
    final String queryInput = context.getProperty(QUERY_INPUT).evaluateAttributeExpressions(flowFile)
            .getValue();
    final String queryParser = context.getProperty(QUERY_PARSER).getValue();
    final String queryRegex = context.getProperty(QUERY_PARSER_INPUT).getValue();

    boolean found = false;
    try {
        Attributes results = doLookup(queryInput, queryType);
        // NOERROR & NODATA seem to return empty Attributes handled bellow
        // but defaulting to not found in any case
        if (results.size() < 1) {
            found = false;
        } else {
            int recordNumber = 0;
            NamingEnumeration<?> dnsEntryIterator = results.get(queryType).getAll();

            while (dnsEntryIterator.hasMoreElements()) {
                String dnsRecord = dnsEntryIterator.next().toString();
                // While NXDOMAIN is being generated by doLookup catch

                if (dnsRecord != "NXDOMAIN") {
                    // Map<String, String> parsedResults = parseResponse(recordNumber, dnsRecord, queryParser, queryRegex, "dns");
                    Map<String, String> parsedResults = parseResponse(String.valueOf(recordNumber), dnsRecord,
                            queryParser, queryRegex, "dns");
                    flowFile = session.putAllAttributes(flowFile, parsedResults);
                    found = true;
                } else {
                    // Otherwise treat as not found
                    found = false;
                }

                // Increase the counter and iterate over next record....
                recordNumber++;
            }
        }
    } catch (NamingException e) {
        context.yield();
        throw new ProcessException(
                "Unexpected NamingException while processing records. Please review your configuration.", e);

    }

    // Finally prepare to send the data down the pipeline
    if (found) {
        // Sending the resulting flowfile (with attributes) to REL_FOUND
        session.transfer(flowFile, REL_FOUND);
    } else {
        // NXDOMAIN received, accepting the fate but forwarding
        // to REL_NOT_FOUND
        session.transfer(flowFile, REL_NOT_FOUND);
    }
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

@Override
public void doSyncSingleUser(Identity ident) {
    LdapContext ctx = bindSystem();
    if (ctx == null) {
        log.error("could not bind to ldap", null);
    }/*from  w w  w .  j  a v  a2  s .co  m*/
    String userDN = ldapDao.searchUserDN(ident.getName(), ctx);

    final List<Attributes> ldapUserList = new ArrayList<Attributes>();
    // TODO: use userDN instead of filter to get users attribs
    ldapDao.searchInLdap(new LDAPVisitor() {
        @Override
        public void visit(SearchResult result) {
            Attributes resAttribs = result.getAttributes();
            log.debug("        found : " + resAttribs.size() + " attributes in result " + result.getName());
            ldapUserList.add(resAttribs);
        }
    }, userDN, syncConfiguration.getUserAttributes(), ctx);

    Attributes attrs = ldapUserList.get(0);
    Map<String, String> olatProToSync = prepareUserPropertyForSync(attrs, ident);
    if (olatProToSync != null) {
        syncUser(olatProToSync, ident);
    }
}

From source file:org.springframework.security.ldap.authentication.BindAuthenticator.java

private DirContextOperations bindWithDn(String userDnStr, String username, String password, Attributes attrs) {
    BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource();
    DistinguishedName userDn = new DistinguishedName(userDnStr);
    DistinguishedName fullDn = new DistinguishedName(userDn);
    fullDn.prepend(ctxSource.getBaseLdapPath());

    logger.debug("Attempting to bind as " + fullDn);

    DirContext ctx = null;/*from   w ww  . java2s.  c o m*/
    try {
        ctx = getContextSource().getContext(fullDn.toString(), password);
        // Check for password policy control
        PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx);

        logger.debug("Retrieving attributes...");
        if (attrs == null || attrs.size() == 0) {
            attrs = ctx.getAttributes(userDn, getUserAttributes());
        }

        DirContextAdapter result = new DirContextAdapter(attrs, userDn, ctxSource.getBaseLdapPath());

        if (ppolicy != null) {
            result.setAttributeValue(ppolicy.getID(), ppolicy);
        }

        return result;
    } catch (NamingException e) {
        // This will be thrown if an invalid user name is used and the method may
        // be called multiple times to try different names, so we trap the exception
        // unless a subclass wishes to implement more specialized behaviour.
        if ((e instanceof org.springframework.ldap.AuthenticationException)
                || (e instanceof org.springframework.ldap.OperationNotSupportedException)) {
            handleBindException(userDnStr, username, e);
        } else {
            throw e;
        }
    } catch (javax.naming.NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        LdapUtils.closeContext(ctx);
    }

    return null;
}