- REST PDF/PNG/Freemind transform working...

This commit is contained in:
Paulo Gustavo Veiga 2012-02-17 10:42:20 -03:00
parent a786c0de09
commit 6edb3d46a5
8 changed files with 883 additions and 567 deletions

View File

@ -1,214 +1,214 @@
/* /*
* Copyright [2011] [wisemapping] * Copyright [2011] [wisemapping]
* *
* Licensed under WiseMapping Public License, Version 1.0 (the "License"). * Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the * It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page; * "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the license at * You may obtain a copy of the license at
* *
* http://www.wisemapping.org/license * http://www.wisemapping.org/license
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.wisemapping.controller; package com.wisemapping.controller;
import com.wisemapping.exporter.ExportException; import com.wisemapping.exporter.ExportException;
import com.wisemapping.exporter.ExportFormat; import com.wisemapping.exporter.ExportFormat;
import com.wisemapping.exporter.ExporterFactory; import com.wisemapping.exporter.ExporterFactory;
import com.wisemapping.model.MindMap; import com.wisemapping.model.MindMap;
import com.wisemapping.service.MindmapService; import com.wisemapping.service.MindmapService;
import com.wisemapping.view.MindMapBean; import com.wisemapping.view.MindMapBean;
import com.wisemapping.exporter.ExportProperties; import com.wisemapping.exporter.ExportProperties;
import com.wisemapping.filter.UserAgent; import com.wisemapping.filter.UserAgent;
import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderException;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException; import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import sun.misc.BASE64Encoder; import sun.misc.BASE64Encoder;
import javax.servlet.ServletOutputStream; import javax.servlet.ServletOutputStream;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
public class ExportController extends BaseMultiActionController { public class ExportController extends BaseMultiActionController {
private static final String IMG_EXPORT_FORMAT = "IMG_EXPORT_FORMAT"; private static final String IMG_EXPORT_FORMAT = "IMG_EXPORT_FORMAT";
private static final String MAP_ID_PARAMETER = "mapId"; private static final String MAP_ID_PARAMETER = "mapId";
private static final String MAP_SVG_PARAMETER = "mapSvg"; private static final String MAP_SVG_PARAMETER = "mapSvg";
private static final String EXPORT_FORMAT_PARAMETER = "exportFormat"; private static final String EXPORT_FORMAT_PARAMETER = "exportFormat";
private static final String IMG_SIZE_PARAMETER = "imgSize"; private static final String IMG_SIZE_PARAMETER = "imgSize";
private static final String MAP_XML_PARAM = "mapXml"; private static final String MAP_XML_PARAM = "mapXml";
public ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException noSuchRequestHandlingMethodException, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { public ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException noSuchRequestHandlingMethodException, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
logger.info("Mindmap Controller: EXPORT action"); logger.info("Mindmap Controller: EXPORT action");
final MindMap mindmap = getMindmapFromRequest(httpServletRequest); final MindMap mindmap = getMindmapFromRequest(httpServletRequest);
return new ModelAndView("mindmapExport", "mindmap", new MindMapBean(mindmap)); return new ModelAndView("mindmapExport", "mindmap", new MindMapBean(mindmap));
} }
public ModelAndView export(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException { public ModelAndView export(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException {
logger.info("Export Controller: exporting WiseMap action"); logger.info("Export Controller: exporting WiseMap action");
final String mapIdStr = request.getParameter(MAP_ID_PARAMETER); final String mapIdStr = request.getParameter(MAP_ID_PARAMETER);
if (mapIdStr != null) { if (mapIdStr != null) {
final String mapSvg = request.getParameter(MAP_SVG_PARAMETER); final String mapSvg = request.getParameter(MAP_SVG_PARAMETER);
try { try {
int mindmapId = Integer.parseInt(mapIdStr); int mindmapId = Integer.parseInt(mapIdStr);
logger.debug("SVG Map to export:" + mapSvg); logger.debug("SVG Map to export:" + mapSvg);
if (mapSvg == null || mapSvg.isEmpty()) { if (mapSvg == null || mapSvg.isEmpty()) {
throw new IllegalArgumentException("SVG map could not be null"); throw new IllegalArgumentException("SVG map could not be null");
} }
String formatStr = request.getParameter(EXPORT_FORMAT_PARAMETER); String formatStr = request.getParameter(EXPORT_FORMAT_PARAMETER);
if (IMG_EXPORT_FORMAT.endsWith(formatStr)) { if (IMG_EXPORT_FORMAT.endsWith(formatStr)) {
formatStr = request.getParameter("imgFormat"); formatStr = request.getParameter("imgFormat");
} }
final MindmapService service = getMindmapService(); final MindmapService service = getMindmapService();
final MindMap mindMap = service.getMindmapById(mindmapId); final MindMap mindMap = service.getMindmapById(mindmapId);
// Build format properties ... // Build format properties ...
final ExportFormat format = ExportFormat.valueOf(formatStr); final ExportFormat format = ExportFormat.valueOf(formatStr);
final ExportProperties properties = ExportProperties.create(format); final ExportProperties properties = ExportProperties.create(format);
if (properties instanceof ExportProperties.ImageProperties) { if (properties instanceof ExportProperties.ImageProperties) {
final String sizeStr = request.getParameter(IMG_SIZE_PARAMETER); final String sizeStr = request.getParameter(IMG_SIZE_PARAMETER);
final ExportProperties.ImageProperties imageProperties = (ExportProperties.ImageProperties) properties; final ExportProperties.ImageProperties imageProperties = (ExportProperties.ImageProperties) properties;
if (sizeStr != null) { if (sizeStr != null) {
final ExportProperties.ImageProperties.Size size = ExportProperties.ImageProperties.Size.valueOf(sizeStr); final ExportProperties.ImageProperties.Size size = ExportProperties.ImageProperties.Size.valueOf(sizeStr);
imageProperties.setSize(size); imageProperties.setSize(size);
} else { } else {
imageProperties.setSize(ExportProperties.ImageProperties.Size.LARGE); imageProperties.setSize(ExportProperties.ImageProperties.Size.LARGE);
} }
} }
final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final ByteArrayOutputStream bos = new ByteArrayOutputStream();
// Change image link URL. // Change image link URL.
setBaseBaseImgUrl(format, properties); setBaseBaseImgUrl(format, properties);
ExporterFactory.export(properties, mindMap, bos, mapSvg); ExporterFactory.export(properties, mindMap.getUnzippedXml(), bos, mapSvg);
// If the export goes ok, write the map to the stream ... // If the export goes ok, write the map to the stream ...
// Set format content type... // Set format content type...
final String contentType = format.getContentType(); final String contentType = format.getContentType();
response.setContentType(contentType); response.setContentType(contentType);
// Set file name... // Set file name...
final String fileName = mindMap.getTitle() + "." + format.getFileExtension(); final String fileName = mindMap.getTitle() + "." + format.getFileExtension();
response.setHeader("Content-Disposition", "attachment;filename=" + fileName); response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// Write content ... // Write content ...
final ServletOutputStream outputStream = response.getOutputStream(); final ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(bos.toByteArray()); outputStream.write(bos.toByteArray());
} catch (Throwable e) { } catch (Throwable e) {
logger.error("Unexpexted error during export process", e); logger.error("Unexpexted error during export process", e);
response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND);
logger.error("map: " + mapSvg); logger.error("map: " + mapSvg);
} }
} else { } else {
logger.warn("mapIdStr is null.Image could not be imported. UserAgent:" + request.getHeaders(UserAgent.USER_AGENT_HEADER)); logger.warn("mapIdStr is null.Image could not be imported. UserAgent:" + request.getHeaders(UserAgent.USER_AGENT_HEADER));
response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND);
} }
return null; return null;
} }
private void setBaseBaseImgUrl(@NotNull ExportFormat format, @NotNull ExportProperties properties) { private void setBaseBaseImgUrl(@NotNull ExportFormat format, @NotNull ExportProperties properties) {
final String baseUrl; final String baseUrl;
if (format == ExportFormat.SVG) { if (format == ExportFormat.SVG) {
baseUrl = "http://www.wisemapping.com/images"; baseUrl = "http://www.wisemapping.com/images";
} else { } else {
final ServletContext servletContext = this.getServletContext(); final ServletContext servletContext = this.getServletContext();
baseUrl = "file://" + servletContext.getRealPath("/icons/") + "/"; baseUrl = "file://" + servletContext.getRealPath("/icons/") + "/";
} }
properties.setBaseImagePath(baseUrl); properties.setBaseImagePath(baseUrl);
} }
public ModelAndView print(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException { public ModelAndView print(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException {
logger.info("Export Controller: printing WiseMap action"); logger.info("Export Controller: printing WiseMap action");
final String mapIdStr = request.getParameter(MAP_ID_PARAMETER); final String mapIdStr = request.getParameter(MAP_ID_PARAMETER);
int mindmapId = Integer.parseInt(mapIdStr); int mindmapId = Integer.parseInt(mapIdStr);
final MindmapService service = getMindmapService(); final MindmapService service = getMindmapService();
final MindMap mindmap = service.getMindmapById(mindmapId); final MindMap mindmap = service.getMindmapById(mindmapId);
final String mapSvg = request.getParameter(MAP_SVG_PARAMETER); final String mapSvg = request.getParameter(MAP_SVG_PARAMETER);
final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final ByteArrayOutputStream bos = new ByteArrayOutputStream();
try { try {
exportImage(response, mapSvg, bos, false); exportImage(response, mapSvg, bos, false);
} catch (Throwable e) { } catch (Throwable e) {
logger.error("Unexpexted error generating the image", e); logger.error("Unexpexted error generating the image", e);
logger.error("map: " + mapSvg); logger.error("map: " + mapSvg);
} }
BASE64Encoder encoder = new BASE64Encoder(); BASE64Encoder encoder = new BASE64Encoder();
String content = encoder.encode(bos.toByteArray()); String content = encoder.encode(bos.toByteArray());
final String exportContent = "data:image/png;base64," + content; final String exportContent = "data:image/png;base64," + content;
bos.close(); bos.close();
ModelAndView view = new ModelAndView("mindmapPrint", "mindmap", new MindMapBean(mindmap)); ModelAndView view = new ModelAndView("mindmapPrint", "mindmap", new MindMapBean(mindmap));
final String xmlMap = mindmap.getNativeXmlAsJsLiteral(); final String xmlMap = mindmap.getNativeXmlAsJsLiteral();
view.addObject(MAP_XML_PARAM, xmlMap); view.addObject(MAP_XML_PARAM, xmlMap);
view.addObject(MAP_SVG_PARAMETER, exportContent); view.addObject(MAP_SVG_PARAMETER, exportContent);
return view; return view;
} }
public ModelAndView image(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException { public ModelAndView image(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException {
logger.info("Export Controller: generating image WiseMap action"); logger.info("Export Controller: generating image WiseMap action");
final String mapIdStr = request.getParameter(MAP_ID_PARAMETER); final String mapIdStr = request.getParameter(MAP_ID_PARAMETER);
final String mapSvg = request.getParameter(MAP_SVG_PARAMETER); final String mapSvg = request.getParameter(MAP_SVG_PARAMETER);
try { try {
final ServletOutputStream outputStream = response.getOutputStream(); final ServletOutputStream outputStream = response.getOutputStream();
exportImage(response, mapSvg, outputStream, true); exportImage(response, mapSvg, outputStream, true);
} catch (Throwable e) { } catch (Throwable e) {
logger.error("Unexpexted error generating the image", e); logger.error("Unexpexted error generating the image", e);
logger.error("map: " + mapSvg); logger.error("map: " + mapSvg);
} }
return null; return null;
} }
private void exportImage(HttpServletResponse response, String mapSvg, OutputStream outputStream, boolean setOutput) throws TranscoderException, IOException, ParserConfigurationException, SAXException, XMLStreamException, TransformerException, JAXBException, ExportException { private void exportImage(HttpServletResponse response, String mapSvg, OutputStream outputStream, boolean setOutput) throws TranscoderException, IOException, ParserConfigurationException, SAXException, XMLStreamException, TransformerException, JAXBException, ExportException {
//Image Format //Image Format
ExportFormat imageFormat = ExportFormat.PNG; ExportFormat imageFormat = ExportFormat.PNG;
// Build format properties ... // Build format properties ...
final ExportProperties.ImageProperties imageProperties = new ExportProperties.ImageProperties(imageFormat); final ExportProperties.ImageProperties imageProperties = new ExportProperties.ImageProperties(imageFormat);
imageProperties.setSize(ExportProperties.ImageProperties.Size.XMEDIUM); imageProperties.setSize(ExportProperties.ImageProperties.Size.XMEDIUM);
// Change image link URL. // Change image link URL.
setBaseBaseImgUrl(imageFormat, imageProperties); setBaseBaseImgUrl(imageFormat, imageProperties);
// Set format content type... // Set format content type...
if (setOutput) if (setOutput)
response.setContentType(imageFormat.getContentType()); response.setContentType(imageFormat.getContentType());
// Write content ... // Write content ...
ExporterFactory.export(imageProperties, null, outputStream, mapSvg); ExporterFactory.export(imageProperties, null, outputStream, mapSvg);
} }
} }

View File

@ -1,44 +1,55 @@
/* /*
* Copyright [2011] [wisemapping] * Copyright [2011] [wisemapping]
* *
* Licensed under WiseMapping Public License, Version 1.0 (the "License"). * Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the * It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page; * "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the license at * You may obtain a copy of the license at
* *
* http://www.wisemapping.org/license * http://www.wisemapping.org/license
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.wisemapping.exporter; package com.wisemapping.exporter;
public enum ExportFormat { import org.jetbrains.annotations.NotNull;
SVG("image/svg+xml", "svg"),
JPEG("image/jpeg", "jpg"), public enum ExportFormat {
PNG("image/png", "png"), SVG("image/svg+xml", "svg"),
MINDJET("text/xml", "xml"), JPEG("image/jpeg", "jpg"),
PDF("application/pdf", "pdf"), PNG("image/png", "png"),
FREEMIND("text/xml", "mm"); PDF("application/pdf", "pdf"),
FREEMIND("application/freemind", "mm");
private String contentType;
private String fileExtension; private String contentType;
private String fileExtension;
ExportFormat(String contentType, String fileExtension) {
this.contentType = contentType; ExportFormat(String contentType, String fileExtension) {
this.fileExtension = fileExtension; this.contentType = contentType;
} this.fileExtension = fileExtension;
}
public String getFileExtension() {
return fileExtension; public String getFileExtension() {
} return fileExtension;
}
public String getContentType() {
return contentType; 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,304 +1,304 @@
/* /*
* Copyright [2011] [wisemapping] * Copyright [2011] [wisemapping]
* *
* Licensed under WiseMapping Public License, Version 1.0 (the "License"). * Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the * It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page; * "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the license at * You may obtain a copy of the license at
* *
* http://www.wisemapping.org/license * http://www.wisemapping.org/license
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.wisemapping.exporter; package com.wisemapping.exporter;
import com.wisemapping.model.MindMap; import com.wisemapping.model.MindMap;
import org.apache.batik.transcoder.Transcoder; import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.ImageTranscoder; import org.apache.batik.transcoder.image.ImageTranscoder;
import org.apache.batik.transcoder.image.JPEGTranscoder; import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.fop.svg.PDFTranscoder; import org.apache.fop.svg.PDFTranscoder;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.w3c.dom.*; import org.w3c.dom.*;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource; import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamResult;
import java.io.*; import java.io.*;
public class ExporterFactory { public class ExporterFactory {
private static final String GROUP_NODE_NAME = "g"; private static final String GROUP_NODE_NAME = "g";
private static final String RECT_NODE_NAME = "rect"; private static final String RECT_NODE_NAME = "rect";
private static final String IMAGE_NODE_NAME = "image"; private static final String IMAGE_NODE_NAME = "image";
private ExporterFactory() throws ParserConfigurationException { private ExporterFactory() throws ParserConfigurationException {
} }
public static void export(@NotNull ExportProperties properties, @Nullable MindMap map, @NotNull OutputStream output, @NotNull String mapSvg) throws TranscoderException, IOException, ParserConfigurationException, SAXException, XMLStreamException, TransformerException, JAXBException, ExportException { public static void export(@NotNull ExportProperties properties, @NotNull String xml, @NotNull OutputStream output, @NotNull String mapSvg) throws TranscoderException, IOException, ParserConfigurationException, SAXException, XMLStreamException, TransformerException, JAXBException, ExportException {
final ExportFormat format = properties.getFormat(); final ExportFormat format = properties.getFormat();
final String imgPath = properties.getBaseImgPath(); final String imgPath = properties.getBaseImgPath();
switch (format) { switch (format) {
case PNG: { case PNG: {
// Create a JPEG transcoder // Create a JPEG transcoder
final Transcoder transcoder = new PNGTranscoder(); final Transcoder transcoder = new PNGTranscoder();
final ExportProperties.ImageProperties imageProperties = final ExportProperties.ImageProperties imageProperties =
(ExportProperties.ImageProperties) properties; (ExportProperties.ImageProperties) properties;
final ExportProperties.ImageProperties.Size size = imageProperties.getSize(); final ExportProperties.ImageProperties.Size size = imageProperties.getSize();
transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, size.getWidth()); transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, size.getWidth());
// Create the transcoder input. // Create the transcoder input.
final Document document = normalizeSvg(mapSvg, imgPath); final Document document = normalizeSvg(mapSvg, imgPath);
final String svgString = domToString(document); final String svgString = domToString(document);
final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray())); final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray()));
TranscoderOutput trascoderOutput = new TranscoderOutput(output); TranscoderOutput trascoderOutput = new TranscoderOutput(output);
// Save the image. // Save the image.
transcoder.transcode(input, trascoderOutput); transcoder.transcode(input, trascoderOutput);
break; break;
} }
case JPEG: { case JPEG: {
// Create a JPEG transcoder // Create a JPEG transcoder
final Transcoder transcoder = new JPEGTranscoder(); final Transcoder transcoder = new JPEGTranscoder();
transcoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.99)); transcoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.99));
final ExportProperties.ImageProperties imageProperties = final ExportProperties.ImageProperties imageProperties =
(ExportProperties.ImageProperties) properties; (ExportProperties.ImageProperties) properties;
final ExportProperties.ImageProperties.Size size = imageProperties.getSize(); final ExportProperties.ImageProperties.Size size = imageProperties.getSize();
transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, size.getWidth()); transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, size.getWidth());
// Create the transcoder input. // Create the transcoder input.
final Document document = normalizeSvg(mapSvg, imgPath); final Document document = normalizeSvg(mapSvg, imgPath);
final String svgString = domToString(document); final String svgString = domToString(document);
final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray())); final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray()));
TranscoderOutput trascoderOutput = new TranscoderOutput(output); TranscoderOutput trascoderOutput = new TranscoderOutput(output);
// Save the image. // Save the image.
transcoder.transcode(input, trascoderOutput); transcoder.transcode(input, trascoderOutput);
break; break;
} }
case PDF: { case PDF: {
// Create a JPEG transcoder // Create a JPEG transcoder
final Transcoder transcoder = new PDFTranscoder(); final Transcoder transcoder = new PDFTranscoder();
// Create the transcoder input. // Create the transcoder input.
final Document document = normalizeSvg(mapSvg, imgPath); final Document document = normalizeSvg(mapSvg, imgPath);
final String svgString = domToString(document); final String svgString = domToString(document);
final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray())); final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray()));
TranscoderOutput trascoderOutput = new TranscoderOutput(output); TranscoderOutput trascoderOutput = new TranscoderOutput(output);
// Save the image. // Save the image.
transcoder.transcode(input, trascoderOutput); transcoder.transcode(input, trascoderOutput);
break; break;
} }
case SVG: { case SVG: {
final Document dom = normalizeSvg(mapSvg, imgPath); final Document dom = normalizeSvg(mapSvg, imgPath);
output.write(domToString(dom).getBytes("UTF-8")); output.write(domToString(dom).getBytes("UTF-8"));
break; break;
} }
case FREEMIND: { case FREEMIND: {
final FreemindExporter exporter = new FreemindExporter(); final FreemindExporter exporter = new FreemindExporter();
exporter.export(map.getUnzippedXml().getBytes(), output); exporter.export(xml.getBytes(), output);
break; break;
} }
default: default:
throw new UnsupportedOperationException("Export method not supported."); throw new UnsupportedOperationException("Export method not supported.");
} }
} }
private static Document normalizeSvg(@NotNull String svgXml, final String imgBaseUrl) throws XMLStreamException, ParserConfigurationException, IOException, SAXException, TransformerException { private static Document normalizeSvg(@NotNull String svgXml, final String imgBaseUrl) throws XMLStreamException, ParserConfigurationException, IOException, SAXException, TransformerException {
final DocumentBuilder documentBuilder = getDocumentBuilder(); final DocumentBuilder documentBuilder = getDocumentBuilder();
svgXml = svgXml.replaceFirst("<svg ", "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" "); svgXml = svgXml.replaceFirst("<svg ", "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" ");
// @Todo: This must not happen... // @Todo: This must not happen...
svgXml = svgXml.replaceAll("NaN,", "0"); svgXml = svgXml.replaceAll("NaN,", "0");
svgXml = svgXml.replaceAll(",NaN", "0"); svgXml = svgXml.replaceAll(",NaN", "0");
Document document; Document document;
try { try {
final Reader in = new CharArrayReader(svgXml.toCharArray()); final Reader in = new CharArrayReader(svgXml.toCharArray());
final InputSource is = new InputSource(in); final InputSource is = new InputSource(in);
document = documentBuilder.parse(is); document = documentBuilder.parse(is);
} catch (SAXException e) { } catch (SAXException e) {
// It must be a corrupted SVG format. Try to hack it and try again ... // It must be a corrupted SVG format. Try to hack it and try again ...
svgXml = svgXml.replaceAll("<image([^>]+)>", "<image$1/>"); svgXml = svgXml.replaceAll("<image([^>]+)>", "<image$1/>");
final Reader in = new CharArrayReader(svgXml.toCharArray()); final Reader in = new CharArrayReader(svgXml.toCharArray());
final InputSource is = new InputSource(in); final InputSource is = new InputSource(in);
document = documentBuilder.parse(is); document = documentBuilder.parse(is);
} }
fitSvg(document); fitSvg(document);
fixImageTagHref(document, imgBaseUrl); fixImageTagHref(document, imgBaseUrl);
return document; return document;
} }
private static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException { private static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
return factory.newDocumentBuilder(); return factory.newDocumentBuilder();
} }
private static String domToString(@NotNull Document document) throws TransformerException { private static String domToString(@NotNull Document document) throws TransformerException {
DOMSource domSource = new DOMSource(document); DOMSource domSource = new DOMSource(document);
// Create a string writer // Create a string writer
final CharArrayWriter result = new CharArrayWriter(); final CharArrayWriter result = new CharArrayWriter();
// Create the stream stream for the transform // Create the stream stream for the transform
StreamResult stream = new StreamResult(result); StreamResult stream = new StreamResult(result);
// Create a Transformer to serialize the document // Create a Transformer to serialize the document
TransformerFactory tFactory = TransformerFactory.newInstance(); TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(); Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty("indent", "yes"); transformer.setOutputProperty("indent", "yes");
// Transform the document to the stream stream // Transform the document to the stream stream
transformer.transform(domSource, stream); transformer.transform(domSource, stream);
return result.toString(); return result.toString();
} }
private static void fixImageTagHref(Document document, String imgBaseUrl) { private static void fixImageTagHref(Document document, String imgBaseUrl) {
final Node child = document.getFirstChild(); final Node child = document.getFirstChild();
fixImageTagHref(document, (Element) child, imgBaseUrl); fixImageTagHref(document, (Element) child, imgBaseUrl);
} }
private static void fixImageTagHref(@NotNull Document document, @NotNull Element element, String imgBaseUrl) { private static void fixImageTagHref(@NotNull Document document, @NotNull Element element, String imgBaseUrl) {
final NodeList list = element.getChildNodes(); final NodeList list = element.getChildNodes();
for (int i = 0; i < list.getLength(); i++) { for (int i = 0; i < list.getLength(); i++) {
final Node node = list.item(i); final Node node = list.item(i);
// find all groups // find all groups
if (GROUP_NODE_NAME.equals(node.getNodeName())) { if (GROUP_NODE_NAME.equals(node.getNodeName())) {
// Must continue looking .... // Must continue looking ....
fixImageTagHref(document, (Element) node, imgBaseUrl); fixImageTagHref(document, (Element) node, imgBaseUrl);
} else if (IMAGE_NODE_NAME.equals(node.getNodeName())) { } else if (IMAGE_NODE_NAME.equals(node.getNodeName())) {
Element elem = (Element) node; Element elem = (Element) node;
// Cook image href ... // Cook image href ...
final String imgUrl = elem.getAttribute("href"); final String imgUrl = elem.getAttribute("href");
int index = imgUrl.lastIndexOf("/"); int index = imgUrl.lastIndexOf("/");
elem.removeAttribute("href"); elem.removeAttribute("href");
if (index != -1) { if (index != -1) {
final String iconName = imgUrl.substring(index+1); final String iconName = imgUrl.substring(index+1);
// Hack for backward compatibility . This can be removed in 2012. :) // Hack for backward compatibility . This can be removed in 2012. :)
String imgPath; String imgPath;
if (imgUrl.contains("images")) { if (imgUrl.contains("images")) {
imgPath = imgBaseUrl + "/../icons/legacy/" + iconName; imgPath = imgBaseUrl + "/../icons/legacy/" + iconName;
} else { } else {
imgPath = imgBaseUrl + "/" + imgUrl; imgPath = imgBaseUrl + "/" + imgUrl;
} }
elem.setAttribute("xlink:href", imgPath); elem.setAttribute("xlink:href", imgPath);
elem.appendChild(document.createTextNode(" ")); elem.appendChild(document.createTextNode(" "));
} }
} }
} }
} }
private static void fitSvg(Document document) { private static void fitSvg(Document document) {
// viewBox size // viewBox size
int mapWidth = 1024; int mapWidth = 1024;
int mapHeight = 768; int mapHeight = 768;
// some browser return width and heigth with precision // some browser return width and heigth with precision
float currentMaxWidth = 0; float currentMaxWidth = 0;
float currentMaxHeight = 0; float currentMaxHeight = 0;
final Element svgNode = (Element) document.getFirstChild(); final Element svgNode = (Element) document.getFirstChild();
final NodeList list = svgNode.getChildNodes(); final NodeList list = svgNode.getChildNodes();
for (int i = 0; i < list.getLength(); i++) { for (int i = 0; i < list.getLength(); i++) {
final Node node = list.item(i); final Node node = list.item(i);
// find all groups // find all groups
if (GROUP_NODE_NAME.equals(node.getNodeName())) { if (GROUP_NODE_NAME.equals(node.getNodeName())) {
final NamedNodeMap groupAttributes = node.getAttributes(); final NamedNodeMap groupAttributes = node.getAttributes();
final String[] transformUnit = getTransformUnit(groupAttributes); final String[] transformUnit = getTransformUnit(groupAttributes);
int groupPositionX = Integer.parseInt(transformUnit[0].trim()); int groupPositionX = Integer.parseInt(transformUnit[0].trim());
int groupPositionY = 0; int groupPositionY = 0;
if (transformUnit.length > 1) { if (transformUnit.length > 1) {
groupPositionY = Integer.parseInt(transformUnit[1].trim()); groupPositionY = Integer.parseInt(transformUnit[1].trim());
} }
int signumX = Integer.signum(groupPositionX); int signumX = Integer.signum(groupPositionX);
int signumY = Integer.signum(groupPositionY); int signumY = Integer.signum(groupPositionY);
final NodeList groupChildren = node.getChildNodes(); final NodeList groupChildren = node.getChildNodes();
for (int idx = 0; idx < groupChildren.getLength(); idx++) { for (int idx = 0; idx < groupChildren.getLength(); idx++) {
final Node rectNode = groupChildren.item(idx); final Node rectNode = groupChildren.item(idx);
float curentHeight = 0; float curentHeight = 0;
float curentWidth = 0; float curentWidth = 0;
// If has a rect use the rect to calcular the real width of the topic // If has a rect use the rect to calcular the real width of the topic
if (RECT_NODE_NAME.equals(rectNode.getNodeName())) { if (RECT_NODE_NAME.equals(rectNode.getNodeName())) {
final NamedNodeMap rectAttributes = rectNode.getAttributes(); final NamedNodeMap rectAttributes = rectNode.getAttributes();
final Node attributeHeight = rectAttributes.getNamedItem("height"); final Node attributeHeight = rectAttributes.getNamedItem("height");
final Node attributeWidth = rectAttributes.getNamedItem("width"); final Node attributeWidth = rectAttributes.getNamedItem("width");
curentHeight = Float.valueOf(attributeHeight.getNodeValue()); curentHeight = Float.valueOf(attributeHeight.getNodeValue());
curentWidth = Float.valueOf(attributeWidth.getNodeValue()); curentWidth = Float.valueOf(attributeWidth.getNodeValue());
} }
float newMaxWidth = groupPositionX + (curentWidth * signumX); float newMaxWidth = groupPositionX + (curentWidth * signumX);
if (Math.abs(currentMaxWidth) < Math.abs(newMaxWidth)) { if (Math.abs(currentMaxWidth) < Math.abs(newMaxWidth)) {
currentMaxWidth = newMaxWidth; currentMaxWidth = newMaxWidth;
} }
float newMaxHeight = groupPositionY + curentHeight * signumY; float newMaxHeight = groupPositionY + curentHeight * signumY;
if (Math.abs(currentMaxHeight) < Math.abs(newMaxHeight)) { if (Math.abs(currentMaxHeight) < Math.abs(newMaxHeight)) {
currentMaxHeight = newMaxHeight; currentMaxHeight = newMaxHeight;
} }
} }
} }
} }
svgNode.setAttribute("viewBox", -Math.abs(currentMaxWidth) + " " + -Math.abs(currentMaxHeight) + " " + Math.abs(currentMaxWidth * 2) + " " + Math.abs(currentMaxHeight * 2)); svgNode.setAttribute("viewBox", -Math.abs(currentMaxWidth) + " " + -Math.abs(currentMaxHeight) + " " + Math.abs(currentMaxWidth * 2) + " " + Math.abs(currentMaxHeight * 2));
svgNode.setAttribute("width", Float.toString(mapWidth / 2)); svgNode.setAttribute("width", Float.toString(mapWidth / 2));
svgNode.setAttribute("height", Float.toString(mapHeight / 2)); svgNode.setAttribute("height", Float.toString(mapHeight / 2));
svgNode.setAttribute("preserveAspectRatio", "xMinYMin"); svgNode.setAttribute("preserveAspectRatio", "xMinYMin");
} }
private static String[] getTransformUnit(NamedNodeMap groupAttributes) { private static String[] getTransformUnit(NamedNodeMap groupAttributes) {
final String value = groupAttributes.getNamedItem("transform").getNodeValue(); final String value = groupAttributes.getNamedItem("transform").getNodeValue();
final int pos = value.indexOf("translate"); final int pos = value.indexOf("translate");
final int initTranslate = value.indexOf("(", pos); final int initTranslate = value.indexOf("(", pos);
final int endTranslate = value.indexOf(")", pos); final int endTranslate = value.indexOf(")", pos);
final String transate = value.substring(initTranslate + 1, endTranslate); final String transate = value.substring(initTranslate + 1, endTranslate);
return transate.split(","); return transate.split(",");
} }
} }

View File

@ -2,8 +2,11 @@ package com.wisemapping.rest;
import com.wisemapping.model.MindMap; import com.wisemapping.model.MindMap;
import com.wisemapping.model.MindmapUser;
import com.wisemapping.model.User;
import com.wisemapping.rest.model.RestMindMap; import com.wisemapping.rest.model.RestMindMap;
import com.wisemapping.service.MindmapService; import com.wisemapping.service.MindmapService;
import com.wisemapping.validator.Utils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@ -14,20 +17,30 @@ import org.springframework.web.servlet.ModelAndView;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
@Controller @Controller
@RequestMapping("/map")
public class MindmapController { public class MindmapController {
@Autowired @Autowired
private MindmapService mindmapService; private MindmapService mindmapService;
@RequestMapping(method = RequestMethod.GET, value = "/{id}") @RequestMapping(method = RequestMethod.GET, value = "/map/{id}")
@ResponseBody @ResponseBody
public ModelAndView getMindmap(@PathVariable int id) throws IOException { public ModelAndView getMindmap(@PathVariable int id) throws IOException {
final MindMap mindMap = mindmapService.getMindmapById(id); final MindMap mindMap = mindmapService.getMindmapById(id);
final RestMindMap map = new RestMindMap(mindMap); final RestMindMap map = new RestMindMap(mindMap);
return new ModelAndView("mapView", "map", map); return new ModelAndView("mapView", "map", map);
} }
@RequestMapping(method = RequestMethod.GET, value = "/maps")
public ModelAndView getMindmaps() throws IOException {
final User user = com.wisemapping.security.Utils.getUser();
final List<MindmapUser> list = mindmapService.getMindmapUserByUser(user);
// final RestMindMap map = new RestMindMap(mindMap);
// return new ModelAndView("mapView", "map", map);
return null;
}
} }

View File

@ -0,0 +1,63 @@
package com.wisemapping.rest;
import com.wisemapping.exporter.ExportProperties;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Controller
public class TransformerController {
@RequestMapping(method = RequestMethod.POST, value = "/transform", produces = {"application/pdf"}, consumes = {"image/svg+xml"})
@ResponseBody
public ModelAndView transformPdf(@RequestBody @Nullable final String content) throws IOException {
final Map<String, Object> values = new HashMap<String, Object>();
if (content == null || content.length() == 0) {
throw new IllegalArgumentException("Body can not be null.");
}
values.put("content", content);
return new ModelAndView("transformViewPdf", values);
}
@RequestMapping(method = RequestMethod.POST, value = "/transform", produces = {"image/png"}, consumes = {"image/svg+xml"})
@ResponseBody
public ModelAndView transformPng(@RequestBody @Nullable final String content) throws IOException {
final Map<String, Object> values = new HashMap<String, Object>();
if (content == null || content.length() == 0) {
throw new IllegalArgumentException("Body can not be null.");
}
values.put("content", content);
values.put("imageSize", ExportProperties.ImageProperties.Size.LARGE);
return new ModelAndView("transformViewPng", values);
}
@RequestMapping(method = RequestMethod.POST, value = "/transform", produces = {"image/jpeg"}, consumes = {"image/svg+xml"})
@ResponseBody
public ModelAndView transformJpeg(@RequestBody @Nullable final String content) throws IOException {
final Map<String, Object> values = new HashMap<String, Object>();
if (content == null || content.length() == 0) {
throw new IllegalArgumentException("Body can not be null.");
}
values.put("content", content);
values.put("imageSize", ExportProperties.ImageProperties.Size.LARGE);
return new ModelAndView("transformViewJpg", values);
}
@RequestMapping(method = RequestMethod.POST, value = "/transform", produces = {"application/freemind"}, consumes = {"text/xml"})
@ResponseBody
public ModelAndView transformFreemind(@RequestBody @Nullable final String content) throws IOException {
final Map<String, Object> values = new HashMap<String, Object>();
if (content == null || content.length() == 0) {
throw new IllegalArgumentException("Body can not be null.");
}
values.put("content", content);
return new ModelAndView("transformViewFreemind", values);
}
}

View File

@ -0,0 +1,123 @@
package com.wisemapping.rest.model;
import com.wisemapping.model.MindMap;
import com.wisemapping.model.User;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.jetbrains.annotations.NotNull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
@XmlRootElement(name = "map")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class RestMindMap {
@JsonIgnore
private MindMap mindmap;
public RestMindMap() {
this(null);
}
public RestMindMap(@NotNull MindMap mindmap) {
this.mindmap = mindmap;
}
public String getOwner() {
return mindmap.getOwner().getUsername();
}
public Calendar getCreationTime() {
return mindmap.getCreationTime();
}
public String getDescription() {
return mindmap.getDescription();
}
public String getTags() {
return mindmap.getTags();
}
public String getTitle() {
return mindmap.getTitle();
}
public int getId() {
return mindmap.getId();
}
public String getCreator() {
return mindmap.getCreator();
}
public String getLastModifierUser() {
return mindmap.getLastModifierUser();
}
public Date getLastModificationDate() {
return mindmap.getLastModificationDate();
}
public boolean isPublic() {
return mindmap.isPublic();
}
public String getXml() throws IOException {
return mindmap.getNativeXml();
}
public void setXml(String xml) throws IOException {
mindmap.setNativeXml(xml);
}
public void setId(int id) {
mindmap.setId(id);
}
public void setTitle(String title) {
mindmap.setTitle(title);
}
public void setTags(String tags) {
mindmap.setTags(tags);
}
public void setDescription(String description) {
mindmap.setDescription(description);
}
public void setOwner(User owner) {
mindmap.setOwner(owner);
}
public void setCreator(String creatorUser) {
mindmap.setCreator(creatorUser);
}
public void setProperties(String properties) {
mindmap.setProperties(properties);
}
public void setLastModificationTime(Calendar lastModificationTime) {
mindmap.setLastModificationTime(lastModificationTime);
}
public void setLastModifierUser(String lastModifierUser) {
mindmap.setLastModifierUser(lastModifierUser);
}
@JsonIgnore
public MindMap getDelegated() {
return this.mindmap;
}
}

View File

@ -0,0 +1,88 @@
package com.wisemapping.rest.view;
import com.wisemapping.exporter.ExportFormat;
import com.wisemapping.exporter.ExportProperties;
import com.wisemapping.exporter.ExporterFactory;
import org.jetbrains.annotations.NotNull;
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 java.io.ByteArrayOutputStream;
import java.util.Map;
public class TransformView extends AbstractView {
private String contentType;
private ExportFormat exportFormat;
public TransformView(@NotNull final String contentType) {
this.contentType = contentType;
this.exportFormat = ExportFormat.fromContentType(contentType);
}
@Override
protected void renderMergedOutputModel(@NotNull Map<String, Object> viewMap, @NotNull HttpServletRequest request, @NotNull final HttpServletResponse response) throws Exception {
final String content = (String) viewMap.get("content");
// Build format properties ...
final ExportProperties properties = ExportProperties.create(exportFormat);
if (properties instanceof ExportProperties.ImageProperties) {
final String sizeStr = request.getParameter(IMG_SIZE_PARAMETER);
final ExportProperties.ImageProperties imageProperties = (ExportProperties.ImageProperties) properties;
if (sizeStr != null) {
final ExportProperties.ImageProperties.Size size = ExportProperties.ImageProperties.Size.valueOf(sizeStr);
imageProperties.setSize(size);
} else {
imageProperties.setSize(ExportProperties.ImageProperties.Size.LARGE);
}
}
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
// Change image link URL.
setBaseBaseImgUrl(exportFormat, properties);
if (exportFormat == ExportFormat.FREEMIND) {
ExporterFactory.export(properties, content, bos, null);
} else {
ExporterFactory.export(properties, null, bos, content);
}
// Set format content type...
final String contentType = exportFormat.getContentType();
response.setContentType(contentType);
// Set file name...
final String fileName = "map" + "." + exportFormat.getFileExtension();
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// Write content ...
final ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(bos.toByteArray());
}
@Override
public String getContentType() {
return contentType;
}
private void setBaseBaseImgUrl(@NotNull ExportFormat format, @NotNull ExportProperties properties) {
final String baseUrl;
if (format == ExportFormat.SVG) {
baseUrl = "http://www.wisemapping.com/images";
} else {
final ServletContext servletContext = this.getServletContext();
baseUrl = "file://" + servletContext.getRealPath("/icons/") + "/";
}
properties.setBaseImagePath(baseUrl);
}
private static final String IMG_SIZE_PARAMETER = "imgSize";
}

View File

@ -28,21 +28,22 @@
</property> </property>
</bean> </bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="defaultContentType" value="application/json"/> <property name="defaultContentType" value="application/json"/>
<property name="favorPathExtension" value="true"/> <property name="favorPathExtension" value="true"/>
<property name="mediaTypes"> <property name="mediaTypes">
<map> <map>
<entry key="xml" value="application/xml"/> <entry key="xml" value="text/xml"/>
<entry key="html" value="text/html"/> <entry key="html" value="text/html"/>
<entry key="json" value="application/json"/> <entry key="json" value="application/json"/>
<entry key="pdf" value="application/pdf"/> <entry key="pdf" value="application/pdf"/>
<entry key="png" value="application/pdf"/> <entry key="png" value="application/png"/>
</map> </map>
</property> </property>
<property name="viewResolvers"> <property name="viewResolvers">
<list> <list>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp-rest/"/> <property name="prefix" value="/WEB-INF/jsp-rest/"/>
<property name="suffix" value=".jsp"/> <property name="suffix" value=".jsp"/>
@ -59,4 +60,21 @@
</property> </property>
</bean> </bean>
<bean id="transformViewPdf" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="application/pdf"/>
</bean>
<bean id="transformViewPng" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="image/png"/>
</bean>
<bean id="transformViewJpeg" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="image/jpeg"/>
</bean>
<bean id="transformViewFreemind" class="com.wisemapping.rest.view.TransformView">
<constructor-arg value="application/freemind"/>
</bean>
</beans> </beans>