Example usage for javax.naming.directory Attributes get

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

Introduction

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

Prototype

Attribute get(String attrID);

Source Link

Document

Retrieves the attribute with the given attribute id from the attribute set.

Usage

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);/* w w  w . j a 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.kitodo.production.services.data.LdapServerService.java

private URI getUserHomeDirectoryWithTLS(Hashtable<String, String> env, String userFolderBasePath, User user) {
    env.put("java.naming.ldap.version", "3");
    LdapContext ctx = null;// w ww.  jav a 2  s.c o m
    StartTlsResponse tls = null;
    try {
        ctx = new InitialLdapContext(env, null);

        // Authentication must be performed over a secure channel
        tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        tls.negotiate();

        ctx.reconnect(null);

        Attributes attrs = ctx.getAttributes(buildUserDN(user));
        Attribute la = attrs.get("homeDirectory");
        return URI.create((String) la.get(0));
    } catch (IOException e) {
        logger.error("TLS negotiation error:", e);
        return Paths.get(userFolderBasePath, user.getLogin()).toUri();
    } catch (NamingException e) {
        logger.error("JNDI error:", e);
        return Paths.get(userFolderBasePath, user.getLogin()).toUri();
    } finally {
        closeConnections(ctx, tls);
    }
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private String getAttribute(Attributes attrs, String name) throws NamingException {
    if (name == null)
        return null;

    Attribute attr = attrs.get(name);
    if (attr != null) {
        try {//from w ww  . j ava 2  s.  c om
            return (String) attr.get(0);
        } catch (ArrayIndexOutOfBoundsException ex) {
        }
    }

    return null;
}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Get next free uidNumber./*  ww w.j a v  a  2 s .com*/
 *
 * @return next free uidNumber
 */
private String getNextUidNumber(LdapServer ldapServer) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(ldapServer);
    DirContext ctx;
    String rueckgabe = "";
    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes attrs = ctx.getAttributes(ldapServer.getNextFreeUnixIdPattern());
        Attribute la = attrs.get("uidNumber");
        rueckgabe = (String) la.get(0);
        ctx.close();
    } catch (NamingException e) {
        Helper.setErrorMessage(e.getMessage(), logger, e);
    }
    return rueckgabe;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Gets a personBean from LDAP//from  ww w  .  j a v a 2 s  . c o  m
 * 
 * @param searchResult
 * @param loginAttributeName
 * @param firstNameAttributeName
 * @param lastNameAttributName
 * @param emailAttributeName
 * @param phoneAttributName
 * @return
 */
public static TPersonBean getPersonBean(SearchResult searchResult, String loginAttributeName,
        String firstNameAttributeName, String lastNameAttributName, String emailAttributeName,
        String phoneAttributName) {
    Attributes attributes = searchResult.getAttributes();
    if (attributes == null) {
        LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName());
        return null;
    }
    TPersonBean personBean = new TPersonBean();
    try {
        Attribute loginAttribute = attributes.get(loginAttributeName);
        if (loginAttribute != null) {
            String loginName = (String) loginAttribute.get();
            LOGGER.debug("Loginname: " + loginName);
            if (loginName == null || "".equals(loginName)) {
                LOGGER.info("No value for loginame attribute " + loginAttributeName);
                return null;
            } else {
                // loginname is mandatory for person
                personBean.setLoginName(loginName);
            }
        } else {
            LOGGER.info("No loginame attribute " + loginAttributeName);
            return null;
        }
        Attribute emailAttribute = attributes.get(emailAttributeName);
        if (emailAttribute != null) {
            String email = (String) emailAttribute.get();
            LOGGER.debug("E-mail: " + email);
            if (email == null || "".equals(email)) {
                LOGGER.info("No value for e-mail attribute " + emailAttributeName);
                // e-mail is mandatory for person
                return null;
            } else {
                personBean.setEmail(email);
            }
        } else {
            LOGGER.info("No e-mail attribute " + emailAttributeName);
            return null;
        }
        Attribute firstNameAttribute = attributes.get(firstNameAttributeName);
        if (firstNameAttribute != null) {
            String firstName = (String) firstNameAttribute.get();
            LOGGER.debug("Firstname: " + firstName);
            personBean.setFirstName(firstName);
        }
        Attribute lastNameAttribute = attributes.get(lastNameAttributName);
        if (lastNameAttribute != null) {
            String lastName = (String) lastNameAttribute.get();
            LOGGER.debug("Lastname: " + lastName);
            if (lastName == null || "".equals(lastName)) {
                LOGGER.info("No value for lastname attribute " + lastNameAttributName);
                // lastname is mandatory for person
                return null;
            } else {
                personBean.setLastName(lastName);
            }
        }
        if (phoneAttributName != null) {
            Attribute phoneAttribute = attributes.get(phoneAttributName);
            if (phoneAttribute != null) {
                String phone = (String) phoneAttribute.get();
                LOGGER.debug("Phone: " + phone);
                personBean.setPhone(phone);
            }
        }
        LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get());
        LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName() + " "
                + personBean.getLastName() + ")");
    } catch (Exception e) {
        LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage());
        LOGGER.warn("This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml");
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    return personBean;
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * Get next free uidNumber.//w  w w .j  av a  2s .  co m
 *
 * @return next free uidNumber
 */
