source: default/trunk/de.ugoe.cs.swe.bnftools.xtools/src/resource/tools/xtools/ResourceTool.java @ 62

Last change on this file since 62 was 58, checked in by phdmakk, 11 years ago

+ initial commit for additional tools for testing and development

  • Property svn:mime-type set to text/plain
File size: 7.4 KB
RevLine 
[58]1package resource.tools.xtools;
2
3import java.io.File;
4import java.io.IOException;
5import java.util.HashMap;
6import java.util.Map;
7import java.util.Properties;
8
9import org.apache.commons.io.FileUtils;
10import org.eclipse.emf.common.util.BasicDiagnostic;
11import org.eclipse.emf.common.util.Diagnostic;
12import org.eclipse.emf.common.util.EList;
13import org.eclipse.emf.common.util.TreeIterator;
14import org.eclipse.emf.common.util.URI;
15import org.eclipse.emf.ecore.EObject;
16import org.eclipse.emf.ecore.EOperation;
17import org.eclipse.emf.ecore.EPackage;
18import org.eclipse.emf.ecore.EStructuralFeature;
19import org.eclipse.emf.ecore.EValidator;
20import org.eclipse.emf.ecore.resource.Resource;
21import org.eclipse.emf.ecore.resource.ResourceSet;
22import org.eclipse.emf.ecore.resource.impl.FileURIHandlerImpl;
23import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
24import org.eclipse.emf.ecore.util.Diagnostician;
25import org.eclipse.emf.ecore.util.EObjectValidator;
26import org.eclipse.emf.ecore.util.EcoreUtil;
27import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
28import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
29import org.eclipse.ocl.common.OCLConstants;
30import org.eclipse.ocl.ecore.delegate.OCLInvocationDelegateFactory;
31import org.eclipse.ocl.ecore.delegate.OCLSettingDelegateFactory;
32import org.eclipse.ocl.ecore.delegate.OCLValidationDelegateFactory;
33import org.eclipse.xtext.resource.SaveOptions;
34import org.eclipse.xtext.resource.XtextResource;
35import org.eclipse.xtext.resource.XtextResourceSet;
36import org.eclipse.xtext.serializer.impl.Serializer;
37import org.slf4j.Logger;
38import org.slf4j.LoggerFactory;
39import org.slf4j.impl.SimpleLogger;
40
41import com.google.inject.Injector;
42
43public class ResourceTool {
44
45        protected static Logger log;
46        protected Injector injector;
47
48        public ResourceTool() {
49                System.setProperty(Logger.class.getName(),SimpleLogger.class.getName());
50                System.setProperty("org.slf4j.simpleLogger.logFile","validation.log");
51                System.setProperty("org.slf4j.simpleLogger.logFile","System.out");
52                log = LoggerFactory.getLogger(ResourceTool.class);     
53        }
54
55        public Resource loadResourceFromXtext(String workspace, String pathName, boolean resolveAll) {
56                // "workspace" is a string that contains the path to the workspace containing the DSL program.
57                new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri(workspace);
58               
59                XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
60
61                //TODO:why is this not needed for FAMIX but needed for DAG?
62                if (resolveAll) {
63                        resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
64                }
65
66                Resource resource = resourceSet.getResource(URI.createURI(pathName), true);
67                for (org.eclipse.emf.ecore.resource.Resource.Diagnostic diagnostic : resource.getErrors()) {
68                        log.warn("xtext: "+diagnostic.getLine() +" :"+diagnostic.getMessage());
69                }
70                return resource;
71        }
72
73        @SuppressWarnings("restriction")
74        public Resource storeResourceInXtext(String workspace, String pathName, EList<EObject> contents) {
75                // "workspace" is a string that contains the path to the workspace containing the DSL program.
76                new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri(workspace);
77               
78                XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
79
80                String s = "";
81                Serializer serializer = injector.getInstance(Serializer.class);
82
83                try { 
84                        EObject tdlPackage = contents.get(0);
85                        s += serializer.serialize(tdlPackage); 
86                } catch (Exception ex) { // fall back: 
87                        System.out.println("Model could not be serialized");
88                        ex.printStackTrace();
89                } 
90//              TreeIterator<Object> iterator = EcoreUtil.getAllContents(contents);
91//              while (iterator.hasNext()) {
92//                      EObject next = (EObject) iterator.next();
93//                      try { 
94//                              s += serializer.serialize(next)+"\n"; 
95//                      } catch (Exception ex) { // fall back: 
96//                              System.out.println(next.eClass().getName() +" could not be serialized"); 
97//                      } 
98//              }
99                System.out.println(s);
100               
101                try {
102                        FileUtils.writeStringToFile(new File(pathName), s);
103                } catch (IOException e) {
104                        // TODO Auto-generated catch block
105                        e.printStackTrace();
106                }
107                Resource resource = null;
108                //Resource resource = loadResourceFromXtext(workspace, pathName, true);
109
110                return resource;
111        }
112
113       
114        @SuppressWarnings({ "rawtypes", "unchecked" })
115        public Resource loadResourceFromXMI(String inputPath, String extension) {
116            Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
117            Map<String, Object> m = reg.getExtensionToFactoryMap();
118                m.put(extension, new XMIResourceFactoryImpl());
119            ResourceSet resSetIn = new ResourceSetImpl();
120            Resource inputResource = resSetIn.createResource(URI.createURI(inputPath));
121            try {
122                Map options = new HashMap<>();
123                options.put(XMIResourceImpl.OPTION_DEFER_IDREF_RESOLUTION, Boolean.TRUE);
124//              options.put(XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF, XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF_DISCARD);
125                        inputResource.load(options);
126                } catch (IOException e) {
127                        e.printStackTrace();
128                }
129                return inputResource;
130        }
131
132        protected void initializeValidator() {
133        //              OCL.initialize(null);
134                        String oclDelegateURI = OCLConstants.OCL_DELEGATE_URI+"/Pivot";
135                       
136                    EOperation.Internal.InvocationDelegate.Factory.Registry.INSTANCE.put(oclDelegateURI,
137                        new OCLInvocationDelegateFactory(oclDelegateURI));
138                    EStructuralFeature.Internal.SettingDelegate.Factory.Registry.INSTANCE.put(oclDelegateURI,
139                        new OCLSettingDelegateFactory(oclDelegateURI));
140                    EValidator.ValidationDelegate.Registry.INSTANCE.put(oclDelegateURI,
141                        new OCLValidationDelegateFactory(oclDelegateURI));
142                   
143        //          EStructuralFeature.Internal.SettingDelegate.Factory.Registry.INSTANCE.put(oclDelegateURI,
144        //              new OCLSettingDelegateFactory.Global());
145        //          QueryDelegate.Factory.Registry.INSTANCE.put(oclDelegateURI, new OCLQueryDelegateFactory.Global());
146                   
147                }
148
149        public void validateResource(Resource resource) {
150            BasicDiagnostic diagnostics = new BasicDiagnostic();
151            boolean valid = true;
152            for (EObject eo : resource.getContents())
153            {
154                Map<Object, Object> context = new HashMap<Object, Object>();
155                boolean validationResult = Diagnostician.INSTANCE.validate(eo, diagnostics, context);
156                showDiagnostics(diagnostics, "");
157                        valid &= validationResult;
158            }
159           
160            if (!valid){
161                System.out.println("Problem with validation!");
162            }
163        }
164
165        protected void showDiagnostics(Diagnostic diagnostics, String indent) {
166                indent+="  ";
167                for (Diagnostic d : diagnostics.getChildren()){
168                        log.warn(indent+d.getSource());
169                        log.warn(indent+"  "+d.getMessage());
170                        showDiagnostics(d,indent);
171                }
172        }
173
174        @SuppressWarnings({ "unchecked", "rawtypes" })
175        protected void storeResourceContents(EList<EObject> contents, String outputPath, String extension) {
176                //TODO: duplicated from loadResourceFromXMI => move to a more appropriate location
177                Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
178            Map<String, Object> m = reg.getExtensionToFactoryMap();
179                m.put(extension, new XMIResourceFactoryImpl());
180               
181            ResourceSet resSet = new ResourceSetImpl();
182                Resource outputResource = resSet.createResource(URI.createURI(outputPath));
183            outputResource.getContents().addAll(contents);
184            try {
185              Map options = new HashMap<>();
186              options.put(XMIResourceImpl.OPTION_ENCODING, "UTF-8");
187//            options.put(XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF, XMIResourceImpl.OPTION_PROCESS_DANGLING_HREF_DISCARD);
188              outputResource.save(options);
189            } catch (IOException e) {
190              e.printStackTrace();
191            }
192        }
193
194}
Note: See TracBrowser for help on using the repository browser.