source: trunk/CrossPare/src/de/ugoe/cs/cpdp/decentApp/ResourceTool.java @ 61

Last change on this file since 61 was 41, checked in by sherbold, 9 years ago
  • formatted code and added copyrights
  • Property svn:mime-type set to text/plain
File size: 13.2 KB
Line 
1// Copyright 2015 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.cpdp.decentApp;
16
17import java.io.File;
18import java.io.IOException;
19import java.util.HashMap;
20import java.util.Map;
21
22import org.eclipse.emf.common.util.BasicDiagnostic;
23import org.eclipse.emf.common.util.Diagnostic;
24import org.eclipse.emf.common.util.EList;
25import org.eclipse.emf.common.util.URI;
26import org.eclipse.emf.ecore.EObject;
27import org.eclipse.emf.ecore.EOperation;
28import org.eclipse.emf.ecore.EPackage;
29import org.eclipse.emf.ecore.EStructuralFeature;
30import org.eclipse.emf.ecore.EValidator;
31import org.eclipse.emf.ecore.resource.Resource;
32import org.eclipse.emf.ecore.resource.ResourceSet;
33import org.eclipse.emf.ecore.resource.impl.BinaryResourceImpl;
34import org.eclipse.emf.ecore.resource.impl.ResourceFactoryImpl;
35import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
36import org.eclipse.emf.ecore.util.Diagnostician;
37import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
38import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
39import org.eclipse.ocl.common.OCLConstants;
40import org.eclipse.ocl.ecore.delegate.OCLInvocationDelegateFactory;
41import org.eclipse.ocl.ecore.delegate.OCLSettingDelegateFactory;
42import org.eclipse.ocl.ecore.delegate.OCLValidationDelegateFactory;
43
44/**
45 * Class for handling different EMF Ressources
46 *
47 * @author Philip Makedonski
48 *
49 */
50public class ResourceTool {
51
52    protected ResourceFactoryImpl resourceFactory = new XMIResourceFactoryImpl();
53
54    /**
55     * Constructor
56     *
57     * @param loggedClass
58     */
59    public ResourceTool(String loggedClass) {
60        System.setProperty("org.slf4j.simpleLogger.logFile", "validation.log");
61        System.setProperty("org.slf4j.simpleLogger.logFile", "System.out");
62    }
63
64    /**
65     * Initializes the validator
66     */
67    protected void initializeValidator() {
68        // OCL.initialize(null);
69        String oclDelegateURI = OCLConstants.OCL_DELEGATE_URI + "/Pivot";
70
71        EOperation.Internal.InvocationDelegate.Factory.Registry.INSTANCE
72            .put(oclDelegateURI, new OCLInvocationDelegateFactory(oclDelegateURI));
73        EStructuralFeature.Internal.SettingDelegate.Factory.Registry.INSTANCE
74            .put(oclDelegateURI, new OCLSettingDelegateFactory(oclDelegateURI));
75        EValidator.ValidationDelegate.Registry.INSTANCE
76            .put(oclDelegateURI, new OCLValidationDelegateFactory(oclDelegateURI));
77
78        // EStructuralFeature.Internal.SettingDelegate.Factory.Registry.INSTANCE.put(oclDelegateURI,
79        // new OCLSettingDelegateFactory.Global());
80        // QueryDelegate.Factory.Registry.INSTANCE.put(oclDelegateURI, new
81        // OCLQueryDelegateFactory.Global());
82
83    }
84
85    /**
86     * Validates the ressource
87     *
88     * @param resource
89     *            to validate
90     */
91    public void validateResource(Resource resource) {
92        BasicDiagnostic diagnostics = new BasicDiagnostic();
93        boolean valid = true;
94        for (EObject eo : resource.getContents()) {
95            Map<Object, Object> context = new HashMap<Object, Object>();
96            boolean validationResult = Diagnostician.INSTANCE.validate(eo, diagnostics, context);
97            showDiagnostics(diagnostics, "");
98            valid &= validationResult;
99        }
100
101        if (!valid) {
102            System.out.println("Problem with validation!");
103        }
104    }
105
106    /**
107     * Output method for showing diagnostics for different ressources
108     *
109     * @param diagnostics
110     * @param indent
111     */
112    protected void showDiagnostics(Diagnostic diagnostics, String indent) {
113        indent += "  ";
114        for (Diagnostic d : diagnostics.getChildren()) {
115            System.out.println(indent + d.getSource());
116            System.out.println(indent + "  " + d.getMessage());
117            showDiagnostics(d, indent);
118        }
119    }
120
121    /**
122     * Loads a ressource from XMI
123     *
124     * @param inputPath
125     *            path to the xmi
126     * @param extension
127     *            of the ressource to load
128     * @param p
129     *            the given EPackage
130     * @return
131     */
132    // TODO: workarounds copied from respective methods without EPackage parameter
133    @SuppressWarnings(
134        { "rawtypes", "unchecked" })
135    public Resource loadResourceFromXMI(String inputPath, String extension, EPackage p) {
136        Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
137        Map<String, Object> m = reg.getExtensionToFactoryMap();
138        m.put(extension, resourceFactory);
139        ResourceSet resSetIn = new ResourceSetImpl();
140        // critical part
141        resSetIn.getPackageRegistry().put(p.getNsURI(), p);
142
143        Resource inputResource = resSetIn.createResource(URI.createURI(inputPath));
144        try {
145            Map options = new HashMap<>();
146            options.put(XMIResourceImpl.OPTION_DEFER_IDREF_RESOLUTION, Boolean.TRUE);
147            // options.put(XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF,
148            // XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF_DISCARD);
149            inputResource.load(options);
150        }
151        catch (IOException e) {
152            e.printStackTrace();
153        }
154        return inputResource;
155    }
156
157    /**
158     * Loads a ressource from XMI
159     *
160     * @param inputPath
161     *            path to the xmi
162     * @param extension
163     *            of the ressource to load
164     * @return
165     */
166
167    @SuppressWarnings(
168        { "rawtypes", "unchecked" })
169    public Resource loadResourceFromXMI(String inputPath, String extension) {
170        Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
171        Map<String, Object> m = reg.getExtensionToFactoryMap();
172        m.put(extension, resourceFactory);
173        ResourceSet resSetIn = new ResourceSetImpl();
174        Resource inputResource = resSetIn.createResource(URI.createURI(inputPath));
175        try {
176            Map options = new HashMap<>();
177            options.put(XMIResourceImpl.OPTION_DEFER_IDREF_RESOLUTION, Boolean.TRUE);
178            // options.put(XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF,
179            // XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF_DISCARD);
180            inputResource.load(options);
181        }
182        catch (IOException e) {
183            e.printStackTrace();
184        }
185        return inputResource;
186    }
187
188    /**
189     * Gets a ressource from a binary form
190     *
191     * @param inputPath
192     *            path to the binary
193     * @param extension
194     *            of the model to load
195     * @param p
196     *            EPackage to put the loaded ressource in
197     * @return
198     */
199    public Resource getResourceFromBinary(String inputPath, String extension, EPackage p) {
200        Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
201        Map<String, Object> m = reg.getExtensionToFactoryMap();
202        m.put(extension, new Resource.Factory() {
203
204            @Override
205            public Resource createResource(URI uri) {
206                return new BinaryResourceImpl(uri);
207            }
208
209        });
210
211        ResourceSet resSetIn = new ResourceSetImpl();
212        // critical part
213        resSetIn.getPackageRegistry().put(p.getNsURI(), p);
214
215        Resource inputResource = resSetIn.createResource(URI.createURI(inputPath));
216        return inputResource;
217    }
218
219    /**
220     * Loads a ressource from a binary form
221     *
222     * @param inputPath
223     *            path to the binary
224     * @param extension
225     *            of the model to load
226     * @param p
227     *            EPackage to put the loaded ressource in
228     * @return
229     */
230    // TODO: workarounds copied from respective methods without EPackage parameter
231    @SuppressWarnings(
232        { "rawtypes" })
233    public Resource loadResourceFromBinary(String inputPath, String extension, EPackage p) {
234        Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
235        Map<String, Object> m = reg.getExtensionToFactoryMap();
236        m.put(extension, new Resource.Factory() {
237
238            @Override
239            public Resource createResource(URI uri) {
240                return new BinaryResourceImpl(uri);
241            }
242
243        });
244
245        ResourceSet resSetIn = new ResourceSetImpl();
246        // critical part
247        resSetIn.getPackageRegistry().put(p.getNsURI(), p);
248
249        Resource inputResource = resSetIn.createResource(URI.createURI(inputPath));
250        if (new File(inputPath).exists()) {
251
252            try {
253                Map options = new HashMap<>();
254                // options.put(BinaryResourceImpl.OPTION_DEFER_IDREF_RESOLUTION, Boolean.TRUE);
255                // options.put(BinaryResourceImpl.OPTION_DEFER_IDREF_RESOLUTION, Boolean.TRUE);
256                // options.put(XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF,
257                // XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF_DISCARD);
258                inputResource.load(options);
259            }
260            catch (IOException e) {
261                e.printStackTrace();
262            }
263        }
264        return inputResource;
265    }
266
267    /**
268     * Loads a ressource from a binary form
269     *
270     * @param inputPath
271     *            path to the binary
272     * @param extension
273     *            of the model to load
274     * @return
275     */
276    @SuppressWarnings(
277        { "rawtypes" })
278    public Resource loadResourceFromBinary(String inputPath, String extension) {
279        Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
280        Map<String, Object> m = reg.getExtensionToFactoryMap();
281        m.put(extension, new Resource.Factory() {
282
283            @Override
284            public Resource createResource(URI uri) {
285                return new BinaryResourceImpl(uri);
286            }
287
288        });
289
290        ResourceSet resSetIn = new ResourceSetImpl();
291        Resource inputResource = resSetIn.createResource(URI.createURI(inputPath));
292        try {
293            Map options = new HashMap<>();
294            // options.put(XMIResourceImpl.OPTION_DEFER_IDREF_RESOLUTION, Boolean.TRUE);
295            // options.put(XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF,
296            // XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF_DISCARD);
297            inputResource.load(options);
298        }
299        catch (IOException e) {
300            e.printStackTrace();
301        }
302        return inputResource;
303    }
304
305    /**
306     * Stores the binary resource contents to a given path
307     *
308     * @param contents
309     *            EList of different EObjects to store
310     * @param outputPath
311     *            path to store to
312     * @param extension
313     *            of the model to store
314     */
315    @SuppressWarnings(
316        { "rawtypes" })
317    public void storeBinaryResourceContents(EList<EObject> contents,
318                                            String outputPath,
319                                            String extension)
320    {
321        Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
322        Map<String, Object> m = reg.getExtensionToFactoryMap();
323        m.put(extension, new Resource.Factory() {
324
325            @Override
326            public Resource createResource(URI uri) {
327                return new BinaryResourceImpl(uri);
328            }
329
330        });
331
332        ResourceSet resSet = new ResourceSetImpl();
333        Resource outputResource = resSet.createResource(URI.createURI(outputPath));
334        outputResource.getContents().addAll(contents);
335        try {
336            Map options = new HashMap<>();
337            // options.put(XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF,
338            // XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF_DISCARD);
339            outputResource.save(options);
340        }
341        catch (IOException e) {
342            e.printStackTrace();
343        }
344    }
345
346    /**
347     * Stores the resource contents to a given path
348     *
349     * @param contents
350     *            EList of different EObjects to store
351     * @param outputPath
352     *            path to store to
353     * @param extension
354     *            of the model to store
355     */
356    @SuppressWarnings(
357        { "unchecked", "rawtypes" })
358    public void storeResourceContents(EList<EObject> contents, String outputPath, String extension)
359    {
360        // TODO: duplicated from loadResourceFromXMI => move to a more appropriate location
361        Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
362        Map<String, Object> m = reg.getExtensionToFactoryMap();
363        m.put(extension, resourceFactory);
364
365        ResourceSet resSet = new ResourceSetImpl();
366        Resource outputResource = resSet.createResource(URI.createURI(outputPath));
367        outputResource.getContents().addAll(contents);
368        try {
369            Map options = new HashMap<>();
370            options.put(XMIResourceImpl.OPTION_ENCODING, "UTF-8");
371            // options.put(XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF,
372            // XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF_DISCARD);
373            outputResource.save(options);
374        }
375        catch (IOException e) {
376            e.printStackTrace();
377        }
378    }
379
380}
Note: See TracBrowser for help on using the repository browser.