Search in sources :

Example 86 with Attribute

use of javax.naming.directory.Attribute in project perun by CESNET.

the class ExtSourceEGISSO method processResultToSubject.

protected Map<String, String> processResultToSubject(SearchResult sr) throws InternalErrorException {
    if (sr == null)
        throw new InternalErrorException("SearchResult is empty so cannot be proceed.");
    Map<String, String> subject = new HashMap<>();
    try {
        NamingEnumeration<? extends Attribute> attributes = sr.getAttributes().getAll();
        while (attributes.hasMore()) {
            Attribute attr = attributes.next();
            String attrName = attr.toString().replaceAll(":.*", "");
            boolean found = false;
            for (String key : mapping.keySet()) {
                String value = mapping.get(key);
                if (value.equals(attrName) && key.equals("certificates")) {
                    NamingEnumeration<?> attrs = attr.getAll();
                    int counter = 1;
                    List<String> uniqueExtSources = new ArrayList<>();
                    while (attrs.hasMore()) {
                        byte[] cert = (byte[]) attrs.next();
                        Pair<String, String> additionalues = getCertficiateSubjectAndIssure(cert, counter);
                        //add to subject only if this extSource is unique
                        if (!uniqueExtSources.contains(additionalues.getRight())) {
                            uniqueExtSources.add(additionalues.getRight());
                            subject.put(additionalues.getLeft(), additionalues.getRight());
                            counter++;
                        }
                    }
                    break;
                } else if (value.equals(attrName)) {
                    //everything else has just 1 existence in LDAP for now
                    if (attr.size() > 1)
                        throw new InternalErrorException("Some attributes has more than 1 occurence and it is not attribute.");
                    String attrValue = ((String) attr.get()).replaceAll("^.*: ", "");
                    subject.put(key, attrValue);
                    break;
                }
            }
        }
    } catch (NamingException ex) {
        log.error("Problem when listing through search results from EGI SSO.");
        throw new InternalErrorException("Problem when listing through search results from EGI SSO", ex);
    }
    return subject;
}
Also used : HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) NamingException(javax.naming.NamingException)

Example 87 with Attribute

use of javax.naming.directory.Attribute in project perun by CESNET.

the class ExtSourceLdap method getLdapAttributeValue.

