Example usage for javax.naming.ldap LdapName LdapName

List of usage examples for javax.naming.ldap LdapName LdapName

Introduction

In this page you can find the example usage for javax.naming.ldap LdapName LdapName.

Prototype

public LdapName(List<Rdn> rdns) 

Source Link

Document

Constructs an LDAP name given its parsed RDN components.

Usage

From source file:nu.yona.server.subscriptions.rest.UserController.java

@PostConstruct
private void setSslRootCertificateCn() // YD-544
{
    try {/* w  w  w.j  a  va  2s. co m*/
        LdapName name = new LdapName(sslRootCertificate.getIssuerX500Principal().getName());
        UserResource.setSslRootCertificateCn(name.getRdn(0).getValue().toString());
    } catch (InvalidNameException e) {
        throw YonaException.unexpected(e);
    }
}

From source file:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions.java

public String determineLdapSingleAttributeValue(String dn, String attributeName, Collection<?> values)
        throws NamingException {
    if (values == null || values.isEmpty()) {
        return null;
    }/*from  w w  w.  j  a  v  a 2 s  . co m*/

    Collection<String> stringValues = null;
    // Determine item type, try to convert to strings
    Object firstElement = values.iterator().next();
    if (firstElement instanceof String) {
        stringValues = (Collection) values;
    } else if (firstElement instanceof Element) {
        stringValues = new ArrayList<String>(values.size());
        for (Object value : values) {
            Element element = (Element) value;
            stringValues.add(element.getTextContent());
        }
    } else {
        throw new IllegalArgumentException("Unexpected value type " + firstElement.getClass());
    }

    if (stringValues.size() == 1) {
        return stringValues.iterator().next();
    }

    if (StringUtils.isBlank(dn)) {
        throw new IllegalArgumentException(
                "No dn argument specified, cannot determine which of " + values.size() + " values to use");
    }

    LdapName parsedDn = new LdapName(dn);
    for (int i = 0; i < parsedDn.size(); i++) {
        Rdn rdn = parsedDn.getRdn(i);
        Attributes rdnAttributes = rdn.toAttributes();
        NamingEnumeration<String> rdnIDs = rdnAttributes.getIDs();
        while (rdnIDs.hasMore()) {
            String rdnID = rdnIDs.next();
            Attribute attribute = rdnAttributes.get(rdnID);
            if (attributeName.equals(attribute.getID())) {
                for (int j = 0; j < attribute.size(); j++) {
                    Object value = attribute.get(j);
                    if (stringValues.contains(value)) {
                        return (String) value;
                    }
                }
            }
        }
    }

    // Fallback. No values in DN. Just return the first alphabetically-wise value.
    return Collections.min(stringValues);
}

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * X509??.//from   w w  w . ja v  a2s .  co  m
 * @param privateKeyFileName ???
 * @param certificateFileName ??
 * @param rootCertificateFileNames ??
 * @throws IOException IOException
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws CertificateException CertificateException
 * @throws InvalidNameException InvalidNameException
 */
public static void configureX509(String privateKeyFileName, String certificateFileName,
        String[] rootCertificateFileNames) throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException, CertificateException, InvalidNameException {

    xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    // Read RootCA Certificate
    x509RootCertificateFileNames = new ArrayList<String>();
    if (rootCertificateFileNames != null) {
        for (String fileName : rootCertificateFileNames) {
            x509RootCertificateFileNames.add(fileName);
        }
    }

    // Read Private Key
    InputStream is = null;
    if (privateKeyFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH);
    } else {
        is = new FileInputStream(privateKeyFileName);
    }

    PEMReader privateKeyPemReader = new PEMReader(is);
    byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes();
    PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec());

    // Read Certificate
    if (certificateFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH);
    } else {
        is = new FileInputStream(certificateFileName);
    }
    PEMReader serverCertificatePemReader;
    serverCertificatePemReader = new PEMReader(is);
    byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes();
    CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE);
    x509Certificate = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert));

    // Create the KeyInfo containing the X509Data
    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    List x509Content = new ArrayList();
    x509Content.add(x509Certificate.getSubjectX500Principal().getName());
    x509Content.add(x509Certificate);
    X509Data xd = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd));

    // Get FQDN from Certificate and set FQDN to PersoniumCoreUtils
    String dn = x509Certificate.getSubjectX500Principal().getName();
    LdapName ln = new LdapName(dn);
    for (Rdn rdn : ln.getRdns()) {
        if (rdn.getType().equalsIgnoreCase("CN")) {
            PersoniumCoreUtils.setFQDN(rdn.getValue().toString());
            break;
        }
    }

    // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/

}

