source: java/main/src/main/java/com/framsticks/params/SimpleAbstractAccess.java @ 78

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

Add f0 parsing and f0->Model transformation.

File size: 9.7 KB
Line 
1package com.framsticks.params;
2
3import java.io.IOException;
4import java.text.DecimalFormat;
5import java.text.DecimalFormatSymbols;
6import java.util.ArrayList;
7import java.util.Collection;
8import java.util.List;
9
10import com.framsticks.params.types.*;
11import org.apache.log4j.Logger;
12import java.util.Locale;
13
14/**
15 * The Class SimpleAbstractAccess implements all the methods of AccessInterface
16 * which actions can be implemented with usage of {@link AccessInterface} methods
17 * or concern schema, which is stored in {@link #framsClass}
18 *
19 * Based on c++ class SimpleAbstractParam located in: cpp/gdk/param.*
20 *
21 * @author Jarek Szymczak <name.surname@gmail.com>, Mateusz Jarus (please
22 *         replace name and surname with my personal data)
23 *
24 * @author Piotr Sniegowski
25 */
26public abstract class SimpleAbstractAccess implements AccessInterface {
27
28        private final static Logger LOGGER = Logger.getLogger(SimpleAbstractAccess.class.getName());
29
30
31
32    @Override
33        public final FramsClass getFramsClass() {
34                return framsClass;
35        }
36
37        public void setFramsClass(FramsClass framsClass) {
38                this.framsClass = framsClass;
39        }
40    /**
41         * Simple String key, value class.
42         */
43        public static class Entry {
44
45                public final String key;
46                public final String value;
47
48                public Entry(String key, String value) {
49                        this.key = key;
50                        this.value = value;
51                }
52
53                @Override
54                public String toString() {
55                        return key + " = " + value;
56                }
57        }
58
59        protected FramsClass framsClass;
60
61        @Override
62        public String getId() {
63                return framsClass.getId();
64        }
65
66    @Override
67        public int getParamCount() {
68                return framsClass.getParamCount();
69        }
70
71        @Override
72        public Param getParam(int i) {
73                return framsClass.getParamEntry(i);
74        }
75
76        @Override
77        public Param getParam(String id) {
78                return framsClass.getParamEntry(id);
79        }
80
81
82        @Override
83        public Param getGroupMember(int gi, int n) {
84                return framsClass.getGroupMember(gi, n);
85        }
86
87        @Override
88        public <T> T get(int i, Class<T> type) {
89                return get(getParam(i), type);
90        }
91
92        @Override
93        public <T> T get(String id, Class<T> type) {
94                return get(getParam(id), type);
95        }
96
97
98        @Override
99        public <T> int set(String id, T value) {
100                return set(getParam(id), value);
101        }
102
103        @Override
104        public <T> int set(int i, T value) {
105                return set(getParam(i), value);
106        }
107
108        @SuppressWarnings("unchecked")
109        @Override
110        public <T> int set(Param param, T value) {
111                int flags = 0;
112                //String id = param.getEffectiveId();
113                try {
114            Object oldValue = get(param, param.getStorageType());
115            Object casted = param.reassign(value, oldValue);
116            if (casted != oldValue) {
117                internalSet(param, casted);
118            }
119        } catch (CastFailure e) {
120            LOGGER.error("casting failure while set: ", e);
121
122        }
123        return flags;
124    }
125
126
127
128
129        @Override
130        public void setDefault(boolean numericOnly) {
131                for (int i = 0; i < framsClass.getParamCount(); i++)
132                        setDefault(i, numericOnly);
133        }
134
135        @Override
136        public void setDefault(int i, boolean numericOnly) {
137                Param entry = framsClass.getParamEntry(i);
138                if ((entry != null)     && (!numericOnly || entry.isNumeric())) {
139                        set(i, entry.getDef(entry.getStorageType()));
140                }
141        }
142
143        @Override
144        public void setMin() {
145                for (int i = 0; i < framsClass.getParamCount(); i++) {
146                        setMin(i);
147                }
148        }
149
150        @SuppressWarnings("unchecked")
151        @Override
152        public void setMin(int i) {
153                Param entry = framsClass.getParamEntry(i);
154                Object min = entry.getMin(entry.getStorageType());
155                if (min != null) {
156                        set(i, min);
157                }
158        }
159
160        @Override
161        public void setMax() {
162                for (int i = 0; i < framsClass.getParamCount(); i++) {
163                        setMax(i);
164                }
165        }
166
167        @SuppressWarnings("unchecked")
168        @Override
169        public void setMax(int i) {
170                Param entry = framsClass.getParamEntry(i);
171                Object max = entry.getMax(entry.getStorageType());
172                if (max != null) {
173                        set(i, max);
174                }
175        }
176
177        @Override
178        public void copyFrom(AccessInterface src) {
179                clearValues();
180                //TODO: iterate over self, and pull from src
181                /*
182                for (int i = 0; i < src.getFramsClass().size(); i++) {
183                        this.set(i, src.get(i, Object.class));
184                }
185                */
186        }
187
188
189
190
191        @Override
192        public void save(SinkInterface sink) {
193        assert framsClass != null;
194        sink.print(framsClass.getId()).print(":").breakLine();
195        for (Param p : framsClass.getParamEntries()) {
196            if (p instanceof ValueParam) {
197                Object value = get(p, Object.class);
198                if (value == null) {
199                    continue;
200                }
201                sink.print(p.getId()).print(":");
202                ((ValueParam)p).save(sink, value);
203                sink.breakLine();
204
205
206                //continue;
207            }
208            /*
209            if (p instanceof CompositeParam) {
210                if (!(p instanceof ListParam)) {
211                    continue;
212                }
213                Collection c = get(p, Collection.class);
214                if (c != null) {
215                    save(stream, p, c.size());
216                }
217            }
218            */
219
220        }
221        sink.breakLine();
222        }
223
224        @Override
225        public String save2(boolean omitDefaultValues) {
226                StringBuilder stringBuilder = new StringBuilder();
227                DecimalFormat df = new DecimalFormat("#.###", new DecimalFormatSymbols(
228                                Locale.ENGLISH));
229                boolean canOmitName = false;
230                int n = 0;
231                for (int i = 0; i < framsClass.getParamCount(); i++) {
232                        Object value = this.get(i, Object.class);
233                        Object def = framsClass.getParamEntry(i).getDef(Object.class);
234                        if (value != null && (!omitDefaultValues || !value.equals(def))) {
235                                if ((n != i && !canOmitName)
236                                                || (getParam(i).getFlags() & Flags.CANOMITNAME) == 0) {
237                                        stringBuilder.append(getParam(i).getId());
238                                        stringBuilder.append("=");
239                                }
240                                n++;
241                                canOmitName = true;
242                                if (this.get(i, Object.class) instanceof String) {
243                                        String valueString = this.get(i, String.class);
244                                        valueString = valueString.replaceAll("\\\"", "\\\\\"");
245                                        valueString = valueString.contains(",") ? "\""
246                                                        + valueString + "\"" : valueString;
247                                        // if ("".equals(valueString.trim()))
248                                        // value = "\"\"";
249                                        stringBuilder.append(valueString);
250                                } else if (this.get(i, Object.class) instanceof Double) {
251                                        stringBuilder.append(df.format(this.get(i, Double.class)));
252                                } else
253                                        stringBuilder.append(this.get(i, Object.class));
254                                stringBuilder.append(", ");
255                        } else {
256                                canOmitName = false;
257                        }
258                }
259
260                String params = "";
261                if (stringBuilder.length() > 1)
262                        params = stringBuilder.substring(0, stringBuilder.length() - 2);
263
264                return getId() + ":" + params;
265        }
266
267    /*
268    private static void appendToValue(StringBuilder value, String line) {
269
270        if (value.length() != 0) {
271            value.append(System.getProperty("line.separator"));
272        }
273        value.append(line);
274    }
275    */
276
277    private Entry readEntry(SourceInterface source)
278            throws IOException {
279
280        String line;
281        String key = null;
282        StringBuilder value = null;
283        while ((line = source.readLine()) != null)
284        {
285            if (key == null) {
286                int colonIndex = line.indexOf(':');
287                if (colonIndex == -1) {
288                    return null;
289                }
290                key = line.substring(0, colonIndex);
291                String inlineValue = line.substring(colonIndex + 1);
292
293
294                if (!inlineValue.startsWith("~")) {
295                    return new Entry(key, inlineValue);
296                }
297                value = new StringBuilder();
298                value.append(inlineValue.substring(1));
299                continue;
300            }
301            if (value.length() != 0) {
302                value.append(System.getProperty("line.separator"));
303            }
304            if (line.contains("~")) {
305                value.append(line.substring(0, line.indexOf("~")));
306                return new Entry(key, value.toString());
307            }
308            value.append(line);
309            /*
310            if (line.contains("~")) {
311                String lastLine = line.substring(0, line.indexOf("~"));
312                if (lastLine.length() > 0) {
313                    appendToValue(value, lastLine);
314                }
315                return new Entry(key, value.toString());
316            }
317            appendToValue(value, line);
318            */
319        }
320        return null;
321    }
322
323    @Override
324    public void load(SourceInterface source) throws Exception {
325        //TODO not clearing values, because get from manager gives only fields, not children
326        //this.clearValues();
327
328        Entry entry;
329        while ((entry = readEntry(source)) != null) {
330            Param param = getParam(entry.key);
331            if (param == null) {
332                continue;
333            }
334            if ((param.getFlags() & Flags.DONTLOAD) != 0) {
335                LOGGER.debug("DontLoad flag was set - not loading...");
336            } else {
337                int retFlags = this.set(param, entry.value);
338                if ((retFlags & (Flags.PSET_HITMIN | Flags.PSET_HITMAX)) != 0) {
339                    String which = ((retFlags & Flags.PSET_HITMIN) != 0) ? "small"
340                            : "big";
341                    LOGGER.warn("value of key '" + entry.key
342                            + "' was too " + which + ", adjusted");
343                }
344            }
345        }
346    }
347
348
349
350        protected abstract <T> void internalSet(Param param, T value);
351
352    @Override
353    public Collection<Param> getParams() {
354        return framsClass.getParamEntries();
355    }
356
357    /*
358        protected <T extends Comparable<T>> int setAndCut(Param param, Object value, Class<T> type) {
359                int flags = 0;
360                T val = type.cast(value);
361                T min = param.getMin(type);
362                T max = param.getMax(type);
363                if (min != null && val.compareTo(min) < 0) {
364                        val = min;
365                        flags |= Flags.PSET_HITMIN;
366                }
367                if (max != null && val.compareTo(max) > 0) {
368                        val = max;
369                        flags |= Flags.PSET_HITMAX;
370                }
371                internalSet(param, val);
372                return flags;
373        }*/
374
375
376}
Note: See TracBrowser for help on using the repository browser.