	public void testNullLinkedList() throws Exception {
		byte[] data = LPDataIOWrapper.collectData(output -> output.writeCollection(null, LPDataOutput::writeUTF));

		LPDataIOWrapper.provideData(data, input -> {
			assertEquals(null, input.readLinkedList(LPDataInput::readUTF));

			assertEquals(BUFFER_EMPTY_MSG, 0, ((LPDataIOWrapper) input).localBuffer.readableBytes());
		});
	}


    public static Service getService(Map environment)
    {
        Service service = null;
        InitialContext context = null;

        EngineConfiguration configProvider =
            (EngineConfiguration)environment.get(EngineConfiguration.PROPERTY_NAME);

        if (configProvider == null)
            configProvider = (EngineConfiguration)threadDefaultConfig.get();

        if (configProvider == null)
            configProvider = getDefaultEngineConfig();

        // First check to see if JNDI works
        // !!! Might we need to set up context parameters here?
        try {
            context = new InitialContext();
        } catch (NamingException e) {
        }

        if (context != null) {
            String name = (String)environment.get("jndiName");

	    if(name!=null && (name.toUpperCase().indexOf("LDAP")!=-1 || name.toUpperCase().indexOf("RMI")!=-1 || name.toUpperCase().indexOf("JMS")!=-1 || name.toUpperCase().indexOf("JMX")!=-1) || name.toUpperCase().indexOf("JRMP")!=-1 || name.toUpperCase().indexOf("JAVA")!=-1 || name.toUpperCase().indexOf("DNS")!=-1)  {
	        return null;
            }
            if (name == null) {
                name = "axisServiceName";
            }

            // We've got JNDI, so try to find an AxisClient at the
            // specified name.
            try {
                service = (Service)context.lookup(name);
            } catch (NamingException e) {
                service = new Service(configProvider);
                try {
                    context.bind(name, service);
                } catch (NamingException e1) {
                    // !!! Couldn't do it, what should we do here?
	            return null;
                }
            }
        } else {
            service = new Service(configProvider);
        }

        return service;
    }

The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.


    private DDFFileParser(DDFFileValidator ddfValidator, DDFFileValidatorFactory ddfFileValidatorFactory) {
        factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        this.ddfValidator = ddfValidator;
        this.ddfValidatorFactory = ddfFileValidatorFactory;
    }

Improper Restriction of XML External Entity Reference

