source: java/main/src/main/java/com/framsticks/params/ParamsUtil.java @ 105

Last change on this file since 105 was 105, checked in by psniegowski, 11 years ago

HIGHLIGHTS:

  • import refactorization: move Tree, Path, etc.

from core to structure package

  • initial serialization implementation
  • improve PrimeExperiment? test
  • many organizational changes and convenience improvements

CHANGELOG:
Make registry in AbstractTree? final.

Move most classes from core to structure package.

Minor changes.

Switch names of Future and FutureHandler?.

Rename ExceptionResultHandler? to ExceptionHandler?.

Rename ExceptionHandler? to ExceptionDispatcherHandler?.

Fix bug in ParamCandidate? cache.

Add missing synchronization to the BufferedDispatcher?.

Develop @Serialized support.

Rework serialization further.

Add serialization/deserialization interface to ValueParam?.

Move getStorageType and isNumeric from Param down to params hierarchy.

Minor changes.

Improve param type induction.

Add TestSerializedClass? for testing new serialization.

Add info files gor GenePool? and Population.

Add standard.expt exemplary netfile.

Add type name field to PropertiesObject?.

Use PropertiesObject? for PropertiesAccess? instead of ordinary map.

Hide getFramsClass is several more places.

More unification accross FramsClass?, Access and Path.

Add ParamCollection?.

Simplify interface for getting params from FramsClass?, Access
or Path.

Make Access.call() interface variadic.

Add arguments(args) convenience wrapper around new Object[] {args}.

Upgrade to apache.commons.lang version 3.1

Minor improvement with Response constructors.

Develop proper result printing in ClientAtServer?.

Add experimentNetsave to PrimeExperiment?.

