Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: c95f1a497258869513e13bcbb9a6633e4f4a7eb5 (plain) (blame)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/*******************************************************************************
 * Copyright (c) 2004, 2010 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * IBM - Initial API and implementation
 * Anton Leherbauer (Wind River Systems)
 *******************************************************************************/
package org.eclipse.cdt.make.internal.core.scannerconfig;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.cdt.make.core.MakeCorePlugin;
import org.eclipse.cdt.make.core.scannerconfig.IDiscoveredPathManager.IDiscoveredScannerInfoSerializable;
import org.eclipse.cdt.make.core.scannerconfig.InfoContext;
import org.eclipse.cdt.make.internal.core.MakeMessages;
import org.eclipse.cdt.make.internal.core.scannerconfig2.PerProjectSICollector;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.Status;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.xml.sax.SAXException;

/**
 * Discovered scanner info persistance store
 *
 * @author vhirsl
 */
public final class DiscoveredScannerInfoStore {
	private static final QualifiedName dscFileNameProperty = new
            QualifiedName(MakeCorePlugin.getUniqueIdentifier(), "discoveredScannerConfigFileName"); //$NON-NLS-1$
	private static final String CDESCRIPTOR_ID = MakeCorePlugin.getUniqueIdentifier() + ".discoveredScannerInfo"; //$NON-NLS-1$
    public static final String SCD_STORE_VERSION = "scdStore"; //$NON-NLS-1$
	public static final String SI_ELEM = "scannerInfo"; //$NON-NLS-1$
	public static final String COLLECTOR_ELEM = "collector"; //$NON-NLS-1$
	public static final String ID_ATTR = "id"; //$NON-NLS-1$

	private static final String INSTANCE_ELEM = "instance";  //$NON-NLS-1$

	private static DiscoveredScannerInfoStore instance;

	/**
	 * Caches scanner config XML Documents per project using soft references.
	 */
	private final Map<IProject, Reference<Document>> fDocumentCache = new HashMap<IProject, Reference<Document>>();

	public static DiscoveredScannerInfoStore getInstance() {
		if (instance == null) {
			instance = new DiscoveredScannerInfoStore();
		}
		return instance;
	}
	/**
	 *
	 */
	private DiscoveredScannerInfoStore() {
	}

	public void loadDiscoveredScannerInfoFromState(IProject project, IDiscoveredScannerInfoSerializable serializable)
			throws CoreException {
		loadDiscoveredScannerInfoFromState(project, new InfoContext(project), serializable);
	}

	public void loadDiscoveredScannerInfoFromState(IProject project, InfoContext context, IDiscoveredScannerInfoSerializable serializable)
			throws CoreException {
		// Get the document
		Element rootElem = getRootElement(project, context, serializable);

		if(rootElem != null){
	        // get the collector element
	        NodeList collectorList = rootElem.getElementsByTagName(COLLECTOR_ELEM);
	        if (collectorList.getLength() > 0) {
	        	// find the collector element
	        	for (int i = 0; i < collectorList.getLength(); ++i) {
	        		Element collectorElem = (Element) collectorList.item(i);
	        		String collectorId = collectorElem.getAttribute(ID_ATTR);
	        		if (serializable.getCollectorId().equals(collectorId)) {
	    		        serializable.deserialize(collectorElem);
	        			break;
	        		}
	        	}
	        }
		}
	}

	public boolean hasInfo(IProject project, InfoContext context, IDiscoveredScannerInfoSerializable serializable){
		try {
			if(getRootElement(project, context, serializable) != null)
				return true;
		} catch (CoreException e) {
			MakeCorePlugin.log(e);
		}
		return false;
	}

	private Element getRootElement(IProject project, InfoContext context, IDiscoveredScannerInfoSerializable serializable) throws CoreException{
		if(serializable == null)
			return null;

		Document document = getDocument(project);
		Element rootElem = null;
		if (document != null) {
			NodeList rootList = document.getElementsByTagName(SI_ELEM);
			if (rootList.getLength() > 0) {
				rootElem = (Element) rootList.item(0);

				if(!context.isDefaultContext()){
					String instanceId = context.getInstanceId();

		        	Element instanceElem = findChild(rootElem, INSTANCE_ELEM, ID_ATTR, instanceId);

		        	rootElem = instanceElem;
				}
			}
		}

		return rootElem;
	}

