<commit_before>/*
 * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */

package org.gluu.site.ldap.persistence;

import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.gluu.site.ldap.OperationsFacade;
import org.gluu.site.ldap.exception.ConnectionException;
import org.gluu.site.ldap.persistence.AttributeDataModification.AttributeModificationType;
import org.gluu.site.ldap.persistence.annotation.LdapEnum;
import org.gluu.site.ldap.persistence.exception.AuthenticationException;
import org.gluu.site.ldap.persistence.exception.EntryPersistenceException;
import org.gluu.site.ldap.persistence.exception.InvalidArgumentException;
import org.gluu.site.ldap.persistence.exception.MappingException;
import org.gluu.site.ldap.persistence.property.Getter;
import org.gluu.site.ldap.persistence.property.Setter;
import org.gluu.site.ldap.persistence.util.ReflectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xdi.ldap.model.SearchScope;
import org.xdi.ldap.model.SortOrder;
import org.xdi.ldap.model.VirtualListViewResponse;
import org.xdi.util.ArrayHelper;
import org.xdi.util.StringHelper;

import com.unboundid.ldap.sdk.Attribute;
import com.unboundid.ldap.sdk.Filter;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPSearchException;
import com.unboundid.ldap.sdk.Modification;
import com.unboundid.ldap.sdk.ModificationType;
import com.unboundid.ldap.sdk.ResultCode;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.util.StaticUtils;

/**
 * LDAP Entry Manager
 *
 * @author <NAME> Date: 10.07.2010
 */
public class LdapEntryManager extends AbstractEntryManager implements Serializable {

	private static final long serialVersionUID = -2544614410981223105L;

	private static final Logger log = LoggerFactory.getLogger(LdapEntryManager.class);

	private static final Class<?>[] GROUP_BY_ALLOWED_DATA_TYPES = { String.class, Date.class, Integer.class, LdapEnum.class };
	private static final Class<?>[] SUM_BY_ALLOWED_DATA_TYPES = { int.class, Integer.class, float.class, Float.class, double.class, Double.class };
	private static final String[] NO_STRINGS = new String[0];
	
	private static final Comparator<String> LINE_LENGHT_COMPARATOR = new LineLenghtComparator<String>(false);

	private transient OperationsFacade ldapOperationService;
	private transient List<DeleteNotifier> subscribers;

	public LdapEntryManager() {}

	public LdapEntryManager(OperationsFacade ldapOperationService) {
		this.ldapOperationService = ldapOperationService;
		subscribers = new LinkedList<DeleteNotifier>();
	}

	public boolean destroy() {
		boolean destroyResult = this.ldapOperationService.destroy();
		
		return destroyResult;
	}

	public OperationsFacade getLdapOperationService() {
		return ldapOperationService;
	}

	public void addDeleteSubscriber(DeleteNotifier subscriber) {
		subscribers.add(subscriber);
	}

	public void removerDeleteSubscriber(DeleteNotifier subscriber) {
		subscribers.remove(subscriber);
	}

	@Override
	protected void persist(String dn, List<AttributeData> attributes) {
		List<Attribute> ldapAttributes = new ArrayList<Attribute>(attributes.size());
		for (AttributeData attribute : attributes) {
			String attributeName = attribute.getName();
			String attributeValues[] = attribute.getValues();

            if (ArrayHelper.isNotEmpty(attributeValues) && StringHelper.isNotEmpty(attributeValues[0])) {
                if (ldapOperationService.isCertificateAttribute(attributeName)) {
					byte[][] binaryValues = toBinaryValues(attributeValues);

					ldapAttributes.add(new Attribute(attributeName + ";binary", binaryValues));
				} else {
					ldapAttributes.add(new Attribute(attributeName, attributeValues));
				}
			}
		}

		// Persist entry
		try {
			boolean result = this.ldapOperationService.addEntry(dn, ldapAttributes);
			if (!result) {
				throw new EntryPersistenceException(String.format("Failed to persist entry: %s", dn));
			}
		} catch (ConnectionException ex) {
            throw new EntryPersistenceException(String.format("Failed to persist entry: %s", dn), ex.getCause());
		} catch (Exception ex) {
			throw new EntryPersistenceException(String.format("Failed to persist entry: %s", dn), ex);
		}
	}

	@Override
	public void merge(String dn, List<AttributeDataModification> attributeDataModifications) {
		// Update entry
		try {
			List<Modification> modifications = new ArrayList<Modification>(attributeDataModifications.size());
			for (AttributeDataModification attributeDataModification : attributeDataModifications) {
				AttributeData attribute = attributeDataModification.getAttribute();
				AttributeData oldAttribute = attributeDataModification.getOldAttribute();

				String attributeName = attribute.getName();
				String[] attributeValues = attribute.getValues();

				String oldAttributeName = null;
				String[] oldAttributeValues = null;
				if (oldAttribute != null) {
					oldAttributeName = oldAttribute.getName();
					oldAttributeValues = oldAttribute.getValues();
				}

				Modification modification = null;
				if (AttributeModificationType.ADD.equals(attributeDataModification.getModificationType())) {
					modification = createModification(ModificationType.ADD, attributeName, attributeValues);
				} else {
					if (AttributeModificationType.REMOVE.equals(attributeDataModification.getModificationType())) {<commit_msg>Use same code style in NPE fix <commit_after>/*
 * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */

package org.gluu.site.ldap.persistence;

import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.gluu.site.ldap.OperationsFacade;
import org.gluu.site.ldap.exception.ConnectionException;
import org.gluu.site.ldap.persistence.AttributeDataModification.AttributeModificationType;
import org.gluu.site.ldap.persistence.annotation.LdapEnum;
import org.gluu.site.ldap.persistence.exception.AuthenticationException;
import org.gluu.site.ldap.persistence.exception.EntryPersistenceException;
import org.gluu.site.ldap.persistence.exception.InvalidArgumentException;
import org.gluu.site.ldap.persistence.exception.MappingException;
import org.gluu.site.ldap.persistence.property.Getter;
import org.gluu.site.ldap.persistence.property.Setter;
import org.gluu.site.ldap.persistence.util.ReflectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xdi.ldap.model.SearchScope;
import org.xdi.ldap.model.SortOrder;
import org.xdi.ldap.model.VirtualListViewResponse;
import org.xdi.util.ArrayHelper;
import org.xdi.util.StringHelper;

import com.unboundid.ldap.sdk.Attribute;
import com.unboundid.ldap.sdk.Filter;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPSearchException;
import com.unboundid.ldap.sdk.Modification;
import com.unboundid.ldap.sdk.ModificationType;
import com.unboundid.ldap.sdk.ResultCode;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.util.StaticUtils;

/**
 * LDAP Entry Manager
 *
 * @author <NAME> Date: 10.07.2010
 */
public class LdapEntryManager extends AbstractEntryManager implements Serializable {

	private static final long serialVersionUID = -2544614410981223105L;

	private static final Logger log = LoggerFactory.getLogger(LdapEntryManager.class);

	private static final Class<?>[] GROUP_BY_ALLOWED_DATA_TYPES = { String.class, Date.class, Integer.class, LdapEnum.class };
	private static final Class<?>[] SUM_BY_ALLOWED_DATA_TYPES = { int.class, Integer.class, float.class, Float.class, double.class, Double.class };
	private static final String[] NO_STRINGS = new String[0];
	
	private static final Comparator<String> LINE_LENGHT_COMPARATOR = new LineLenghtComparator<String>(false);

	private transient OperationsFacade ldapOperationService;
	private transient List<DeleteNotifier> subscribers;

	public LdapEntryManager() {}

	public LdapEntryManager(OperationsFacade ldapOperationService) {
		this.ldapOperationService = ldapOperationService;
		subscribers = new LinkedList<DeleteNotifier>();
	}

	public boolean destroy() {
		boolean destroyResult = this.ldapOperationService.destroy();
		
		return destroyResult;
	}

	public OperationsFacade getLdapOperationService() {
		return ldapOperationService;
	}

	public void addDeleteSubscriber(DeleteNotifier subscriber) {
		subscribers.add(subscriber);
	}

	public void removerDeleteSubscriber(DeleteNotifier subscriber) {
		subscribers.remove(subscriber);
	}

	@Override
	protected void persist(String dn, List<AttributeData> attributes) {
		List<Attribute> ldapAttributes = new ArrayList<Attribute>(attributes.size());
		for (AttributeData attribute : attributes) {
			String attributeName = attribute.getName();
			String attributeValues[] = attribute.getValues();

            if (ArrayHelper.isNotEmpty(attributeValues) && StringHelper.isNotEmpty(attributeValues[0])) {
                if (ldapOperationService.isCertificateAttribute(attributeName)) {
					byte[][] binaryValues = toBinaryValues(attributeValues);

					ldapAttributes.add(new Attribute(attributeName + ";binary", binaryValues));
				} else {
					ldapAttributes.add(new Attribute(attributeName, attributeValues));
				}
			}
		}

		// Persist entry
		try {
			boolean result = this.ldapOperationService.addEntry(dn, ldapAttributes);
			if (!result) {
				throw new EntryPersistenceException(String.format("Failed to persist entry: %s", dn));
			}
		} catch (ConnectionException ex) {
            throw new EntryPersistenceException(String.format("Failed to persist entry: %s", dn), ex.getCause());
		} catch (Exception ex) {
			throw new EntryPersistenceException(String.format("Failed to persist entry: %s", dn), ex);
		}
	}

	@Override
	public void merge(String dn, List<AttributeDataModification> attributeDataModifications) {
		// Update entry
		try {
			List<Modification> modifications = new ArrayList<Modification>(attributeDataModifications.size());
			for (AttributeDataModification attributeDataModification : attributeDataModifications) {
				AttributeData attribute = attributeDataModification.getAttribute();
				AttributeData oldAttribute = attributeDataModification.getOldAttribute();

				String attributeName = null;
				String[] attributeValues = null;
				if (attribute != null) {
					attributeName = attribute.getName();
					attributeValues = attribute.getValues();
				}

				String oldAttributeName = null;
				String[] oldAttributeValues = null;
				if (oldAttribute != null) {
					oldAttributeName = oldAttribute.getName();
					oldAttributeValues = oldAttribute.getValues();
				}

				Modification modification = null;
				if (AttributeModificationType.ADD.equals(attributeDataModification.getModificationType())) {
					modification = createModification(ModificationType.ADD, attributeName, attributeValues);
				} else {
					if (AttributeModificationType.REMOVE.equals(attributeDataModification.getModificationType())) {
{'fraction_non_alphanumeric': 0.10191512697207458, 'fraction_numerical': 0.006918079811018308, 'mean_word_length': 5.4846827133479215, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5219286', 'n_tokens_mistral': 3722, 'n_tokens_neox': 3427, 'n_words': 690}