001/* 002 * (C) Copyright 2006-2018 Nuxeo (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nuxeo - initial API and implementation 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.ecm.platform.preview.adapter; 023 024import java.io.IOException; 025import java.io.UnsupportedEncodingException; 026import java.util.ArrayList; 027import java.util.List; 028 029import org.apache.commons.lang3.StringUtils; 030import org.nuxeo.ecm.core.api.Blob; 031import org.nuxeo.ecm.core.api.Blobs; 032import org.nuxeo.ecm.core.api.DocumentModel; 033import org.nuxeo.ecm.platform.preview.api.PreviewException; 034import org.nuxeo.ecm.platform.preview.helper.PreviewHelper; 035 036import com.ibm.icu.text.CharsetDetector; 037 038public class PlainTextPreviewer extends AbstractPreviewer implements MimeTypePreviewer { 039 040 public String htmlContent(String content) { 041 // & and < are the only two that we really need to escape 042 // then we also make newlines visible 043 String escaped = StringUtils.replaceEach(content, // 044 new String[] { "&", "<", "\n" }, // 045 new String[] { "&", "<", "<br/>" }); 046 return "<pre>" + escaped + "</pre>"; 047 } 048 049 @Override 050 public List<Blob> getPreview(Blob blob, DocumentModel dm) throws PreviewException { 051 List<Blob> blobResults = new ArrayList<>(); 052 053 byte[] data; 054 try { 055 data = blob.getByteArray(); 056 } catch (IOException e) { 057 throw new PreviewException("Cannot fetch blob content", e); 058 } 059 String encoding = blob.getEncoding(); 060 if (StringUtils.isEmpty(encoding)) { 061 CharsetDetector detector = new CharsetDetector(); 062 detector.setText(data); 063 encoding = detector.detect().getName(); 064 } 065 066 String content; 067 try { 068 content = new String(data, encoding); 069 } catch (UnsupportedEncodingException e) { 070 throw new PreviewException("Cannot encode blob content to string", e); 071 } 072 073 String html = PreviewHelper.makeHtmlPage(htmlContent(content)); 074 Blob mainBlob = Blobs.createBlob(html, "text/html", "UTF-8", "index.html"); 075 076 blobResults.add(mainBlob); 077 return blobResults; 078 } 079 080}