	private Document getDocument(IProject project) throws CoreException {
		// Get the document
		Reference<Document> ref= fDocumentCache.get(project);
		Document document = ref != null ? ref.get() : null;
		if (document == null) {
		    try {
		        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		        IPath path = getDiscoveredScannerConfigStore(project);
		        if (path.toFile().exists()) {
		            // read form file
		            FileInputStream file = new FileInputStream(path.toFile());
		            document = builder.parse(file);
		            Node rootElem = document.getFirstChild();
		            if (rootElem.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE) {
		                // no version info; upgrade
		                upgradeDocument(document, project);
		            }
		        }
		        else {
		            // create new document
		            document = builder.newDocument();
		            ProcessingInstruction pi = document.createProcessingInstruction(SCD_STORE_VERSION, "version=\"2\""); //$NON-NLS-1$
		            document.appendChild(pi);
		            Element rootElement = document.createElement(SI_ELEM);
		            rootElement.setAttribute(ID_ATTR, CDESCRIPTOR_ID);
		            document.appendChild(rootElement);
		        }
		        fDocumentCache.put(project, new SoftReference<Document>(document));
		    }
		    catch (IOException e) {
		        MakeCorePlugin.log(e);
		        throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
		                MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
		    }
		    catch (ParserConfigurationException e) {
		        MakeCorePlugin.log(e);
		        throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
		                MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
		    }
		    catch (SAXException e) {
		        MakeCorePlugin.log(e);
		        throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
		                MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
		    }
		}
		return document;
	}

	private void upgradeDocument(Document document, IProject project) {
		Element rootElem = (Element) document.getElementsByTagName(SI_ELEM).item(0);
		ProcessingInstruction pi = document.createProcessingInstruction(SCD_STORE_VERSION, "version=\"2.0\""); //$NON-NLS-1$
		document.insertBefore(pi, rootElem);

		Element collectorElem = document.createElement(COLLECTOR_ELEM);
		collectorElem.setAttribute(ID_ATTR, PerProjectSICollector.COLLECTOR_ID);
		for (Node child = rootElem.getFirstChild(); child != null; child = rootElem.getFirstChild()) {
			collectorElem.appendChild(rootElem.removeChild(child));
		}
		rootElem.appendChild(collectorElem);
	}

	private Element findChild(Element parentElem, String name, String attr, String attrValue){
        Element cfgElem = null;
        NodeList cfgList = parentElem.getElementsByTagName(name);
        if (cfgList.getLength() > 0) {
        	// find per file collector element and remove children
        	for (int i = 0; i < cfgList.getLength(); ++i) {
        		Element cElem = (Element) cfgList.item(i);
        		String value = cElem.getAttribute(attr);
        		if (value.equals(attrValue)) {
        			cfgElem = cElem;
        			break;
        		}
        	}
        }

        return cfgElem;
	}

	private void saveDiscoveredScannerInfo(InfoContext context, IDiscoveredScannerInfoSerializable serializable, Document doc) {
		NodeList rootList = doc.getElementsByTagName(SI_ELEM);
		if (rootList.getLength() > 0) {
			Element rootElem = (Element) rootList.item(0);

			// get the collector element
			if(!context.isDefaultContext()){
				String instanceId = context.getInstanceId();

				Element instanceElem = findChild(rootElem, INSTANCE_ELEM, ID_ATTR, instanceId);

				if(instanceElem == null){
		        	instanceElem = doc.createElement(INSTANCE_ELEM);
		        	instanceElem.setAttribute(ID_ATTR, instanceId);
		        	rootElem.appendChild(instanceElem);
		        }

	        	rootElem = instanceElem;
			}

			// get the collector element
	        Element collectorElem = null;
	        NodeList collectorList = rootElem.getElementsByTagName(COLLECTOR_ELEM);
	        if (collectorList.getLength() > 0) {
	        	// find per file collector element and remove children
	        	for (int i = 0; i < collectorList.getLength(); ++i) {
	        		Element cElem = (Element) collectorList.item(i);
	        		String collectorId = cElem.getAttribute(ID_ATTR);
	        		if (serializable.getCollectorId().equals(collectorId)) {
	        			for (Node child = cElem.getFirstChild(); child != null;
	        					child = cElem.getFirstChild()) {
	        				cElem.removeChild(child);
	        			}
	        			collectorElem = cElem;
	        			break;
	        		}
	        	}
	        }
	        if (collectorElem == null) {
	        	// create per profile element
	        	collectorElem = doc.createElement(COLLECTOR_ELEM);
	        	collectorElem.setAttribute(ID_ATTR, serializable.getCollectorId());
	        	rootElem.appendChild(collectorElem);
	        }

			// Save the discovered scanner info
			serializable.serialize(collectorElem);
		}
	}
	public void saveDiscoveredScannerInfoToState(IProject project, IDiscoveredScannerInfoSerializable serializable) throws CoreException {
		saveDiscoveredScannerInfoToState(project, new InfoContext(project), serializable);
	}

