nstream.adapter.common.ingress.ValueAssembler Maven / Gradle / Ivy
Show all versions of nstream-adapter-common Show documentation
// Copyright 2015-2024 Nstream, inc.
//
// Licensed under the Redis Source Available License 2.0 (RSALv2) Agreement;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://redis.com/legal/rsalv2-agreement/
//
// 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 nstream.adapter.common.ingress;
import swim.structure.Record;
import swim.structure.Value;
/**
* A transformer of specific nominally-typed Java objects into structurally
* typed {@link Value Values}.
*
* This class's {@link #assemble} method operates much like {@link
* swim.structure.Form#mold(Object)}. The difference between a {@code Form} and
* a {@code ValueAssembler} is in the usage intent. {@code Forms} wrap
* transformations between structurally and nominally typed objects in both
* directions, and they are typically constructed in code. The more lightweight
* {@code ValueAssemblers} may be wholly configured within a (usually recon)
* document and are best suited for situations where the nominally typed object
* is minimally used. They are also capable of throwing checked Exceptions.
*
* @param the type of object that this {@code ValueAssembler} can transform
*/
public abstract class ValueAssembler {
public ValueAssembler(Value settings) {
// no-op
}
/**
* Transforms an object into Swim's structured data model.
*
* @param raw the object to transform
*
* @return the structural representation of some object
*/
public abstract Value assemble(V raw) throws AssemblyException;
/**
* Reflection-based creator-type utility function.
*
* @param settings constructor arguments
* @param the parametrized type of the returned {@code ValueAssembler}
*
* @return a {@code ValueAssembler} constructed against {@code
* settings.tail()} and with class {@code settings.head().toValue()}
*/
// TODO: throw RuntimeException instead of returning null?
@SuppressWarnings("unchecked")
public static ValueAssembler create(Value settings) {
if (settings == null || !settings.isDistinct() || !(settings instanceof Record)) {
return null;
}
final String header = settings.head().key().stringValue(null),
clazz = settings.head().toValue().stringValue(null);
try {
return !"valueAssembler".equals(header) || clazz == null ? null
: (ValueAssembler) Class.forName(clazz).getConstructor(Value.class).newInstance(settings);
} catch (Exception e) {
e.printStackTrace(); // FIXME
return null;
}
}
}