1 | package com.framsticks.util.lang; |
---|
2 | |
---|
3 | import java.lang.reflect.Field; |
---|
4 | import org.apache.logging.log4j.Logger; |
---|
5 | import org.apache.logging.log4j.LogManager; |
---|
6 | |
---|
7 | import com.framsticks.util.lang.Delimeted; |
---|
8 | |
---|
9 | public final class FlagsUtil { |
---|
10 | |
---|
11 | private final static Logger log = LogManager.getLogger(FlagsUtil.class); |
---|
12 | |
---|
13 | private FlagsUtil() { |
---|
14 | } |
---|
15 | |
---|
16 | public static String write(Class<?> flagsClass, int flags, String empty) { |
---|
17 | Delimeted<String> d = new Delimeted<String>("+", empty); |
---|
18 | try { |
---|
19 | for (Field f : flagsClass.getDeclaredFields()) { |
---|
20 | if (f.getType() != int.class) { |
---|
21 | continue; |
---|
22 | } |
---|
23 | if ((flags & f.getInt(null)) != 0) { |
---|
24 | d.append(f.getName()); |
---|
25 | } |
---|
26 | } |
---|
27 | } catch (IllegalArgumentException | IllegalAccessException e) { |
---|
28 | e.printStackTrace(); |
---|
29 | } |
---|
30 | return d.build(); |
---|
31 | } |
---|
32 | |
---|
33 | public static Integer read(Class<?> flagsClass, String flags) { |
---|
34 | Integer allFlags = 0; |
---|
35 | String[] flagsSplitted = flags.split("\\+"); |
---|
36 | for (String flag : flagsSplitted) { |
---|
37 | try { |
---|
38 | allFlags |= Integer.valueOf(flag); |
---|
39 | } catch (NumberFormatException ex) { |
---|
40 | try { |
---|
41 | Field field = flagsClass.getDeclaredField(flag.toUpperCase()); |
---|
42 | allFlags |= Integer.parseInt(field.get(null).toString()); |
---|
43 | } catch (SecurityException e) { |
---|
44 | log.warn("security exception was thrown while trying to read flag ({})", flag); |
---|
45 | } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { |
---|
46 | log.warn("selected flag is not known ({})", flag); |
---|
47 | } |
---|
48 | } |
---|
49 | } |
---|
50 | return allFlags; |
---|
51 | } |
---|
52 | } |
---|