Example usage for javax.naming.directory DirContext getAttributes

List of usage examples for javax.naming.directory DirContext getAttributes

Introduction

In this page you can find the example usage for javax.naming.directory DirContext getAttributes.

Prototype

public Attributes getAttributes(String name) throws NamingException;

Source Link

Document

Retrieves all of the attributes associated with a named object.

Usage

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 w  w  . j  a v  a 2s  .  co  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;
        }
    };
}

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

/**
 * Set next free uidNumber./*w w  w. j  a v a2s .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);
    }

}

From source file:hudson.security.LDAPSecurityRealm.java

/**
 * Infer the root DN./*from   w ww. j  a v  a  2 s.com*/
 *
 * @return null if not found.
 */
private String inferRootDN(String server) {
    try {
        Hashtable<String, String> props = new Hashtable<String, String>();
        if (managerDN != null) {
            props.put(Context.SECURITY_PRINCIPAL, managerDN);
            props.put(Context.SECURITY_CREDENTIALS, getManagerPassword());
        }
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, getServerUrl() + '/');

        DirContext ctx = new InitialDirContext(props);
        Attributes atts = ctx.getAttributes("");
        Attribute a = atts.get("defaultNamingContext");
        if (a != null) // this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx
            return a.toString();

        a = atts.get("namingcontexts");
        if (a == null) {
            LOGGER.warning("namingcontexts attribute not found in root DSE of " + server);
            return null;
        }
        return a.get().toString();
    } catch (NamingException e) {
        LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e);
        return null;
    }
}

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

/**
 * Get next free uidNumber.//w w w.ja  v a2  s.  c  o 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:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

/**
 * This method retrieves data using LDAP protocol.
 * - CRL from given LDAP url, e.g. ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com
 *
 * @param urlString//from   w  ww  .j a v a  2s .c o m
 * @return
 */
private byte[] ldapGet(final String urlString) {

    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, urlString);
    try {

        final DirContext ctx = new InitialDirContext(env);
        final Attributes attributes = ctx.getAttributes("");
        final javax.naming.directory.Attribute attribute = attributes.get("certificateRevocationList;binary");
        final byte[] ldapBytes = (byte[]) attribute.get();
        if (ldapBytes == null || ldapBytes.length == 0) {
            throw new DSSException("Cannot download CRL from: " + urlString);
        }
        return ldapBytes;
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    return null;
}

From source file:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java

/**
 * This method retrieves data using LDAP protocol.
 * - CRL from given LDAP url, e.g. ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com
 * - ex URL from AIA ldap://xadessrv.plugtests.net/CN=LevelBCAOK,OU=Plugtests_2015-2016,O=ETSI,C=FR?cACertificate;binary
 *
 * @param urlString//from  ww w .jav a2s  . c o m
 * @return
 */
private byte[] ldapGet(final String urlString) {

    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, urlString);
    try {

        String attributeName = StringUtils.substringAfterLast(urlString, "?");
        if (StringUtils.isEmpty(attributeName)) {
            // default was CRL
            attributeName = "certificateRevocationList;binary";
        }

        final DirContext ctx = new InitialDirContext(env);
        final Attributes attributes = ctx.getAttributes(StringUtils.EMPTY);
        final Attribute attribute = attributes.get(attributeName);
        final byte[] ldapBytes = (byte[]) attribute.get();
        if (ArrayUtils.isEmpty(ldapBytes)) {
            throw new DSSException("Cannot download CRL from: " + urlString);
        }
        return ldapBytes;
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    return null;
}

From source file:CreateJavaSchema.java

private void printSchema(DirContext ctx, String[] ids) {
    for (int i = 0; i < ids.length; i++) {
        try {// w  w  w  . jav a2  s . c o  m
            System.out.print(ids[i] + ": ");
            System.out.print(ctx.getAttributes(ids[i]));
        } catch (NamingException e) {
        } finally {
            System.out.println();
        }
    }
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

private boolean getUserInf(UserEdit edit, String filter) {

    String id = null;/*ww w  .ja v a 2  s  . c om*/
    String firstName = null;
    String lastName = null;
    String employeenumber = null;
    String email = null;
    try {
        DirContext ctx = new InitialDirContext(env);

        // Setup subtree scope to tell LDAP to recursively descend directory structure
        // during searches.
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // We want the user's id, first name and last name ...
        searchControls.setReturningAttributes(new String[] { "uid", "givenName", "sn" });

        // Execute the search, starting at the directory level of Users
        NamingEnumeration results = ctx.search(getBasePath(), filter, searchControls);

        while (results.hasMore()) {
            SearchResult result = (SearchResult) results.next();
            String dn = result.getName().toString() + "," + getBasePath();
            Attributes attrs = ctx.getAttributes(dn);
            id = attrs.get("uid").get().toString();
            String cn = attrs.get("cn").get().toString();
            firstName = cn.substring(0, cn.indexOf(" "));
            lastName = cn.substring(cn.indexOf(" "));
            email = attrs.get("mail").get().toString();
        }

        results.close();
        ctx.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

    edit.setId(id);
    edit.setFirstName(firstName);
    edit.setLastName(lastName);
    edit.setEmail(email);
    return true;
}