001/* 002 * (C) Copyright 2006-2015 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Nuxeo - initial API and implementation 016 * 017 * $Id$ 018 */ 019 020package org.nuxeo.ecm.platform.preview.adapter; 021 022import java.io.IOException; 023import java.io.UnsupportedEncodingException; 024import java.util.ArrayList; 025import java.util.List; 026 027import org.apache.commons.lang.StringUtils; 028import org.nuxeo.ecm.core.api.Blob; 029import org.nuxeo.ecm.core.api.Blobs; 030import org.nuxeo.ecm.core.api.DocumentModel; 031import org.nuxeo.ecm.platform.preview.api.PreviewException; 032 033import com.ibm.icu.text.CharsetDetector; 034 035public class PlainTextPreviewer extends AbstractPreviewer implements MimeTypePreviewer { 036 037 public String htmlContent(String content) { 038 // & and < are the only two that we really need to escape 039 // then we also make newlines visible 040 String escaped = StringUtils.replaceEach(content, // 041 new String[] { "&", "<", "\n" }, // 042 new String[] { "&", "<", "<br/>" }); 043 return "<pre>" + escaped + "</pre>"; 044 } 045 046 @Override 047 public List<Blob> getPreview(Blob blob, DocumentModel dm) throws PreviewException { 048 List<Blob> blobResults = new ArrayList<Blob>(); 049 050 StringBuilder htmlPage = new StringBuilder(); 051 052 byte[] data; 053 try { 054 data = blob.getByteArray(); 055 } catch (IOException e) { 056 throw new PreviewException("Cannot fetch blob content", e); 057 } 058 String encoding = blob.getEncoding(); 059 if (StringUtils.isEmpty(encoding)) { 060 CharsetDetector detector = new CharsetDetector(); 061 detector.setText(data); 062 encoding = detector.detect().getName(); 063 } 064 065 String content = null; 066 try { 067 content = new String(data, encoding); 068 } catch (UnsupportedEncodingException e) { 069 throw new PreviewException("Cannot encode blob content to string", e); 070 } 071 072 htmlPage.append("<?xml version=\"1.0\" encoding=\"UTF-8\"/>"); 073 htmlPage.append("<html>"); 074 htmlPage.append("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/></head>"); 075 htmlPage.append("<body>"); 076 htmlPage.append(htmlContent(content)); 077 htmlPage.append("</body></html>"); 078 079 Blob mainBlob = Blobs.createBlob(htmlPage.toString(), "text/html", "UTF-8", "index.html"); 080 081 blobResults.add(mainBlob); 082 return blobResults; 083 } 084 085}