Remove transformers

This commit is contained in:
Paulo Gustavo Veiga 2022-01-03 16:49:28 -08:00
parent ea5e990b76
commit 7153b0b103
10 changed files with 2 additions and 664 deletions

View File

@ -1,57 +0,0 @@
/*
* Copyright [2015] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wisemapping.exporter;
import org.jetbrains.annotations.NotNull;
public enum ExportFormat {
FREEMIND("application/freemind", "mm"),
TEXT("text/plain", "txt"),
MICROSOFT_EXCEL("application/vnd.ms-excel", "xls"),
MICROSOFT_WORD("application/msword", "doc"),
MINDJET("application/vnd.mindjet.mindmanager", "mmap"),
WISEMAPPING("application/wisemapping+xml", "wxml");
private final String contentType;
private final String fileExtension;
ExportFormat(String contentType, String fileExtension) {
this.contentType = contentType;
this.fileExtension = fileExtension;
}
public String getFileExtension() {
return fileExtension;
}
public String getContentType() {
return contentType;
}
public static ExportFormat fromContentType(@NotNull final String contentType) {
final ExportFormat[] values = ExportFormat.values();
for (ExportFormat value : values) {
if (value.getContentType().equals(contentType)) {
return value;
}
}
throw new IllegalStateException("ComponentType could not be mapped:" + contentType);
}
}

View File

@ -1,51 +0,0 @@
/*
* Copyright [2015] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wisemapping.exporter;
public class ExportProperties {
private final ExportFormat format;
private String version;
public ExportFormat getFormat() {
return format;
}
private ExportProperties(final ExportFormat format) {
this.format = format;
}
public static ExportProperties create(final ExportFormat format) {
return new GenericProperties(format);
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
private static class GenericProperties extends ExportProperties {
private GenericProperties(ExportFormat format) {
super(format);
}
}
}

View File

@ -1,217 +0,0 @@
/*
* Copyright [2015] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wisemapping.exporter;
import com.wisemapping.importer.VersionNumber;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.servlet.ServletContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 javax.xml.xpath.*;
import java.awt.geom.AffineTransform;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.regex.Pattern;
public class ExporterFactory {
private static final String GROUP_NODE_NAME = "g";
private static final String IMAGE_NODE_NAME = "image";
private static final int MANGING = 50;
private final File baseImgDir;
public ExporterFactory(@NotNull final ServletContext servletContext) {
this.baseImgDir = new File(servletContext.getRealPath("/"));
}
public ExporterFactory(@NotNull final File baseImgDir) {
this.baseImgDir = baseImgDir;
}
public void export(@NotNull ExportProperties properties, @Nullable String xml, @NotNull OutputStream output, @Nullable String mapSvg) throws ExportException, IOException {
final ExportFormat format = properties.getFormat();
switch (format) {
case TEXT: {
final Exporter exporter = XSLTExporter.create(XSLTExporter.Type.TEXT);
exporter.export(xml.getBytes(StandardCharsets.UTF_8), output);
break;
}
case MICROSOFT_EXCEL: {
final Exporter exporter = XSLTExporter.create(XSLTExporter.Type.MICROSOFT_EXCEL);
exporter.export(xml.getBytes(StandardCharsets.UTF_8), output);
break;
}
case FREEMIND: {
final FreemindExporter exporter = new FreemindExporter();
exporter.setVersion(new VersionNumber(properties.getVersion()));
exporter.export(xml.getBytes(StandardCharsets.UTF_8), output);
break;
}
case MINDJET: {
final Exporter exporter = XSLTExporter.create(XSLTExporter.Type.MINDJET);
exporter.export(xml.getBytes(StandardCharsets.UTF_8), output);
break;
}
default:
throw new UnsupportedOperationException("Export method not supported.");
}
output.flush();
output.close();
}
private static String domToString(@NotNull Document document) throws TransformerException {
DOMSource domSource = new DOMSource(document);
// Create a string writer
final CharArrayWriter result = new CharArrayWriter();
// Create the stream stream for the transform
StreamResult stream = new StreamResult(result);
// Create a Transformer to serialize the document
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
// Transform the document to the stream stream
transformer.transform(domSource, stream);
return result.toString();
}
private void inlineImages(@NotNull Document document, @NotNull Element element) {
final NodeList list = element.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
final Node node = list.item(i);
// find all groups
if (GROUP_NODE_NAME.equals(node.getNodeName())) {
// Must continue looking ....
inlineImages(document, (Element) node);
} else if (IMAGE_NODE_NAME.equals(node.getNodeName())) {
Element elem = (Element) node;
final String imgUrl = fixHref(elem);
if (!imgUrl.isEmpty() && (!imgUrl.startsWith("image/png;base64") || !imgUrl.startsWith("data:image/png;base64"))) {
elem.removeAttribute("href");
InputStream fis = null;
// Obtains file name ...
try {
final File iconFile = iconFile(imgUrl);
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
fis = new FileInputStream(iconFile);
Base64.Encoder enc = Base64.getEncoder();
bos.write(enc.encode(IOUtils.toByteArray(fis)));
elem.setAttribute("xlink:href", "data:image/png;base64," + bos.toString("8859_1"));
elem.appendChild(document.createTextNode(" "));
} catch (IOException e) {
e.printStackTrace();
} finally {
close(fis);
}
}
}
}
}
@NotNull
private String fixHref(@NotNull Element elem) {
// Fix href attribute ...
// Hack for IE: If the image is a external URL, embeed it...
String result = elem.getAttribute("href");
if (result.isEmpty()) {
// Bug WISE-422: This seems to be a bug in Safari. For some reason, img add prefixed with NS1
// <image NS1:href="icons/sign_help.png"
// Also: Remove replace "xlink:href" to href to uniform ...
final NamedNodeMap attributes = elem.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
final Node node = attributes.item(i);
String nodeName = node.getNodeName();
if(nodeName.contains(":href")){
elem.removeAttribute(nodeName);
result = node.getNodeValue();
}
}
elem.setAttribute("href", result);
}
return result;
}
private File iconFile(@NotNull final String imgUrl) throws IOException {
int index = imgUrl.lastIndexOf("/");
final String iconName = imgUrl.substring(index + 1);
final File iconsDir = new File(baseImgDir, "icons");
File result = new File(iconsDir, iconName);
if (!result.exists()) {
// It's not a icon, must be a note, attach image ...
final File legacyIconsDir = new File(baseImgDir, "images");
result = new File(legacyIconsDir, iconName);
}
if (!result.exists()) {
final File legacyIconsDir = new File(iconsDir, "legacy");
result = new File(legacyIconsDir, iconName);
}
if (!result.exists() || result.isDirectory()) {
throw new IOException("Icon could not be found:" + imgUrl);
}
return result;
}
private void close(Closeable fis) {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// Ignore ...
}
}
}
}

View File

@ -1,86 +0,0 @@
package com.wisemapping.exporter;
import com.wisemapping.model.Mindmap;
import org.jetbrains.annotations.NotNull;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
public class XSLTExporter implements Exporter {
private final Type type;
public XSLTExporter(@NotNull Type type) {
this.type = type;
}
@Override
public void export(@NotNull byte[] xml, @NotNull OutputStream outputStream) throws ExportException {
final ByteArrayOutputStream mmos = new ByteArrayOutputStream();
// Convert to freemind ...
final FreemindExporter exporter = new FreemindExporter();
exporter.export(xml, mmos);
// Convert to xslt transform ...
final InputStream xsltis = this.getClass().getResourceAsStream("/com/wisemapping/export/xslt/" + type.getXsltName());
if (xsltis == null) {
throw new IllegalStateException("XSLT could not be resolved.");
}
try {
final TransformerFactory factory = TransformerFactory.newInstance();
final Source xslt = new StreamSource(xsltis);
Transformer transformer = factory.newTransformer(xslt);
final CharArrayReader reader = new CharArrayReader(mmos.toString(StandardCharsets.ISO_8859_1).toCharArray());
final Source mmSource = new StreamSource(reader);
transformer.transform(mmSource, new StreamResult(outputStream));
} catch (TransformerException e) {
throw new ExportException(e);
}
}
@Override
public void export(@NotNull Mindmap map, OutputStream outputStream) throws ExportException {
throw new UnsupportedOperationException();
}
@NotNull
public static Exporter create(@NotNull Type type) {
return new XSLTExporter(type);
}
public enum Type {
TEXT("mm2text.xsl"),
WORD("mm2wordml_utf8.xsl"),
CSV("mm2csv.xsl"),
LATEX("mm2latex.xsl"),
MICROSOFT_EXCEL("mm2xls_utf8.xsl"),
MINDJET("mm2mj.xsl"),
OPEN_OFFICE("mm2oowriter.xsl");
public String getXsltName() {
return xsltName;
}
private final String xsltName;
Type(@NotNull String xstFile) {
this.xsltName = xstFile;
}
}
}

View File

@ -69,68 +69,6 @@ public class MindmapController extends BaseController {
return new RestMindmap(mindMap, user);
}
@RequestMapping(method = RequestMethod.GET, value = "/maps/{id}", produces = {"application/wisemapping+xml"}, params = {"download=wxml"})
@ResponseBody
public ModelAndView retrieveAsWise(@PathVariable int id) throws WiseMappingException {
final Mindmap mindMap = findMindmapById(id);
final Map<String, Object> values = new HashMap<String, Object>();
final User user = Utils.getUser();
values.put("mindmap", new RestMindmap(mindMap, user));
values.put("filename", mindMap.getTitle());
return new ModelAndView("transformViewWise", values);
}
@RequestMapping(method = RequestMethod.GET, value = "/maps/{id}", produces = {"application/freemind"}, params = {"download=mm"})
@ResponseBody
public ModelAndView retrieveDocumentAsFreemind(@PathVariable int id) throws IOException, MapCouldNotFoundException {
final Mindmap mindMap = findMindmapById(id);
final Map<String, Object> values = new HashMap<String, Object>();
values.put("content", mindMap.getXmlStr());
values.put("filename", mindMap.getTitle());
return new ModelAndView("transformViewFreemind", values);
}
@RequestMapping(method = RequestMethod.GET, value = "/maps/{id}", produces = {"text/plain"}, params = {"download=txt"})
@ResponseBody
public ModelAndView retrieveDocumentAsText(@PathVariable int id) throws IOException, MapCouldNotFoundException {
final Mindmap mindMap = findMindmapById(id);
final Map<String, Object> values = new HashMap<String, Object>();
values.put("content", mindMap.getXmlStr());
values.put("filename", mindMap.getTitle());
return new ModelAndView("transformViewTxt", values);
}
@RequestMapping(method = RequestMethod.GET, value = "/maps/{id}", produces = {"application/vnd.mindjet.mindmanager"}, params = {"download=mmap"})
@ResponseBody
public ModelAndView retrieveDocumentAsMindJet(@PathVariable int id) throws IOException, MapCouldNotFoundException {
final Mindmap mindMap = findMindmapById(id);
final Map<String, Object> values = new HashMap<String, Object>();
values.put("content", mindMap.getXmlStr());
values.put("filename", mindMap.getTitle());
return new ModelAndView("transformViewMMap", values);
}
@RequestMapping(method = RequestMethod.GET, value = "/maps/{id}", produces = {"application/vnd.ms-excel"}, params = {"download=xls"})
@ResponseBody
public ModelAndView retrieveDocumentAsExcel(@PathVariable int id) throws IOException, MapCouldNotFoundException {
final Mindmap mindMap = findMindmapById(id);
final Map<String, Object> values = new HashMap<String, Object>();
values.put("content", mindMap.getXmlStr());
values.put("filename", mindMap.getTitle());
return new ModelAndView("transformViewXls", values);
}
@RequestMapping(method = RequestMethod.GET, value = "/maps/{id}", produces = {"application/vnd.oasis.opendocument.text"}, params = {"download=odt"})
@ResponseBody
public ModelAndView retrieveDocumentAsOdt(@PathVariable int id) throws IOException, MapCouldNotFoundException {
final Mindmap mindMap = findMindmapById(id);
final Map<String, Object> values = new HashMap<String, Object>();
values.put("content", mindMap.getXmlStr());
values.put("filename", mindMap.getTitle());
return new ModelAndView("transformViewOdt", values);
}
@RequestMapping(method = RequestMethod.GET, value = "/maps/", produces = {"application/json", "application/xml"})
public RestMindmapList retrieveList(@RequestParam(required = false) String q) throws IOException {
final User user = Utils.getUser();

View File

@ -18,10 +18,6 @@
package com.wisemapping.rest;
import com.wisemapping.exporter.ExportFormat;
import com.wisemapping.exporter.ExportProperties;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
@ -30,7 +26,6 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@ -38,11 +33,7 @@ import java.util.Map;
@Controller
public class TransformerController extends BaseController {
private static final String PARAM_SVG_XML = "svgXml";
private static final String PARAM_WISE_MAP_XML = "mapXml";
private static final String PARAM_FILENAME = "filename";
@RequestMapping(method = RequestMethod.POST, value = "/transform", produces = {"application/freemind"}, consumes = {"application/xml"})
@RequestMapping(method = RequestMethod.POST, value = "/transform", produces = {"application/freemind"}, consumes = {"application/xml"})
@ResponseBody
public ModelAndView transformFreemind(@RequestBody @Nullable final String content) throws IOException {
final Map<String, Object> values = new HashMap<String, Object>();

View File

@ -1,127 +0,0 @@
/*
* Copyright [2015] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wisemapping.rest.view;
import com.wisemapping.exporter.ExportFormat;
import com.wisemapping.exporter.ExportProperties;
import com.wisemapping.exporter.ExporterFactory;
import com.wisemapping.mail.NotificationService;
import com.wisemapping.security.Utils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.servlet.view.AbstractView;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.stream.StreamResult;
import java.io.UnsupportedEncodingException;
import java.util.Map;
public class TransformView extends AbstractView {
@NonNls
private static final String DEFAULT_ENCODING = "UTF-8";
private final String contentType;
private final ExportFormat exportFormat;
private final NotificationService notificationService;
@Autowired
private Jaxb2Marshaller jaxbMarshaller;
public TransformView(@NotNull final String contentType, @NotNull NotificationService notificationService) {
this.contentType = contentType;
this.notificationService = notificationService;
this.exportFormat = ExportFormat.fromContentType(contentType);
}
@Override
protected void renderMergedOutputModel(@NotNull Map<String, Object> viewMap, @NotNull HttpServletRequest request, @NotNull final HttpServletResponse response) {
final String content = (String) viewMap.get("content");
final String filename = (String) viewMap.get("filename");
final String version = (String) viewMap.get("version");
// Build format properties ...
final ExportProperties properties = ExportProperties.create(exportFormat);
if (version != null) {
properties.setVersion(version);
}
// Set format content type...
final String contentType = exportFormat.getContentType();
response.setContentType(contentType);
// Set file name...:http://stackoverflow.com/questions/5325322/java-servlet-download-filename-special-characters/13359949#13359949
final String fileName = (filename != null ? filename : "map") + "." + exportFormat.getFileExtension();
this.setContentDisposition(request, response, fileName);
// Change image link URL.
final ServletContext servletContext = getServletContext();
final ExporterFactory factory = new ExporterFactory(servletContext);
try {
// Write the conversion content ...
final ServletOutputStream outputStream = response.getOutputStream();
if (exportFormat == ExportFormat.FREEMIND) {
response.setContentType(String.format("%s; charset=%s", contentType, "ASCII"));
factory.export(properties, content, outputStream, null);
} else if (exportFormat == ExportFormat.WISEMAPPING) {
response.setContentType(String.format("%s; charset=%s", contentType, DEFAULT_ENCODING));
final Object mindmap = viewMap.get("mindmap");
final StreamResult result = new StreamResult(outputStream);
jaxbMarshaller.marshal(mindmap, result);
} else if (exportFormat == ExportFormat.MICROSOFT_EXCEL || exportFormat == ExportFormat.TEXT || exportFormat == ExportFormat.MINDJET) {
response.setContentType(String.format("%s; charset=%s", contentType, DEFAULT_ENCODING));
factory.export(properties, content, outputStream, null);
} else {
// Image export ...
factory.export(properties, null, outputStream, content);
}
} catch (Throwable e) {
notificationService.reportJavaException(e, Utils.getUser(), content, request);
}
}
private void setContentDisposition(HttpServletRequest request, HttpServletResponse response, String fileName) {
final String userAgent = request.getHeader("user-agent");
boolean isInternetExplorer = (userAgent.contains("MSIE"));
String disposition = fileName;
try {
byte[] fileNameBytes = fileName.getBytes((isInternetExplorer) ? ("windows-1250") : ("utf-8"));
final StringBuilder dispositionFileName = new StringBuilder();
for (byte b : fileNameBytes) {
dispositionFileName.append((char) (b & 0xff));
}
disposition = "attachment; filename=\"" + dispositionFileName + "\"";
} catch (UnsupportedEncodingException ence) {
// ... handle exception ...
}
response.setHeader("Content-disposition", disposition);
}
@Override
public String getContentType() {
return contentType;
}
}

View File

@ -94,58 +94,6 @@
</property>
</bean>
<bean id="transformViewPdf" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="application/pdf"/>
<constructor-arg ref="notificationService"/>
</bean>
<bean id="transformViewPng" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="image/png"/>
<constructor-arg ref="notificationService"/>
</bean>
<bean id="transformViewJpeg" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="image/jpeg"/>
<constructor-arg ref="notificationService"/>
</bean>
<bean id="transformViewFreemind" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="application/freemind"/>
<constructor-arg ref="notificationService"/>
</bean>
<bean id="transformViewSvg" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="image/svg+xml"/>
<constructor-arg ref="notificationService"/>
</bean>
<bean id="transformViewXls" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="application/vnd.ms-excel"/>
<constructor-arg ref="notificationService"/>
</bean>
<bean id="transformViewOdt" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="application/vnd.oasis.opendocument.text"/>
<constructor-arg ref="notificationService"/>
</bean>
<bean id="transformViewTxt" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="text/plain"/>
<constructor-arg ref="notificationService"/>
</bean>
<bean id="transformViewMMap" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="application/vnd.mindjet.mindmanager"/>
<constructor-arg ref="notificationService"/>
</bean>
<bean id="transformViewWise" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="application/wisemapping+xml"/>
<constructor-arg ref="notificationService"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>

View File

@ -27,7 +27,6 @@ public class FreeMindImportExportTest {
ImporterFactory exporterFactory = ImporterFactory.getInstance();
importer = exporterFactory.getImporter(ImportFormat.FREEMIND);
exporter = new FreemindExporter();
}