private String getNextUidNumber() {
    Hashtable<String, String> env = getLdapConnectionSettings();
    env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
    env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));
    DirContext ctx;
    String rueckgabe = "";
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId"));
        Attribute la = attrs.get("uidNumber");
        rueckgabe = (String) la.get(0);
        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
        Helper.setFehlerMeldung(e.getMessage());
    }
    return rueckgabe;
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * /*from  w  ww  .j av a 2 s  .c  om*/
 * @param attributes1
 * @return subject
 */
private Subject createSubject(Attributes attributes1) {
    String name1 = "";
    String subjectID = "";
    String description = "";
    try {
        Attribute attribute = attributes1.get(this.subjectIDAttributeName);
        if (attribute == null) {
            log.error("The LDAP attribute \"" + this.subjectIDAttributeName
                    + "\" does not have a value. It is beging used as the Grouper special attribute \"SubjectID\".");
            return null;
        }
        subjectID = (String) attribute.get();
        attribute = attributes1.get(this.nameAttributeName);
        if (attribute == null) {
            log.error("The LDAP attribute \"" + this.nameAttributeName
                    + "\" does not have a value. It is being used as the Grouper special attribute \"name\".");
            return null;
        }
        name1 = (String) attribute.get();
        attribute = attributes1.get(this.descriptionAttributeName);
        if (attribute == null) {
            log.error("The LDAP attribute \"" + this.descriptionAttributeName
                    + "\" does not have a value. It is being used as the Grouper special attribute \"description\".");
        } else {
            description = (String) attribute.get();
        }
    } catch (NamingException ex) {
        log.error("LDAP Naming Except: " + ex.getMessage(), ex);
    }

    return new JNDISubject(subjectID, name1, description, this.getSubjectType().getName(), this.getId(), null);
}

From source file:LDAPTest.java

/**
     * Saves the changes that the user made.
     *///from w w  w.  j  a  v a  2  s.  c  om
    public void saveEntry() {
        try {
            if (dataPanel == null)
                return;
            if (context == null)
                context = getContext();
            if (uidField.getText().equals(uid)) // update existing entry
            {
                String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com";
                Attributes editedAttrs = dataPanel.getEditedAttributes();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute attr = attrEnum.next();
                    String id = attr.getID();
                    Attribute editedAttr = editedAttrs.get(id);
                    if (editedAttr != null && !attr.get().equals(editedAttr.get()))
                        context.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE,
                                new BasicAttributes(id, editedAttr.get()));
                }
            } else
            // create new entry
            {
                String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com";
                attrs = dataPanel.getEditedAttributes();
                Attribute objclass = new BasicAttribute("objectClass");
                objclass.add("uidObject");
                objclass.add("person");
                attrs.put(objclass);
                attrs.put("uid", uidField.getText());
                context.createSubcontext(dn, attrs);
            }

            findEntry();
        } catch (NamingException e) {
            JOptionPane.showMessageDialog(LDAPFrame.this, e);
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(LDAPFrame.this, e);
            e.printStackTrace();
        }
    }

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Set next free uidNumber.// www.j a va2  s  .  c o m
 */
private void setNextUidNumber(LdapServer ldapServer) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(ldapServer);
    DirContext ctx;

    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes attrs = ctx.getAttributes(ldapServer.getNextFreeUnixIdPattern());
        Attribute la = attrs.get("uidNumber");
        String oldValue = (String) la.get(0);
        int bla = Integer.parseInt(oldValue) + 1;

        BasicAttribute attrNeu = new BasicAttribute("uidNumber", String.valueOf(bla));
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attrNeu);
        ctx.modifyAttributes(ldapServer.getNextFreeUnixIdPattern(), mods);

        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * Set next free uidNumber./*from   w  w  w  .  j  av a  2  s . c om*/
 */
private void setNextUidNumber() {
    Hashtable<String, String> env = getLdapConnectionSettings();
    env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
    env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));
    DirContext ctx;

    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId"));
        Attribute la = attrs.get("uidNumber");
        String oldValue = (String) la.get(0);
        int bla = Integer.parseInt(oldValue) + 1;

        BasicAttribute attrNeu = new BasicAttribute("uidNumber", String.valueOf(bla));
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attrNeu);
        ctx.modifyAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId"), mods);

        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }

}