protected String getLdapAttributeValue(Attributes attributes, String ldapAttrNameRaw) throws InternalErrorException {
    String ldapAttrName;
    String rule = null;
    Matcher matcher = null;
    String attrValue = "";
    ;
    // Check if the ldapAttrName contains regex
    if (ldapAttrNameRaw.contains("|")) {
        int splitter = ldapAttrNameRaw.indexOf('|');
        ldapAttrName = ldapAttrNameRaw.substring(0, splitter);
        rule = ldapAttrNameRaw.substring(splitter + 1, ldapAttrNameRaw.length());
    } else {
        ldapAttrName = ldapAttrNameRaw;
    }
    // Check if the ldapAttrName contains specification of the value index
    int attributeValueIndex = -1;
    if (ldapAttrNameRaw.contains("[")) {
        Pattern indexPattern = Pattern.compile("^(.*)\\[([0-9]+)\\]$");
        Matcher indexMatcher = indexPattern.matcher(ldapAttrNameRaw);
        if (indexMatcher.find()) {
            ldapAttrName = indexMatcher.group(1);
            attributeValueIndex = Integer.parseInt(indexMatcher.group(2));
        } else {
            throw new InternalErrorException("Wrong attribute name format for attribute: " + ldapAttrNameRaw + ", it should be name[0-9+]");
        }
    }
    // Mapping to the LDAP attribute
    Attribute attr = attributes.get(ldapAttrName);
    if (attr != null) {
        // There could be more than one value in the attribute. Separator is defined in the AttributesManagerImpl
        for (int i = 0; i < attr.size(); i++) {
            if (attributeValueIndex != -1 && attributeValueIndex != i) {
                // We want only value on concrete index, so skip the other ones
                continue;
            }
            String tmpAttrValue = "";
            try {
                if (attr.get() instanceof byte[]) {
                    // It can be byte array with cert or binary file
                    char[] encodedValue = Base64Coder.encode((byte[]) attr.get());
                    tmpAttrValue = new String(encodedValue);
                } else {
                    tmpAttrValue = (String) attr.get(i);
                }
            } catch (NamingException e) {
                throw new InternalErrorException(e);
            }
            if (rule != null) {
                if (rule.contains("#")) {
                    // Rules are in place, so apply them
                    String regex = rule.substring(0, rule.indexOf('#'));
                    String replacement = rule.substring(rule.indexOf('#') + 1);
                    tmpAttrValue = tmpAttrValue.replaceAll(regex, replacement);
                //DEPRECATED way
                } else {
                    // Rules are in place, so apply them
                    Pattern pattern = Pattern.compile(rule);
                    matcher = pattern.matcher(tmpAttrValue);
                    // Get the first group which matched
                    if (matcher.matches()) {
                        tmpAttrValue = matcher.group(1);
                    }
                }
            }
            if (i == 0 || attributeValueIndex != -1) {
                // Do not add delimiter before first entry or if the particular index has been requested
                attrValue += tmpAttrValue;
            } else {
                attrValue += AttributesManagerImpl.LIST_DELIMITER + tmpAttrValue;
            }
        }
        if (attrValue.isEmpty()) {
            return "";
        } else {
            return attrValue;
        }
    } else {
        return "";
    }
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Attribute(javax.naming.directory.Attribute) NamingException(javax.naming.NamingException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException)

Example 88 with Attribute

use of javax.naming.directory.Attribute in project OpenAM by OpenRock.

the class Step4 method getLdapHostAndPort.

// Method to get hostname and port number with the
// provided Domain Name for Active Directory user data store.
private String[] getLdapHostAndPort(String domainName) throws NamingException, IOException {
    if (!domainName.endsWith(".")) {
        domainName += '.';
    }
    DirContext ictx = null;
    // The resource record type A is defined in RFC 1035. 
    try {
        Hashtable env = new Hashtable();
        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        ictx = new InitialDirContext(env);
        Attributes attributes = ictx.getAttributes(domainName, new String[] { "A" });
        Attribute attrib = attributes.get("A");
        if (attrib == null) {
            throw new NamingException();
        }
    } catch (NamingException e) {
        // throw exception.
        throw e;
    }
    // then look for the LDAP server
    String serverHostName = null;
    String serverPortStr = null;
    final String ldapServer = "_ldap._tcp." + domainName;
    try {
        // Attempting to resolve ldapServer to SRV record.
        // This is a mechanism defined in MSDN, querying 
        // SRV records for _ldap._tcp.DOMAINNAME.
        // and get host and port from domain.
        Attributes attributes = ictx.getAttributes(ldapServer, new String[] { "SRV" });
        Attribute attr = attributes.get("SRV");
        if (attr == null) {
            throw new NamingException();
        }
        String[] srv = attr.get().toString().split(" ");
        String hostNam = srv[3];
        serverHostName = hostNam.substring(0, hostNam.length() - 1);
        if ((serverHostName != null) && serverHostName.length() > 0) {
            getContext().setSessionAttribute(SessionAttributeNames.USER_STORE_HOST, serverHostName);
        }
        serverPortStr = srv[2];
    } catch (NamingException e) {
        // throw exception.
        throw e;
    }
    // try to connect to LDAP port to make sure this machine 
    // has LDAP service
    int serverPort = Integer.parseInt(serverPortStr);
    if ((serverPort > 0) && (serverPort < 65535)) {
        getContext().setSessionAttribute(SessionAttributeNames.USER_STORE_PORT, serverPortStr);
    }
    try {
        new Socket(serverHostName, serverPort).close();
    } catch (IOException e) {
        throw e;
    }
    String[] hostAndPort = new String[2];
    hostAndPort[0] = serverHostName;
    hostAndPort[1] = serverPortStr;
    return hostAndPort;
}
Also used : Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) Attributes(javax.naming.directory.Attributes) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext) IOException(java.io.IOException) Socket(java.net.Socket)

Example 89 with Attribute

use of javax.naming.directory.Attribute in project OpenAM by OpenRock.

the class SMSJAXRPCObject method toMods.