File size: 6.5 KB
Line 
1package com.framsticks.params;
2
3import java.util.ArrayList;
4import java.util.List;
5import java.util.Map;
6
7import javax.annotation.Nonnull;
8
9import com.framsticks.util.FramsticksException;
10
11
12import static com.framsticks.util.lang.Containers.filterInstanceof;
13
14/**
15 * @author Piotr Sniegowski
16 */
17public abstract class ParamsUtil {
18
19        public static String readSourceToString(Source source) {
20                StringBuilder result = new StringBuilder();
21                String line;
22                while ((line = source.readLine()) != null) {
23                        result.append(line).append(" ");
24                }
25                source.close();
26                return result.toString();
27        }
28
29        public static <T> List<T> stripAccess(List<Access> accesses, Class<T> type) {
30                List<T> result = new ArrayList<T>();
31                for (Access a : accesses) {
32                        Object object = a.getSelected();
33                        if (!type.isInstance(object)) {
34                                throw new FramsticksException().msg("extracted object is of invalid type").arg("object", object).arg("desired", type).arg("actual", object.getClass()).arg("access", a);
35                        }
36                        result.add(type.cast(object));
37                }
38                return result;
39        }
40
41        public static int takeAllNonNullValues(Access to, Access from) {
42                int copied = 0;
43                for (ValueParam f : filterInstanceof(from.getParams(), ValueParam.class)) {
44                        Object v = from.get(f, Object.class);
45                        if (v == null) {
46                                continue;
47                        }
48                        // if (to.get(f, Object.class) != null) {
49                        //      continue;
50                        // }
51                        to.set(f, v);
52                        ++copied;
53                }
54                return copied;
55        }
56
57        public static int copyExistingParamsTypeSafe(Access to, Access from) {
58                int copied = 0;
59                for (ValueParam f : filterInstanceof(from.getParams(), ValueParam.class)) {
60                        Param t = from.getParam(f.getId());
61                        if (!(t instanceof ValueParam)) {
62                                continue;
63                        }
64                        if (to.getClass() != f.getClass()) {
65                                continue;
66                        }
67                        to.set((ValueParam) t, from.get(f, Object.class));
68                        ++copied;
69                }
70                return copied;
71        }
72
73        public static <T> T selectObjectForAccess(Access access, Object object, Class<T> type) {
74                if (object == null) {
75                        return null;
76                }
77                if (!type.isInstance(object)) {
78                        throw new FramsticksException().msg("trying to select object of wrong type").arg("object", object).arg("type", object.getClass()).arg("in", access);
79                }
80                return type.cast(object);
81        }
82
83        public static int getNumberOfCompositeParamChild(Access access, Object child) {
84                int count = access.getCompositeParamCount();
85                for (int i = 0; i < count; ++i) {
86                        if (access.get(i, Object.class) == child) {
87                                return i;
88                        }
89                }
90                return -1;
91        }
92
93        public static Object[] arguments(Object... args) {
94                return args;
95        }
96
97        public static Param getParam(ParamCollection collection, int i) {
98                return collection.getParam(i);
99        }
100
101        public static Param getParam(ParamCollection collection, String id) {
102                return collection.getParam(id);
103        }
104
105        public static @Nonnull <T extends Param> T castedParam(ParamCollection collection, @Nonnull final Param param, @Nonnull final Class<T> type, Object name) {
106                if (param == null) {
107                        // return null;
108                        throw new FramsticksException().msg("param is missing").arg("name", name).arg("in", collection);
109                }
110                if (!type.isInstance(param)) {
111                        // return null;
112                        throw new FramsticksException().msg("wrong type of param").arg("actual", param.getClass()).arg("requested", type).arg("in", collection);
113                }
114                return type.cast(param);
115        }
116
117        /**
118         * Gets the param entry.
119         *
120         * @param i
121         *            the offset of parameter
122         * @return the param entry
123         */
124        public static @Nonnull <T extends Param> T getParam(ParamCollection collection, final int i, @Nonnull final Class<T> type) {
125                return castedParam(collection, collection.getParam(i), type, i);
126        }
127
128        /**
129         * Gets the param entry.
130         *
131         * @param id
132         *            the getId of parameter
133         * @return the param entry
134         */
135        public static @Nonnull <T extends Param> T getParam(ParamCollection collection, @Nonnull final String id, @Nonnull final Class<T> type) {
136                return castedParam(collection, collection.getParam(id), type, id);
137        }
138
139        public static final String SERIALIZED = "@Serialized:";
140
141        public static class SerializationContext {
142                protected final StringBuilder builder = new StringBuilder();
143                protected final ArrayList<Object> objects = new ArrayList<>();
144
145                protected void appendString(String value) {
146                        builder.append('"').append(value).append('"');
147                }
148
149                protected boolean serializeInternal(Object value) {
150                        if (value == null) {
151                                builder.append("null");
152                                return true;
153                        }
154                        /** indexOf is not used here, because it uses equals() internally, which results in StackOverflowError */
155                        Class<?> type = value.getClass();
156                        if (type.equals(String.class)) {
157                                String stringValue = (String) value;
158                                appendString(stringValue);
159                                return stringValue.startsWith(SERIALIZED);
160                        }
161                        if (type.equals(Boolean.class)) {
162                                builder.append(((Boolean) value) ? "1" : "0");
163                                return false;
164                        }
165                        if (type.equals(Double.class) || type.equals(Integer.class)) {
166                                builder.append(value.toString());
167                                return false;
168                        }
169
170                        for (int i = 0; i < objects.size(); ++i) {
171                                if (objects.get(i) == value) {
172                                        builder.append("^").append(i);
173                                        return true;
174                                }
175                        }
176
177                        if (List.class.isAssignableFrom(type)) {
178                                objects.add(value);
179                                List<?> list = (List<?>) value;
180                                boolean placeComma = false;
181                                builder.append("[");
182                                for (Object element : list) {
183                                        if (placeComma) {
184                                                builder.append(",");
185                                        } else {
186                                                placeComma = true;
187                                        }
188                                        serializeInternal(element);
189                                }
190                                builder.append("]");
191                                return true;
192                        }
193                        if (Map.class.isAssignableFrom(type)) {
194                                objects.add(value);
195                                Map<?, ?> map = (Map<?, ?>) value;
196                                boolean placeComma = false;
197                                builder.append("{");
198                                for (Map.Entry<?, ?> entry : map.entrySet()) {
199                                        if (placeComma) {
200                                                builder.append(",");
201                                        } else {
202                                                placeComma = true;
203                                        }
204                                        if (!(entry.getKey() instanceof String)) {
205                                                throw new FramsticksException().msg("non string keys are not allowed in serialization").arg("key type", entry.getKey().getClass());
206                                        }
207                                        appendString((String) entry.getKey());
208                                        builder.append(":");
209                                        serializeInternal(entry.getValue());
210                                }
211                                builder.append("}");
212                                return true;
213                        }
214                        throw new FramsticksException().msg("invalid type for serialization").arg("type", type);
215                }
216
217                public String serialize(Object value) {
218                        if (value instanceof String) {
219                                String stringValue = (String) value;
220                                if (!stringValue.startsWith(SERIALIZED)) {
221                                        return stringValue;
222                                }
223                        }
224                        boolean complex = serializeInternal(value);
225                        return (complex ? SERIALIZED : "") + builder.toString();
226                }
227
228        }
229
230
231        public static <T> String serialize(T value) {
232                return new SerializationContext().serialize(value);
233        }
234
235        public static <T> T deserialize(String value, Class<T> type) {
236                return null;
237        }
238
239}
Note: See TracBrowser for help on using the repository browser.