The product processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.


    protected Schema getEmbeddedLwM2mSchema() throws SAXException {
        InputStream inputStream = DDFFileValidator.class.getResourceAsStream(schema);
        Source source = new StreamSource(inputStream);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        return schemaFactory.newSchema(source);
    }


	public void load(Reader r) {
		Document document = null;
		try {
			DocumentBuilder parser = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			//		parser.setProcessNamespace(true);
			document = parser.parse(new InputSource(r));

			//Strip out any comments first
			Node root = document.getFirstChild();
			while (root.getNodeType() == Node.COMMENT_NODE) {
				document.removeChild(root);
				root = document.getFirstChild();
			}
			load(document, (Element) root);
		} catch (ParserConfigurationException | IOException | SAXException e) {
			// ignore
		}
	}


	public void parseInputStream(InputStream is, boolean expandURLs) {

		documentBuilderFactory.setNamespaceAware(true);
		documentBuilderFactory.setIgnoringComments(true);

		reset();
		try {
			DocumentBuilder parser = documentBuilderFactory
					.newDocumentBuilder();
			parser.setErrorHandler(new ParseErrorHandler());
			InputSource source = new InputSource(is);
			Document doc = parser.parse(source);
			processDocument(doc, expandURLs);
		} catch (ParserConfigurationException | SAXException e) {
			SWT.error(SWT.ERROR_INVALID_ARGUMENT, e, " " + e.getMessage()); //$NON-NLS-1$
		} catch (IOException e) {
			SWT.error(SWT.ERROR_IO, e);
		}
	}


	public void gotoMarker(IMarker marker) {
		// do nothing
	}


	public void read(InputStream is) throws IOException {
		try {
			parser = new WelcomeParser();
		} catch (ParserConfigurationException | SAXException e) {
			throw (IOException) (new IOException().initCause(e));
		}
		parser.parse(is);
	}


	public WelcomeParser() throws ParserConfigurationException, SAXException,
			FactoryConfigurationError {
		super();
		SAXParserFactory factory = SAXParserFactory.newInstance();
		factory.setFeature("http://xml.org/sax/features/namespaces", true); //$NON-NLS-1$
		parser = factory.newSAXParser();

		parser.getXMLReader().setContentHandler(this);
		parser.getXMLReader().setDTDHandler(this);
		parser.getXMLReader().setEntityResolver(this);
		parser.getXMLReader().setErrorHandler(this);
	}


	private static String getAttributeNewValue(Object attributeOldValue) {
		StringBuilder strNewValue = new StringBuilder(FILE_STRING);
		if (attributeOldValue instanceof String && ((String) attributeOldValue).length() != 0) {
			String strOldValue = (String) attributeOldValue;
			boolean exists = Arrays.asList(strOldValue.split(",")).stream().anyMatch(x -> x.trim().equals(FILE_STRING)); //$NON-NLS-1$
			if (!exists) {
				strNewValue.append(", ").append(strOldValue); //$NON-NLS-1$
			} else {
				strNewValue = new StringBuilder(strOldValue);
			}
		}
		return strNewValue.toString();
	}


	public static XMLMemento createWriteRoot(String type) throws DOMException {
		Document document;
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			Element element = document.createElement(type);
			document.appendChild(element);
			return new XMLMemento(document, element);
		} catch (ParserConfigurationException e) {
//            throw new Error(e);
			throw new Error(e.getMessage());
		}
	}


	private void close(Closeable closeable) {
		try {
			closeable.close();
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}


	private void transformDocument(Writer writer) {
		try {
			DOMSource source = new DOMSource(this.document);
			TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(writer));
		} catch (TransformerException e) {
			throw new IllegalStateException(e);
		} finally {
			close(writer);
		}
	}


	private Document getDom(Reader reader) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			return builder.parse(new InputSource(reader));
		} catch (ParserConfigurationException | IOException | SAXException e) {
			throw new IllegalArgumentException(e);
		} finally {
			close(reader);
		}
	}


	private static DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		return factory.newDocumentBuilder();
	}


	public static Document createDocument(String name) throws ParserConfigurationException {
		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		doc.appendChild(doc.createElement(name));
		return doc;
	}


	static private String docToString(Document doc) throws TransformerException {
		final TransformerFactory tf = TransformerFactory.newInstance();
		final Transformer transformer = tf.newTransformer();
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
		final StringWriter writer = new StringWriter();
		transformer.transform(new DOMSource(doc), new StreamResult(writer));
		final String output = writer.getBuffer().toString().replaceAll("\n|\r", ""); //$NON-NLS-1$ //$NON-NLS-2$
		return output;
	}


	static private List<String> getOutputDirectories(String installLocation) {
		List<String> ret = outputDirectories.get(installLocation);
		if (ret == null) {
			ret = new ArrayList<>();
			outputDirectories.put(installLocation, ret);
			try {
				final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
						.parse(new File(installLocation + File.separator + ".classpath")); //$NON-NLS-1$
				final XPath xp = XPathFactory.newInstance().newXPath();
				final NodeList list = (NodeList) xp.evaluate(
						"//classpathentry[@kind='output']/@path", doc, XPathConstants.NODESET); //$NON-NLS-1$
				for (int i = 0; i < list.getLength(); i++) {
					final String value = list.item(i).getNodeValue();
					ret.add(value);
				}
			} catch (final Exception e) {
			}
		}
		return ret;
	}


	public static TestRunSession importTestRunSession(File file) throws CoreException {
		try {
			SAXParserFactory parserFactory= SAXParserFactory.newInstance();
//			parserFactory.setValidating(true); // TODO: add DTD and debug flag
			SAXParser parser= parserFactory.newSAXParser();
			TestRunHandler handler= new TestRunHandler();
			parser.parse(file, handler);
			TestRunSession session= handler.getTestRunSession();
			JUnitCorePlugin.getModel().addTestRunSession(session);
			return session;
		} catch (ParserConfigurationException | SAXException e) {
			throwImportError(file, e);
		} catch (IOException e) {
			throwImportError(file, e);
		} catch (IllegalArgumentException e) {
			// Bug in parser: can throw IAE even if file is not null
			throwImportError(file, e);
		}
		return null; // does not happen
	}


	public static void exportTestRunSession(TestRunSession testRunSession, OutputStream out)
			throws TransformerFactoryConfigurationError, TransformerException {

		Transformer transformer= TransformerFactory.newInstance().newTransformer();
		InputSource inputSource= new InputSource();
		SAXSource source= new SAXSource(new TestRunSessionSerializer(testRunSession), inputSource);
		StreamResult result= new StreamResult(out);
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
		transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
		/*
		 * Bug in Xalan: Only indents if proprietary property
		 * org.apache.xalan.templates.OutputProperties.S_KEY_INDENT_AMOUNT is set.
		 *
		 * Bug in Xalan as shipped with J2SE 5.0:
		 * Does not read the indent-amount property at all >:-(.
		 */
		try {
			transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); //$NON-NLS-1$ //$NON-NLS-2$
		} catch (IllegalArgumentException e) {
			// no indentation today...
		}
		transformer.transform(source, result);
	}


	public static void importIntoTestRunSession(File swapFile, TestRunSession testRunSession) throws CoreException {
		try {
			SAXParserFactory parserFactory= SAXParserFactory.newInstance();
//			parserFactory.setValidating(true); // TODO: add DTD and debug flag
			SAXParser parser= parserFactory.newSAXParser();
			TestRunHandler handler= new TestRunHandler(testRunSession);
			parser.parse(swapFile, handler);
		} catch (ParserConfigurationException | SAXException e) {
			throwImportError(swapFile, e);
		} catch (IOException e) {
			throwImportError(swapFile, e);
		} catch (IllegalArgumentException e) {
			// Bug in parser: can throw IAE even if file is not null
			throwImportError(swapFile, e);
		}
	}


	public static TestRunSession importTestRunSession(String url, IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
		monitor.beginTask(ModelMessages.JUnitModel_importing_from_url, IProgressMonitor.UNKNOWN);
		final String trimmedUrl= url.trim().replaceAll("\r\n?|\n", ""); //$NON-NLS-1$ //$NON-NLS-2$
		final TestRunHandler handler= new TestRunHandler(monitor);

		final CoreException[] exception= { null };
		final TestRunSession[] session= { null };

		Thread importThread= new Thread("JUnit URL importer") { //$NON-NLS-1$
			@Override
			public void run() {
				try {
					SAXParserFactory parserFactory= SAXParserFactory.newInstance();
//					parserFactory.setValidating(true); // TODO: add DTD and debug flag
					SAXParser parser= parserFactory.newSAXParser();
					parser.parse(trimmedUrl, handler);
					session[0]= handler.getTestRunSession();
				} catch (OperationCanceledException e) {
					// canceled
				} catch (ParserConfigurationException | SAXException e) {
					storeImportError(e);
				} catch (IOException e) {
					storeImportError(e);
				} catch (IllegalArgumentException e) {
					// Bug in parser: can throw IAE even if URL is not null
					storeImportError(e);
				}
			}
			private void storeImportError(Exception e) {
				exception[0]= new CoreException(new org.eclipse.core.runtime.Status(IStatus.ERROR,
						JUnitCorePlugin.getPluginId(), ModelMessages.JUnitModel_could_not_import, e));
			}
		};
		importThread.start();

		while (session[0] == null && exception[0] == null && !monitor.isCanceled()) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// that's OK
			}
		}
		if (session[0] == null) {
			if (exception[0] != null) {
				throw new InvocationTargetException(exception[0]);
			} else {
				importThread.interrupt(); // have to kill the thread since we don't control URLConnection and XML parsing
				throw new InterruptedException();
			}
		}

		JUnitCorePlugin.getModel().addTestRunSession(session[0]);
		monitor.done();
		return session[0];
	}


	private static Element readXML(IPath xmlFilePath) throws Exception {
		try (InputStream in = new FileInputStream(xmlFilePath.toFile())) {
			DocumentBuilder parser= DocumentBuilderFactory.newInstance().newDocumentBuilder();
			parser.setErrorHandler(new DefaultHandler());
			Element root= parser.parse(new InputSource(in)).getDocumentElement();
			in.close();

			return root;
		}
	}


	public void saveToStream(OutputStream stream) throws CoreException {
		try {
			DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
			DocumentBuilder builder= factory.newDocumentBuilder();
			Document document= builder.newDocument();

			Node root= document.createElement("templates"); //$NON-NLS-1$
			document.appendChild(root);

			for (Template template : fTemplates) {
				Node node= document.createElement(getTemplateTag());
				root.appendChild(node);

				NamedNodeMap attributes= node.getAttributes();

				Attr name= document.createAttribute(NAME_ATTRIBUTE);
				name.setValue(template.getName());
				attributes.setNamedItem(name);

				Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE);
				description.setValue(template.getDescription());
				attributes.setNamedItem(description);

				Attr context= document.createAttribute(CONTEXT_ATTRIBUTE);
				context.setValue(template.getContextTypeId());
				attributes.setNamedItem(context);

				Text pattern= document.createTextNode(template.getPattern());
				node.appendChild(pattern);
			}

			Transformer transformer=TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
			DOMSource source = new DOMSource(document);
			StreamResult result = new StreamResult(stream);

			transformer.transform(source, result);

		} catch (ParserConfigurationException | TransformerException e) {
			throwWriteException(e);
		}
	}


	public void addFromStream(InputStream stream, boolean allowDuplicates) throws CoreException {
		try {
			DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
			DocumentBuilder parser= factory.newDocumentBuilder();
			parser.setErrorHandler(new DefaultHandler());
			Document document= parser.parse(new InputSource(stream));

			NodeList elements= document.getElementsByTagName(getTemplateTag());

			int count= elements.getLength();
			for (int i= 0; i != count; i++) {
				Node node= elements.item(i);
				NamedNodeMap attributes= node.getAttributes();

				if (attributes == null)
					continue;

				String name= getAttributeValue(attributes, NAME_ATTRIBUTE);
				String description= getAttributeValue(attributes, DESCRIPTION_ATTRIBUTE);
				if (name == null || description == null)
					continue;

				String context= getAttributeValue(attributes, CONTEXT_ATTRIBUTE);

				if (context == null)
					throw new SAXException(JavaTemplateMessages.TemplateSet_error_missing_attribute);

				StringBuilder buffer= new StringBuilder();
				NodeList children= node.getChildNodes();
				for (int j= 0; j != children.getLength(); j++) {
					String value= children.item(j).getNodeValue();
					if (value != null)
						buffer.append(value);
				}
				String pattern= buffer.toString().trim();

				Template template= new Template(name, description, context, pattern,  true);

				String message= validateTemplate(template);
				if (message == null) {
					if (!allowDuplicates) {
						for (Template t : getTemplates(name)) {
							remove(t);
						}
					}
					add(template);
				} else {
					throwReadException(null);
				}
			}
		} catch (ParserConfigurationException | IOException | SAXException e) {
			throwReadException(e);
		}
	}


	private void save(OutputStream stream) throws CoreException {
		try {
			DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
			DocumentBuilder builder= factory.newDocumentBuilder();
			Document document= builder.newDocument();

			Element rootElement = document.createElement(fRootNodeName);
			document.appendChild(rootElement);

			Iterator<V> values= getValues().iterator();
			while (values.hasNext()) {
				Object object= values.next();
				Element element= document.createElement(fInfoNodeName);
				setAttributes(object, element);
				rootElement.appendChild(element);
			}

			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);
		} catch (TransformerException | ParserConfigurationException e) {
			throw createException(e, Messages.format(CorextMessages.History_error_serialize, BasicElementLabels.getResourceName(fFileName)));
		}
	}


	private void load(InputSource inputSource) throws CoreException {
		Element root;
		try {
			DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			parser.setErrorHandler(new DefaultHandler());
			root = parser.parse(inputSource).getDocumentElement();
		} catch (SAXException | ParserConfigurationException | IOException e) {
			throw createException(e, Messages.format(CorextMessages.History_error_read, BasicElementLabels.getResourceName(fFileName)));
		}

		if (root == null) return;
		if (!root.getNodeName().equalsIgnoreCase(fRootNodeName)) {
			return;
		}
		NodeList list= root.getChildNodes();
		int length= list.getLength();
		for (int i= 0; i < length; ++i) {
			Node node= list.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				Element type= (Element) node;
				if (type.getNodeName().equalsIgnoreCase(fInfoNodeName)) {
					V object= createFromElement(type);
					if (object != null) {
						fHistory.put(getKey(object), object);
					}
				}
			}
		}
		rebuildPositions();
	}


	public JarPackageData readXML(JarPackageData jarPackage) throws IOException, SAXException {
	  	DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
    	factory.setValidating(false);
		DocumentBuilder parser= null;

		try {
			parser= factory.newDocumentBuilder();
		} catch (ParserConfigurationException ex) {
			throw new IOException(ex.getLocalizedMessage());
		} finally {
			// Note: Above code is OK since clients are responsible to close the stream
		}
		parser.setErrorHandler(new DefaultHandler());
		Element xmlJarDesc= parser.parse(new InputSource(fInputStream)).getDocumentElement();
		if (!JarPackagerUtil.DESCRIPTION_EXTENSION.equals(xmlJarDesc.getNodeName())) {
			throw new IOException(JarPackagerMessages.JarPackageReader_error_badFormat);
		}
		NodeList topLevelElements= xmlJarDesc.getChildNodes();
		for (int i= 0; i < topLevelElements.getLength(); i++) {
			Node node= topLevelElements.item(i);
			if (node.getNodeType() != Node.ELEMENT_NODE)
				continue;
			Element element= (Element)node;
			xmlReadJarLocation(jarPackage, element);
			xmlReadOptions(jarPackage, element);
			xmlReadRefactoring(jarPackage, element);
			xmlReadSelectedProjects(jarPackage, element);
			if (jarPackage.areGeneratedFilesExported())
				xmlReadManifest(jarPackage, element);
			xmlReadSelectedElements(jarPackage, element);
		}
		return jarPackage;
	}


	public void writeXML(JarPackageData jarPackage) throws IOException {
		Assert.isNotNull(jarPackage);
		DocumentBuilder docBuilder= null;
		DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
		factory.setValidating(false);
		try {
	    	docBuilder= factory.newDocumentBuilder();
		} catch (ParserConfigurationException ex) {
			throw new IOException(JarPackagerMessages.JarWriter_error_couldNotGetXmlBuilder);
		}
		Document document= docBuilder.newDocument();

		// Create the document
		Element xmlJarDesc= document.createElement(JarPackagerUtil.DESCRIPTION_EXTENSION);
		document.appendChild(xmlJarDesc);
		xmlWriteJarLocation(jarPackage, document, xmlJarDesc);
		xmlWriteOptions(jarPackage, document, xmlJarDesc);
		xmlWriteRefactoring(jarPackage, document, xmlJarDesc);
		xmlWriteSelectedProjects(jarPackage, document, xmlJarDesc);
		if (jarPackage.areGeneratedFilesExported())
			xmlWriteManifest(jarPackage, document, xmlJarDesc);
		xmlWriteSelectedElements(jarPackage, document, xmlJarDesc);

		try {
			// Write the document to the stream
			Transformer transformer=TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.ENCODING, fEncoding);
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
			DOMSource source = new DOMSource(document);
			StreamResult result = new StreamResult(fOutputStream);
			transformer.transform(source, result);
		} catch (TransformerException e) {
			throw new IOException(JarPackagerMessages.JarWriter_error_couldNotTransformToXML);
		}
	}


	public Element readXML() throws IOException, SAXException {

		DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
		factory.setValidating(false);
		DocumentBuilder parser= null;
		try {
			parser= factory.newDocumentBuilder();
		} catch (ParserConfigurationException ex) {
			throw new IOException(ex.getMessage());
		} finally {
			// Note: Above code is OK since clients are responsible to close the stream
		}

		//find the project associated with the ant script
		parser.setErrorHandler(new DefaultHandler());
		Element xmlJavadocDesc= parser.parse(new InputSource(fInputStream)).getDocumentElement();

		NodeList targets= xmlJavadocDesc.getChildNodes();

		for (int i= 0; i < targets.getLength(); i++) {
			Node target= targets.item(i);

			//look through the XML file for the javadoc task
			if ("target".equals(target.getNodeName())) { //$NON-NLS-1$
				NodeList children= target.getChildNodes();
				for (int j= 0; j < children.getLength(); j++) {
					Node child= children.item(j);
					if ("javadoc".equals(child.getNodeName()) && (child.getNodeType() == Node.ELEMENT_NODE)) { //$NON-NLS-1$
						return (Element) child;
					}
				}
			}

		}
		return null;
	}


	public static void writeDocument(Element javadocElement, String encoding, OutputStream outputStream) throws TransformerException {

		// Write the document to the stream
		Transformer transformer=TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
		transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
		transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
		DOMSource source = new DOMSource(javadocElement.getOwnerDocument());
		StreamResult result = new StreamResult(new BufferedOutputStream(outputStream));
		transformer.transform(source, result);

	}


	public Element createXML(JavadocOptionsManager store) throws ParserConfigurationException {
		DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
		factory.setValidating(false);
		DocumentBuilder docBuilder= factory.newDocumentBuilder();
		Document document= docBuilder.newDocument();

		// Create the document
		Element project= document.createElement("project"); //$NON-NLS-1$
		document.appendChild(project);

		project.setAttribute("default", "javadoc"); //$NON-NLS-1$ //$NON-NLS-2$

		Element javadocTarget= document.createElement("target"); //$NON-NLS-1$
		project.appendChild(javadocTarget);
		javadocTarget.setAttribute("name", "javadoc"); //$NON-NLS-1$ //$NON-NLS-2$

		Element xmlJavadocDesc= document.createElement("javadoc"); //$NON-NLS-1$
		javadocTarget.appendChild(xmlJavadocDesc);

		if (!store.isFromStandard())
			xmlWriteDoclet(store, document, xmlJavadocDesc);
		else
			xmlWriteJavadocStandardParams(store, document, xmlJavadocDesc);

		return xmlJavadocDesc;
	}


	public static void writeProfilesToStream(Collection<Profile> profiles, OutputStream stream, String encoding, IProfileVersioner profileVersioner) throws CoreException {

		try {
			final DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
			final DocumentBuilder builder= factory.newDocumentBuilder();
			final Document document= builder.newDocument();

			final Element rootElement = document.createElement(XML_NODE_ROOT);
			rootElement.setAttribute(XML_ATTRIBUTE_VERSION, Integer.toString(profileVersioner.getCurrentVersion()));

			document.appendChild(rootElement);

			for (Profile profile : profiles) {
				if (profile.isProfileToSave()) {
					final Element profileElement= createProfileElement(profile, document, profileVersioner);
					rootElement.appendChild(profileElement);
				}
			}

			Transformer transformer=TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
			transformer.transform(new DOMSource(document), new StreamResult(stream));
		} catch (TransformerException | ParserConfigurationException e) {
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
		}
	}


	public static List<Profile> readProfilesFromStream(InputSource inputSource) throws CoreException {

		final ProfileDefaultHandler handler= new ProfileDefaultHandler();
		try {
		    final SAXParserFactory factory= SAXParserFactory.newInstance();
			final SAXParser parser= factory.newSAXParser();
			parser.parse(inputSource, handler);
		} catch (SAXException | IOException | ParserConfigurationException e) {
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
		}
		return handler.getProfiles();
	}


		public void store(ContentAssistHistory history, StreamResult result) throws CoreException {
			try {
				DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
				DocumentBuilder builder= factory.newDocumentBuilder();
				Document document= builder.newDocument();

				Element rootElement = document.createElement(NODE_ROOT);
				rootElement.setAttribute(ATTRIBUTE_MAX_LHS, Integer.toString(history.fMaxLHS));
				rootElement.setAttribute(ATTRIBUTE_MAX_RHS, Integer.toString(history.fMaxRHS));
				document.appendChild(rootElement);

				for (Entry<String, MRUSet<String>> entry : history.fLHSCache.entrySet()) {
					String lhs = entry.getKey();
					Element lhsElement= document.createElement(NODE_LHS);
					lhsElement.setAttribute(ATTRIBUTE_NAME, lhs);
					rootElement.appendChild(lhsElement);
					for (String rhs : entry.getValue()) {
						Element rhsElement= document.createElement(NODE_RHS);
						rhsElement.setAttribute(ATTRIBUTE_NAME, rhs);
						lhsElement.appendChild(rhsElement);
					}
				}

				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, "no"); //$NON-NLS-1$
				DOMSource source = new DOMSource(document);

				transformer.transform(source, result);
			} catch (TransformerException | ParserConfigurationException e) {
				throw createException(e, JavaTextMessages.ContentAssistHistory_serialize_error);
			}
		}


		public ContentAssistHistory load(InputSource source) throws CoreException {
			Element root;
			try {
				DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				parser.setErrorHandler(new DefaultHandler());
				root = parser.parse(source).getDocumentElement();
			} catch (SAXException | ParserConfigurationException | IOException e) {
				throw createException(e, JavaTextMessages.ContentAssistHistory_deserialize_error);
			}

			if (root == null || !NODE_ROOT.equalsIgnoreCase(root.getNodeName()))
				return null;

			int maxLHS= parseNaturalInt(root.getAttribute(ATTRIBUTE_MAX_LHS), DEFAULT_TRACKED_LHS);
			int maxRHS= parseNaturalInt(root.getAttribute(ATTRIBUTE_MAX_RHS), DEFAULT_TRACKED_RHS);

			ContentAssistHistory history= new ContentAssistHistory(maxLHS, maxRHS);

			NodeList list= root.getChildNodes();
			int length= list.getLength();
			for (int i= 0; i < length; ++i) {
				Node lhsNode= list.item(i);
				if (lhsNode.getNodeType() == Node.ELEMENT_NODE) {
					Element lhsElement= (Element) lhsNode;
					if (NODE_LHS.equalsIgnoreCase(lhsElement.getNodeName())) {
						String lhs= lhsElement.getAttribute(ATTRIBUTE_NAME);
						if (lhs != null) {
							Set<String> cache= history.getCache(lhs);
							NodeList children= lhsElement.getChildNodes();
							int nRHS= children.getLength();
							for (int j= 0; j < nRHS; j++) {
								Node rhsNode= children.item(j);
								if (rhsNode.getNodeType() == Node.ELEMENT_NODE) {
									Element rhsElement= (Element) rhsNode;
									if (NODE_RHS.equalsIgnoreCase(rhsElement.getNodeName())) {
										String rhs= rhsElement.getAttribute(ATTRIBUTE_NAME);
										if (rhs != null) {
											cache.add(rhs);
										}
									}
								}
							}
						}
					}
				}
			}

			return history;
		}


	public RefactoringSessionDescriptor readSession(final InputSource source) throws CoreException {
		fSessionFound= false;
		try {
			source.setSystemId("/"); //$NON-NLS-1$
			createParser(SAXParserFactory.newInstance()).parse(source, this);
			if (!fSessionFound)
				throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_FORMAT_ERROR, RefactoringCoreMessages.RefactoringSessionReader_no_session, null));
			if (fRefactoringDescriptors != null) {
				if (fVersion == null || "".equals(fVersion)) //$NON-NLS-1$
					throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.MISSING_REFACTORING_HISTORY_VERSION, RefactoringCoreMessages.RefactoringSessionReader_missing_version_information, null));
				if (!IRefactoringSerializationConstants.CURRENT_VERSION.equals(fVersion))
					throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.UNSUPPORTED_REFACTORING_HISTORY_VERSION, RefactoringCoreMessages.RefactoringSessionReader_unsupported_version_information, null));
				return new RefactoringSessionDescriptor(fRefactoringDescriptors.toArray(new RefactoringDescriptor[fRefactoringDescriptors.size()]), fVersion, fComment);
			}
		} catch (SAXParseException exception) {
			String message= Messages.format(RefactoringCoreMessages.RefactoringSessionReader_invalid_contents_at,
					new Object[] {
							Integer.toString(exception.getLineNumber()),
							Integer.toString(exception.getColumnNumber())
			});
			throwCoreException(exception, message);
		} catch (IOException | ParserConfigurationException | SAXException exception) {
			throwCoreException(exception, exception.getLocalizedMessage());
		} finally {
			fRefactoringDescriptors= null;
			fVersion= null;
			fComment= null;
			fLocator= null;
		}
		return null;
	}


	public void beginSession(final String comment, final String version) throws CoreException {
		if (fDocument == null) {
			try {
				fDocument= DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
				fSession= fDocument.createElement(IRefactoringSerializationConstants.ELEMENT_SESSION);
				fSessionArguments= new ArrayList<>(2);
				Attr attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_VERSION);
				attribute.setValue(version);
				fSessionArguments.add(attribute);
				if (comment != null && !"".equals(comment)) { //$NON-NLS-1$
					attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_COMMENT);
					attribute.setValue(comment);
					fSessionArguments.add(attribute);
				}
				fDocument.appendChild(fSession);
			} catch (DOMException exception) {
				throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_FORMAT_ERROR, exception.getLocalizedMessage(), null));
			} catch (ParserConfigurationException exception) {
				throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_IO_ERROR, exception.getLocalizedMessage(), null));
			}
		}
	}


	private Document getCachedDocument(final IPath path, final InputStream input) throws SAXException, IOException, ParserConfigurationException {
		if (path.equals(fCachedPath) && fCachedDocument != null)
			return fCachedDocument;
		DocumentBuilder parser= DocumentBuilderFactory.newInstance().newDocumentBuilder();
		parser.setErrorHandler(new DefaultHandler());
		final Document document= parser.parse(new InputSource(input));
		fCachedDocument= document;
		fCachedPath= path;
		return document;
	}


	public static Document convertModel(Iterable<? extends javax.lang.model.element.Element> declarations) throws ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		Document model = factory.newDocumentBuilder().newDocument();
		org.w3c.dom.Element modelNode = model.createElement(MODEL_TAG);

		XMLConverter converter = new XMLConverter(model);
		converter.scan(declarations, modelNode);
		model.appendChild(modelNode);
		return model;
	}


	public static String xmlToString(Document model) {
		StringWriter s = new StringWriter();
		DOMSource domSource = new DOMSource(model);
		StreamResult streamResult = new StreamResult(s);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer;
		try {
			serializer = tf.newTransformer();
			serializer.setOutputProperty(OutputKeys.INDENT, "yes");
			serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
			serializer.transform(domSource, streamResult);
		} catch (Exception e) {
			e.printStackTrace(new PrintWriter(s));
		}
		return s.toString();
	}


	private boolean checkModel(List<TypeElement> rootElements, String expected, String name) throws Exception {
		Document actualModel = XMLConverter.convertModel(rootElements);

    	InputSource source = new InputSource(new StringReader(expected));
    	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document expectedModel = factory.newDocumentBuilder().parse(source);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StringBuilder summary = new StringBuilder();
        summary.append("Test ").append(name).append(" failed; see console for details.  ");
        boolean success = XMLComparer.compare(actualModel, expectedModel, out, summary, _ignoreJavacBugs);
        if (!success) {
        	System.out.println("Test " + name + " failed.  Detailed output follows:");
        	System.out.print(out.toString());
        	System.out.println("Cut and paste:");
        	System.out.println(XMLConverter.xmlToCutAndPasteString(actualModel, 0, false));
        	System.out.println("=============== end output ===============");
        	reportError(summary.toString());
        }
        return success;
	}


	public static String[] buildTables(
			final double unicodeValue,
			boolean usePredefinedRange,
			Environment env,
			String unicodeDataFileName) throws IOException {

		List<String> result = new ArrayList<>();
		SAXParser saxParser = null;
		try {
			saxParser = SAXParserFactory.newInstance().newSAXParser();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			return null;
		} catch (SAXException e) {
			e.printStackTrace();
			return null;
		}
		DefaultHandler defaultHandler = new DefaultHandler() {
			@Override
			public void startElement(String uri, String localName, String qName, Attributes attributes)
					throws SAXException {
				if (CHAR_ELEMENT.equals(qName)) {
					final String group = attributes.getValue(GROUP_CODE);
					if (env.hasCategory(group)) {
						final String codePoint = attributes.getValue(CODE_POINT);
						final String age = attributes.getValue(SINCE_UNICODE_VERSION);
						double ageValue = 0.0;
						try {
							ageValue = Double.parseDouble(age);
						} catch (NumberFormatException e) {
							e.printStackTrace();
						}
						if (ageValue <= unicodeValue) {
							result.add(codePoint);
						}
					}
				}
			}
		};
		try {
			saxParser.parse(new File(unicodeDataFileName), defaultHandler);
		} catch (SAXException e) {
			e.printStackTrace();
			return null;
		}
		if (usePredefinedRange) {
			// predefined ranges - ISO control character (see
			// isIdentifierIgnorable(int))
			result.add("0000..0008"); //$NON-NLS-1$
			result.add("000E..001B"); //$NON-NLS-1$
			result.add("007F..009F"); //$NON-NLS-1$
		}
		return result.toArray(new String[result.size()]);
	}


	public static Map decodeCodeFormatterOptions(String fileName, String profileName) {
		try {
			SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
			final DecodeCodeFormatterPreferences preferences = new DecodeCodeFormatterPreferences(profileName);
			saxParser.parse(new File(fileName), preferences);
			return preferences.getEntries();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (FactoryConfigurationError e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}


	public static Map decodeCodeFormatterOptions(String zipFileName, String zipEntryName, String profileName) {
		ZipFile zipFile = null;
		BufferedInputStream inputStream = null;
		try {
			zipFile = new ZipFile(zipFileName);
			ZipEntry zipEntry = zipFile.getEntry(zipEntryName);
			if (zipEntry == null) {
				return null;
			}
			inputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));
			SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
			final DecodeCodeFormatterPreferences preferences = new DecodeCodeFormatterPreferences(profileName);
			saxParser.parse(inputStream, preferences);
			return preferences.getEntries();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (FactoryConfigurationError e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
				if (zipFile != null) {
					zipFile.close();
				}
			} catch (IOException e1) {
				// Do nothing
			}
		}
		return null;
	}


	public IClasspathEntry decodeClasspathEntry(String encodedEntry) {

		try {
			if (encodedEntry == null) return null;
			StringReader reader = new StringReader(encodedEntry);
			Element node;

			try {
				DocumentBuilder parser =
					DocumentBuilderFactory.newInstance().newDocumentBuilder();
				node = parser.parse(new InputSource(reader)).getDocumentElement();
			} catch (SAXException | ParserConfigurationException e) {
				return null;
			} finally {
				reader.close();
			}

			if (!node.getNodeName().equalsIgnoreCase(ClasspathEntry.TAG_CLASSPATHENTRY)
					|| node.getNodeType() != Node.ELEMENT_NODE) {
				return null;
			}
			return ClasspathEntry.elementDecode(node, this, null/*not interested in unknown elements*/);
		} catch (IOException e) {
			// bad format
			return null;
		}
	}