// Converts ModificationItem to String
static String toMods(ModificationItem[] mods) throws SMSException {
    if (mods == null)
        return (null);
    StringBuilder sb = new StringBuilder(100);
    sb.append("<Modifications size=\"");
    sb.append(mods.length);
    sb.append("\">");
    for (int i = 0; i < mods.length; i++) {
        sb.append("<AttributeValuePair event=\"");
        switch(mods[i].getModificationOp()) {
            case DirContext.ADD_ATTRIBUTE:
                sb.append("ADD");
                break;
            case DirContext.REPLACE_ATTRIBUTE:
                sb.append("REPLACE");
                break;
            case DirContext.REMOVE_ATTRIBUTE:
                sb.append("DELETE");
                break;
        }
        sb.append("\"><Attribute name=\"");
        Attribute attr = mods[i].getAttribute();
        sb.append(attr.getID());
        sb.append("\"/>");
        int size = attr.size();
        for (int j = 0; j < size; j++) {
            sb.append("<Value>");
            try {
                sb.append(SMSSchema.escapeSpecialCharacters((String) attr.get(j)));
            } catch (NamingException ne) {
                throw (new SMSException(ne, "sms-JAXRPC-cannot-copy-fromModItemToString"));
            }
            sb.append("</Value>");
        }
        sb.append("</AttributeValuePair>");
    }
    sb.append("</Modifications>");
    if (debug.messageEnabled()) {
        debug.message("SMSJAXRPCObject::ModsToString: " + sb.toString());
    }
    return (sb.toString());
}
Also used : Attribute(javax.naming.directory.Attribute) SMSException(com.sun.identity.sm.SMSException) NamingException(javax.naming.NamingException)

Example 90 with Attribute

use of javax.naming.directory.Attribute in project OpenAM by OpenRock.

the class SMSFlatFileObjectBase method modifyValues.

protected void modifyValues(String objName, ModificationItem modItem, Properties props) {
    // will not be null
    Attribute attr = modItem.getAttribute();
    // will not be null
    String key = attr.getID();
    try {
        int op = modItem.getModificationOp();
        switch(op) {
            case DirContext.ADD_ATTRIBUTE:
                Set values = toValSet(key, (String) props.get(key));
                for (NamingEnumeration e = attr.getAll(); e.hasMoreElements(); ) {
                    values.add(e.nextElement());
                }
                props.put(key, toValString(values));
                break;
            case DirContext.REMOVE_ATTRIBUTE:
                Set val = toValSet(key, (String) props.get(key));
                for (NamingEnumeration e = attr.getAll(); e.hasMoreElements(); ) {
                    val.remove(e.nextElement());
                }
                props.put(key, toValString(val));
                break;
            case DirContext.REPLACE_ATTRIBUTE:
                props.put(key, toValString(attr.getAll()));
                break;
        }
    } catch (NamingException e) {
        mDebug.error("SMSFlatFileObjectBase.modifyValues", e);
        throw new IllegalArgumentException("SMSFlatFileObjectBase.modifyValues: " + objName + ": Error modifying attributes: " + e.getMessage());
    }
}
Also used : CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) CaseInsensitiveTreeSet(com.sun.identity.common.CaseInsensitiveTreeSet) Set(java.util.Set) Attribute(javax.naming.directory.Attribute) NamingEnumeration(javax.naming.NamingEnumeration) NamingException(javax.naming.NamingException)

Aggregations

Attribute (javax.naming.directory.Attribute)110 Attributes (javax.naming.directory.Attributes)57 NamingException (javax.naming.NamingException)39 BasicAttribute (javax.naming.directory.BasicAttribute)39 BasicAttributes (javax.naming.directory.BasicAttributes)30 ArrayList (java.util.ArrayList)29 SearchResult (javax.naming.directory.SearchResult)25 NamingEnumeration (javax.naming.NamingEnumeration)22 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)18 HashSet (java.util.HashSet)17 DirContext (javax.naming.directory.DirContext)17 SearchControls (javax.naming.directory.SearchControls)17 IOException (java.io.IOException)11 InitialDirContext (javax.naming.directory.InitialDirContext)11 ModificationItem (javax.naming.directory.ModificationItem)11 Hashtable (java.util.Hashtable)9 File (java.io.File)7 List (java.util.List)7 MutablePartitionConfiguration (org.apache.directory.server.core.configuration.MutablePartitionConfiguration)7 AbstractBootstrapSchema (org.apache.directory.server.core.schema.bootstrap.AbstractBootstrapSchema)7