/* (non-Javadoc)
@see com.dell.doradus.search.aggregate.EntitySequenceFactory#getSequence(com.dell.doradus.common.TableDefinition, java.lang.Iterable, java.util.List, com.dell.doradus.search.aggregate.EntitySequenceOptions)
184687
@Override
    public <T> EntitySequence getSequence(TableDefinition tableDef, Iterable<T> collection, List<String> fields) {
        return getSequence(tableDef, collection, fields, null);
    }
445684
protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException
    {
        boolean needsCommit = false;
        long result = 0;
        /*
        arminw:
        use the associated broker instance, check if broker was in tx or
        we need to commit used connection.
        */
        PersistenceBroker targetBroker = getBrokerForClass();
        if(!targetBroker.isInTransaction())
        {
            targetBroker.beginTransaction();
            needsCommit = true;
        }
        try
        {
            // lookup sequence name
            String sequenceName = calculateSequenceName(field);
            try
            {
                result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);
                /*
                if 0 was returned we assume that the stored procedure
                did not work properly.
                */
                if (result == 0)
                {
                    throw new SequenceManagerException("No incremented value retrieved");
                }
            }
            catch (Exception e)
            {
                // maybe the sequence was not created
                log.info("Could not grab next key, message was " + e.getMessage() +
                        " - try to write a new sequence entry to database");
                try
                {
                    // on create, make sure to get the max key for the table first
                    long maxKey = SequenceManagerHelper.getMaxForExtent(targetBroker, field);
                    createSequence(targetBroker, field, sequenceName, maxKey);
                }
                catch (Exception e1)
                {
                    String eol = SystemUtils.LINE_SEPARATOR;
                    throw new SequenceManagerException(eol + "Could not grab next id, failed with " + eol +
                            e.getMessage() + eol + "Creation of new sequence failed with " +
                            eol + e1.getMessage() + eol, e1);
                }
                try
                {
                    result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);
                }
                catch (Exception e1)
                {
                    throw new SequenceManagerException("Could not grab next id although a sequence seems to exist", e);
                }
            }
        }
        finally
        {
            if(targetBroker != null && needsCommit)
            {
                targetBroker.commitTransaction();
            }
        }
        return result;
    }
637054
public static Set<String> simpleSequenceToSet(SimpleSequence simpleSequence)
    {
        if (simpleSequence == null)
            return Collections.emptySet();

        Set<String> result = new HashSet<>();
        for (int i = 0; i < simpleSequence.size(); i++)
        {
            try
            {
                Object sequenceEntry = simpleSequence.get(i);
                if (sequenceEntry instanceof SimpleScalar)
                {
                    result.add(((SimpleScalar) sequenceEntry).getAsString());
                }
                else
                {
                    result.add(simpleSequence.get(i).toString());
                }
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }
        }
        return result;
    }
1284269
private void fillPrimaryKeysBySequence(Object entity){
        if(!dialect.supportsGenerationType(GenerationType.SEQUENCE)){
            return;
        }

        BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass());
        int size = beanDesc.getPropertyDescSize();

        for(int i=0; i < size; i++){
            PropertyDesc propertyDesc = beanDesc.getPropertyDesc(i);
            PrimaryKey primaryKey = propertyDesc.getAnnotation(PrimaryKey.class);

            if(primaryKey != null && primaryKey.generationType() == GenerationType.SEQUENCE){
                String sql = dialect.getSequenceSql(primaryKey.generator());
                Object value = sqlExecutor.getSingleResult(propertyDesc.getPropertyType(), sql, new Object[0]);
                propertyDesc.setValue(entity, value);
            }
        }
    }
214804
public long getPreviousSequenceID()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "getPreviousSequenceID");
    long previousSequenceID=0;
    previousSequenceID = msgItem.getMessage().getGuaranteedValueStartTick()-1;

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "getPreviousSequenceID", new Long(previousSequenceID));
    return previousSequenceID;
  }
712297
def _sequence_query(self):
        
        klass = self.__class__
        query = klass.select().where(klass.sequence.is_null(False))
        seq_scope_field_names =\
            (self.__seq_scope_field_name__ or '').split(',')
        for name in seq_scope_field_names:
            seq_scope_field = getattr(klass, name, None)
            if seq_scope_field:
                seq_scope_field_value = getattr(self, name)
                query = query.where(seq_scope_field == seq_scope_field_value)
        return query
359784
@Override
    public E next()
    {
        if (current != null && checkOnEmptyResult() && current.equals(results.get(results.size() - 1)))
        {
            hasNext();
        }

        if (scrollComplete)
        {
            throw new NoSuchElementException("Nothing to scroll further for:" + entityMetadata.getEntityClazz());
        }

        E lastFetchedEntity = getEntity(results.get(results.size() - 1));
        start = lastFetchedEntity != null ? idValueInByteArr() : null;
        current = getEntity(results.get(results.size() - 1));

        return current;
    }
471537
public static String getOrderByClause(Class<?> entityClass) {
        EntityTable table = getEntityTable(entityClass);
        if (table.getOrderByClause() != null) {
            return table.getOrderByClause();
        }

        List<EntityColumn> orderEntityColumns = new ArrayList<EntityColumn>();
        for (EntityColumn column : table.getEntityClassColumns()) {
            if (column.getOrderBy() != null) {
                orderEntityColumns.add(column);
            }
        }

        Collections.sort(orderEntityColumns, new Comparator<EntityColumn>() {
            @Override
            public int compare(EntityColumn o1, EntityColumn o2) {
                return o1.getOrderPriority() - o2.getOrderPriority();
            }
        });

        StringBuilder orderBy = new StringBuilder();
        for (EntityColumn column : orderEntityColumns) {
            if (orderBy.length() != 0) {
                orderBy.append(",");
            }
            orderBy.append(column.getColumn()).append(" ").append(column.getOrderBy());
        }
        table.setOrderByClause(orderBy.toString());
        return table.getOrderByClause();
    }
