Search in sources :

Example 51 with EntryPersistenceException

use of io.jans.orm.exception.EntryPersistenceException in project jans by JanssenProject.

the class LdapUpateMissingEntrySample method main.

public static void main(String[] args) {
    // Prepare sample connection details
    LdapEntryManagerSample sqlSampleEntryManager = new LdapEntryManagerSample();
    // Create SQL entry manager
    LdapEntryManager sqlEntryManager = sqlSampleEntryManager.createLdapEntryManager();
    String sessionId = UUID.randomUUID().toString();
    final String sessionDn = "uniqueIdentifier=" + sessionId + ",ou=session,o=jans";
    final SimpleSessionState simpleSessionState = new SimpleSessionState();
    simpleSessionState.setDn(sessionDn);
    simpleSessionState.setId(sessionId);
    simpleSessionState.setLastUsedAt(new Date());
    try {
        sqlEntryManager.merge(simpleSessionState);
        System.out.println("Updated");
    } catch (EntryPersistenceException ex) {
        LOG.info(String.format("Failed to update, root case exception: %s", ex.getCause().getClass()), ex);
    }
}
Also used : SimpleSessionState(io.jans.orm.ldap.model.SimpleSessionState) LdapEntryManager(io.jans.orm.ldap.impl.LdapEntryManager) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) Date(java.util.Date)

Example 52 with EntryPersistenceException

use of io.jans.orm.exception.EntryPersistenceException in project jans by JanssenProject.

the class LdapEntryManager method removeSubtreeThroughIteration.

private void removeSubtreeThroughIteration(String dn) {
    SearchScope scope = SearchScope.SUB;
    SearchResult searchResult = null;
    try {
        searchResult = getOperationService().search(dn, toLdapFilter(Filter.createPresenceFilter("objectClass")), toLdapSearchScope(scope), null, 0, 0, 0, null, "dn");
        if (!ResultCode.SUCCESS.equals(searchResult.getResultCode())) {
            throw new EntryPersistenceException(String.format("Failed to find sub-entries of entry '%s' for removal", dn));
        }
    } catch (SearchScopeException ex) {
        throw new AuthenticationException(String.format("Failed to convert scope: %s", scope), ex);
    } catch (SearchException ex) {
        throw new EntryDeleteException(String.format("Failed to find sub-entries of entry '%s' for removal", dn), ex);
    }
    List<String> removeEntriesDn = new ArrayList<String>(searchResult.getEntryCount());
    for (SearchResultEntry searchResultEntry : searchResult.getSearchEntries()) {
        removeEntriesDn.add(searchResultEntry.getDN());
    }
    Collections.sort(removeEntriesDn, LINE_LENGHT_COMPARATOR);
    for (String removeEntryDn : removeEntriesDn) {
        remove(removeEntryDn);
    }
}
Also used : AuthenticationException(io.jans.orm.exception.AuthenticationException) SearchScope(io.jans.orm.model.SearchScope) ArrayList(java.util.ArrayList) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) SearchException(io.jans.orm.exception.operation.SearchException) SearchResult(com.unboundid.ldap.sdk.SearchResult) EntryDeleteException(io.jans.orm.exception.EntryDeleteException) SearchScopeException(io.jans.orm.exception.operation.SearchScopeException) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry)

Example 53 with EntryPersistenceException

use of io.jans.orm.exception.EntryPersistenceException in project jans by JanssenProject.

the class LdapEntryManager method findEntries.

@Override
public <T> List<T> findEntries(String baseDN, Class<T> entryClass, Filter filter, SearchScope scope, String[] ldapReturnAttributes, BatchOperation<T> batchOperation, int start, int count, int chunkSize) {
    if (StringHelper.isEmptyString(baseDN)) {
        throw new MappingException("Base DN to find entries is null");
    }
    // Check entry class
    checkEntryClass(entryClass, false);
    String[] objectClasses = getTypeObjectClasses(entryClass);
    List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
    String[] currentLdapReturnAttributes = ldapReturnAttributes;
    if (ArrayHelper.isEmpty(currentLdapReturnAttributes)) {
        currentLdapReturnAttributes = getAttributes(null, propertiesAnnotations, false);
    }
    // Find entries
    Filter searchFilter;
    if (objectClasses.length > 0) {
        searchFilter = addObjectClassFilter(filter, objectClasses);
    } else {
        searchFilter = filter;
    }
    SearchResult searchResult = null;
    try {
        LdapBatchOperationWraper<T> batchOperationWraper = new LdapBatchOperationWraper<T>(batchOperation, this, entryClass, propertiesAnnotations);
        searchResult = getOperationService().search(baseDN, toLdapFilter(searchFilter), toLdapSearchScope(scope), batchOperationWraper, start, chunkSize, count, null, currentLdapReturnAttributes);
    } catch (Exception ex) {
        throw new EntryPersistenceException(String.format("Failed to find entries with baseDN: %s, filter: %s", baseDN, searchFilter), ex);
    }
    if (!ResultCode.SUCCESS.equals(searchResult.getResultCode())) {
        throw new EntryPersistenceException(String.format("Failed to find entries with baseDN: %s, filter: %s", baseDN, searchFilter));
    }
    if (searchResult.getEntryCount() == 0) {
        return new ArrayList<T>(0);
    }
    List<T> entries = createEntities(entryClass, propertiesAnnotations, searchResult.getSearchEntries().toArray(new SearchResultEntry[searchResult.getSearchEntries().size()]));
    // Default sort if needed
    sortEntriesIfNeeded(entryClass, entries);
    return entries;
}
Also used : ArrayList(java.util.ArrayList) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) SearchResult(com.unboundid.ldap.sdk.SearchResult) MappingException(io.jans.orm.exception.MappingException) ParseException(java.text.ParseException) EntryDeleteException(io.jans.orm.exception.EntryDeleteException) SearchScopeException(io.jans.orm.exception.operation.SearchScopeException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) ConnectionException(io.jans.orm.exception.operation.ConnectionException) SearchException(io.jans.orm.exception.operation.SearchException) AuthenticationException(io.jans.orm.exception.AuthenticationException) MappingException(io.jans.orm.exception.MappingException) PropertyAnnotation(io.jans.orm.reflect.property.PropertyAnnotation) Filter(io.jans.orm.search.filter.Filter) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry)

Example 54 with EntryPersistenceException

use of io.jans.orm.exception.EntryPersistenceException in project jans by JanssenProject.

the class SpannerBatchJobSample method main.

public static void main(String[] args) {
    // Prepare sample connection details
    SpannerEntryManagerSample sqlEntryManagerSample = new SpannerEntryManagerSample();
    // Create SQL entry manager
    final SpannerEntryManager sqlEntryManager = sqlEntryManagerSample.createSpannerEntryManager();
    BatchOperation<SimpleToken> tokenSQLBatchOperation = new ProcessBatchOperation<SimpleToken>() {

        private int processedCount = 0;

        @Override
        public void performAction(List<SimpleToken> objects) {
            for (SimpleToken simpleTokenSQL : objects) {
                try {
                    CustomAttribute customAttribute = getUpdatedAttribute(sqlEntryManager, simpleTokenSQL.getDn(), "exp", simpleTokenSQL.getAttribute("exp"));
                    simpleTokenSQL.setCustomAttributes(Arrays.asList(new CustomAttribute[] { customAttribute }));
                    sqlEntryManager.merge(simpleTokenSQL);
                    processedCount++;
                } catch (EntryPersistenceException ex) {
                    LOG.error("Failed to update entry", ex);
                }
            }
            LOG.info("Total processed tokens: " + processedCount);
        }
    };
    final Filter filter1 = Filter.createPresenceFilter("exp");
    sqlEntryManager.findEntries("o=jans", SimpleToken.class, filter1, SearchScope.SUB, new String[] { "exp" }, tokenSQLBatchOperation, 0, 0, 100);
    BatchOperation<SimpleSession> sessionBatchOperation = new ProcessBatchOperation<SimpleSession>() {

        private int processedCount = 0;

        @Override
        public void performAction(List<SimpleSession> objects) {
            int currentProcessedCount = 0;
            for (SimpleSession simpleSession : objects) {
                try {
                    CustomAttribute customAttribute = getUpdatedAttribute(sqlEntryManager, simpleSession.getDn(), "jansLastAccessTime", simpleSession.getAttribute("jansLastAccessTime"));
                    simpleSession.setCustomAttributes(Arrays.asList(new CustomAttribute[] { customAttribute }));
                    sqlEntryManager.merge(simpleSession);
                    processedCount++;
                    currentProcessedCount++;
                } catch (EntryPersistenceException ex) {
                    LOG.error("Failed to update entry", ex);
                }
            }
            LOG.info("Currnet batch count processed sessions: " + currentProcessedCount);
            LOG.info("Total processed sessions: " + processedCount);
        }
    };
    final Filter filter2 = Filter.createPresenceFilter("jansLastAccessTime");
    sqlEntryManager.findEntries("o=jans", SimpleSession.class, filter2, SearchScope.SUB, new String[] { "jansLastAccessTime" }, sessionBatchOperation, 0, 0, 100);
    BatchOperation<SimpleClient> clientBatchOperation = new ProcessBatchOperation<SimpleClient>() {

        private int processedCount = 0;

        @Override
        public void performAction(List<SimpleClient> objects) {
            for (SimpleClient simpleClient : objects) {
                processedCount++;
            }
            LOG.info("Total processed clients: " + processedCount);
        }
    };
    final Filter filter3 = Filter.createPresenceFilter("exp");
    List<SimpleClient> result3 = sqlEntryManager.findEntries("o=jans", SimpleClient.class, filter3, SearchScope.SUB, new String[] { "exp" }, clientBatchOperation, 0, 0, 1000);
    LOG.info("Result count (without collecting results): " + result3.size());
    BatchOperation<SimpleClient> clientBatchOperation2 = new DefaultBatchOperation<SimpleClient>() {

        private int processedCount = 0;

        @Override
        public void performAction(List<SimpleClient> objects) {
            for (SimpleClient simpleClient : objects) {
                processedCount++;
            }
            LOG.info("Total processed clients: " + processedCount);
        }
    };
    final Filter filter4 = Filter.createPresenceFilter("exp");
    List<SimpleClient> result4 = sqlEntryManager.findEntries("o=jans", SimpleClient.class, filter4, SearchScope.SUB, new String[] { "exp" }, clientBatchOperation2, 0, 0, 1000);
    LOG.info("Result count (with collecting results): " + result4.size());
}
Also used : CustomAttribute(io.jans.orm.model.base.CustomAttribute) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) DefaultBatchOperation(io.jans.orm.model.DefaultBatchOperation) Filter(io.jans.orm.search.filter.Filter) SpannerEntryManagerSample(io.jans.orm.cloud.spanner.persistence.SpannerEntryManagerSample) ProcessBatchOperation(io.jans.orm.model.ProcessBatchOperation) List(java.util.List) SimpleClient(io.jans.orm.cloud.spanner.model.SimpleClient) SimpleSession(io.jans.orm.cloud.spanner.model.SimpleSession) SimpleToken(io.jans.orm.cloud.spanner.model.SimpleToken) SpannerEntryManager(io.jans.orm.cloud.spanner.impl.SpannerEntryManager)

Example 55 with EntryPersistenceException

use of io.jans.orm.exception.EntryPersistenceException in project jans by JanssenProject.

the class LdapEntryManager method merge.

