Project

General

Profile

Download (7.42 KB) Statistics
| Branch: | Tag: | Revision:
1
package eu.etaxonomy.cdm.cache;
2

    
3
import java.io.File;
4
import java.io.FileOutputStream;
5
import java.io.IOException;
6
import java.io.InputStream;
7
import java.io.ObjectInputStream;
8
import java.io.ObjectOutputStream;
9
import java.lang.reflect.Field;
10
import java.net.URISyntaxException;
11
import java.net.URL;
12
import java.util.HashMap;
13
import java.util.Iterator;
14
import java.util.Map;
15

    
16
import org.hibernate.SessionFactory;
17
import org.hibernate.boot.Metadata;
18
import org.hibernate.boot.MetadataSources;
19
import org.hibernate.boot.registry.StandardServiceRegistry;
20
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
21
import org.hibernate.cfg.Configuration;
22
import org.hibernate.mapping.PersistentClass;
23
import org.hibernate.mapping.Property;
24
import org.hibernate.metadata.ClassMetadata;
25
import org.hibernate.property.access.spi.Getter;
26

    
27
import net.sf.ehcache.Cache;
28
import net.sf.ehcache.Element;
29

    
30

    
31
/**
32
 * This class serializing and deserializing the CDM model for performance purposes.
33
 * To serialize it see the comments on {@link #main(String[])} and on
34
 * https://dev.e-taxonomy.eu/redmine/projects/edit/wiki/TaxonomicEditorDevelopersGuide#Model-Change-Actions
35
 *
36
 * @author c.mathew
37
 \* @since 2015
38
 *
39
 */
