package org.eclipse.text.templates;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.eclipse.osgi.util.NLS;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.templates.Template;
public class TemplateReaderWriter {
private static final String TEMPLATE_ROOT = "templates";
private static final String TEMPLATE_ELEMENT = "template";
private static final String NAME_ATTRIBUTE= "name";
private static final String ID_ATTRIBUTE= "id";
private static final String DESCRIPTION_ATTRIBUTE= "description";
private static final String CONTEXT_ATTRIBUTE= "context";
private static final String ENABLED_ATTRIBUTE= "enabled";
private static final String DELETED_ATTRIBUTE= "deleted";
private static final String AUTO_INSERTABLE_ATTRIBUTE= "autoinsert";
public TemplateReaderWriter() {
}
public TemplatePersistenceData[] read(Reader reader) throws IOException {
return read(reader, null);
}
public TemplatePersistenceData readSingle(Reader reader, String id) throws IOException {
TemplatePersistenceData[] datas= read(new InputSource(reader), null, id);
if (datas.length > 0)
return datas[0];
return null;
}
public TemplatePersistenceData[] read(Reader reader, ResourceBundle bundle) throws IOException {
return read(new InputSource(reader), bundle, null);
}
public TemplatePersistenceData[] read(InputStream stream, ResourceBundle bundle) throws IOException {
return read(new InputSource(stream), bundle, null);
}
private TemplatePersistenceData[] read(InputSource source, ResourceBundle bundle, String singleId) throws IOException {
try {
Collection<TemplatePersistenceData> templates= new ArrayList<>();
Set<String> ids= new HashSet<>();
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder parser= factory.newDocumentBuilder();
parser.setErrorHandler(new DefaultHandler());
Document document= parser.parse(source);
NodeList elements= document.getElementsByTagName(TEMPLATE_ELEMENT);
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 id= getStringValue(attributes, ID_ATTRIBUTE, null);
if (id != null && ids.contains(id)) {
String PLUGIN_ID= "org.eclipse.jface.text";
ILog log= Platform.getLog(Platform.getBundle(PLUGIN_ID));
String message= NLS.bind(TextTemplateMessages.getString("TemplateReaderWriter.duplicate.id"), id);
log.log(new Status(IStatus.WARNING, PLUGIN_ID, IStatus.OK, message, null));
} else {
ids.add(id);
}
if (singleId != null && !singleId.equals(id))
continue;
boolean deleted = getBooleanValue(attributes, DELETED_ATTRIBUTE, false);
String name= getStringValue(attributes, NAME_ATTRIBUTE);
name= translateString(name, bundle);
String description= getStringValue(attributes, DESCRIPTION_ATTRIBUTE, "");
description= translateString(description, bundle);
String context= getStringValue(attributes, CONTEXT_ATTRIBUTE);
if (name == null || context == null)
throw new IOException(TextTemplateMessages.getString("TemplateReaderWriter.error.missing_attribute"));
boolean enabled = getBooleanValue(attributes, ENABLED_ATTRIBUTE, true);
boolean autoInsertable= getBooleanValue(attributes, AUTO_INSERTABLE_ATTRIBUTE, true);
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();
pattern= translateString(pattern, bundle);
Template template= new Template(name, description, context, pattern, autoInsertable);
TemplatePersistenceData data= new TemplatePersistenceData(template, enabled, id);
data.setDeleted(deleted);
templates.add(data);
if (singleId != null && singleId.equals(id))
break;
}
return templates.toArray(new TemplatePersistenceData[templates.size()]);
} catch (ParserConfigurationException e) {
Assert.isTrue(false);
} catch (SAXException e) {
throw (IOException)new IOException("Could not read template file").initCause(e);
}
return null;
}
public void save(TemplatePersistenceData[] templates, OutputStream stream) throws IOException {
save(templates, new StreamResult(stream));
}
public void save(TemplatePersistenceData[] templates, Writer writer) throws IOException {
save(templates, new StreamResult(writer));
}
private void save(TemplatePersistenceData[] templates, StreamResult result) throws IOException {
try {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder builder= factory.newDocumentBuilder();
Document document= builder.newDocument();
Node root= document.createElement(TEMPLATE_ROOT);
document.appendChild(root);
for (TemplatePersistenceData data : templates) {
Template template= data.getTemplate();
Node node= document.createElement(TEMPLATE_ELEMENT);
root.appendChild(node);
NamedNodeMap attributes= node.getAttributes();
String id= data.getId();
if (id != null) {
Attr idAttr= document.createAttribute(ID_ATTRIBUTE);
idAttr.setValue(id);
attributes.setNamedItem(idAttr);
}
if (template != null) {
Attr name= document.createAttribute(NAME_ATTRIBUTE);
name.setValue(validateXML(template.getName()));
attributes.setNamedItem(name);
}
if (template != null) {
Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE);
description.setValue(validateXML(template.getDescription()));
attributes.setNamedItem(description);
}
if (template != null) {
Attr context= document.createAttribute(CONTEXT_ATTRIBUTE);
context.setValue(validateXML(template.getContextTypeId()));
attributes.setNamedItem(context);
}
Attr enabled= document.createAttribute(ENABLED_ATTRIBUTE);
enabled.setValue(data.isEnabled() ? Boolean.toString(true) : Boolean.toString(false));
attributes.setNamedItem(enabled);
Attr deleted= document.createAttribute(DELETED_ATTRIBUTE);
deleted.setValue(data.isDeleted() ? Boolean.toString(true) : Boolean.toString(false));
attributes.setNamedItem(deleted);
if (template != null) {
Attr autoInsertable= document.createAttribute(AUTO_INSERTABLE_ATTRIBUTE);
autoInsertable.setValue(template.isAutoInsertable() ? Boolean.toString(true) : Boolean.toString(false));
attributes.setNamedItem(autoInsertable);
}
if (template != null) {
Text pattern= document.createTextNode(validateXML(template.getPattern()));
node.appendChild(pattern);
}
}
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
DOMSource source = new DOMSource(document);
transformer.transform(source, result);
} catch (ParserConfigurationException e) {
Assert.isTrue(false);
} catch (TransformerException e) {
if (e.getException() instanceof IOException)
throw (IOException) e.getException();
Assert.isTrue(false);
}
}
private static String validateXML(String string) throws IOException {
for (int i= 0; i < string.length(); i++) {
char ch= string.charAt(i);
if (!(ch == 9 || ch == 10 || ch == 13 || ch >= 32))
throw new IOException("Character reference \"&#" + Integer.toString(ch) + "\" is an invalid XML character.");
}
return string;
}
private boolean getBooleanValue(NamedNodeMap attributes, String attribute, boolean defaultValue) throws SAXException {
Node enabledNode= attributes.getNamedItem(attribute);
if (enabledNode == null)
return defaultValue;
else if (enabledNode.getNodeValue().equals(Boolean.toString(true)))
return true;
else if (enabledNode.getNodeValue().equals(Boolean.toString(false)))
return false;
else
throw new SAXException(TextTemplateMessages.getString("TemplateReaderWriter.error.illegal_boolean_attribute"));
}
private String getStringValue(NamedNodeMap attributes, String name) throws SAXException {
String val= getStringValue(attributes, name, null);
if (val == null)
throw new SAXException(TextTemplateMessages.getString("TemplateReaderWriter.error.missing_attribute"));
return val;
}
private String getStringValue(NamedNodeMap attributes, String name, String defaultValue) {
Node node= attributes.getNamedItem(name);
return node == null ? defaultValue : node.getNodeValue();
}
private String translateString(String str, ResourceBundle bundle) {
if (bundle == null)
return str;
int idx= str.indexOf('%');
if (idx == -1) {
return str;
}
StringBuilder buf= new StringBuilder();
int k= 0;
while (idx != -1) {
buf.append(str.substring(k, idx));
for (k= idx + 1; k < str.length() && !Character.isWhitespace(str.charAt(k)); k++) {
}
String key= str.substring(idx + 1, k);
buf.append(getBundleString(key, bundle));
idx= str.indexOf('%', k);
}
buf.append(str.substring(k));
return buf.toString();
}
private String getBundleString(String key, ResourceBundle bundle) {
if (bundle != null) {
try {
return bundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
return TextTemplateMessages.getString(key);
}
}