de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java Source code

Java tutorial

Introduction

Here is the source code for de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

Source

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.fiz.ddb.aas.utils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;

import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;

import org.apache.commons.lang.StringUtils;

import de.fiz.ddb.aas.administration.AasPrincipal;
import de.fiz.ddb.aas.administration.ConstEnumOrgSector;
import de.fiz.ddb.aas.administration.ConstEnumOrgStatus;
import de.fiz.ddb.aas.administration.ConstEnumOrgSubSector;
import de.fiz.ddb.aas.administration.Constants;
import de.fiz.ddb.aas.administration.Organisation;
import de.fiz.ddb.aas.authorization.PrivilegeEnum;
import de.fiz.ddb.aas.auxiliaryobjects.OIDs;
import de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationRead;
import de.fiz.ddb.aas.exceptions.AASUnauthorizedException;
import de.fiz.ddb.ldap.connector.LDAPConnector;

/**
 * 
 * @author bk
 */
public abstract class LDAPEngineUtilityOrganisation extends LDAPEngineUtility {

    // --- Konstante aus der LDAP- Schema:
    // ***************************************************************************
    protected Organisation convertLdapOrganizationToOrganisation(
            NamingEnumeration<SearchResult> pOrganizationResult, NamingEnumeration<SearchResult> pPrivilegesResult)
            throws ExecutionException, NameNotFoundException {
        Organisation vOrganisation = null;
        try {
            if ((pOrganizationResult != null) && pOrganizationResult.hasMore()) {

                SearchResult sr = pOrganizationResult.next();
                vOrganisation = convertSearchResultToOrganization(sr);
                // -- Organization privileges:
                vOrganisation = this.convertLdapGroupsToOrganizationPrivileges(vOrganisation, pPrivilegesResult);
            }
        } catch (NameNotFoundException ex) {
            LOG.log(Level.SEVERE, null, ex);
            throw ex;
        } catch (NamingException ne) {
            LOG.log(Level.SEVERE, null, ne);
            throw new ExecutionException(ne.getMessage(), ne.getCause());
        } finally {
            // -- releases this context's resources immediately, instead of waiting for the garbage collector
            if (pOrganizationResult != null) {
                try {
                    pOrganizationResult.close();
                } catch (NamingException ex) {
                }
            }
        }
        return vOrganisation;
    }