40
public class CdmModelCacher {
41

    
42

    
43
    public static String HB_CONFIG_FILE_PATH= "/eu/etaxonomy/cdm/mappings/hibernate.cfg.xml";
44

    
45
    public static final String CDM_MAP_SER_FILE = "cdm.map.ser";
46
    public static final String CDM_MAP_SER_FOLDER = "/eu/etaxonomy/cdm/mappings/";
47
    public static final String CDM_MAP_SER_FILE_PATH = CDM_MAP_SER_FOLDER + CDM_MAP_SER_FILE;
48

    
49

    
50

    
51

    
52
    public void cacheGetterFields(Cache cache) throws IOException, ClassNotFoundException, URISyntaxException {
53
        Map<String, CdmModelFieldPropertyFromClass> modelClassMap = loadModelClassMap();
54

    
55
        cache.removeAll();
56

    
57
        for(Map.Entry<String, CdmModelFieldPropertyFromClass> entry : modelClassMap.entrySet()) {
58
            cache.put(new Element(entry.getKey(), entry.getValue()));
59
        }
60
    }
61

    
62
    public Map<String, CdmModelFieldPropertyFromClass> loadModelClassMap() throws URISyntaxException, IOException, ClassNotFoundException  {
63

    
64
        // ============== Eclpipse specific ============== //
65
        /*Bundle bundle = Platform.getBundle("eu.etaxonomy.taxeditor.cdmlib");
66

    
67
        URL modelMapFileBundleURL = bundle.getEntry(CDM_MAP_SER_FILE_PATH);
68
        URL modelMapFileURL = FileLocator.resolve(modelMapFileBundleURL);
69
        String modelMapFilePath = modelMapFileURL.getFile();
70
        FileInputStream fin = new FileInputStream(modelMapFilePath);
71
        */
72
        InputStream fin = this.getClass().getResourceAsStream(CDM_MAP_SER_FILE_PATH);
73
        // ==============000000000000000 ============== //
74

    
75
        ObjectInputStream ois = new ObjectInputStream(fin);
76
        @SuppressWarnings("unchecked")
77
		Map<String, CdmModelFieldPropertyFromClass> modelClassMap = (Map<String, CdmModelFieldPropertyFromClass>) ois.readObject();
78
        ois.close();
79
        return modelClassMap;
80
    }
81

    
82

    
83
    public Map<String, CdmModelFieldPropertyFromClass> generateModelClassMap() {
84

    
85
    	// A SessionFactory is set up once for an application!
86
        URL hibernateConfigFile = this.getClass().getResource(HB_CONFIG_FILE_PATH);
87
    	final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
88
    			.configure(hibernateConfigFile) // configures settings from hibernate.cfg.xml
89
    			.build();
90
    	SessionFactory sessionFactory = null;
91
    	Map<String, CdmModelFieldPropertyFromClass> modelClassMap = new HashMap<>();
92
    	try {
93
//    		ConnectionProvider connectionProvider = registry.getService(ConnectionProvider.class);
94
//    		DatasourceConnectionProviderImpl providerImpl = registry.getService(DatasourceConnectionProviderImpl.class);
95

    
96
    		Metadata metadata = new MetadataSources( registry ).buildMetadata();
97
    		sessionFactory = metadata.buildSessionFactory();
98
//    		Configuration configuration = buildConfiguration(HB_CONFIG_FILE_PATH);
99
        	Map<String, ClassMetadata> classMetaDataMap = sessionFactory.getAllClassMetadata();
100
//        	Metadata metadata = new MetadataSources( registry ).getMetadataBuilder().applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ).build();
101

    
102

    
103
            for(ClassMetadata classMetaData :classMetaDataMap.values()) {
104
            	Class<?> mappedClass = classMetaData.getMappedClass();
105

    
106
                String mappedClassName = mappedClass.getName();
107

    
108
                PersistentClass persistentClass =metadata.getEntityBinding(mappedClassName);
109
                CdmModelFieldPropertyFromClass cmgmfc = new CdmModelFieldPropertyFromClass(mappedClassName);
110
                System.out.println("Adding class : " + mappedClassName + " to cache");
111
                addGetters(persistentClass, cmgmfc);
112
                modelClassMap.put(mappedClassName, cmgmfc);
113
            }
114
    	}
115
    	catch (Exception e) {
116
    		// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
117
    		// so destroy it manually.
118
    		StandardServiceRegistryBuilder.destroy( registry );
119
    		e.printStackTrace();
120
    	}
121

    
122

    
123
        return modelClassMap;
124
    }
125

    
126

    
127
    public static Configuration buildConfiguration(String hibernateConfigFilePath) {
128
        Configuration configuration = new Configuration().configure(hibernateConfigFilePath);
129
        configuration.buildMappings();
130
        return configuration;
131
    }
132

    
133
    private void addGetters(PersistentClass persistentClass, CdmModelFieldPropertyFromClass cmgmfc) {
134
        if (persistentClass != null) {
135
            Iterator propertyIt = persistentClass.getPropertyIterator();
136

    
137
            while(propertyIt.hasNext())
138
            {
139
                Property property = (Property)propertyIt.next();
140
                Getter getter = property.getGetter(persistentClass.getMappedClass());
141
                if(getter != null && getter.getMember() != null) {
142
                    Field field = (Field)getter.getMember();
143

    
144
                    //logger.info(" - contains field '" + field.getName() + "' of type '" + field.getType().getName() + "'");
145
                    cmgmfc.addGetMethods(field.getName());
146
                }
147
            }
148
            addGetters(persistentClass.getSuperclass(), cmgmfc);
149
        }
150
    }
151

    
152

    
153

    
154
    public static void main(String argv[]) {
155

    
156
        // To re-create the serialised cdm map run,
157
        // mvn exec:java -Dexec.mainClass="eu.etaxonomy.cdm.cache.CdmModelCacher"
158
        // in the eu.etaxonomy.taxeditor.cdmlib project root dir
159
    	// See also https://dev.e-taxonomy.eu/redmine/projects/edit/wiki/TaxonomicEditorDevelopersGuide#Model-Change-Actions
160
    	//Note AM: does not fully work for me, but running the main from the IDE works.
161

    
162

    
163
        CdmModelCacher cdmModelCacher = new CdmModelCacher();
164
        Map<String, CdmModelFieldPropertyFromClass> modelClassMap = cdmModelCacher.generateModelClassMap();
165
        try{
166
        	if (!modelClassMap.isEmpty()){
167
        	    File outFile = new File("src/main/resources/" + CDM_MAP_SER_FILE_PATH);
168
        	    System.out.println("writing to " + outFile.getAbsolutePath());
169
        		FileOutputStream fout = new FileOutputStream(outFile);
170
        		ObjectOutputStream oos = new ObjectOutputStream(fout);
171
        		oos.writeObject(modelClassMap);
172
        		oos.close();
173
        		System.out.println("CDM Map serialized");
174
        	}else{
175
        		String message = "CDM Map was empty. Model cache update NOT successful";
176
        		System.out.println(message);
177
        	}
178

    
179
        }catch(Exception ex){
180
            ex.printStackTrace();
181
        }
182

    
183
    }
184

    
185

    
186
}
(4-4/11)