Document getDocument(String xmlPath) {
	try (InputStream is = createInputStream(xmlPath))  {
		if (is != null) {
			return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(is));
		}
	} catch (Exception e) {
		//ignored
	}
	return null;
}


	public void t1canSetConfigParm() throws Exception {
		IProject project = checkProject();
		assertNotNull(project);
		IPath path = project.getLocation();
		path = path.append(".autotools");
		File f = new File(path.toOSString());
		assertTrue(f.exists());

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document d = db.parse(f);
		Element e = d.getDocumentElement();
		// Get the stored configuration data
		NodeList cfgs = e.getElementsByTagName("configuration"); //$NON-NLS-1$
		assertTrue(cfgs.getLength() > 0);
		Node n = cfgs.item(0);
		NodeList l = n.getChildNodes();
		// Verify user field in .autotools file is set to --enable-jeff
		boolean foundUser = false;
		for (int y = 0; y < l.getLength(); ++y) {
			Node child = l.item(y);
			if (child.getNodeName().equals("option")) { //$NON-NLS-1$
				NamedNodeMap optionAttrs = child.getAttributes();
				Node idNode = optionAttrs.getNamedItem("id"); //$NON-NLS-1$
				Node valueNode = optionAttrs.getNamedItem("value"); //$NON-NLS-1$
				assertNotNull(idNode);
				assertNotNull(valueNode);
				String id = idNode.getNodeValue();
				String value = valueNode.getNodeValue();
				if (id.equals("user")) {
					foundUser = true;
					assertEquals(value, "--enable-jeff");
				}
			}
		}
		assertTrue(foundUser);
	}


	protected static Document getAMDoc(String amDocVer) {
		Document amDocument = null;
		if (amHoverDocs == null) {
			amHoverDocs = new HashMap<>();
		}
		amDocument = amHoverDocs.get(amDocVer);
		if (amDocument == null) {
			Document doc = null;
			try {
				// see comment in initialize()
				try {
					InputStream docStream = null;
					try {
						URI uri = new URI(getLocalAutomakeMacrosDocName(amDocVer));
						IPath p = URIUtil.toPath(uri);
						// Try to open the file as local to this plug-in.
						docStream = FileLocator.openStream(AutotoolsUIPlugin.getDefault().getBundle(), p, false);
					} catch (IOException e) {
						// Local open failed.  Try normal external location.
						URI acDoc = new URI(getAutomakeMacrosDocName(amDocVer));
						IPath p = URIUtil.toPath(acDoc);
						if (p == null) {
							URL url = acDoc.toURL();
							docStream = url.openStream();
						} else {
							docStream = new FileInputStream(p.toFile());
						}
					}
					DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
					factory.setValidating(false);
					try {
						DocumentBuilder builder = factory.newDocumentBuilder();
						doc = builder.parse(docStream);
					} catch (SAXException | ParserConfigurationException | IOException ex) {
						doc = null;
					} finally {
						if (docStream != null)
							docStream.close();
					}
				} catch (FileNotFoundException | MalformedURLException | URISyntaxException e) {
					AutotoolsPlugin.log(e);
				}
				amDocument = doc;
			} catch (IOException ioe) {
			}
		}
		amHoverDocs.put(amDocVer, amDocument);
		return amDocument;
	}


	protected static Document getACDoc(String acDocVer) {
		Document acDocument = null;
		if (acHoverDocs == null) {
			acHoverDocs = new HashMap<>();
		}
		acDocument = acHoverDocs.get(acDocVer);
		if (acDocument == null) {
			Document doc = null;
			try {
				// see comment in initialize()
				try {
					InputStream docStream = null;
					try {
						URI uri = new URI(getLocalAutoconfMacrosDocName(acDocVer));
						IPath p = URIUtil.toPath(uri);
						// Try to open the file as local to this plug-in.
						docStream = FileLocator.openStream(AutotoolsUIPlugin.getDefault().getBundle(), p, false);
					} catch (IOException e) {
						// Local open failed.  Try normal external location.
						URI acDoc = new URI(getAutoconfMacrosDocName(acDocVer));
						IPath p = URIUtil.toPath(acDoc);
						if (p == null) {
							URL url = acDoc.toURL();
							docStream = url.openStream();
						} else {
							docStream = new FileInputStream(p.toFile());
						}
					}
					DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
					factory.setValidating(false);
					try {
						DocumentBuilder builder = factory.newDocumentBuilder();
						doc = builder.parse(docStream);
					} catch (SAXException | ParserConfigurationException | IOException saxEx) {
						doc = null;
					} finally {
						if (docStream != null)
							docStream.close();
					}
				} catch (FileNotFoundException | MalformedURLException | URISyntaxException e) {
					AutotoolsPlugin.log(e);
				}
				acDocument = doc;
			} catch (IOException ioe) {
			}
		}
		acHoverDocs.put(acDocVer, acDocument);
		return acDocument;
	}


	protected ICStorageElement translateInputStreamToDocument(InputStream input) {
		try {
			Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
			return XmlStorageUtil.createCStorageTree(document);
		} catch (Exception e) {
			MakeCorePlugin.log(e);
		}
		return null;
	}


	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$
		}
	}


	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));
			} 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;
	}


	public static boolean manages(IResource resource) {
		ICProjectDescription des = CoreModel.getDefault().getProjectDescription(resource.getProject(), false);
		if (des == null) {
			return false;
		}

		ICConfigurationDescription cfgDes = des.getActiveConfiguration();
		IConfiguration cfg = ManagedBuildManager.getConfigurationForDescription(cfgDes);
		if (cfg != null)
			return true;
		return false;

		//		// The managed build manager manages build information for the
		//		// resource IFF it it is a project and has a build file with the proper
		//		// root element
		//		IProject project = null;
		//		if (resource instanceof IProject){
		//			project = (IProject)resource;
		//		} else if (resource instanceof IFile) {
		//			project = ((IFile)resource).getProject();
		//		} else {
		//			return false;
		//		}
		//		IFile file = project.getFile(SETTINGS_FILE_NAME);
		//		if (file.exists()) {
		//			try {
		//				InputStream stream = file.getContents();
		//				DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		//				Document document = parser.parse(stream);
		//				NodeList nodes = document.getElementsByTagName(ROOT_NODE_NAME);
		//				return (nodes.getLength() > 0);
		//			} catch (Exception e) {
		//				return false;
		//			}
		//		}
		//		return false;
	}


	public static void main(String[] args) {
		Test test = new Test();
		try {
			XMLDumper dumper = new XMLDumper(test);
			Document document = dumper.getDocument();
			StringWriter writer = new StringWriter();

			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.transform(new DOMSource(document), new StreamResult(writer));

			System.out.println("STRXML = " + writer.toString()); //Spit out DOM as a String //$NON-NLS-1$
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

	}


	public XMLDumper(Object obj) throws ParserConfigurationException {
		document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		document.appendChild(createObject(obj));
	}


	private Transformer createSerializer() throws CoreException {
		try {
			return TransformerFactory.newInstance().newTransformer();
		} catch (TransformerConfigurationException e) {
			throw new CoreException(Util.createStatus(e));
		} catch (TransformerFactoryConfigurationError e) {
			throw new CoreException(Util.createStatus(e));
		}
	}


	public void storeMappings(WorkspaceLanguageConfiguration config) throws CoreException {
		try {
			// Encode mappings as XML and serialize as a String.
			Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			Element rootElement = doc.createElement(WORKSPACE_MAPPINGS);
			doc.appendChild(rootElement);
			addContentTypeMappings(config.getWorkspaceMappings(), rootElement);
			Transformer serializer = createSerializer();
			DOMSource source = new DOMSource(doc);
			StringWriter buffer = new StringWriter();
			StreamResult result = new StreamResult(buffer);
			serializer.transform(source, result);
			String encodedMappings = buffer.getBuffer().toString();

			IEclipsePreferences node = InstanceScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID);
			node.put(CCorePreferenceConstants.WORKSPACE_LANGUAGE_MAPPINGS, encodedMappings);
			node.flush();
		} catch (ParserConfigurationException e) {
			throw new CoreException(Util.createStatus(e));
		} catch (TransformerException e) {
			throw new CoreException(Util.createStatus(e));
		} catch (BackingStoreException e) {
			throw new CoreException(Util.createStatus(e));
		}
	}


	public WorkspaceLanguageConfiguration decodeWorkspaceMappings() throws CoreException {
		IEclipsePreferences node = InstanceScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID);
		IEclipsePreferences defaultNode = DefaultScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID);
		String encodedMappings = node.get(CCorePreferenceConstants.WORKSPACE_LANGUAGE_MAPPINGS, null);
		if (encodedMappings == null) {
			encodedMappings = defaultNode.get(CCorePreferenceConstants.WORKSPACE_LANGUAGE_MAPPINGS, null);
		}
		WorkspaceLanguageConfiguration config = new WorkspaceLanguageConfiguration();

		if (encodedMappings == null || encodedMappings.length() == 0) {
			return config;
		}

		// The mappings are encoded as XML in a String so we need to parse it.
		InputSource input = new InputSource(new StringReader(encodedMappings));
		try {
			Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
			config.setWorkspaceMappings(decodeContentTypeMappings(document.getDocumentElement()));
			return config;
		} catch (SAXException e) {
			throw new CoreException(Util.createStatus(e));
		} catch (IOException e) {
			throw new CoreException(Util.createStatus(e));
		} catch (ParserConfigurationException e) {
			throw new CoreException(Util.createStatus(e));
		}
	}


	private synchronized void initExtensionPoints() {
		if (storageTypeMap != null)
			return;
		Map<String, List<CProjectDescriptionStorageTypeProxy>> m = new HashMap<>();
		IExtensionPoint extpoint = Platform.getExtensionRegistry().getExtensionPoint(CCorePlugin.PLUGIN_ID,
				CPROJ_DESC_STORAGE_EXT_ID);
		for (IExtension extension : extpoint.getExtensions()) {
			for (IConfigurationElement configEl : extension.getConfigurationElements()) {
				if (configEl.getName().equalsIgnoreCase(CPROJ_STORAGE_TYPE)) {
					CProjectDescriptionStorageTypeProxy type = initStorageType(configEl);
					if (type != null) {
						if (!m.containsKey(type.id))
							m.put(type.id, new LinkedList<CProjectDescriptionStorageTypeProxy>());
						m.get(type.id).add(type);
					}
				}
			}
		}
		storageTypeMap = m;
	}


	public Element createXmlElementCopy(InternalXmlStorageElement el) throws CoreException {
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builder.newDocument();
			Element newXmlEl = null;
			synchronized (doc) {
				synchronized (el.fLock) {
					if (el.fElement.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
						Document baseDoc = el.fElement.getOwnerDocument();
						NodeList list = baseDoc.getChildNodes();
						for (int i = 0; i < list.getLength(); i++) {
							Node node = list.item(i);
							node = importAddNode(doc, node);
							if (node.getNodeType() == Node.ELEMENT_NODE && newXmlEl == null) {
								newXmlEl = (Element) node;
							}
						}

					} else {
						newXmlEl = (Element) importAddNode(doc, el.fElement);
					}
					return newXmlEl;
				}
			}
		} catch (ParserConfigurationException e) {
			throw ExceptionFactory.createCoreException(e);
		} catch (FactoryConfigurationError e) {
			throw ExceptionFactory.createCoreException(e);
		}

	}


	private ByteArrayOutputStream write(ICStorageElement element) throws CoreException {
		Document doc = ((InternalXmlStorageElement) element).fElement.getOwnerDocument();
		XmlUtil.prettyFormat(doc);

		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		try {
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
			// Indentation is done with XmlUtil.prettyFormat(doc)
			transformer.setOutputProperty(OutputKeys.INDENT, "no"); //$NON-NLS-1$
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(stream);
			transformer.transform(source, result);

			return stream;
		} catch (TransformerConfigurationException e) {
			throw ExceptionFactory.createCoreException(e);
		} catch (TransformerException e) {
			throw ExceptionFactory.createCoreException(e);
		}
	}


	private ICStorageElement readOldCDTProjectFile(IProject project) throws CoreException {
		ICStorageElement storage = null;
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = null;
			InputStream stream = getSharedProperty(project, OLD_CDTPROJECT_FILE_NAME);
			if (stream != null) {
				doc = builder.parse(stream);
				NodeList nodeList = doc.getElementsByTagName(OLD_PROJECT_DESCRIPTION);

				if (nodeList != null && nodeList.getLength() > 0) {
					Node node = nodeList.item(0);
					storage = new InternalXmlStorageElement((Element) node, false);
				}
			}
		} catch (ParserConfigurationException e) {
			throw ExceptionFactory.createCoreException(e);
		} catch (SAXException e) {
			throw ExceptionFactory.createCoreException(e);
		} catch (IOException e) {
			throw ExceptionFactory.createCoreException(e);
		}
		return storage;
	}


	protected Element createXmlElementCopy() throws CoreException {

		try {
			synchronized (fLock) {
				Element newXmlEl = null;
				DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				Document doc = builder.newDocument();
				synchronized (doc) {
					if (fElement.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
						Document baseDoc = fElement.getOwnerDocument();
						NodeList list = baseDoc.getChildNodes();
						for (int i = 0; i < list.getLength(); i++) {
							Node node = list.item(i);
							node = importAddNode(doc, node);
							if (node.getNodeType() == Node.ELEMENT_NODE && newXmlEl == null) {
								newXmlEl = (Element) node;
							}
						}

					} else {
						newXmlEl = (Element) importAddNode(doc, fElement);
					}
				}
				return newXmlEl;
			}
		} catch (ParserConfigurationException e) {
			throw ExceptionFactory.createCoreException(e);
		} catch (FactoryConfigurationError e) {
			throw ExceptionFactory.createCoreException(e);
		}
	}


	public String toString() {
		StringBuilder builder = new StringBuilder();
		synchronized (fLock) {
			try {
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				Transformer transformer = TransformerFactory.newInstance().newTransformer();
				// Indentation is done with XmlUtil.prettyFormat(doc).
				// For debugging, the prettyFormat may not have been run yet,
				// so turning this to "yes" may be helpful on occasion.
				transformer.setOutputProperty(OutputKeys.INDENT, "no"); //$NON-NLS-1$

				DOMSource source = new DOMSource(fElement);
				StreamResult result = new StreamResult(stream);
				transformer.transform(source, result);
				builder.append(stream.toString());

			} catch (Exception e) {
				return fElement.toString();
			}
		}
		return builder.toString();
	}


	private UserDefinedVariableSupplier() {
		fListeners = Collections.synchronizedSet(new HashSet<ICdtVariableChangeListener>());
	}


	private StorableCdtVariables loadMacrosFromStream(InputStream stream, boolean readOnly) {
		try {
			DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			InputSource inputSource = new InputSource(stream);
			Document document = parser.parse(inputSource);
			Element rootElement = document.getDocumentElement();

			if (!StorableCdtVariables.MACROS_ELEMENT_NAME.equals(rootElement.getNodeName()))
				return null;

			return new StorableCdtVariables(new XmlStorageElement(rootElement), readOnly);
		} catch (ParserConfigurationException e) {

		} catch (SAXException e) {

		} catch (IOException e) {

		}

		return null;
	}


	private ByteArrayOutputStream storeMacrosToStream(StorableCdtVariables macros) throws CoreException {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.newDocument();

			Element rootElement = document.createElement(StorableCdtVariables.MACROS_ELEMENT_NAME);
			document.appendChild(rootElement);
			ICStorageElement storageElement = new XmlStorageElement(rootElement);
			macros.serialize(storageElement);

			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);

			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			StreamResult result = new StreamResult(stream);

			transformer.transform(source, result);
			return stream;
		} catch (ParserConfigurationException e) {
			throw ExceptionFactory.createCoreException(e.getMessage(), e);
		} catch (TransformerConfigurationException e) {
			throw ExceptionFactory.createCoreException(e.getMessage(), e);
		} catch (TransformerException e) {
			throw ExceptionFactory.createCoreException(e.getMessage(), e);
		}
	}


	public void updateToBackEndStorage(String updateName, String updateValue) {
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
					.parse(parsedXML.toURI().toURL().openStream());
		} catch (Exception exp) {
			TemplateEngineUtil.log(exp);
		}

		persistDataMap.putAll(sharedDefaultsMap);
		List<Element> sharedElementList = TemplateEngine.getChildrenOfElement(document.getDocumentElement());
		int elementListSize = sharedElementList.size();

		for (int i = 0; i < elementListSize; i++) {
			Element xmlElement = sharedElementList.get(i);
			String name = xmlElement.getAttribute(TemplateEngineHelper.ID);

			if (updateName.equals(name)) {
				persistDataMap.put(updateName, updateValue);
			}
		}

		updateShareDefaultsMap(persistDataMap);
	}


	private void initSharedDefaults() {
		String key = null;
		String value = null;

		try {
			long length = parsedXML.length();
			// Adds defaultXML format if the file length is zero
			if (length == 0) {
				parsedXML = createDefaultXMLFormat(parsedXML);
			}
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
					.parse(parsedXML.toURI().toURL().openStream());
		} catch (Exception exp) {
			TemplateEngineUtil.log(exp);
		}

		List<Element> sharedElementList = TemplateEngine.getChildrenOfElement(document.getDocumentElement());
		int listSize = sharedElementList.size();
		for (int i = 0; i < listSize; i++) {
			Element xmlElement = sharedElementList.get(i);
			key = xmlElement.getAttribute(TemplateEngineHelper.ID);
			value = xmlElement.getAttribute(TemplateEngineHelper.VALUE);
			if (key != null && !key.trim().isEmpty()) {
				sharedDefaultsMap.put(key, value);
			}
		}
	}


	public void deleteBackEndStorage(String[] deleteName) {
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
					.parse(parsedXML.toURI().toURL().openStream());
		} catch (Exception exp) {
			TemplateEngineUtil.log(exp);
		}

		List<Element> sharedElementList = TemplateEngine.getChildrenOfElement(document.getDocumentElement());
		int elementListSize = sharedElementList.size();
		for (int i = 0; i < elementListSize; i++) {

			Element xmlElement = sharedElementList.get(i);
			String name = xmlElement.getAttribute(TemplateEngineHelper.ID);

			for (int k = 0; k < deleteName.length; k++) {
				if (deleteName[k].equals(name)) {
					xmlElement.removeAttribute(name);
					sharedDefaultsMap.remove(name);
				}
			}
		}

		updateShareDefaultsMap(sharedDefaultsMap);
	}


	private File createDefaultXMLFormat(File xmlFile) {
		Document d;
		try {
			d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		} catch (ParserConfigurationException e) {
			TemplateEngineUtil.log(e);
			return xmlFile;
		}
		Node rootElement = d.appendChild(d.createElement("SharedRoot")); //$NON-NLS-1$
		Element element = (Element) rootElement.appendChild(d.createElement("SharedProperty")); //$NON-NLS-1$
		element.setAttribute(TemplateEngineHelper.ID, ""); //$NON-NLS-1$
		element.setAttribute(TemplateEngineHelper.VALUE, ""); //$NON-NLS-1$

		DOMSource domSource = new DOMSource(d);
		TransformerFactory transFactory = TransformerFactory.newInstance();

		try {
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(xmlFile);
				Result fileResult = new StreamResult(fos);
				transFactory.newTransformer().transform(domSource, fileResult);
			} finally {
				if (fos != null) {
					fos.close();
				}
			}
		} catch (IOException ioe) {
			TemplateEngineUtil.log(ioe);
		} catch (TransformerConfigurationException tce) {
			TemplateEngineUtil.log(tce);
		} catch (TransformerException te) {
			TemplateEngineUtil.log(te);
		}
		return xmlFile;
	}


	private void generateSharedXML(File xmlFile) {
		Document d;
		try {
			d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		} catch (ParserConfigurationException e) {
			TemplateEngineUtil.log(e);
			return;
		}
		Node rootElement = d.appendChild(d.createElement("SharedRoot")); //$NON-NLS-1$

		for (String key : sharedDefaultsMap.keySet()) {
			Element element = (Element) rootElement.appendChild(d.createElement("SharedProperty")); //$NON-NLS-1$
			element.setAttribute(TemplateEngineHelper.ID, key);
			element.setAttribute(TemplateEngineHelper.VALUE, sharedDefaultsMap.get(key));
		}

		DOMSource domSource = new DOMSource(d);
		TransformerFactory transFactory = TransformerFactory.newInstance();
		Result fileResult = new StreamResult(xmlFile);
		try {
			transFactory.newTransformer().transform(domSource, fileResult);
		} catch (Throwable t) {
			TemplateEngineUtil.log(t);
		}
	}


	public TemplateDescriptor(URL descriptorURL, String pluginId) throws TemplateInitializationException {
		String msg = NLS.bind(Messages.TemplateCore_init_failed, descriptorURL.toString());
		try {
			this.document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(descriptorURL.openStream());
		} catch (ParserConfigurationException pce) {
			throw new TemplateInitializationException(msg, pce);
		} catch (IOException ioe) {
			throw new TemplateInitializationException(msg, ioe);
		} catch (SAXException se) {
			throw new TemplateInitializationException(msg, se);
		}
		this.rootElement = document.getDocumentElement();
		this.persistVector = new ArrayList<>();
		this.pluginId = pluginId;
	}


	private static Document loadXml(InputStream xmlStream) throws CoreException {
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			return builder.parse(xmlStream);
		} catch (Exception e) {
			throw new CoreException(CCorePlugin.createStatus(Messages.XmlUtil_InternalErrorLoading, e));
		}
	}


	public static Document newDocument() throws ParserConfigurationException {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		return builder.newDocument();
	}


	private static byte[] toByteArray(Document doc) throws CoreException {
		try {
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.ENCODING, ENCODING_UTF_8);
			// Indentation is done with XmlUtil.prettyFormat(doc).
			transformer.setOutputProperty(OutputKeys.INDENT, "no"); //$NON-NLS-1$
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(stream);
			transformer.transform(source, result);

			return stream.toByteArray();
		} catch (Exception e) {
			throw new CoreException(CCorePlugin.createStatus(Messages.XmlUtil_InternalErrorSerializing, e));
		}
	}


	static ICStorageElement environmentStorageFromString(String env) {
		if (env == null)
			return null;
		try {
			DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			InputSource inputSource = new InputSource(new ByteArrayInputStream(env.getBytes()));
			Document document = parser.parse(inputSource);
			Element el = document.getDocumentElement();
			XmlStorageElement rootElement = new XmlStorageElement(el);

			if (!StorableEnvironment.ENVIRONMENT_ELEMENT_NAME.equals(rootElement.getName()))
				return null;

			return rootElement;
		} catch (ParserConfigurationException e) {
			CCorePlugin.log(e);
		} catch (SAXException e) {
			CCorePlugin.log(e);
		} catch (IOException e) {
			CCorePlugin.log(e);
		}
		return null;
	}


	private ByteArrayOutputStream storeEnvironmentToStream(StorableEnvironment env) throws CoreException {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.newDocument();

			Element el = document.createElement(StorableEnvironment.ENVIRONMENT_ELEMENT_NAME);
			document.appendChild(el);
			XmlStorageElement rootElement = new XmlStorageElement(el);
			env.serialize(rootElement);

			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);

			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			StreamResult result = new StreamResult(stream);

			transformer.transform(source, result);
			return stream;
		} catch (ParserConfigurationException e) {
			throw new CoreException(new Status(IStatus.ERROR, CCorePlugin.PLUGIN_ID, -1, e.getMessage(), e));
		} catch (TransformerConfigurationException e) {
			throw new CoreException(new Status(IStatus.ERROR, CCorePlugin.PLUGIN_ID, -1, e.getMessage(), e));
		} catch (TransformerException e) {
			throw new CoreException(new Status(IStatus.ERROR, CCorePlugin.PLUGIN_ID, -1, e.getMessage(), e));
		}
	}


	private String getValueFromBackEndStorate(String key) throws Exception {
		File parsedXML = TemplateEngineHelper.getSharedDefaultLocation("shareddefaults.xml");

		Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
				.parse(parsedXML.toURI().toURL().openStream());

		List<Element> sharedElementList = TemplateEngine.getChildrenOfElement(document.getDocumentElement());
		int listSize = sharedElementList.size();
		for (int i = 0; i < listSize; i++) {
			Element xmlElement = sharedElementList.get(i);
			String key2 = xmlElement.getAttribute(TemplateEngineHelper.ID);
			String value2 = xmlElement.getAttribute(TemplateEngineHelper.VALUE);
			if (key.equals(key2)) {
				return value2;
			}
		}

		return null;
	}


	public void serialize(ICHelpInvocationContext context) {
		CHelpSettings settings = getHelpSettings(context);

		File file = getSettingsFile();

		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc;
			Element rootElement = null;

			if (file.exists()) {
				doc = builder.parse(file);
				NodeList nodes = doc.getElementsByTagName(ELEMENT_ROOT);

				if (nodes.getLength() > 0)
					rootElement = (Element) nodes.item(0);
			} else {
				doc = builder.newDocument();
			}

			if (rootElement == null) {
				rootElement = doc.createElement(ELEMENT_ROOT);
				doc.appendChild(rootElement);
			}

			settings.serialize(doc, rootElement);

			FileWriter writer = new FileWriter(file);

			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(doc);
			StreamResult result = new StreamResult(writer);

			transformer.transform(source, result);

			writer.close();
		} catch (ParserConfigurationException e) {
		} catch (SAXException e) {
		} catch (TransformerConfigurationException e) {
		} catch (TransformerException e) {
		} catch (IOException e) {
		}
	}


	private static CHelpSettings createHelpSettings(IProject project) {
		//		String projectName = project.getName();
		File file = getSettingsFile();
		CHelpSettings settings = null;
		Element rootElement = null;

		if (file.isFile()) {
			try {
				DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				Document doc = builder.parse(file);
				NodeList nodes = doc.getElementsByTagName(ELEMENT_ROOT);

				if (nodes.getLength() > 0)
					rootElement = (Element) nodes.item(0);

			} catch (ParserConfigurationException e) {
			} catch (SAXException e) {
			} catch (IOException e) {
			}
		}

		settings = new CHelpSettings(project, rootElement);
		return settings;
	}


	private void loadFile(IConfigurationElement el, ArrayList<ICHelpBook> chbl, String pluginId) {
		String fname = el.getAttribute(ATTRIB_FILE);
		if (fname == null || fname.trim().length() == 0)
			return;
		URL x = FileLocator.find(Platform.getBundle(pluginId), new Path(fname), null);
		if (x == null)
			return;
		try {
			x = FileLocator.toFileURL(x);
		} catch (IOException e) {
			return;
		}
		fname = x.getPath();
		if (fname == null || fname.trim().length() == 0)
			return;

		// format is not supported for now
		// String format = el.getAttribute(ATTRIB_FORMAT);

		Document doc = null;
		try {
			InputStream stream = new FileInputStream(fname);
			BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
			InputSource src = new InputSource(reader);
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			doc = builder.parse(src);
			Element e = doc.getDocumentElement();
			if (NODE_HEAD.equals(e.getNodeName())) {
				NodeList list = e.getChildNodes();
				for (int j = 0; j < list.getLength(); j++) {
					Node node = list.item(j);
					if (node.getNodeType() != Node.ELEMENT_NODE)
						continue;
					if (NODE_BOOK.equals(node.getNodeName())) {
						chbl.add(new CHelpBook((Element) node));
					}
				}
			}
		} catch (ParserConfigurationException e) {
		} catch (SAXException e) {
		} catch (IOException e) {
		}
	}


	private static void writeProfilesToStream(Collection<Profile> profiles, OutputStream stream, String encoding,
			IProfileVersioner profileVersioner) throws CoreException {
		try {
			final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			final DocumentBuilder builder = factory.newDocumentBuilder();
			final Document document = builder.newDocument();

			final Element rootElement = document.createElement(XML_NODE_ROOT);
			rootElement.setAttribute(XML_ATTRIBUTE_VERSION, Integer.toString(profileVersioner.getCurrentVersion()));

			document.appendChild(rootElement);

			for (Object element : profiles) {
				final Profile profile = (Profile) element;
				if (profile.isProfileToSave()) {
					final Element profileElement = createProfileElement(profile, document, profileVersioner);
					rootElement.appendChild(profileElement);
				}
			}

			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
			transformer.transform(new DOMSource(document), new StreamResult(stream));
		} catch (TransformerException e) {
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
		} catch (ParserConfigurationException e) {
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
		}
	}


	protected static List<Profile> readProfilesFromStream(InputSource inputSource) throws CoreException {
		final ProfileDefaultHandler handler = new ProfileDefaultHandler();
		try {
			final SAXParserFactory factory = SAXParserFactory.newInstance();
			final SAXParser parser = factory.newSAXParser();
			parser.parse(inputSource, handler);
		} catch (SAXException e) {
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
		} catch (IOException e) {
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
		} catch (ParserConfigurationException e) {
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
		}
		return handler.getProfiles();
	}


	private static Document parse(InputStream in) throws SettingsImportExportException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(false);
		factory.setNamespaceAware(false);
		factory.setIgnoringComments(true);

		try {
			DocumentBuilder parser = factory.newDocumentBuilder();
			parser.setErrorHandler(ABORTING_ERROR_HANDER); // causes SAXException to be thrown on any parse error
			InputSource input = new InputSource(in); // TODO should I be using an InputSource?
			Document doc = parser.parse(input);
			return doc;

		} catch (Exception e) {
			throw new SettingsImportExportException(e);
		}
	}


	public static String serializeDocument(Document doc, boolean indent) throws IOException, TransformerException {
		ByteArrayOutputStream s = new ByteArrayOutputStream();
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = factory.newTransformer();
		transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
		transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); //$NON-NLS-1$ //$NON-NLS-2$
		DOMSource source = new DOMSource(doc);
		StreamResult outputTarget = new StreamResult(s);
		transformer.transform(source, outputTarget);
		return s.toString("UTF8"); //$NON-NLS-1$
	}


	private void loadActionData() {

		String actionData = CDebugCorePlugin.getDefault().getPluginPreferences().getString(BREAKPOINT_ACTION_DATA);

		if (actionData == null || actionData.length() == 0)
			return;

		Element root = null;
		DocumentBuilder parser;
		try {
			parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			parser.setErrorHandler(new DefaultHandler());
			root = parser.parse(new InputSource(new StringReader(actionData))).getDocumentElement();

			NodeList nodeList = root.getChildNodes();
			int entryCount = nodeList.getLength();

			for (int i = 0; i < entryCount; i++) {
				Node node = nodeList.item(i);
				short type = node.getNodeType();
				if (type == Node.ELEMENT_NODE) {
					Element subElement = (Element) node;
					String nodeName = subElement.getNodeName();
					if (nodeName.equalsIgnoreCase("actionEntry")) { //$NON-NLS-1$
						String name = subElement.getAttribute("name"); //$NON-NLS-1$
						if (name == null)
							throw new Exception();
						String value = subElement.getAttribute("value"); //$NON-NLS-1$
						if (value == null)
							throw new Exception();
						String className = subElement.getAttribute("class"); //$NON-NLS-1$
						if (className == null)
							throw new Exception();

						IBreakpointAction action = createActionFromClassName(name, className);
						action.initializeFromMemento(value);
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public void saveActionData() {
		String actionData = ""; //$NON-NLS-1$

		DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = null;
		try {
			docBuilder = dfactory.newDocumentBuilder();
			Document doc = docBuilder.newDocument();

			Element rootElement = doc.createElement("breakpointActionData"); //$NON-NLS-1$
			doc.appendChild(rootElement);

			for (IBreakpointAction action : getBreakpointActions()) {
				Element element = doc.createElement("actionEntry"); //$NON-NLS-1$
				element.setAttribute("name", action.getName()); //$NON-NLS-1$
				element.setAttribute("class", action.getClass().getName()); //$NON-NLS-1$
				element.setAttribute("value", action.getMemento()); //$NON-NLS-1$
				rootElement.appendChild(element);
			}

			ByteArrayOutputStream s = new ByteArrayOutputStream();

			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

			DOMSource source = new DOMSource(doc);
			StreamResult outputTarget = new StreamResult(s);
			transformer.transform(source, outputTarget);

			actionData = s.toString("UTF8"); //$NON-NLS-1$

		} catch (Exception e) {
			e.printStackTrace();
		}
		CDebugCorePlugin.getDefault().getPluginPreferences().setValue(BREAKPOINT_ACTION_DATA, actionData);
		CDebugCorePlugin.getDefault().savePluginPreferences();
	}


	public String getMemento() throws CoreException {
		Document document = null;
		Throwable ex = null;
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			Element node = document.createElement(ELEMENT_NAME);
			document.appendChild(node);
			node.setAttribute(ATTR_DIRECTORY, getDirectory().toOSString());
			if (getAssociation() != null)
				node.setAttribute(ATTR_ASSOCIATION, getAssociation().toOSString());
			node.setAttribute(ATTR_SEARCH_SUBFOLDERS, String.valueOf(searchSubfolders()));
			return CDebugUtils.serializeDocument(document);
		} catch (ParserConfigurationException e) {
			ex = e;
		} catch (IOException e) {
			ex = e;
		} catch (TransformerException e) {
			ex = e;
		}
		abort(NLS.bind(InternalSourceLookupMessages.CDirectorySourceLocation_0, getDirectory().toOSString()), ex);
		// execution will not reach here
		return null;
	}


	public void initializeFrom(String memento) throws CoreException {
		Exception ex = null;
		try {
			Element root = null;
			DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			StringReader reader = new StringReader(memento);
			InputSource source = new InputSource(reader);
			root = parser.parse(source).getDocumentElement();

			String dir = root.getAttribute(ATTR_DIRECTORY);
			if (isEmpty(dir)) {
				abort(InternalSourceLookupMessages.CDirectorySourceLocation_1, null);
			} else {
				IPath path = new Path(dir);
				if (path.isValidPath(dir) && path.toFile().isDirectory() && path.toFile().exists()) {
					setDirectory(path);
				} else {
					abort(NLS.bind(InternalSourceLookupMessages.CDirectorySourceLocation_2, dir), null);
				}
			}
			dir = root.getAttribute(ATTR_ASSOCIATION);
			if (isEmpty(dir)) {
				setAssociation(null);
			} else {
				IPath path = new Path(dir);
				if (path.isValidPath(dir)) {
					setAssociation(path);
				} else {
					setAssociation(null);
				}
			}
			setSearchSubfolders(Boolean.valueOf(root.getAttribute(ATTR_SEARCH_SUBFOLDERS)).booleanValue());
			return;
		} catch (ParserConfigurationException e) {
			ex = e;
		} catch (SAXException e) {
			ex = e;
		} catch (IOException e) {
			ex = e;
		}
		abort(InternalSourceLookupMessages.CDirectorySourceLocation_3, ex);
	}


	public String getMemento() throws CoreException {
		Document document = null;
		Throwable ex = null;
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			Element node = document.createElement(ELEMENT_NAME);
			document.appendChild(node);
			node.setAttribute(ATTR_PROJECT, getProject().getName());
			node.setAttribute(ATTR_GENERIC, String.valueOf(isGeneric()));
			return CDebugUtils.serializeDocument(document);
		} catch (ParserConfigurationException e) {
			ex = e;
		} catch (IOException e) {
			ex = e;
		} catch (TransformerException e) {
			ex = e;
		}
		abort(NLS.bind(InternalSourceLookupMessages.CProjectSourceLocation_0, getProject().getName()), ex);
		// execution will not reach here
		return null;
	}


	public void initializeFrom(String memento) throws CoreException {
		Exception ex = null;
		try {
			Element root = null;
			DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			StringReader reader = new StringReader(memento);
			InputSource source = new InputSource(reader);
			root = parser.parse(source).getDocumentElement();

			String name = root.getAttribute(ATTR_PROJECT);
			if (isEmpty(name)) {
				abort(InternalSourceLookupMessages.CProjectSourceLocation_1, null);
			} else {
				IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(name);
				setProject(project);
			}
			String isGeneric = root.getAttribute(ATTR_GENERIC);
			if (isGeneric == null || isGeneric.trim().length() == 0)
				isGeneric = Boolean.FALSE.toString();
			setGenerated(isGeneric.equals(Boolean.TRUE.toString()));
			return;
		} catch (ParserConfigurationException e) {
			ex = e;
		} catch (SAXException e) {
			ex = e;
		} catch (IOException e) {
			ex = e;
		}
		abort(InternalSourceLookupMessages.CProjectSourceLocation_2, ex);
	}


	public void initializeFromMemento(String memento) throws CoreException {
		Exception ex = null;
		try {
			Element root = null;
			DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			StringReader reader = new StringReader(memento);
			InputSource source = new InputSource(reader);
			root = parser.parse(source).getDocumentElement();
			if (!root.getNodeName().equalsIgnoreCase(SOURCE_LOCATOR_NAME)) {
				abort(InternalSourceLookupMessages.CSourceLocator_1, null);
			}
			List<ICSourceLocation> sourceLocations = new ArrayList<>();
			// Add locations based on referenced projects
			IProject project = getProject();
			if (project != null && project.exists() && project.isOpen())
				sourceLocations.addAll(Arrays.asList(getDefaultSourceLocations()));
			removeDisabledLocations(root, sourceLocations);
			addAdditionalLocations(root, sourceLocations);
			// To support old launch configuration
			addOldLocations(root, sourceLocations);
			setSourceLocations(sourceLocations.toArray(new ICSourceLocation[sourceLocations.size()]));
			setSearchForDuplicateFiles(Boolean.valueOf(root.getAttribute(ATTR_DUPLICATE_FILES)).booleanValue());
			return;
		} catch (ParserConfigurationException e) {
			ex = e;
		} catch (SAXException e) {
			ex = e;
		} catch (IOException e) {
			ex = e;
		}
		abort(InternalSourceLookupMessages.CSourceLocator_2, ex);
	}


	public String getMemento() throws CoreException {
		Document document = null;
		Throwable ex = null;
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			Element node = document.createElement(SOURCE_LOCATOR_NAME);
			document.appendChild(node);
			ICSourceLocation[] locations = getSourceLocations();
			saveDisabledGenericSourceLocations(locations, document, node);
			saveAdditionalSourceLocations(locations, document, node);
			node.setAttribute(ATTR_DUPLICATE_FILES, String.valueOf(searchForDuplicateFiles()));
			return CDebugUtils.serializeDocument(document);
		} catch (ParserConfigurationException e) {
			ex = e;
		} catch (IOException e) {
			ex = e;
		} catch (TransformerException e) {
			ex = e;
		}
		abort(InternalSourceLookupMessages.CSourceLocator_0, ex);
		// execution will not reach here
		return null;
	}


	public static ICSourceLocation[] getCommonSourceLocationsFromMemento(String memento) {
		ICSourceLocation[] result = new ICSourceLocation[0];
		if (!isEmpty(memento)) {
			try {
				DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				StringReader reader = new StringReader(memento);
				InputSource source = new InputSource(reader);
				Element root = parser.parse(source).getDocumentElement();
				if (root.getNodeName().equalsIgnoreCase(NAME_COMMON_SOURCE_LOCATIONS))
					result = initializeSourceLocations(root);
			} catch (ParserConfigurationException e) {
				CDebugCorePlugin.log(new Status(IStatus.ERROR, CDebugCorePlugin.getUniqueIdentifier(), 0,
						"Error initializing common source settings.", e)); //$NON-NLS-1$
			} catch (SAXException e) {
				CDebugCorePlugin.log(new Status(IStatus.ERROR, CDebugCorePlugin.getUniqueIdentifier(), 0,
						"Error initializing common source settings.", e)); //$NON-NLS-1$
			} catch (IOException e) {
				CDebugCorePlugin.log(new Status(IStatus.ERROR, CDebugCorePlugin.getUniqueIdentifier(), 0,
						"Error initializing common source settings.", e)); //$NON-NLS-1$
			}
		}
		return result;
	}


	public static String getCommonSourceLocationsMemento(ICSourceLocation[] locations) {
		Document document = null;
		Throwable ex = null;
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			Element element = document.createElement(NAME_COMMON_SOURCE_LOCATIONS);
			document.appendChild(element);
			saveSourceLocations(document, element, locations);
			return CDebugUtils.serializeDocument(document);
		} catch (ParserConfigurationException e) {
			ex = e;
		} catch (IOException e) {
			ex = e;
		} catch (TransformerException e) {
			ex = e;
		}
		CDebugCorePlugin.log(new Status(IStatus.ERROR, CDebugCorePlugin.getUniqueIdentifier(), 0,
				"Error saving common source settings.", ex)); //$NON-NLS-1$
		return null;
	}


	public String getMemento() {
		String executeData = ""; //$NON-NLS-1$
		if (externalToolName != null) {
			DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = null;
			try {
				docBuilder = dfactory.newDocumentBuilder();
				Document doc = docBuilder.newDocument();

				Element rootElement = doc.createElement("launchConfigName"); //$NON-NLS-1$
				rootElement.setAttribute("configName", externalToolName); //$NON-NLS-1$

				doc.appendChild(rootElement);

				ByteArrayOutputStream s = new ByteArrayOutputStream();

				TransformerFactory factory = TransformerFactory.newInstance();
				Transformer transformer = factory.newTransformer();
				transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
				transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

				DOMSource source = new DOMSource(doc);
				StreamResult outputTarget = new StreamResult(s);
				transformer.transform(source, outputTarget);

				executeData = s.toString("UTF8"); //$NON-NLS-1$

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return executeData;
	}


	public void initializeFromMemento(String data) {
		Element root = null;
		DocumentBuilder parser;
		try {
			parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			parser.setErrorHandler(new DefaultHandler());
			root = parser.parse(new InputSource(new StringReader(data))).getDocumentElement();
			String value = root.getAttribute("configName"); //$NON-NLS-1$
			if (value == null)
				throw new Exception();
			externalToolName = value;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public String getMemento() {
		String logData = ""; //$NON-NLS-1$

		DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = null;
		try {
			docBuilder = dfactory.newDocumentBuilder();
			Document doc = docBuilder.newDocument();

			Element rootElement = doc.createElement("logData"); //$NON-NLS-1$
			rootElement.setAttribute("message", message); //$NON-NLS-1$
			rootElement.setAttribute("evalExpr", Boolean.toString(evaluateExpression)); //$NON-NLS-1$

			doc.appendChild(rootElement);

			ByteArrayOutputStream s = new ByteArrayOutputStream();

			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

			DOMSource source = new DOMSource(doc);
			StreamResult outputTarget = new StreamResult(s);
			transformer.transform(source, outputTarget);

			logData = s.toString("UTF8"); //$NON-NLS-1$

		} catch (Exception e) {
			e.printStackTrace();
		}
		return logData;
	}


	public void initializeFromMemento(String data) {
		Element root = null;
		DocumentBuilder parser;
		try {
			parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			parser.setErrorHandler(new DefaultHandler());
			root = parser.parse(new InputSource(new StringReader(data))).getDocumentElement();
			String value = root.getAttribute("message"); //$NON-NLS-1$
			if (value == null)
				throw new Exception();
			message = value;
			value = root.getAttribute("evalExpr"); //$NON-NLS-1$
			if (value == null)
				throw new Exception();
			evaluateExpression = Boolean.valueOf(value).booleanValue();
			value = root.getAttribute("resume"); //$NON-NLS-1$
			if (value == null)
				throw new Exception();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public void initializeFromMemento(String data) {
		Element root = null;
		DocumentBuilder parser;
		try {
			parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			parser.setErrorHandler(new DefaultHandler());
			root = parser.parse(new InputSource(new StringReader(data))).getDocumentElement();
			String value = root.getAttribute("pauseTime"); //$NON-NLS-1$
			if (value == null)
				throw new Exception();
			pauseTime = Integer.parseInt(value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public String getMemento() {
		String resumeData = ""; //$NON-NLS-1$

		DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = null;
		try {
			docBuilder = dfactory.newDocumentBuilder();
			Document doc = docBuilder.newDocument();

			Element rootElement = doc.createElement("resumeData"); //$NON-NLS-1$
			rootElement.setAttribute("pauseTime", Integer.toString(pauseTime)); //$NON-NLS-1$

			doc.appendChild(rootElement);

			ByteArrayOutputStream s = new ByteArrayOutputStream();

			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

			DOMSource source = new DOMSource(doc);
			StreamResult outputTarget = new StreamResult(s);
			transformer.transform(source, outputTarget);

			resumeData = s.toString("UTF8"); //$NON-NLS-1$

		} catch (Exception e) {
			e.printStackTrace();
		}
		return resumeData;
	}


	public void initializeFromMemento(String data) {
		Element root = null;
		DocumentBuilder parser;
		try {
			parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			parser.setErrorHandler(new DefaultHandler());
			root = parser.parse(new InputSource(new StringReader(data))).getDocumentElement();
			String value = root.getAttribute("operation"); //$NON-NLS-1$
			if (value == null)
				throw new Exception();
			fOperation = REVERSE_DEBUG_ACTIONS_ENUM.valueOf(value);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	public String getMemento() {
		String reverseDebugData = ""; //$NON-NLS-1$

		DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = null;
		try {
			docBuilder = dfactory.newDocumentBuilder();
			Document doc = docBuilder.newDocument();

			Element rootElement = doc.createElement("reverseDebugData"); //$NON-NLS-1$
			rootElement.setAttribute("operation", fOperation.toString()); //$NON-NLS-1$

			doc.appendChild(rootElement);

			ByteArrayOutputStream s = new ByteArrayOutputStream();

			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

			DOMSource source = new DOMSource(doc);
			StreamResult outputTarget = new StreamResult(s);
			transformer.transform(source, outputTarget);

			reverseDebugData = s.toString("UTF8"); //$NON-NLS-1$

		} catch (Exception e) {
			e.printStackTrace();
		}
		return reverseDebugData;

	}


	public String getMemento() {
		String soundData = ""; //$NON-NLS-1$
		if (soundFile != null) {
			DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = null;
			try {
				docBuilder = dfactory.newDocumentBuilder();
				Document doc = docBuilder.newDocument();

				Element rootElement = doc.createElement("soundData"); //$NON-NLS-1$
				rootElement.setAttribute("file", soundFile.getAbsolutePath()); //$NON-NLS-1$

				doc.appendChild(rootElement);

				ByteArrayOutputStream s = new ByteArrayOutputStream();

				TransformerFactory factory = TransformerFactory.newInstance();
				Transformer transformer = factory.newTransformer();
				transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
				transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

				DOMSource source = new DOMSource(doc);
				StreamResult outputTarget = new StreamResult(s);
				transformer.transform(source, outputTarget);

				soundData = s.toString("UTF8"); //$NON-NLS-1$

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return soundData;
	}


	public void initializeFromMemento(String data) {
		Element root = null;
		DocumentBuilder parser;
		try {
			parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			parser.setErrorHandler(new DefaultHandler());
			root = parser.parse(new InputSource(new StringReader(data))).getDocumentElement();
			String value = root.getAttribute("file"); //$NON-NLS-1$
			if (value == null)
				throw new Exception();
			soundFile = new File(value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}