    // ***************************************************************************
    protected Organisation convertSearchResultToOrganization(final SearchResult sr)
            throws ExecutionException, NameNotFoundException {
        if (sr == null) {
            throw new ExecutionException("SearchResult sr == NULL", new NullPointerException());
        }
        Organisation vOrganisation = null;
        try {
            Attributes attributes = sr.getAttributes();

            Attribute attr;
            String vStr;
            String vOrgName = ((attr = attributes.get(Constants.ldap_ddbOrg_Id)) != null
                    ? String.valueOf(attr.get())
                    : null);
            String vName = sr.getName();
            String vNameInNamespace = sr.getNameInNamespace();
            // --- EntryDN
            String vEntryDN = ((attr = attributes.get(Constants.ldap_ddb_EntryDN)) != null
                    ? String.valueOf(attr.get())
                    : "");

            int idx;
            // -- Parent node detections:
            String vParent = null;
            //vParent = sr.getName();
            //LOG.log(Level.INFO, "getNameInNamespace() = '" + sr.getNameInNamespace() + "'");
            //LOG.log(Level.INFO, "getName() = '" + sr.getName() + "'");
            // -- getNameInNamespace() = 'o=99900711,o=00008125,o=00050350,ou=Organizations,dc=de'
            // -- getName() = 'o=99900711,o=00008125,o=00050350'

            //sr.getName(): 'o=00000116', 
            //sr.getNameInNamespace(): 'o=00000116,o=00050350,ou=Organizations,dc=de', 
            //vOrgEntryDN: 'o=00000116,o=00050350,ou=Organizations,dc=de'            
            vParent = sr.getNameInNamespace();
            if ((idx = vParent.indexOf(",ou=")) >= 0) {
                vParent = vParent.substring(0, idx);
            }
            vParent = vParent.replaceAll(Constants.ldap_ddbOrg_Id + "=", "");
            // -- 99900711,00008125,00050350'
            String[] vParents = vParent.split(",");

            if (vParents.length >= 2) {
                vParent = vParents[1];
            } else {
                vParent = null;
            }

            LOG.log(Level.INFO,
                    "convertLdapOrganizationToOrganisation: o: '" + vOrgName + "', vParent: '" + vParent
                            + "', sr.getName(): '" + vName + "', sr.getNameInNamespace(): '" + vNameInNamespace
                            + "', vOrgEntryDN: '" + vEntryDN + "', sr.isRelative(): '" + sr.isRelative() + "'");
            /*
             * if ( (vOrgName != null)&&(!vOrgName.isEmpty()) ) { vOrganisation = new Organisation(vOrgName,
             * vDescription, vParent);
             */
            if ((vEntryDN != null) && (!vEntryDN.isEmpty())) {
                vOrganisation = new Organisation(vEntryDN,
                        (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null
                                ? String.valueOf(attr.get())
                                : null);
                // Public-ID: (s.o.)
                // vOrganisation.setOrgPID( (attr = attributes.get(ddbOrg_PID)) != null ? String.valueOf(attr.get()) :
                // "");
                // Parent (s.o.)
                vOrganisation.setOrgParent(vParent);

                // Kurzbeschreibung der Einrichtung
                vOrganisation.setDescription((attr = attributes.get(Constants.ldap_ddbOrg_Description)) != null
                        ? String.valueOf(attr.get())
                        : null);

                // -- Rechtsform
                try {
                    vOrganisation.setBusinessCategory(
                            (attr = attributes.get(Constants.ldap_ddbOrg_BusinessCategory)) != null
                                    ? ConstEnumOrgSector.valueOf(String.valueOf(attr.get()))
                                    : null);
                } catch (IllegalArgumentException ex) {
                    LOG.log(Level.WARNING, "Organisation-Sector-Error: {0}", ex.getMessage());
                    vOrganisation.setStatus(null);
                }

                // -- Sub-Sectors:
                if ((attr = attributes.get(Constants.ldap_ddbOrg_SubBusinessCategory)) != null) {
                    ConstEnumOrgSubSector vSubSector;
                    NamingEnumeration<?> allSubSectors = attr.getAll();
                    while (allSubSectors.hasMore()) {
                        try {
                            vSubSector = ConstEnumOrgSubSector.valueOf((String) allSubSectors.next());
                            vOrganisation.addSubSectors(vSubSector);
                        } catch (IllegalArgumentException ex) {
                            LOG.log(Level.WARNING, "Organisation-SubSector-Error: {0}", ex.getMessage());
                        }
                    }
                }

                // -- Funding Agency
                vOrganisation.setFundingAgency((attr = attributes.get(Constants.ldap_ddbOrg_FundingAgency)) != null
                        ? String.valueOf(attr.get())
                        : null);

                // Name der Einrichtung
                vOrganisation.setDisplayName((attr = attributes.get(Constants.ldap_ddbOrg_DisplayName)) != null
                        ? String.valueOf(attr.get())
                        : "");

                // E-Mail
                vOrganisation.setEmail(
                        (attr = attributes.get(Constants.ldap_ddbOrg_Email)) != null ? String.valueOf(attr.get())
                                : null);
                // Telefonnummer
                vOrganisation.setTel((attr = attributes.get(Constants.ldap_ddbOrg_TelephoneNumber)) != null
                        ? String.valueOf(attr.get())
                        : null);
                // -- FAX
                vOrganisation.setFax((attr = attributes.get(Constants.ldap_ddbOrg_FaxNumber)) != null
                        ? String.valueOf(attr.get())
                        : null);

                // -- PLZ
                vOrganisation.getAddress()
                        .setPostalCode((attr = attributes.get(Constants.ldap_ddbOrg_PostalCode)) != null
                                ? String.valueOf(attr.get())
                                : "");

                // -- City/Ortsname [l, localityName]
                if ((attr = attributes.get(Constants.ldap_ddbOrg_LocalityName)) != null) {
                    vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
                } else if ((attr = attributes.get("l")) != null) {
                    vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
                }

                // -- HouseIdentifier
                vOrganisation.getAddress()
                        .setHouseIdentifier((attr = attributes.get(Constants.ldap_ddbOrg_HouseIdentifier)) != null
                                ? String.valueOf(attr.get())
                                : "");
                // -- Strasse
                vOrganisation.getAddress()
                        .setStreet((attr = attributes.get(Constants.ldap_ddbOrg_Street)) != null
                                ? String.valueOf(attr.get())
                                : "");

                // -- Bundesland [stateOrProvinceName, st]
                if ((attr = attributes.get(Constants.ldap_ddbOrg_StateOrProvinceName)) != null) {
                    vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
                } else if ((attr = attributes.get("st")) != null) {
                    vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
                }

                // -- Land [countryName, c]
                if ((attr = attributes.get(Constants.ldap_ddbOrg_CountryName)) != null) {
                    vOrganisation.getAddress().setCountryName(String.valueOf(attr.get()));
                }
                // -- AddressSuplement
                vOrganisation.getAddress()
                        .setAddressSuplement((attr = attributes.get(Constants.ldap_ddbOrg_AddressSuplement)) != null
                                ? String.valueOf(attr.get())
                                : "");

                // -- Geokoordinaten
                try {
                    vOrganisation.getAddress()
                            .setLatitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLatitude)) != null
                                    ? Double.valueOf(String.valueOf(attr.get()))
                                    : 0.0);
                } catch (NumberFormatException ex) {
                    LOG.log(Level.WARNING, "GeoLatitude-Error: {0}", ex.getMessage());
                }
                try {
                    vOrganisation.getAddress()
                            .setLongitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLongitude)) != null
                                    ? Double.valueOf(String.valueOf(attr.get()))
                                    : 0.0);
                } catch (NumberFormatException ex) {
                    LOG.log(Level.WARNING, "GeoLongitude-Error: {0}", ex.getMessage());
                }
                vOrganisation.getAddress().setLocationDisplayName(
                        (attr = attributes.get(Constants.ldap_ddbOrg_LocationDisplayName)) != null
                                ? String.valueOf(attr.get())
                                : null);

                vOrganisation.setAbbreviation((attr = attributes.get(Constants.ldap_ddbOrg_Abbreviation)) != null
                        ? String.valueOf(attr.get())
                        : null);

                vOrganisation.setLegalStatus((attr = attributes.get(Constants.ldap_ddbOrg_LegalStatus)) != null
                        ? String.valueOf(attr.get())
                        : null);

                if ((attr = attributes.get(Constants.ldap_ddbOrg_URL)) != null) {
                    NamingEnumeration<?> allURLs = attr.getAll();
                    while (allURLs.hasMore()) {
                        vOrganisation.addURLs((String) allURLs.next());
                    }
                }

                vOrganisation.setLogo(
                        (attr = attributes.get(Constants.ldap_ddbOrg_Logo)) != null ? String.valueOf(attr.get())
                                : null);

                // -- org-Status:
                //vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null ? String
                //  .valueOf(attr.get()) : "");
                try {
                    vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null
                            ? ConstEnumOrgStatus.valueOf(String.valueOf(attr.get()))
                            : ConstEnumOrgStatus.pending);
                } catch (IllegalArgumentException ex) {
                    LOG.log(Level.WARNING, "Organisation-Status-Error: {0}", ex.getMessage());
                    vOrganisation.setStatus(null);
                }

                vOrganisation.setCreatedBy((attr = attributes.get(Constants.ldap_ddb_CreatorsName)) != null
                        ? String.valueOf(attr.get())
                        : "");

                try { // createTimestamp-Error: For input string: "20120620142810Z"
                      // 1340205676692 - 20120620152116Z - 2012-06-20-15-21-16Z
                      // vOrganisation.setCreated( (attr = attributes.get(ddbOrg_CreateTimestamp)) != null ?
                      // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                    if ((attr = attributes.get(Constants.ldap_ddb_CreateTimestamp)) != null) {
                        vStr = String.valueOf(attr.get());
                        vOrganisation.setCreated(convertLdapDateToLong(vStr));
                    }
                } catch (NumberFormatException ex) {
                    LOG.log(Level.WARNING, "createTimestamp-Error: {0}", ex.getMessage());
                }

                vOrganisation.setModifiedBy((attr = attributes.get(Constants.ldap_ddb_ModifiersName)) != null
                        ? String.valueOf(attr.get())
                        : "");
                try { // modifyTimestamp-Error: For input string: "20120620142810Z"
                      // vOrganisation.setModified( (attr = attributes.get(ddbOrg_ModifyTimestamp)) != null ?
                      // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                    if ((attr = attributes.get(Constants.ldap_ddb_ModifyTimestamp)) != null) {
                        vStr = String.valueOf(attr.get());
                        vOrganisation.setModified(convertLdapDateToLong(vStr));
                    }
                } catch (NumberFormatException ex) {
                    LOG.log(Level.WARNING, "modifyTimestamp-Error: {0}", ex.getMessage());
                }

                if ((attr = attributes.get(Constants.ldap_ddbOrg_Properties)) != null
                        && attributes.get(Constants.ldap_ddbOrg_Properties).get() != null) {
                    vOrganisation.setProperties(serializer.deserialize((String) attr.get()));
                }

            } else {
                throw new NameNotFoundException();
            }
        } catch (IllegalAccessException ex) {
            LOG.log(Level.SEVERE, null, ex);
            throw new ExecutionException(ex.getMessage(), ex.getCause());
        } catch (NameNotFoundException ex) {
            LOG.log(Level.SEVERE, null, ex);
            throw ex;
        } catch (NamingException ne) {
            LOG.log(Level.SEVERE, null, ne);
            throw new ExecutionException(ne.getMessage(), ne.getCause());
        }
        return vOrganisation;
    }

    // ***************************************************************************
    // ***************************************************************************
    /**
     * Checks attribute if it has to be written to LDAP or removed from LDAP if attribute = null, its like not set.
     * 
     * @param pOrgAtt: ConstEnumOrgStatus or ConstEnumOrgSector
     * @param pOldOrgAtt
     * @param ldapAttributeName
     * @param vOrgAttributes
     * @param vOrgRemoveAttributes
     * @param isUpdate
     */
    private boolean checkAttribute(Enum<?> pOrgAtt, Enum<?> pOldOrgAtt, String ldapAttributeName,
            Attributes vOrgAttributes, Attributes vOrgRemoveAttributes, boolean isUpdate) {
        boolean hasChanged = false;
        if (!isUpdate) {
            if (pOldOrgAtt != null && pOrgAtt != null) {
                vOrgAttributes.put(new BasicAttribute(ldapAttributeName, String.valueOf(pOrgAtt.name())));
            }
        } else {
            if ((pOrgAtt != null) && ((pOldOrgAtt == null) || (pOldOrgAtt != pOrgAtt))) {
                vOrgAttributes.put(ldapAttributeName, String.valueOf(pOrgAtt));
                hasChanged = true;
            } else if ((pOrgAtt == null) && (pOldOrgAtt != null)) {
                vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName));
                hasChanged = true;
            }
        }
        return hasChanged;
    }

    // ***************************************************************************
    /**
     * Checks attribute if it has to be written to LDAP or removed from LDAP
     * 
     * @param pOrganisationAtt
     * @param pOldOrganisationAtt
     * @param ldapAttributeName
     * @param vOrgAttributes
     * @param vOrgRemoveAttributes
     * @param isUpdate
     */
    private boolean checkAttribute(String pOrganisationAtt, String pOldOrganisationAtt, String ldapAttributeName,
            Attributes vOrgAttributes, Attributes vOrgRemoveAttributes, boolean isUpdate) {
        boolean hasChanged = false;
        if (!isUpdate) {
            if ((pOrganisationAtt != null && !pOrganisationAtt.isEmpty())
                    && (pOrganisationAtt.trim().length() > 0)) {
                vOrgAttributes.put(new BasicAttribute(ldapAttributeName, pOrganisationAtt));
            }
        } else {
            if ((pOrganisationAtt != null && !pOrganisationAtt.isEmpty())
                    && ((pOldOrganisationAtt == null) || (!pOldOrganisationAtt.equals(pOrganisationAtt)))) {
                vOrgAttributes.put(ldapAttributeName, pOrganisationAtt);
                hasChanged = true;
            } else if ((pOrganisationAtt == null || pOrganisationAtt.isEmpty())
                    && (pOldOrganisationAtt != null && !pOldOrganisationAtt.isEmpty())) {
                vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName));
                hasChanged = true;
            }
        }
        return hasChanged;
    }

    /**
     * Checks attribute if it has to be written to LDAP or removed from LDAP if attribute = 0, its like not set.
     * 
     * @param pOrganisationAtt
     * @param pOldOrganisationAtt
     * @param ldapAttributeName
     * @param vOrgAttributes
     * @param vOrgRemoveAttributes
     * @param isUpdate
     */
    private boolean checkAttribute(Double pOrganisationAtt, Double pOldOrganisationAtt, String ldapAttributeName,
            Attributes vOrgAttributes, Attributes vOrgRemoveAttributes, boolean isUpdate) {
        boolean hasChanged = false;
        if (!isUpdate) {
            if (pOldOrganisationAtt != null && pOrganisationAtt != 0) {
                vOrgAttributes.put(new BasicAttribute(ldapAttributeName, String.valueOf(pOrganisationAtt)));
            }
        } else {
            if (pOrganisationAtt != null && pOrganisationAtt != 0 && (pOldOrganisationAtt == null
                    || pOldOrganisationAtt == 0 || pOldOrganisationAtt != pOrganisationAtt)) {
                vOrgAttributes.put(ldapAttributeName, String.valueOf(pOrganisationAtt));
                hasChanged = true;
            } else if ((pOrganisationAtt == null || pOrganisationAtt == 0)
                    && (pOldOrganisationAtt != null && pOldOrganisationAtt != 0)) {
                vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName));
                hasChanged = true;
            }
        }
        return hasChanged;
    }

    /**
     * Checks attribute-set if it has to be written to LDAP or removed from LDAP if attribute = 0, its like not set.
     * 
     * @param pOrganisationAtt
     * @param pOldOrganisationAtt
     * @param ldapAttributeName
     * @param vOrgAttributes
     * @param vOrgRemoveAttributes
     * @param isUpdate
     */
    private boolean checkAttribute(List<String> pOrganisationAtt, List<String> pOldOrganisationAtt,
            String ldapAttributeName, Attributes vOrgAttributes, Attributes vOrgRemoveAttributes,
            boolean isUpdate) {
        boolean hasChanged = false;
        if (!isUpdate) {
            // is create
            if ((pOrganisationAtt != null) && (!pOrganisationAtt.isEmpty())) {
                Attribute vAttr = new BasicAttribute(ldapAttributeName);
                for (String url : pOrganisationAtt) {
                    if ((url != null) && (url.trim().length() > 0)) {
                        vAttr.add(url);
                    }
                }
                if (vAttr.size() > 0) {
                    vOrgAttributes.put(vAttr);
                }
            }
        } else {
            if ((pOrganisationAtt != null) && (!pOrganisationAtt.isEmpty())) {
                Attribute vAttr = new BasicAttribute(ldapAttributeName);
                if (pOrganisationAtt.size() == 1 && pOrganisationAtt.contains("") && pOldOrganisationAtt != null
                        && !pOldOrganisationAtt.isEmpty()) {
                    vOrgRemoveAttributes.put(vAttr);
                    hasChanged = true;
                } else {
                    for (String url : pOrganisationAtt) {
                        if ((url != null) && (url.trim().length() > 0)) {
                            vAttr.add(url);
                        }
                    }
                    if (vAttr.size() > 0) {
                        vOrgAttributes.put(vAttr);
                        hasChanged = true;
                    }
                }
            } else if ((pOrganisationAtt == null || pOrganisationAtt.isEmpty())
                    && (pOldOrganisationAtt != null && !pOldOrganisationAtt.isEmpty())) {
                vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName));
                hasChanged = true;
            }
        }
        return hasChanged;
    }

    // ***************************************************************************
    private boolean checkAttributeEnum(
            //List<Enum<?>> pOrgAtt, List<Enum<?>> pOldOrgAtt, String ldapAttributeName,
            List<ConstEnumOrgSubSector> pOrgAtt, List<ConstEnumOrgSubSector> pOldOrgAtt, String ldapAttributeName,
            Attributes vOrgAttributes, Attributes vOrgRemoveAttributes, boolean isUpdate) {
        boolean hasChanged = false;
        if (!isUpdate) {
            // is create
            if ((pOrgAtt != null) && (!pOrgAtt.isEmpty())) {
                Attribute vAttr = new BasicAttribute(ldapAttributeName);
                for (Enum<?> iterEnum : pOrgAtt) {
                    if (iterEnum != null) {
                        vAttr.add(iterEnum.name());
                    }
                }
                if (vAttr.size() > 0) {
                    vOrgAttributes.put(vAttr);
                }
            }
        } else {
            if ((pOrgAtt != null) && (!pOrgAtt.isEmpty())) {
                Attribute vAttr = new BasicAttribute(ldapAttributeName);
                if ((pOrgAtt.isEmpty()) && (pOldOrgAtt != null) && (!pOldOrgAtt.isEmpty())) {
                    vOrgRemoveAttributes.put(vAttr);
                    hasChanged = true;
                } else {
                    for (Enum<?> iterEnum : pOrgAtt) {
                        if (iterEnum != null) {
                            vAttr.add(iterEnum.name());
                        }
                    }
                    if (vAttr.size() > 0) {
                        vOrgAttributes.put(vAttr);
                        hasChanged = true;
                    }
                }
            } else if ((pOrgAtt == null || pOrgAtt.isEmpty()) && (pOldOrgAtt != null && !pOldOrgAtt.isEmpty())) {
                vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName));
                hasChanged = true;
            }
        }
        return hasChanged;
    }

    // ***************************************************************************
    protected boolean organizationExists(String orgId) throws ExecutionException {
        NamingEnumeration<SearchResult> searchResults = null;
        try {
            searchResults = this.query(LDAPConnector.getSingletonInstance().getInstitutionBaseDN(),
                    new StringBuilder("(& (objectclass=").append(Constants.ldap_ddbOrg_ObjectClass).append(") (")
                            .append(Constants.ldap_ddbOrg_Id).append("=").append(orgId).append("))").toString(),
                    new String[] { Constants.ldap_ddbOrg_Id, "+" }, SearchControls.SUBTREE_SCOPE);
            if (searchResults.hasMore()) {
                return true;
            } else {
                return false;
            }
        } catch (IllegalAccessException ex) {
            LOG.log(Level.SEVERE, "Connection-Error", ex);
            throw new ExecutionException(ex.getMessage(), ex.getCause());
        } catch (NamingException ne) {
            LOG.log(Level.SEVERE, "something went wrong while checking if userId exists", ne);
            throw new ExecutionException(ne.getMessage(), ne.getCause());
        } finally {
            if (searchResults != null) {
                try {
                    searchResults.close();
                } catch (NamingException e) {
                }
            }
        }
    }

    // ***************************************************************************
    protected boolean licensedOganizationExists(String orgId) throws ExecutionException {
        NamingEnumeration<SearchResult> searchResults = null;
        try {
            searchResults = this.query(LDAPConnector.getSingletonInstance().getLicensedInstitutionsBaseDN(),
                    new StringBuilder("(& (objectclass=").append(Constants.ldap_ddbOrg_ObjectClass).append(") (")
                            .append(Constants.ldap_ddbOrg_Id).append("=").append(orgId).append("))").toString(),
                    new String[] { Constants.ldap_ddbOrg_Id, "+" }, SearchControls.SUBTREE_SCOPE);
            if (searchResults.hasMore()) {
                return true;
            } else {
                return false;
            }
        } catch (IllegalAccessException ex) {
            LOG.log(Level.SEVERE, "Connection-Error", ex);
            throw new ExecutionException(ex.getMessage(), ex.getCause());
        } catch (NamingException ne) {
            LOG.log(Level.SEVERE, "something went wrong while checking if userId exists", ne);
            throw new ExecutionException(ne.getMessage(), ne.getCause());
        } finally {
            if (searchResults != null) {
                try {
                    searchResults.close();
                } catch (NamingException e) {
                }
            }
        }
    }

    // ***************************************************************************
    /**
     * fill LDAP attributes for create
     * 
     * @param pOrganisation
     * @param vOrgAttributes
     * @return
     * @throws ExecutionException
     */
    protected void convertOrganizationToLdapOrgAttrsForCreate(Organisation pOrganisation, Attributes vOrgAttributes,
            final AasPrincipal performer) throws ExecutionException {
        convertOrganizationToLdapOrgAttrs(pOrganisation, pOrganisation, vOrgAttributes, null, false, performer);
    }

    /**
     * fill LDAP attributes for change and for remove for update.
     * 
     * @param pOrganisation
     * @param pOldOrganization
     * @param vOrgAttributes
     * @param vOrgRemoveAttributes
     * @return
     * @throws ExecutionException
     */
    protected boolean convertOrganizationToLdapOrgAttrsForUpdate(Organisation pOrganisation,
            final Organisation pOldOrganization, Attributes vOrgAttributes, Attributes vOrgRemoveAttributes,
            final AasPrincipal performer) throws ExecutionException {
        return convertOrganizationToLdapOrgAttrs(pOrganisation, pOldOrganization, vOrgAttributes,
                vOrgRemoveAttributes, true, performer);
    }

    // ***************************************************************************
    protected void setAttrRevised(Attributes pOrgRemoveAttributes) {
        LOG.log(Level.INFO, "setAttrRevised");
        pOrgRemoveAttributes.put(new BasicAttribute(Constants.ldap_ddbOrg_Status,
                String.valueOf(ConstEnumOrgStatus.revised.name())));
    }

    // ***************************************************************************
    // ***************************************************************************
    private boolean convertOrganizationToLdapOrgAttrs(Organisation pOrganisation,
            final Organisation pOldOrganisation, Attributes pOrgAttributes, Attributes pOrgRemoveAttributes,
            boolean isUpdate, final AasPrincipal performer) throws ExecutionException {
        boolean hasChanged = false;
        if ((pOrganisation != null) && (pOrgAttributes != null)) {
            // -- Organisation Krzel:
            pOrgAttributes.put(new BasicAttribute("o", pOrganisation.getId()));

            // hierarchical sort
            // reverse orgrdn
            if (pOrganisation.getOrgRDN() != null) {
                String[] parts = pOrganisation.getOrgRDN().split(",");
                if (parts != null && parts.length > 0) {
                    StringBuilder builder = new StringBuilder();
                    for (int i = parts.length - 1; i >= 0; i--) {
                        builder.append(parts[i]);
                        if (i > 0) {
                            builder.append("|");
                        }
                    }
                    pOrgAttributes
                            .put(new BasicAttribute(Constants.ldap_ddbOrg_HierarchicalSort, builder.toString()));
                }
            }

            //properties
            //add create/update properties
            boolean isCreate = true;
            if (isUpdate) {
                isCreate = false;
            }

            pOrganisation.setProperties(PropertiesHelper.setModificationProperties(pOldOrganisation.getProperties(),
                    isCreate, performer));

            // -- PID:
            if (checkAttribute(pOrganisation.getOrgPID(), pOldOrganisation.getOrgPID(), Constants.ldap_ddbOrg_PID,
                    pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }

            // -- Rechtsform:
            if (checkAttribute(pOrganisation.getBusinessCategory(), pOldOrganisation.getBusinessCategory(),
                    Constants.ldap_ddbOrg_BusinessCategory, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- Sub-Sectors:
            if (checkAttributeEnum(pOrganisation.getSubSector(), pOldOrganisation.getSubSector(),
                    Constants.ldap_ddbOrg_SubBusinessCategory, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }

            // -- Funding Agency
            if (checkAttribute(pOrganisation.getFundingAgency(), pOldOrganisation.getFundingAgency(),
                    Constants.ldap_ddbOrg_FundingAgency, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }

            // -- Kurzbeschreibung der Einrichtung
            if (checkAttribute(pOrganisation.getDescription(), pOldOrganisation.getDescription(),
                    Constants.ldap_ddbOrg_Description, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- Name der Einrichtung
            if (checkAttribute(pOrganisation.getDisplayName(), pOldOrganisation.getDisplayName(),
                    Constants.ldap_ddbOrg_DisplayName, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- E-Mail
            if (checkAttribute(pOrganisation.getEmail(), pOldOrganisation.getEmail(), Constants.ldap_ddbOrg_Email,
                    pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- Telefonnummer
            if (checkAttribute(pOrganisation.getTel(), pOldOrganisation.getTel(),
                    Constants.ldap_ddbOrg_TelephoneNumber, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- FAX
            if (checkAttribute(pOrganisation.getFax(), pOldOrganisation.getFax(), Constants.ldap_ddbOrg_FaxNumber,
                    pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }

            // -- HouseIdentifier
            if (checkAttribute(pOrganisation.getAddress().getHouseIdentifier(),
                    pOldOrganisation.getAddress().getHouseIdentifier(), Constants.ldap_ddbOrg_HouseIdentifier,
                    pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- Strasse
            if (checkAttribute(pOrganisation.getAddress().getStreet(), pOldOrganisation.getAddress().getStreet(),
                    Constants.ldap_ddbOrg_Street, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }

            // -- Zusatz-Info:
            if (checkAttribute(pOrganisation.getAddress().getAddressSuplement(),
                    pOldOrganisation.getAddress().getAddressSuplement(), Constants.ldap_ddbOrg_AddressSuplement,
                    pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- PLZ
            if (checkAttribute(pOrganisation.getAddress().getPostalCode(),
                    pOldOrganisation.getAddress().getPostalCode(), Constants.ldap_ddbOrg_PostalCode, pOrgAttributes,
                    pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- I; Ortsname
            if (checkAttribute(pOrganisation.getAddress().getLocalityName(),
                    pOldOrganisation.getAddress().getLocalityName(), Constants.ldap_ddbOrg_LocalityName,
                    pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- Bundesland
            if (checkAttribute(pOrganisation.getAddress().getStateOrProvinceName(),
                    pOldOrganisation.getAddress().getStateOrProvinceName(),
                    Constants.ldap_ddbOrg_StateOrProvinceName, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- Land
            if (checkAttribute(pOrganisation.getAddress().getCountryName(),
                    pOldOrganisation.getAddress().getCountryName(), Constants.ldap_ddbOrg_CountryName,
                    pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- Geokoordinaten:
            if (checkAttribute(pOrganisation.getAddress().getLatitude(),
                    pOldOrganisation.getAddress().getLatitude(), Constants.ldap_ddbOrg_GeoLatitude, pOrgAttributes,
                    pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            if (checkAttribute(pOrganisation.getAddress().getLongitude(),
                    pOldOrganisation.getAddress().getLongitude(), Constants.ldap_ddbOrg_GeoLongitude,
                    pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            if (checkAttribute(pOrganisation.getAddress().getLocationDisplayName(),
                    pOldOrganisation.getAddress().getLocationDisplayName(),
                    Constants.ldap_ddbOrg_LocationDisplayName, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }

            if (checkAttribute(pOrganisation.getAbbreviation(), pOldOrganisation.getAbbreviation(),
                    Constants.ldap_ddbOrg_Abbreviation, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            if (checkAttribute(pOrganisation.getLegalStatus(), pOldOrganisation.getLegalStatus(),
                    Constants.ldap_ddbOrg_LegalStatus, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }

            if (checkAttribute(pOrganisation.getUrl(), pOldOrganisation.getUrl(), Constants.ldap_ddbOrg_URL,
                    pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }

            if (checkAttribute(pOrganisation.getLogo(), pOldOrganisation.getLogo(), Constants.ldap_ddbOrg_Logo,
                    pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }
            // -- Status
            if (checkAttribute(pOrganisation.getStatus(), pOldOrganisation.getStatus(),
                    Constants.ldap_ddbOrg_Status, pOrgAttributes, pOrgRemoveAttributes, isUpdate)) {
                hasChanged = true;
            }

            // -- Properties:
            if (pOrganisation.getProperties() != null && !pOrganisation.getProperties().isEmpty()) {
                try {
                    pOrgAttributes.put(new BasicAttribute(Constants.ldap_ddbOrg_Properties,
                            serializer.serialize(pOrganisation.getProperties())));
                } catch (IllegalAccessException e) {
                    throw new ExecutionException(e);
                }
            }

        }
        return hasChanged;
    }

    // ***************************************************************************
    protected Organisation convertLdapGroupsToOrganizationPrivileges(Organisation pOrg,
            NamingEnumeration<SearchResult> pPrivilegesResult) throws ExecutionException {
        try {
            if (pPrivilegesResult != null) {
                PrivilegeEnum p;
                SearchResult sr;
                String vCnPrivileg;
                // construct privileges
                while (pPrivilegesResult.hasMore()) {
                    sr = pPrivilegesResult.next();
                    vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get();
                    p = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn);
                    if (p != null) {
                        pOrg.addPrivileges(p);
                    } else {
                        LOG.log(Level.WARNING,
                                "Die Organisation ''{0}'' verfgt ber einen nicht existierende Privileg: ''{1}''!",
                                new Object[] { pOrg.getId(), vCnPrivileg });
                    }
                }
                // -- releases this context's resources immediately, instead of waiting for the garbage collector
                pPrivilegesResult.close();
            }
        } catch (NamingException ne) {
            LOG.log(Level.SEVERE, null, ne);
            throw new ExecutionException(ne.getMessage(), ne.getCause());
        } finally {
            // -- releases this context's resources immediately, instead of waiting for the garbage collector
            if (pPrivilegesResult != null) {
                try {
                    pPrivilegesResult.close();
                } catch (NamingException ex) {
                }
            }
        }
        return pOrg;
    }

    // ***************************************************************************
    public NamingEnumeration<SearchResult> getAllSubOrgs(boolean pLicensedOrgs, OIDs pOIDs, int pScopy,
            String[] attributeFilter, AasPrincipal pPerformer) throws ExecutionException {
        if (pPerformer == null) {
            throw new IllegalArgumentException("The contractor is unknown: Performer == null");
        }
        if (attributeFilter == null) {
            attributeFilter = new String[] { "*", "+" };
        }

        String orgRdn = pOIDs.getOrgRDN();
        if (StringUtils.isEmpty(orgRdn)) {
            orgRdn = getOrgRdnForOrgId(pOIDs, pPerformer);
        }

        if (orgRdn == null) {
            throw new ExecutionException("OrgRDN = null", null);
        }
        InitialLdapContext ctx = null;
        try {
            ctx = LDAPConnector.getSingletonInstance().takeCtx();
            StringBuilder vBaseDn = new StringBuilder(Constants.ldap_ddbOrg_Id).append("=")
                    .append(orgRdn.replaceAll(",", "," + Constants.ldap_ddbOrg_Id + "=")).append(",")
                    .append((!pLicensedOrgs ? LDAPConnector.getSingletonInstance().getInstitutionBaseDN()
                            : LDAPConnector.getSingletonInstance().getLicensedInstitutionsBaseDN()));
            StringBuilder vFilter = new StringBuilder("(objectClass=").append(Constants.ldap_ddbOrg_ObjectClass)
                    .append(")");
            NamingEnumeration<SearchResult> searchResults = this.query(ctx, vBaseDn.toString(), vFilter.toString(),
                    attributeFilter, pScopy);
            return searchResults;
        } catch (IllegalAccessException ex) {
            LOG.log(Level.SEVERE, "Connection-Error", ex);
            throw new ExecutionException(ex.getMessage(), ex.getCause());
        } catch (NamingException ne) {
            LOG.log(Level.SEVERE, "NamingException", ne);
            throw new ExecutionException(ne.getMessage(), ne.getCause());
        } finally {
            if (ctx != null) {
                try {
                    LDAPConnector.getSingletonInstance().putCtx(ctx);
                } catch (Exception ex) {
                    LOG.log(Level.SEVERE, "Exception", ex);
                }
            }
        }
    }

    // ***************************************************************************
    public Set<OIDs> getAllSubOrgIds(boolean pLicensedOrgs, OIDs pOIDs, int pScopy, AasPrincipal pPerformer)
            throws ExecutionException {
        Set<OIDs> vSetOIDs = new HashSet<OIDs>();
        NamingEnumeration<SearchResult> searchResults = null;
        try {
            searchResults = getAllSubOrgs(pLicensedOrgs, pOIDs, pScopy,
                    new String[] { Constants.ldap_ddbOrg_Id, Constants.ldap_ddbOrg_PID, "+" }, pPerformer);
            SearchResult sr;
            Attribute attr;
            while (searchResults.hasMore()) {
                sr = searchResults.next();
                if ((attr = sr.getAttributes().get(Constants.ldap_ddb_EntryDN)) != null) {
                    vSetOIDs.add(new OIDs(String.valueOf(attr.get()),
                            (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null
                                    ? String.valueOf(attr.get())
                                    : null));
                } else {
                    throw new ExecutionException("entryDN = null : OIDs = " + pOIDs, null);
                }
            }
        } catch (IllegalAccessException ex) {
            LOG.log(Level.SEVERE, "Connection-Error", ex);
            throw new ExecutionException(ex.getMessage(), ex.getCause());
        } catch (NamingException ne) {
            LOG.log(Level.SEVERE, "NamingException", ne);
            throw new ExecutionException(ne.getMessage(), ne.getCause());
        } finally {
            if (searchResults != null) {
                try {
                    searchResults.close();
                    searchResults = null;
                } catch (NamingException ex) {
                }
            }
        }
        return vSetOIDs;
    }

    // ***************************************************************************
    protected String getOrgRdnForOrgId(final OIDs pOIDs, AasPrincipal pPerformer) throws ExecutionException {
        ThreadOrganisationRead threadOrganisationRead = new ThreadOrganisationRead(pOIDs, pPerformer);
        Organisation vOrganisation = null;
        try {
            vOrganisation = threadOrganisationRead.call();
        } catch (NameNotFoundException e) {
            throw new ExecutionException(e);
        } catch (AASUnauthorizedException e) {
            throw new ExecutionException(e);
        }
        if (vOrganisation != null && vOrganisation.getOIDs() != null) {
            return vOrganisation.getOIDs().getOrgRDN();
        } else {
            throw new ExecutionException("Organization with ID: '" + pOIDs + "' could not be found.", null);
        }

    }

}