From source file:ldap.LdapApi.java

/**
* getSearcher() returns the handle for searcher in ldap
*//*from w ww  . j  a v a  2s  .  co  m*/
private SearchUtility getSearcher(String searchDn) throws LdapException {

    try {
        searchBase = new LdapName(searchDn);
        SearchUtility searcher = new SearchUtility(
                Arrays.asList("username", "section", "division", "group", "area", "company"), false);
        return searcher;
    } catch (Exception e) {
        throw new LdapException("new LdapName(searchDn) or new SearchUtility() exception" + e.getMessage(), e);
    }

    /*
            userList.add(searcher.convertUserEntriesToStrings(users, Config.USER_MAIL_ATT);
            groups = searcher.convertUserEntriesToStrings(users, Config.USER_GROUP_ATT);
            userNames = searcher.convertUserEntriesToStrings(users);
       usersList.add(userNames);
    */
}

From source file:hu.sztaki.lpds.pgportal.portlets.credential.AssertionPortlet.java

private List<String> getResourceList(ActionRequest request, String DN) throws InvalidNameException {
    @SuppressWarnings("unchecked")
    List<Middleware> pResources = (List<Middleware>) request.getPortletSession().getAttribute("resources",
            request.getPortletSession().APPLICATION_SCOPE);

    List<String> Names = new Vector<String>();
    boolean flag = false;

    LdapName name = new LdapName(DN);
    System.out.println("Comparing LDAP name " + name.toString());

    for (Middleware t : pResources) {
        flag = false;//w  w  w  .j  a va  2 s  .  c o  m

        if (t.isEnabled()) {
            for (Certificate c : t.getCertificate()) {
                if (Certificate.SAML.equals(c)) {
                    flag = true;
                }
            }
        }

        if (flag) {
            for (Item i : t.getItem()) {
                Unicore uni = i.getUnicore();
                if (t.isEnabled()) {
                    try {
                        LdapName subject = new LdapName(uni.getSubjectdn());

                        System.out.println("Checking DN: " + uni.getSubjectdn() + "?");
                        System.out.println("Subject: " + subject.toString());
                        if (name.equals(subject)) {
                            Names.add(i.getName());
                        }
                    } catch (InvalidNameException e) {
                        logger.warn("Internal error: Reported certificate from service invalid", uni);
                        logger.warn("Reported DN: " + uni.getSubjectdn());
                        logger.trace("Stack trace:", e);
                    }

                    // System.out.println("uni-alias" + uni.getKeyalias());
                }
            }
        }
    }
    return Names;
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

/**
 * Works around a bug in the JDK DN parsing. If an RDN has trailing escaped whitespace in the format "\\20" then
 * LdapName would normally strip this. This method works around this by replacing "\\20" with "\\ " and "\\0D" with
 * "\\\r".//from w w w  . j a  va2s  .  co  m
 *
 * @param dn
 *            the DN
 * @return the parsed ldap name
 * @throws InvalidNameException
 *             if the DN is invalid
 */
protected static LdapName fixedLdapName(final String dn) throws InvalidNameException {
    // Optimization for DNs without escapes in them
    if (dn.indexOf('\\') == -1) {
        return new LdapName(dn);
    }

    final StringBuilder fixed = new StringBuilder(dn.length());
    final int length = dn.length();
    for (int i = 0; i < length; i++) {
        final char c = dn.charAt(i);
        char c1, c2;
        if (c == '\\') {
            if (i + 2 < length && Character.isLetterOrDigit(c1 = dn.charAt(i + 1))
                    && Character.isLetterOrDigit(c2 = dn.charAt(i + 2))) {
                if (c1 == '2' && c2 == '0') {
                    fixed.append("\\ ");
                } else if (c1 == '0' && c2 == 'D') {
                    fixed.append("\\\r");
                } else {
                    fixed.append(dn, i, i + 3);
                }
                i += 2;
            } else if (i + 1 < length) {
                fixed.append(dn, i, i + 2);
                i += 1;
            } else {
                fixed.append(c);
            }
        } else {
            fixed.append(c);
        }
    }
    return new LdapName(fixed.toString());
}

From source file:com.evolveum.midpoint.testing.model.client.sample.TestExchangeConnector.java

private String distributionGroupOU() throws InvalidNameException {
    LdapName container = new LdapName(getContainer());
    List<String> ous = new ArrayList<>();
    List<String> dcs = new ArrayList<>();
    String retval = "";
    for (Rdn rdn : container.getRdns()) {
        if (rdn.getType().equalsIgnoreCase("OU")) {
            ous.add(rdn.getValue().toString());
        } else if (rdn.getType().equalsIgnoreCase("DC")) {
            dcs.add(rdn.getValue().toString());
        }/*w  w  w. j a  va 2 s .c o  m*/
    }
    for (int i = dcs.size() - 1; i >= 0; i--) {
        if (!retval.isEmpty()) {
            retval += ".";
        }
        retval += dcs.get(i);
    }
    for (int i = 0; i < ous.size(); i++) {
        retval += "/" + ous.get(i);
    }
    return retval;
}

From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java

/**
 * Performs recursive group membership lookup.
 *
 * This was how we did the lookup traditionally until we discovered 1.2.840.113556.1.4.1941.
 * But various people reported that it slows down the execution tremendously to the point that it is unusable,
 * while others seem to report that it runs faster than recursive search (http://social.technet.microsoft.com/Forums/fr-FR/f238d2b0-a1d7-48e8-8a60-542e7ccfa2e8/recursive-retrieval-of-all-ad-group-memberships-of-a-user?forum=ITCG)
 *
 * This implementation is kept for Windows 2003 that doesn't support 1.2.840.113556.1.4.1941, but it can be also
 * enabled for those who are seeing the performance problem.
 *
 * See JENKINS-22830//from  w w w .jav a  2s . c o m
 */
private void recursiveGroupLookup(DirContext context, Attributes id, Set<GrantedAuthority> groups)
        throws NamingException {
    Stack<Attributes> q = new Stack<Attributes>();
    q.push(id);
    while (!q.isEmpty()) {
        Attributes identity = q.pop();
        LOGGER.finer("Looking up group of " + identity);

        Attribute memberOf = identity.get("memberOf");
        if (memberOf == null)
            continue;

        for (int i = 0; i < memberOf.size(); i++) {
            try {
                LOGGER.log(Level.FINE, "Trying to get the CN of {0}", memberOf.get(i));
                Attributes group = context.getAttributes(new LdapName(memberOf.get(i).toString()),
                        new String[] { "CN", "memberOf" });
                Attribute cn = group.get("CN");
                if (cn == null) {
                    LOGGER.fine("Failed to obtain CN of " + memberOf.get(i));
                    continue;
                }
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine(cn.get() + " is a member of " + memberOf.get(i));

                if (groups.add(new GrantedAuthorityImpl(cn.get().toString()))) {
                    q.add(group); // recursively look for groups that this group is a member of.
                }
            } catch (NameNotFoundException e) {
                LOGGER.fine("Failed to obtain CN of " + memberOf.get(i));
            }
        }
    }
}

From source file:controller.CCInstance.java

public String getCertificateProperty(X500Name x500name, String property) {
    String cn = "";
    LdapName ldapDN = null;//from  w  ww  .jav a  2  s .  co m
    try {
        ldapDN = new LdapName(x500name.toString());
    } catch (InvalidNameException ex) {
        java.util.logging.Logger.getLogger(MultipleValidationDialog.class.getName()).log(Level.SEVERE, null,
                ex);
    }
    for (Rdn rdn : ldapDN.getRdns()) {
        if (rdn.getType().equals(property)) {
            cn = rdn.getValue().toString();
        }
    }
    return cn;
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/** {@inheritDoc} */
public Set<PSOIdentifier> orderForDeletion(final Set<PSOIdentifier> psoIdentifiers) throws PspException {

    // tree map keys are in ascending order, this will need to be reversed
    Map<LdapName, PSOIdentifier> map = new TreeMap<LdapName, PSOIdentifier>();

    try {//from  w  ww  . j a v  a  2  s .  c o  m
        for (PSOIdentifier psoIdentifier : psoIdentifiers) {
            LdapName ldapName = new LdapName(psoIdentifier.getID());
            map.put(ldapName, psoIdentifier);
        }
    } catch (InvalidNameException e) {
        LOG.error("An error occurred ordering the PSO identifiers.", e);
        throw new PspException(e);
    }

    // linked hash set to preserver insertion order
    Set<PSOIdentifier> psoIdsOrderedForDeletion = new LinkedHashSet<PSOIdentifier>();

    ArrayList<LdapName> ldapNames = new ArrayList<LdapName>(map.keySet());

    // reverse the order of the keys, suitable for deletion
    Collections.reverse(ldapNames);

    for (LdapName ldapName : ldapNames) {
        psoIdsOrderedForDeletion.add(map.get(ldapName));
    }

    if (LOG.isTraceEnabled()) {
        for (PSOIdentifier psoId : psoIdsOrderedForDeletion) {
            LOG.trace("correct pso id '{}'", PSPUtil.toString(psoId));
        }
    }

    return psoIdsOrderedForDeletion;
}