package com.framsticks.params; import java.util.ArrayList; import java.util.List; import com.framsticks.util.FramsticksException; import static com.framsticks.util.lang.Containers.filterInstanceof; /** * @author Piotr Sniegowski */ public abstract class Util { public static String readSourceToString(SourceInterface source) { StringBuilder result = new StringBuilder(); String line; while ((line = source.readLine()) != null) { result.append(line).append(" "); } source.close(); return result.toString(); } public static List stripAccess(List accesses, Class type) { List result = new ArrayList(); for (Access a : accesses) { Object object = a.getSelected(); if (!type.isInstance(object)) { throw new FramsticksException().msg("extracted object is of invalid type").arg("object", object).arg("desired", type).arg("actual", object.getClass()).arg("framsclass", a.getFramsClass()); } result.add(type.cast(object)); } return result; } public static int takeAllNonNullValues(Access to, Access from) { int copied = 0; for (ValueParam f : filterInstanceof(from.getParams(), ValueParam.class)) { Object v = from.get(f, Object.class); if (v == null) { continue; } // if (to.get(f, Object.class) != null) { // continue; // } to.set(f, v); ++copied; } return copied; } public static int copyExistingParamsTypeSafe(Access to, Access from) { int copied = 0; for (ValueParam f : filterInstanceof(from.getParams(), ValueParam.class)) { Param t = from.getParam(f.getId()); if (!(t instanceof ValueParam)) { continue; } if (to.getClass() != f.getClass()) { continue; } to.set((ValueParam) t, from.get(f, Object.class)); ++copied; } return copied; } public static T selectObjectForAccess(Access access, Object object, Class type) { if (object == null) { return null; } if (!type.isInstance(object)) { throw new FramsticksException().msg("trying to select object of wrong type").arg("object", object).arg("type", object.getClass()).arg("in", access); } return type.cast(object); } public static int getNumberOfCompositeParamChild(Access access, Object child) { int count = access.getCompositeParamCount(); for (int i = 0; i < count; ++i) { if (access.get(i, Object.class) == child) { return i; } } return -1; } }