604835
@Override
	public CallSequence get(int index)
	{
		if (indics == null)
		{
			size();
		}
		Pair<Integer, Integer> v = indics.get(index);

		int r = v.getFirst();

		if (r == 0)
		{
			CallSequence seq = getVars();
			CallStatement skip = new CallStatement()
			{
				public Object execute()
				{
					return Utils.VOID_VALUE;
				}

				@Override
				public String toString()
				{
					return "skip";
				}
			};

			seq.add(skip);
			return seq;

		} else
		{

			TestSequence rtests = repeat.getTests();
			int count = rtests.size();
			int[] c = new int[r];

			for (int i = 0; i < r; i++)
			{
				c[i] = count;
			}

			Permutor p = new Permutor(c);
			int[] select = null;
			for (int i = 0; i < v.getSecond(); i++)
			{
				select = p.next();
			}

			CallSequence seq = getVars();

			for (int i = 0; i < r; i++)
			{
				seq.addAll(rtests.get(select[i]));
			}
			return seq;
		}

	}
278032
private Node getSequence(IdSourceKey idSourceKey) {
		String updateSequenceQuery = getQuery( idSourceKey );
		Result result = neo4jDb.execute( updateSequenceQuery, singletonMap( SEQUENCE_NAME_QUERY_PARAM, (Object) sequenceName( idSourceKey ) ) );
		ResourceIterator<Node> column = result.columnAs( "n" );
		Node node = null;
		if ( column.hasNext() ) {
			node = column.next();
		}
		column.close();
		return node;
	}
927331
private Long getSequence(String sequenceName)
    {
        Long result = null;
        // now lookup the sequence map for calling DB
        Map mapForDB = (Map) sequencesDBMap.get(getBrokerForClass()
                .serviceConnectionManager().getConnectionDescriptor().getJcdAlias());
        if(mapForDB != null)
        {
            result = (Long) mapForDB.get(sequenceName);
        }
        return result;
    }
1294505
@Override
	public <C extends Compound> Sequence<C> getSubSequence(Sequence<C> sequence) {
		if(isCircular()) {
			List<Sequence<C>> sequences = new ArrayList<Sequence<C>>();
			for(Location l: this) {
				sequences.add(l.getSubSequence(sequence));
			}
			return new JoiningSequenceReader<C>(sequence.getCompoundSet(), sequences);
		}
		return reverseSequence(sequence.getSubSequence(
				getStart().getPosition(), getEnd().getPosition()));
	}
393546
protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException
    {
        long result;
        // lookup sequence name
        String sequenceName = calculateSequenceName(field);
        try
        {
            result = buildNextSequence(field.getClassDescriptor(), sequenceName);
        }
        catch (Throwable e)
        {
            // maybe the sequence was not created
            try
            {
                log.info("Create DB sequence key '"+sequenceName+"'");
                createSequence(field.getClassDescriptor(), sequenceName);
            }
            catch (Exception e1)
            {
                throw new SequenceManagerException(
                        SystemUtils.LINE_SEPARATOR +
                        "Could not grab next id, failed with " + SystemUtils.LINE_SEPARATOR +
                        e.getMessage() + SystemUtils.LINE_SEPARATOR +
                        "Creation of new sequence failed with " +
                        SystemUtils.LINE_SEPARATOR + e1.getMessage() + SystemUtils.LINE_SEPARATOR
                        , e1);
            }
            try
            {
                result = buildNextSequence(field.getClassDescriptor(), sequenceName);
            }
            catch (Throwable e1)
            {
                throw new SequenceManagerException("Could not grab next id, sequence seems to exist", e);
            }
        }
        return result;
    }
1113314
@Override
    public Object mapSequence(Object sequence) {
        List<?> values = (List<?>) sequence;
        List<List<Integer>> ret = new ArrayList<>();
        for (Object obj : values) {
            ret.add((List<Integer>) map(obj));
        }
        return ret;
    }
1058155
public Seq<E> union(final Seq<E> seq) {
    final HashSet<E> elements = new HashSet<>();
    final SeqBuilder<E> builder = Seq.builder(size());
    final Consumer<E> appender = element -> {
      if (!elements.contains(element)) {
        builder.add(element);
        elements.add(element);
      }
    };
    forEach(appender);
    seq.forEach(appender);
    return builder.result();
  }
188321
public long getPreviousSequenceId()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "getPreviousSequenceId");
    long previousSequenceID=0;
    try
    {
      SIMPMessage msg = getSIMPMessage();
      if(msg!=null)
      {
        previousSequenceID = msg.getMessage().getGuaranteedValueStartTick()-1;
      }
    }
    catch (SIResourceException e)
    {
      // No FFDC code needed
      SibTr.exception(tc, e);
    } 
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "getPreviousSequenceId", Long.valueOf(previousSequenceID));
    return previousSequenceID;
  }
1331359
public List<SequenceGenerator<EntityMappings<T>>> getAllSequenceGenerator()
   {
      List<SequenceGenerator<EntityMappings<T>>> list = new ArrayList<SequenceGenerator<EntityMappings<T>>>();
      List<Node> nodeList = childNode.get("sequence-generator");
      for(Node node: nodeList)
      {
         SequenceGenerator<EntityMappings<T>>  type = new SequenceGeneratorImpl<EntityMappings<T>>(this, "sequence-generator", childNode, node);
         list.add(type);
      }
      return list;
   }