io.cloudslang.engine.data.SqlInQueryReader Maven / Gradle / Ivy
/*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
package io.cloudslang.engine.data;
import org.apache.commons.lang.Validate;
import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* User:
* Date: 18/07/13
*
* This class is used for executing queries that contain In clauses.
* It is needed because databases have a limitation of 1000 (Depending on the database) items per in clause.
*/
public class SqlInQueryReader {
private final int DATABASE_IN_CLAUSE_LIMIT = 1000;
public List read(Set items, SqlInQueryCallback callback) {
Validate.notNull(callback);
if (items == null) {
return Collections.emptyList();
} else {
return readItems(items, callback);
}
}
private List readItems(Set items, SqlInQueryCallback callback) {
Set source = new HashSet<>(items);
List results = new LinkedList<>();
do {
Set itemsToRead = extractAndRemoveUpToLimit(source, DATABASE_IN_CLAUSE_LIMIT);
List result = callback.readItems(itemsToRead);
if(result!=null){
results.addAll(result);
}
} while (!CollectionUtils.isEmpty(source));
return results;
}
//Extracts items from source in the ammount set in 'limit' and also removes them from source
private Set extractAndRemoveUpToLimit(Set source, int limit) {
Set result = new HashSet<>();
Iterator iterator = source.iterator();
while (iterator.hasNext() && result.size() < limit) {
result.add(iterator.next());
iterator.remove();
}
return result;
}
public interface SqlInQueryCallback {
List readItems(Set items);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy