mirror of
https://bitbucket.org/wisemapping/wisemapping-open-source.git
synced 2024-11-22 06:07:57 +01:00
- REST PDF/PNG/Freemind transform working...
This commit is contained in:
parent
a786c0de09
commit
6edb3d46a5
@ -1,214 +1,214 @@
|
||||
/*
|
||||
* Copyright [2011] [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.controller;
|
||||
|
||||
import com.wisemapping.exporter.ExportException;
|
||||
import com.wisemapping.exporter.ExportFormat;
|
||||
import com.wisemapping.exporter.ExporterFactory;
|
||||
import com.wisemapping.model.MindMap;
|
||||
import com.wisemapping.service.MindmapService;
|
||||
import com.wisemapping.view.MindMapBean;
|
||||
import com.wisemapping.exporter.ExportProperties;
|
||||
import com.wisemapping.filter.UserAgent;
|
||||
import org.apache.batik.transcoder.TranscoderException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
|
||||
import org.xml.sax.SAXException;
|
||||
import sun.misc.BASE64Encoder;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public class ExportController extends BaseMultiActionController {
|
||||
private static final String IMG_EXPORT_FORMAT = "IMG_EXPORT_FORMAT";
|
||||
private static final String MAP_ID_PARAMETER = "mapId";
|
||||
private static final String MAP_SVG_PARAMETER = "mapSvg";
|
||||
private static final String EXPORT_FORMAT_PARAMETER = "exportFormat";
|
||||
private static final String IMG_SIZE_PARAMETER = "imgSize";
|
||||
private static final String MAP_XML_PARAM = "mapXml";
|
||||
|
||||
|
||||
public ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException noSuchRequestHandlingMethodException, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
|
||||
logger.info("Mindmap Controller: EXPORT action");
|
||||
final MindMap mindmap = getMindmapFromRequest(httpServletRequest);
|
||||
return new ModelAndView("mindmapExport", "mindmap", new MindMapBean(mindmap));
|
||||
}
|
||||
|
||||
public ModelAndView export(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException {
|
||||
logger.info("Export Controller: exporting WiseMap action");
|
||||
|
||||
final String mapIdStr = request.getParameter(MAP_ID_PARAMETER);
|
||||
if (mapIdStr != null) {
|
||||
final String mapSvg = request.getParameter(MAP_SVG_PARAMETER);
|
||||
try {
|
||||
|
||||
int mindmapId = Integer.parseInt(mapIdStr);
|
||||
|
||||
logger.debug("SVG Map to export:" + mapSvg);
|
||||
if (mapSvg == null || mapSvg.isEmpty()) {
|
||||
throw new IllegalArgumentException("SVG map could not be null");
|
||||
}
|
||||
|
||||
String formatStr = request.getParameter(EXPORT_FORMAT_PARAMETER);
|
||||
if (IMG_EXPORT_FORMAT.endsWith(formatStr)) {
|
||||
formatStr = request.getParameter("imgFormat");
|
||||
}
|
||||
|
||||
final MindmapService service = getMindmapService();
|
||||
final MindMap mindMap = service.getMindmapById(mindmapId);
|
||||
|
||||
// Build format properties ...
|
||||
final ExportFormat format = ExportFormat.valueOf(formatStr);
|
||||
final ExportProperties properties = ExportProperties.create(format);
|
||||
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(format, properties);
|
||||
ExporterFactory.export(properties, mindMap, bos, mapSvg);
|
||||
|
||||
// If the export goes ok, write the map to the stream ...
|
||||
|
||||
// Set format content type...
|
||||
final String contentType = format.getContentType();
|
||||
response.setContentType(contentType);
|
||||
|
||||
// Set file name...
|
||||
final String fileName = mindMap.getTitle() + "." + format.getFileExtension();
|
||||
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
|
||||
|
||||
// Write content ...
|
||||
final ServletOutputStream outputStream = response.getOutputStream();
|
||||
outputStream.write(bos.toByteArray());
|
||||
|
||||
|
||||
} catch (Throwable e) {
|
||||
logger.error("Unexpexted error during export process", e);
|
||||
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
|
||||
logger.error("map: " + mapSvg);
|
||||
}
|
||||
} else {
|
||||
logger.warn("mapIdStr is null.Image could not be imported. UserAgent:" + request.getHeaders(UserAgent.USER_AGENT_HEADER));
|
||||
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public ModelAndView print(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException {
|
||||
logger.info("Export Controller: printing WiseMap action");
|
||||
|
||||
final String mapIdStr = request.getParameter(MAP_ID_PARAMETER);
|
||||
int mindmapId = Integer.parseInt(mapIdStr);
|
||||
final MindmapService service = getMindmapService();
|
||||
final MindMap mindmap = service.getMindmapById(mindmapId);
|
||||
final String mapSvg = request.getParameter(MAP_SVG_PARAMETER);
|
||||
|
||||
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try {
|
||||
exportImage(response, mapSvg, bos, false);
|
||||
} catch (Throwable e) {
|
||||
logger.error("Unexpexted error generating the image", e);
|
||||
logger.error("map: " + mapSvg);
|
||||
}
|
||||
|
||||
BASE64Encoder encoder = new BASE64Encoder();
|
||||
String content = encoder.encode(bos.toByteArray());
|
||||
final String exportContent = "data:image/png;base64," + content;
|
||||
bos.close();
|
||||
|
||||
ModelAndView view = new ModelAndView("mindmapPrint", "mindmap", new MindMapBean(mindmap));
|
||||
final String xmlMap = mindmap.getNativeXmlAsJsLiteral();
|
||||
view.addObject(MAP_XML_PARAM, xmlMap);
|
||||
view.addObject(MAP_SVG_PARAMETER, exportContent);
|
||||
|
||||
return view;
|
||||
|
||||
}
|
||||
|
||||
public ModelAndView image(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException {
|
||||
logger.info("Export Controller: generating image WiseMap action");
|
||||
|
||||
final String mapIdStr = request.getParameter(MAP_ID_PARAMETER);
|
||||
final String mapSvg = request.getParameter(MAP_SVG_PARAMETER);
|
||||
try {
|
||||
final ServletOutputStream outputStream = response.getOutputStream();
|
||||
|
||||
exportImage(response, mapSvg, outputStream, true);
|
||||
|
||||
|
||||
} catch (Throwable e) {
|
||||
logger.error("Unexpexted error generating the image", e);
|
||||
logger.error("map: " + mapSvg);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void exportImage(HttpServletResponse response, String mapSvg, OutputStream outputStream, boolean setOutput) throws TranscoderException, IOException, ParserConfigurationException, SAXException, XMLStreamException, TransformerException, JAXBException, ExportException {
|
||||
|
||||
//Image Format
|
||||
ExportFormat imageFormat = ExportFormat.PNG;
|
||||
|
||||
// Build format properties ...
|
||||
final ExportProperties.ImageProperties imageProperties = new ExportProperties.ImageProperties(imageFormat);
|
||||
imageProperties.setSize(ExportProperties.ImageProperties.Size.XMEDIUM);
|
||||
|
||||
// Change image link URL.
|
||||
setBaseBaseImgUrl(imageFormat, imageProperties);
|
||||
|
||||
// Set format content type...
|
||||
if (setOutput)
|
||||
response.setContentType(imageFormat.getContentType());
|
||||
|
||||
// Write content ...
|
||||
ExporterFactory.export(imageProperties, null, outputStream, mapSvg);
|
||||
}
|
||||
/*
|
||||
* Copyright [2011] [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.controller;
|
||||
|
||||
import com.wisemapping.exporter.ExportException;
|
||||
import com.wisemapping.exporter.ExportFormat;
|
||||
import com.wisemapping.exporter.ExporterFactory;
|
||||
import com.wisemapping.model.MindMap;
|
||||
import com.wisemapping.service.MindmapService;
|
||||
import com.wisemapping.view.MindMapBean;
|
||||
import com.wisemapping.exporter.ExportProperties;
|
||||
import com.wisemapping.filter.UserAgent;
|
||||
import org.apache.batik.transcoder.TranscoderException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
|
||||
import org.xml.sax.SAXException;
|
||||
import sun.misc.BASE64Encoder;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public class ExportController extends BaseMultiActionController {
|
||||
private static final String IMG_EXPORT_FORMAT = "IMG_EXPORT_FORMAT";
|
||||
private static final String MAP_ID_PARAMETER = "mapId";
|
||||
private static final String MAP_SVG_PARAMETER = "mapSvg";
|
||||
private static final String EXPORT_FORMAT_PARAMETER = "exportFormat";
|
||||
private static final String IMG_SIZE_PARAMETER = "imgSize";
|
||||
private static final String MAP_XML_PARAM = "mapXml";
|
||||
|
||||
|
||||
public ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException noSuchRequestHandlingMethodException, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
|
||||
logger.info("Mindmap Controller: EXPORT action");
|
||||
final MindMap mindmap = getMindmapFromRequest(httpServletRequest);
|
||||
return new ModelAndView("mindmapExport", "mindmap", new MindMapBean(mindmap));
|
||||
}
|
||||
|
||||
public ModelAndView export(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException {
|
||||
logger.info("Export Controller: exporting WiseMap action");
|
||||
|
||||
final String mapIdStr = request.getParameter(MAP_ID_PARAMETER);
|
||||
if (mapIdStr != null) {
|
||||
final String mapSvg = request.getParameter(MAP_SVG_PARAMETER);
|
||||
try {
|
||||
|
||||
int mindmapId = Integer.parseInt(mapIdStr);
|
||||
|
||||
logger.debug("SVG Map to export:" + mapSvg);
|
||||
if (mapSvg == null || mapSvg.isEmpty()) {
|
||||
throw new IllegalArgumentException("SVG map could not be null");
|
||||
}
|
||||
|
||||
String formatStr = request.getParameter(EXPORT_FORMAT_PARAMETER);
|
||||
if (IMG_EXPORT_FORMAT.endsWith(formatStr)) {
|
||||
formatStr = request.getParameter("imgFormat");
|
||||
}
|
||||
|
||||
final MindmapService service = getMindmapService();
|
||||
final MindMap mindMap = service.getMindmapById(mindmapId);
|
||||
|
||||
// Build format properties ...
|
||||
final ExportFormat format = ExportFormat.valueOf(formatStr);
|
||||
final ExportProperties properties = ExportProperties.create(format);
|
||||
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(format, properties);
|
||||
ExporterFactory.export(properties, mindMap.getUnzippedXml(), bos, mapSvg);
|
||||
|
||||
// If the export goes ok, write the map to the stream ...
|
||||
|
||||
// Set format content type...
|
||||
final String contentType = format.getContentType();
|
||||
response.setContentType(contentType);
|
||||
|
||||
// Set file name...
|
||||
final String fileName = mindMap.getTitle() + "." + format.getFileExtension();
|
||||
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
|
||||
|
||||
// Write content ...
|
||||
final ServletOutputStream outputStream = response.getOutputStream();
|
||||
outputStream.write(bos.toByteArray());
|
||||
|
||||
|
||||
} catch (Throwable e) {
|
||||
logger.error("Unexpexted error during export process", e);
|
||||
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
|
||||
logger.error("map: " + mapSvg);
|
||||
}
|
||||
} else {
|
||||
logger.warn("mapIdStr is null.Image could not be imported. UserAgent:" + request.getHeaders(UserAgent.USER_AGENT_HEADER));
|
||||
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public ModelAndView print(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException {
|
||||
logger.info("Export Controller: printing WiseMap action");
|
||||
|
||||
final String mapIdStr = request.getParameter(MAP_ID_PARAMETER);
|
||||
int mindmapId = Integer.parseInt(mapIdStr);
|
||||
final MindmapService service = getMindmapService();
|
||||
final MindMap mindmap = service.getMindmapById(mindmapId);
|
||||
final String mapSvg = request.getParameter(MAP_SVG_PARAMETER);
|
||||
|
||||
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try {
|
||||
exportImage(response, mapSvg, bos, false);
|
||||
} catch (Throwable e) {
|
||||
logger.error("Unexpexted error generating the image", e);
|
||||
logger.error("map: " + mapSvg);
|
||||
}
|
||||
|
||||
BASE64Encoder encoder = new BASE64Encoder();
|
||||
String content = encoder.encode(bos.toByteArray());
|
||||
final String exportContent = "data:image/png;base64," + content;
|
||||
bos.close();
|
||||
|
||||
ModelAndView view = new ModelAndView("mindmapPrint", "mindmap", new MindMapBean(mindmap));
|
||||
final String xmlMap = mindmap.getNativeXmlAsJsLiteral();
|
||||
view.addObject(MAP_XML_PARAM, xmlMap);
|
||||
view.addObject(MAP_SVG_PARAMETER, exportContent);
|
||||
|
||||
return view;
|
||||
|
||||
}
|
||||
|
||||
public ModelAndView image(HttpServletRequest request, HttpServletResponse response) throws TranscoderException, IOException, JAXBException {
|
||||
logger.info("Export Controller: generating image WiseMap action");
|
||||
|
||||
final String mapIdStr = request.getParameter(MAP_ID_PARAMETER);
|
||||
final String mapSvg = request.getParameter(MAP_SVG_PARAMETER);
|
||||
try {
|
||||
final ServletOutputStream outputStream = response.getOutputStream();
|
||||
|
||||
exportImage(response, mapSvg, outputStream, true);
|
||||
|
||||
|
||||
} catch (Throwable e) {
|
||||
logger.error("Unexpexted error generating the image", e);
|
||||
logger.error("map: " + mapSvg);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void exportImage(HttpServletResponse response, String mapSvg, OutputStream outputStream, boolean setOutput) throws TranscoderException, IOException, ParserConfigurationException, SAXException, XMLStreamException, TransformerException, JAXBException, ExportException {
|
||||
|
||||
//Image Format
|
||||
ExportFormat imageFormat = ExportFormat.PNG;
|
||||
|
||||
// Build format properties ...
|
||||
final ExportProperties.ImageProperties imageProperties = new ExportProperties.ImageProperties(imageFormat);
|
||||
imageProperties.setSize(ExportProperties.ImageProperties.Size.XMEDIUM);
|
||||
|
||||
// Change image link URL.
|
||||
setBaseBaseImgUrl(imageFormat, imageProperties);
|
||||
|
||||
// Set format content type...
|
||||
if (setOutput)
|
||||
response.setContentType(imageFormat.getContentType());
|
||||
|
||||
// Write content ...
|
||||
ExporterFactory.export(imageProperties, null, outputStream, mapSvg);
|
||||
}
|
||||
}
|
@ -1,44 +1,55 @@
|
||||
/*
|
||||
* Copyright [2011] [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 enum ExportFormat {
|
||||
SVG("image/svg+xml", "svg"),
|
||||
JPEG("image/jpeg", "jpg"),
|
||||
PNG("image/png", "png"),
|
||||
MINDJET("text/xml", "xml"),
|
||||
PDF("application/pdf", "pdf"),
|
||||
FREEMIND("text/xml", "mm");
|
||||
|
||||
private String contentType;
|
||||
private String fileExtension;
|
||||
|
||||
ExportFormat(String contentType, String fileExtension) {
|
||||
this.contentType = contentType;
|
||||
this.fileExtension = fileExtension;
|
||||
}
|
||||
|
||||
public String getFileExtension() {
|
||||
return fileExtension;
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright [2011] [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 {
|
||||
SVG("image/svg+xml", "svg"),
|
||||
JPEG("image/jpeg", "jpg"),
|
||||
PNG("image/png", "png"),
|
||||
PDF("application/pdf", "pdf"),
|
||||
FREEMIND("application/freemind", "mm");
|
||||
|
||||
private String contentType;
|
||||
private 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);
|
||||
}
|
||||
}
|
||||
|
@ -1,304 +1,304 @@
|
||||
/*
|
||||
* Copyright [2011] [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.model.MindMap;
|
||||
import org.apache.batik.transcoder.Transcoder;
|
||||
import org.apache.batik.transcoder.TranscoderException;
|
||||
import org.apache.batik.transcoder.TranscoderInput;
|
||||
import org.apache.batik.transcoder.TranscoderOutput;
|
||||
import org.apache.batik.transcoder.image.ImageTranscoder;
|
||||
import org.apache.batik.transcoder.image.JPEGTranscoder;
|
||||
import org.apache.batik.transcoder.image.PNGTranscoder;
|
||||
import org.apache.fop.svg.PDFTranscoder;
|
||||
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.xml.bind.JAXBException;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
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 java.io.*;
|
||||
|
||||
public class ExporterFactory {
|
||||
private static final String GROUP_NODE_NAME = "g";
|
||||
private static final String RECT_NODE_NAME = "rect";
|
||||
private static final String IMAGE_NODE_NAME = "image";
|
||||
|
||||
|
||||
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 {
|
||||
final ExportFormat format = properties.getFormat();
|
||||
|
||||
final String imgPath = properties.getBaseImgPath();
|
||||
switch (format) {
|
||||
case PNG: {
|
||||
// Create a JPEG transcoder
|
||||
final Transcoder transcoder = new PNGTranscoder();
|
||||
final ExportProperties.ImageProperties imageProperties =
|
||||
(ExportProperties.ImageProperties) properties;
|
||||
final ExportProperties.ImageProperties.Size size = imageProperties.getSize();
|
||||
transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, size.getWidth());
|
||||
|
||||
// Create the transcoder input.
|
||||
final Document document = normalizeSvg(mapSvg, imgPath);
|
||||
final String svgString = domToString(document);
|
||||
final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray()));
|
||||
|
||||
TranscoderOutput trascoderOutput = new TranscoderOutput(output);
|
||||
|
||||
// Save the image.
|
||||
transcoder.transcode(input, trascoderOutput);
|
||||
break;
|
||||
}
|
||||
case JPEG: {
|
||||
// Create a JPEG transcoder
|
||||
final Transcoder transcoder = new JPEGTranscoder();
|
||||
transcoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.99));
|
||||
|
||||
final ExportProperties.ImageProperties imageProperties =
|
||||
(ExportProperties.ImageProperties) properties;
|
||||
final ExportProperties.ImageProperties.Size size = imageProperties.getSize();
|
||||
transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, size.getWidth());
|
||||
|
||||
// Create the transcoder input.
|
||||
final Document document = normalizeSvg(mapSvg, imgPath);
|
||||
final String svgString = domToString(document);
|
||||
final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray()));
|
||||
|
||||
TranscoderOutput trascoderOutput = new TranscoderOutput(output);
|
||||
|
||||
// Save the image.
|
||||
transcoder.transcode(input, trascoderOutput);
|
||||
break;
|
||||
}
|
||||
case PDF: {
|
||||
// Create a JPEG transcoder
|
||||
final Transcoder transcoder = new PDFTranscoder();
|
||||
|
||||
// Create the transcoder input.
|
||||
final Document document = normalizeSvg(mapSvg, imgPath);
|
||||
final String svgString = domToString(document);
|
||||
final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray()));
|
||||
|
||||
TranscoderOutput trascoderOutput = new TranscoderOutput(output);
|
||||
|
||||
// Save the image.
|
||||
transcoder.transcode(input, trascoderOutput);
|
||||
break;
|
||||
}
|
||||
case SVG: {
|
||||
final Document dom = normalizeSvg(mapSvg, imgPath);
|
||||
output.write(domToString(dom).getBytes("UTF-8"));
|
||||
break;
|
||||
}
|
||||
case FREEMIND: {
|
||||
final FreemindExporter exporter = new FreemindExporter();
|
||||
exporter.export(map.getUnzippedXml().getBytes(), output);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new UnsupportedOperationException("Export method not supported.");
|
||||
}
|
||||
}
|
||||
|
||||
private static Document normalizeSvg(@NotNull String svgXml, final String imgBaseUrl) throws XMLStreamException, ParserConfigurationException, IOException, SAXException, TransformerException {
|
||||
|
||||
final DocumentBuilder documentBuilder = getDocumentBuilder();
|
||||
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...
|
||||
svgXml = svgXml.replaceAll("NaN,", "0");
|
||||
svgXml = svgXml.replaceAll(",NaN", "0");
|
||||
|
||||
Document document;
|
||||
try {
|
||||
final Reader in = new CharArrayReader(svgXml.toCharArray());
|
||||
final InputSource is = new InputSource(in);
|
||||
|
||||
document = documentBuilder.parse(is);
|
||||
} catch (SAXException e) {
|
||||
// It must be a corrupted SVG format. Try to hack it and try again ...
|
||||
svgXml = svgXml.replaceAll("<image([^>]+)>", "<image$1/>");
|
||||
|
||||
final Reader in = new CharArrayReader(svgXml.toCharArray());
|
||||
final InputSource is = new InputSource(in);
|
||||
document = documentBuilder.parse(is);
|
||||
}
|
||||
|
||||
|
||||
fitSvg(document);
|
||||
|
||||
fixImageTagHref(document, imgBaseUrl);
|
||||
|
||||
return document;
|
||||
|
||||
}
|
||||
|
||||
private static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
return factory.newDocumentBuilder();
|
||||
}
|
||||
|
||||
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 static void fixImageTagHref(Document document, String imgBaseUrl) {
|
||||
final Node child = document.getFirstChild();
|
||||
fixImageTagHref(document, (Element) child, imgBaseUrl);
|
||||
}
|
||||
|
||||
private static void fixImageTagHref(@NotNull Document document, @NotNull Element element, String imgBaseUrl) {
|
||||
|
||||
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 ....
|
||||
fixImageTagHref(document, (Element) node, imgBaseUrl);
|
||||
|
||||
} else if (IMAGE_NODE_NAME.equals(node.getNodeName())) {
|
||||
|
||||
Element elem = (Element) node;
|
||||
|
||||
// Cook image href ...
|
||||
final String imgUrl = elem.getAttribute("href");
|
||||
int index = imgUrl.lastIndexOf("/");
|
||||
elem.removeAttribute("href");
|
||||
if (index != -1) {
|
||||
final String iconName = imgUrl.substring(index+1);
|
||||
// Hack for backward compatibility . This can be removed in 2012. :)
|
||||
String imgPath;
|
||||
if (imgUrl.contains("images")) {
|
||||
imgPath = imgBaseUrl + "/../icons/legacy/" + iconName;
|
||||
} else {
|
||||
imgPath = imgBaseUrl + "/" + imgUrl;
|
||||
}
|
||||
elem.setAttribute("xlink:href", imgPath);
|
||||
elem.appendChild(document.createTextNode(" "));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void fitSvg(Document document) {
|
||||
// viewBox size
|
||||
int mapWidth = 1024;
|
||||
int mapHeight = 768;
|
||||
// some browser return width and heigth with precision
|
||||
float currentMaxWidth = 0;
|
||||
float currentMaxHeight = 0;
|
||||
|
||||
final Element svgNode = (Element) document.getFirstChild();
|
||||
final NodeList list = svgNode.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())) {
|
||||
final NamedNodeMap groupAttributes = node.getAttributes();
|
||||
|
||||
final String[] transformUnit = getTransformUnit(groupAttributes);
|
||||
|
||||
int groupPositionX = Integer.parseInt(transformUnit[0].trim());
|
||||
int groupPositionY = 0;
|
||||
if (transformUnit.length > 1) {
|
||||
groupPositionY = Integer.parseInt(transformUnit[1].trim());
|
||||
}
|
||||
|
||||
int signumX = Integer.signum(groupPositionX);
|
||||
int signumY = Integer.signum(groupPositionY);
|
||||
|
||||
final NodeList groupChildren = node.getChildNodes();
|
||||
for (int idx = 0; idx < groupChildren.getLength(); idx++) {
|
||||
final Node rectNode = groupChildren.item(idx);
|
||||
float curentHeight = 0;
|
||||
float curentWidth = 0;
|
||||
|
||||
// If has a rect use the rect to calcular the real width of the topic
|
||||
if (RECT_NODE_NAME.equals(rectNode.getNodeName())) {
|
||||
final NamedNodeMap rectAttributes = rectNode.getAttributes();
|
||||
|
||||
final Node attributeHeight = rectAttributes.getNamedItem("height");
|
||||
final Node attributeWidth = rectAttributes.getNamedItem("width");
|
||||
|
||||
curentHeight = Float.valueOf(attributeHeight.getNodeValue());
|
||||
curentWidth = Float.valueOf(attributeWidth.getNodeValue());
|
||||
}
|
||||
|
||||
float newMaxWidth = groupPositionX + (curentWidth * signumX);
|
||||
if (Math.abs(currentMaxWidth) < Math.abs(newMaxWidth)) {
|
||||
currentMaxWidth = newMaxWidth;
|
||||
}
|
||||
|
||||
float newMaxHeight = groupPositionY + curentHeight * signumY;
|
||||
if (Math.abs(currentMaxHeight) < Math.abs(newMaxHeight)) {
|
||||
currentMaxHeight = newMaxHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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("height", Float.toString(mapHeight / 2));
|
||||
svgNode.setAttribute("preserveAspectRatio", "xMinYMin");
|
||||
}
|
||||
|
||||
private static String[] getTransformUnit(NamedNodeMap groupAttributes) {
|
||||
final String value = groupAttributes.getNamedItem("transform").getNodeValue();
|
||||
final int pos = value.indexOf("translate");
|
||||
final int initTranslate = value.indexOf("(", pos);
|
||||
final int endTranslate = value.indexOf(")", pos);
|
||||
final String transate = value.substring(initTranslate + 1, endTranslate);
|
||||
return transate.split(",");
|
||||
}
|
||||
|
||||
}
|
||||
/*
|
||||
* Copyright [2011] [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.model.MindMap;
|
||||
import org.apache.batik.transcoder.Transcoder;
|
||||
import org.apache.batik.transcoder.TranscoderException;
|
||||
import org.apache.batik.transcoder.TranscoderInput;
|
||||
import org.apache.batik.transcoder.TranscoderOutput;
|
||||
import org.apache.batik.transcoder.image.ImageTranscoder;
|
||||
import org.apache.batik.transcoder.image.JPEGTranscoder;
|
||||
import org.apache.batik.transcoder.image.PNGTranscoder;
|
||||
import org.apache.fop.svg.PDFTranscoder;
|
||||
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.xml.bind.JAXBException;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
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 java.io.*;
|
||||
|
||||
public class ExporterFactory {
|
||||
private static final String GROUP_NODE_NAME = "g";
|
||||
private static final String RECT_NODE_NAME = "rect";
|
||||
private static final String IMAGE_NODE_NAME = "image";
|
||||
|
||||
|
||||
private ExporterFactory() throws ParserConfigurationException {
|
||||
|
||||
}
|
||||
|
||||
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 String imgPath = properties.getBaseImgPath();
|
||||
switch (format) {
|
||||
case PNG: {
|
||||
// Create a JPEG transcoder
|
||||
final Transcoder transcoder = new PNGTranscoder();
|
||||
final ExportProperties.ImageProperties imageProperties =
|
||||
(ExportProperties.ImageProperties) properties;
|
||||
final ExportProperties.ImageProperties.Size size = imageProperties.getSize();
|
||||
transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, size.getWidth());
|
||||
|
||||
// Create the transcoder input.
|
||||
final Document document = normalizeSvg(mapSvg, imgPath);
|
||||
final String svgString = domToString(document);
|
||||
final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray()));
|
||||
|
||||
TranscoderOutput trascoderOutput = new TranscoderOutput(output);
|
||||
|
||||
// Save the image.
|
||||
transcoder.transcode(input, trascoderOutput);
|
||||
break;
|
||||
}
|
||||
case JPEG: {
|
||||
// Create a JPEG transcoder
|
||||
final Transcoder transcoder = new JPEGTranscoder();
|
||||
transcoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.99));
|
||||
|
||||
final ExportProperties.ImageProperties imageProperties =
|
||||
(ExportProperties.ImageProperties) properties;
|
||||
final ExportProperties.ImageProperties.Size size = imageProperties.getSize();
|
||||
transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, size.getWidth());
|
||||
|
||||
// Create the transcoder input.
|
||||
final Document document = normalizeSvg(mapSvg, imgPath);
|
||||
final String svgString = domToString(document);
|
||||
final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray()));
|
||||
|
||||
TranscoderOutput trascoderOutput = new TranscoderOutput(output);
|
||||
|
||||
// Save the image.
|
||||
transcoder.transcode(input, trascoderOutput);
|
||||
break;
|
||||
}
|
||||
case PDF: {
|
||||
// Create a JPEG transcoder
|
||||
final Transcoder transcoder = new PDFTranscoder();
|
||||
|
||||
// Create the transcoder input.
|
||||
final Document document = normalizeSvg(mapSvg, imgPath);
|
||||
final String svgString = domToString(document);
|
||||
final TranscoderInput input = new TranscoderInput(new CharArrayReader(svgString.toCharArray()));
|
||||
|
||||
TranscoderOutput trascoderOutput = new TranscoderOutput(output);
|
||||
|
||||
// Save the image.
|
||||
transcoder.transcode(input, trascoderOutput);
|
||||
break;
|
||||
}
|
||||
case SVG: {
|
||||
final Document dom = normalizeSvg(mapSvg, imgPath);
|
||||
output.write(domToString(dom).getBytes("UTF-8"));
|
||||
break;
|
||||
}
|
||||
case FREEMIND: {
|
||||
final FreemindExporter exporter = new FreemindExporter();
|
||||
exporter.export(xml.getBytes(), output);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new UnsupportedOperationException("Export method not supported.");
|
||||
}
|
||||
}
|
||||
|
||||
private static Document normalizeSvg(@NotNull String svgXml, final String imgBaseUrl) throws XMLStreamException, ParserConfigurationException, IOException, SAXException, TransformerException {
|
||||
|
||||
final DocumentBuilder documentBuilder = getDocumentBuilder();
|
||||
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...
|
||||
svgXml = svgXml.replaceAll("NaN,", "0");
|
||||
svgXml = svgXml.replaceAll(",NaN", "0");
|
||||
|
||||
Document document;
|
||||
try {
|
||||
final Reader in = new CharArrayReader(svgXml.toCharArray());
|
||||
final InputSource is = new InputSource(in);
|
||||
|
||||
document = documentBuilder.parse(is);
|
||||
} catch (SAXException e) {
|
||||
// It must be a corrupted SVG format. Try to hack it and try again ...
|
||||
svgXml = svgXml.replaceAll("<image([^>]+)>", "<image$1/>");
|
||||
|
||||
final Reader in = new CharArrayReader(svgXml.toCharArray());
|
||||
final InputSource is = new InputSource(in);
|
||||
document = documentBuilder.parse(is);
|
||||
}
|
||||
|
||||
|
||||
fitSvg(document);
|
||||
|
||||
fixImageTagHref(document, imgBaseUrl);
|
||||
|
||||
return document;
|
||||
|
||||
}
|
||||
|
||||
private static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
return factory.newDocumentBuilder();
|
||||
}
|
||||
|
||||
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 static void fixImageTagHref(Document document, String imgBaseUrl) {
|
||||
final Node child = document.getFirstChild();
|
||||
fixImageTagHref(document, (Element) child, imgBaseUrl);
|
||||
}
|
||||
|
||||
private static void fixImageTagHref(@NotNull Document document, @NotNull Element element, String imgBaseUrl) {
|
||||
|
||||
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 ....
|
||||
fixImageTagHref(document, (Element) node, imgBaseUrl);
|
||||
|
||||
} else if (IMAGE_NODE_NAME.equals(node.getNodeName())) {
|
||||
|
||||
Element elem = (Element) node;
|
||||
|
||||
// Cook image href ...
|
||||
final String imgUrl = elem.getAttribute("href");
|
||||
int index = imgUrl.lastIndexOf("/");
|
||||
elem.removeAttribute("href");
|
||||
if (index != -1) {
|
||||
final String iconName = imgUrl.substring(index+1);
|
||||
// Hack for backward compatibility . This can be removed in 2012. :)
|
||||
String imgPath;
|
||||
if (imgUrl.contains("images")) {
|
||||
imgPath = imgBaseUrl + "/../icons/legacy/" + iconName;
|
||||
} else {
|
||||
imgPath = imgBaseUrl + "/" + imgUrl;
|
||||
}
|
||||
elem.setAttribute("xlink:href", imgPath);
|
||||
elem.appendChild(document.createTextNode(" "));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void fitSvg(Document document) {
|
||||
// viewBox size
|
||||
int mapWidth = 1024;
|
||||
int mapHeight = 768;
|
||||
// some browser return width and heigth with precision
|
||||
float currentMaxWidth = 0;
|
||||
float currentMaxHeight = 0;
|
||||
|
||||
final Element svgNode = (Element) document.getFirstChild();
|
||||
final NodeList list = svgNode.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())) {
|
||||
final NamedNodeMap groupAttributes = node.getAttributes();
|
||||
|
||||
final String[] transformUnit = getTransformUnit(groupAttributes);
|
||||
|
||||
int groupPositionX = Integer.parseInt(transformUnit[0].trim());
|
||||
int groupPositionY = 0;
|
||||
if (transformUnit.length > 1) {
|
||||
groupPositionY = Integer.parseInt(transformUnit[1].trim());
|
||||
}
|
||||
|
||||
int signumX = Integer.signum(groupPositionX);
|
||||
int signumY = Integer.signum(groupPositionY);
|
||||
|
||||
final NodeList groupChildren = node.getChildNodes();
|
||||
for (int idx = 0; idx < groupChildren.getLength(); idx++) {
|
||||
final Node rectNode = groupChildren.item(idx);
|
||||
float curentHeight = 0;
|
||||
float curentWidth = 0;
|
||||
|
||||
// If has a rect use the rect to calcular the real width of the topic
|
||||
if (RECT_NODE_NAME.equals(rectNode.getNodeName())) {
|
||||
final NamedNodeMap rectAttributes = rectNode.getAttributes();
|
||||
|
||||
final Node attributeHeight = rectAttributes.getNamedItem("height");
|
||||
final Node attributeWidth = rectAttributes.getNamedItem("width");
|
||||
|
||||
curentHeight = Float.valueOf(attributeHeight.getNodeValue());
|
||||
curentWidth = Float.valueOf(attributeWidth.getNodeValue());
|
||||
}
|
||||
|
||||
float newMaxWidth = groupPositionX + (curentWidth * signumX);
|
||||
if (Math.abs(currentMaxWidth) < Math.abs(newMaxWidth)) {
|
||||
currentMaxWidth = newMaxWidth;
|
||||
}
|
||||
|
||||
float newMaxHeight = groupPositionY + curentHeight * signumY;
|
||||
if (Math.abs(currentMaxHeight) < Math.abs(newMaxHeight)) {
|
||||
currentMaxHeight = newMaxHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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("height", Float.toString(mapHeight / 2));
|
||||
svgNode.setAttribute("preserveAspectRatio", "xMinYMin");
|
||||
}
|
||||
|
||||
private static String[] getTransformUnit(NamedNodeMap groupAttributes) {
|
||||
final String value = groupAttributes.getNamedItem("transform").getNodeValue();
|
||||
final int pos = value.indexOf("translate");
|
||||
final int initTranslate = value.indexOf("(", pos);
|
||||
final int endTranslate = value.indexOf(")", pos);
|
||||
final String transate = value.substring(initTranslate + 1, endTranslate);
|
||||
return transate.split(",");
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -2,8 +2,11 @@ package com.wisemapping.rest;
|
||||
|
||||
|
||||
import com.wisemapping.model.MindMap;
|
||||
import com.wisemapping.model.MindmapUser;
|
||||
import com.wisemapping.model.User;
|
||||
import com.wisemapping.rest.model.RestMindMap;
|
||||
import com.wisemapping.service.MindmapService;
|
||||
import com.wisemapping.validator.Utils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
@ -14,20 +17,30 @@ import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/map")
|
||||
public class MindmapController {
|
||||
@Autowired
|
||||
private MindmapService mindmapService;
|
||||
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/map/{id}")
|
||||
@ResponseBody
|
||||
public ModelAndView getMindmap(@PathVariable int id) throws IOException {
|
||||
final MindMap mindMap = mindmapService.getMindmapById(id);
|
||||
final RestMindMap map = new RestMindMap(mindMap);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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";
|
||||
|
||||
}
|
@ -28,21 +28,22 @@
|
||||
</property>
|
||||
</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="favorPathExtension" value="true"/>
|
||||
<property name="mediaTypes">
|
||||
<map>
|
||||
<entry key="xml" value="application/xml"/>
|
||||
<entry key="xml" value="text/xml"/>
|
||||
<entry key="html" value="text/html"/>
|
||||
<entry key="json" value="application/json"/>
|
||||
<entry key="pdf" value="application/pdf"/>
|
||||
<entry key="png" value="application/pdf"/>
|
||||
<entry key="png" value="application/png"/>
|
||||
</map>
|
||||
</property>
|
||||
<property name="viewResolvers">
|
||||
<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="prefix" value="/WEB-INF/jsp-rest/"/>
|
||||
<property name="suffix" value=".jsp"/>
|
||||
@ -59,4 +60,21 @@
|
||||
</property>
|
||||
</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>
|
Loading…
Reference in New Issue
Block a user