com.rapiddweller.script.expression.ArrayJoinExpression Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rd-lib-script Show documentation
Show all versions of rd-lib-script Show documentation
'rapiddweller Script' is an open source software library for resolving Java-like script expressions,
forked from Databene Scripts written by Volker Bergmann.
/*
* Copyright (C) 2011-2014 Volker Bergmann ([email protected]).
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rapiddweller.script.expression;
import com.rapiddweller.commons.ArrayUtil;
import com.rapiddweller.commons.Context;
import com.rapiddweller.script.Expression;
/**
* {@link Expression} implementation which assembles other expression that evaluate to arrays
* and joins their results to a single array.
* Created: 11.09.2010 07:57:38
* @since 0.5.4
* @author Volker Bergmann
*/
public class ArrayJoinExpression extends CompositeExpression {
private Class componentType;
public ArrayJoinExpression(Class componentType, Expression... terms) {
super(terms);
this.componentType = componentType;
}
@Override
@SuppressWarnings("unchecked")
public E[] evaluate(Context context) {
E[][] arrays = (E[][]) ExpressionUtil.evaluateAll(terms, context);
int totalLength = totalLength(arrays);
E[] result = ArrayUtil.newInstance(componentType(arrays), totalLength);
int resultIndex = 0;
for (E[] array : arrays)
for (int localIndex = 0; localIndex < array.length; localIndex++)
result[resultIndex] = array[localIndex];
return result;
}
@SuppressWarnings("unchecked")
private Class componentType(E[][] arrays) {
if (this.componentType == null) {
for (E[] array : arrays)
if (array != null) {
this.componentType = (Class) array.getClass().getComponentType();
break;
}
}
return (this.componentType != null ? this.componentType : (Class) Object.class);
}
private static int totalLength(T[][] arrays) {
int totalLength = 0;
for (T[] array : arrays)
totalLength += array.length;
return totalLength;
}
}