1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.content2bean.impl;
35
36 import info.magnolia.cms.util.ClasspathResourcesUtil;
37 import info.magnolia.content2bean.TypeDescriptor;
38
39 import java.io.File;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.util.Properties;
43
44 import info.magnolia.objectfactory.ClassFactory;
45 import info.magnolia.objectfactory.Classes;
46 import org.apache.commons.io.IOUtils;
47 import org.apache.commons.lang.StringUtils;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51
52
53
54
55
56
57
58 public class DescriptorFileBasedTypeMapping extends TypeMappingImpl {
59
60 private static Logger log = LoggerFactory.getLogger(DescriptorFileBasedTypeMapping.class);
61
62 public DescriptorFileBasedTypeMapping() {
63 String[] fileNames = ClasspathResourcesUtil.findResources(new ClasspathResourcesUtil.Filter(){
64 public boolean accept(String name) {
65 return name.endsWith(".content2bean");
66 }
67 });
68
69 for (int i = 0; i < fileNames.length; i++) {
70 String fileName = fileNames[i];
71 processFile(fileName);
72 }
73 }
74
75 protected void processFile(String fileName) {
76 Properties props = new Properties();
77 InputStream stream = null;
78 try {
79 stream = ClasspathResourcesUtil.getStream(fileName);
80 props.load(stream);
81
82 }
83 catch (IOException e) {
84 log.error("can't read collection to bean information " + fileName, e);
85 }
86 IOUtils.closeQuietly(stream);
87
88 String className = StringUtils.replaceChars(fileName, File.separatorChar, '.');
89 className = StringUtils.removeStart(className, ".");
90 className = StringUtils.removeEnd(className, ".content2bean");
91 try {
92 Class<?> typeClass = Classes.getClassFactory().forName(className);
93
94 TypeDescriptor typeDescriptor = processProperties(typeClass, props);
95 addTypeDescriptor(typeClass, typeDescriptor);
96 } catch (Exception e) {
97 log.error("can't instantiate type descriptor for " + className, e);
98 }
99 }
100
101 protected TypeDescriptor processProperties(Class<?> className, Properties props) throws Exception {
102 String descriptorClassName = StringUtils.defaultIfEmpty(props.getProperty("descriptorClass"), PropertiesBasedTypeDescriptor.class.getName());
103 final ClassFactory cl = Classes.getClassFactory();
104 Class<? extends TypeDescriptor> descriptorClass = cl.forName(descriptorClassName);
105 return cl.newInstance(descriptorClass, props);
106 }
107 }