	public void saveDiscoveredScannerInfoToState(IProject project, InfoContext context, IDiscoveredScannerInfoSerializable serializable) throws CoreException {
		Document document = getDocument(project);
		// Create document
		try {
			saveDiscoveredScannerInfo(context, serializable, document);

			// Transform the document to something we can save in a file
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
			DOMSource source = new DOMSource(document);
			StreamResult result = new StreamResult(stream);
			transformer.transform(source, result);

			// Save the document
			try {
				IPath path = getDiscoveredScannerConfigStore(project);
				FileOutputStream file = new FileOutputStream(path.toFile());
				file.write(stream.toByteArray());
				file.close();
			} catch (IOException e) {
				throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
						MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
			}

			// Close the streams
			stream.close();
		} catch (TransformerException e) {
			MakeCorePlugin.log(e);
			throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
					MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
		} catch (IOException e) {
			MakeCorePlugin.log(e);
			throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
					MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
		}
	}

    public IPath getDiscoveredScannerConfigStore(IProject project) {
        String fileName = project.getName() + ".sc"; //$NON-NLS-1$
        String storedFileName = null;
        try {
            storedFileName = project.getPersistentProperty(dscFileNameProperty);
        } catch (CoreException e) {
            MakeCorePlugin.log(e.getStatus());
        }
        if (storedFileName != null && !storedFileName.equals(fileName)) {
            // try to move 2.x file name format to 3.x file name format
            movePluginStateFile(storedFileName, fileName);
        }
        try {
            project.setPersistentProperty(dscFileNameProperty, fileName);
        } catch (CoreException e) {
            MakeCorePlugin.log(e.getStatus());
        }

        return MakeCorePlugin.getWorkingDirectory().append(fileName);
    }

    public void updateScannerConfigStore(IResourceDelta delta) {
        try {
            delta.accept(new IResourceDeltaVisitor() {

                @Override
				public boolean visit(IResourceDelta delta) throws CoreException {
                    IResource resource = delta.getResource();
                    if (resource instanceof IProject) {
                        IProject project = (IProject) resource;
                        int kind = delta.getKind();
                        switch (kind) {
                        case IResourceDelta.REMOVED:
                            if ((delta.getFlags() & IResourceDelta.MOVED_TO) != 0) {
                                // project renamed
                                IPath newPath = delta.getMovedToPath();
                                IProject newProject = delta.getResource().getWorkspace().
                                        getRoot().getProject(newPath.toString());
                                scProjectRenamed(project, newProject);
                            }
                            else {
                                // project deleted
                                scProjectDeleted(project);
                            }
                            // remove from cache
                            fDocumentCache.remove(project);
                        }
                        return false;
                    }
                    return true;
                }

            });
        }
        catch (CoreException e) {
            MakeCorePlugin.log(e);
        }
    }

    private void scProjectDeleted(IProject project) {
        String scFileName = project.getName() + ".sc"; //$NON-NLS-1$
        deletePluginStateFile(scFileName);
    }

    private void deletePluginStateFile(String scFileName) {
        IPath path = MakeCorePlugin.getWorkingDirectory().append(scFileName);
        File file = path.toFile();
        if (file.exists()) {
            file.delete();
        }
    }

    private void scProjectRenamed(IProject project, IProject newProject) {
        String scOldFileName = project.getName() + ".sc"; //$NON-NLS-1$
        String scNewFileName = newProject.getName() + ".sc"; //$NON-NLS-1$
        movePluginStateFile(scOldFileName, scNewFileName);
        try {
            newProject.setPersistentProperty(dscFileNameProperty, scNewFileName);
        }
        catch (CoreException e) {
            MakeCorePlugin.log(e);
        }
    }

    private void movePluginStateFile(String oldFileName, String newFileName) {
        IPath oldPath = MakeCorePlugin.getWorkingDirectory().append(oldFileName);
        IPath newPath = MakeCorePlugin.getWorkingDirectory().append(newFileName);
        File oldFile = oldPath.toFile();
        File newFile = newPath.toFile();
        if (oldFile.exists()) {
            oldFile.renameTo(newFile);
        }
    }

}

Back to the top