@Override
public void merge(String dn, String[] objectClasses, List<AttributeDataModification> attributeDataModifications, Integer expiration) {
    // 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.getStringValues();
            }
            String oldAttributeName = null;
            String[] oldAttributeValues = null;
            if (oldAttribute != null) {
                oldAttributeName = oldAttribute.getName();
                oldAttributeValues = oldAttribute.getStringValues();
            }
            Modification modification = null;
            if (AttributeModificationType.ADD.equals(attributeDataModification.getModificationType())) {
                modification = createModification(ModificationType.ADD, attributeName, attributeValues);
            } else {
                if (AttributeModificationType.REMOVE.equals(attributeDataModification.getModificationType())) {
                    modification = createModification(ModificationType.DELETE, oldAttributeName, oldAttributeValues);
                } else if (AttributeModificationType.REPLACE.equals(attributeDataModification.getModificationType())) {
                    if (attributeValues.length == 1) {
                        modification = createModification(ModificationType.REPLACE, attributeName, attributeValues);
                    } else {
                        String[] oldValues = ArrayHelper.arrayClone(oldAttributeValues);
                        String[] newValues = ArrayHelper.arrayClone(attributeValues);
                        Arrays.sort(oldValues);
                        Arrays.sort(newValues);
                        boolean[] retainOldValues = new boolean[oldValues.length];
                        Arrays.fill(retainOldValues, false);
                        List<String> addValues = new ArrayList<String>();
                        List<String> removeValues = new ArrayList<String>();
                        // Add new values
                        for (String value : newValues) {
                            int idx = Arrays.binarySearch(oldValues, value, new Comparator<String>() {

                                @Override
                                public int compare(String o1, String o2) {
                                    return o1.toLowerCase().compareTo(o2.toLowerCase());
                                }
                            });
                            if (idx >= 0) {
                                // Old values array contains new value. Retain
                                // old value
                                retainOldValues[idx] = true;
                            } else {
                                // This is new value
                                addValues.add(value);
                            }
                        }
                        // Remove values which we don't have in new values
                        for (int i = 0; i < oldValues.length; i++) {
                            if (!retainOldValues[i]) {
                                removeValues.add(oldValues[i]);
                            }
                        }
                        if (removeValues.size() > 0) {
                            Modification removeModification = createModification(ModificationType.DELETE, attributeName, removeValues.toArray(new String[removeValues.size()]));
                            modifications.add(removeModification);
                        }
                        if (addValues.size() > 0) {
                            Modification addModification = createModification(ModificationType.ADD, attributeName, addValues.toArray(new String[addValues.size()]));
                            modifications.add(addModification);
                        }
                    }
                }
            }
            if (modification != null) {
                modifications.add(modification);
            }
        }
        if (modifications.size() > 0) {
            boolean result = getOperationService().updateEntry(dn, modifications);
            if (!result) {
                throw new EntryPersistenceException(String.format("Failed to update entry: %s", dn));
            }
        }
    } catch (ConnectionException ex) {
        throw new EntryPersistenceException(String.format("Failed to update entry: %s", dn), ex.getCause());
    } catch (Exception ex) {
        throw new EntryPersistenceException(String.format("Failed to update entry: %s", dn), ex);
    }
}
Also used : Modification(com.unboundid.ldap.sdk.Modification) AttributeDataModification(io.jans.orm.model.AttributeDataModification) ArrayList(java.util.ArrayList) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) MappingException(io.jans.orm.exception.MappingException) ParseException(java.text.ParseException) EntryDeleteException(io.jans.orm.exception.EntryDeleteException) SearchScopeException(io.jans.orm.exception.operation.SearchScopeException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) ConnectionException(io.jans.orm.exception.operation.ConnectionException) SearchException(io.jans.orm.exception.operation.SearchException) AuthenticationException(io.jans.orm.exception.AuthenticationException) Comparator(java.util.Comparator) AttributeDataModification(io.jans.orm.model.AttributeDataModification) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) AttributeData(io.jans.orm.model.AttributeData) ConnectionException(io.jans.orm.exception.operation.ConnectionException)

Aggregations

EntryPersistenceException (io.jans.orm.exception.EntryPersistenceException)61 SearchException (io.jans.orm.exception.operation.SearchException)33 AuthenticationException (io.jans.orm.exception.AuthenticationException)31 EntryDeleteException (io.jans.orm.exception.EntryDeleteException)30 MappingException (io.jans.orm.exception.MappingException)30 Filter (io.jans.orm.search.filter.Filter)24 AttributeData (io.jans.orm.model.AttributeData)16 DateTimeParseException (java.time.format.DateTimeParseException)15 PropertyAnnotation (io.jans.orm.reflect.property.PropertyAnnotation)13 ParsedKey (io.jans.orm.impl.model.ParsedKey)12 ArrayList (java.util.ArrayList)11 Date (java.util.Date)10 SearchScopeException (io.jans.orm.exception.operation.SearchScopeException)9 JsonObject (com.couchbase.client.java.document.json.JsonObject)8 ConnectionException (io.jans.orm.exception.operation.ConnectionException)8 ParseException (java.text.ParseException)8 DateTimeException (java.time.DateTimeException)7 List (java.util.List)7 SearchResultEntry (com.unboundid.ldap.sdk.SearchResultEntry)6 EntryData (io.jans.orm.model.EntryData)6