001/* 002 * Copyright 2019 Anyware Services 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 */ 016package org.ametys.cms.data; 017 018import java.io.IOException; 019import java.io.InputStream; 020 021import org.apache.avalon.framework.component.Component; 022import org.apache.avalon.framework.service.ServiceException; 023import org.apache.avalon.framework.service.ServiceManager; 024import org.apache.avalon.framework.service.Serviceable; 025import org.apache.excalibur.xml.sax.SAXParser; 026import org.xml.sax.InputSource; 027import org.xml.sax.SAXException; 028 029import org.ametys.cms.content.RichTextHandler; 030import org.ametys.runtime.plugin.component.AbstractLogEnabled; 031 032/** 033 * Rich-text helper 034 */ 035public class RichTextHelper extends AbstractLogEnabled implements Serviceable, Component 036{ 037 /** The Avalon role */ 038 public static final String ROLE = RichTextHelper.class.getName(); 039 040 /** The service manager */ 041 protected ServiceManager _manager; 042 043 public void service(ServiceManager manager) throws ServiceException 044 { 045 _manager = manager; 046 } 047 048 /** 049 * Transform the rich text to string 050 * @param richText the rich-text to transform 051 * @return the transformed rich-text 052 */ 053 public String richTextToString(RichText richText) 054 { 055 return richTextToString(richText, 0); 056 } 057 058 /** 059 * Transform the rich text to string 060 * @param richText the rich-text to transform 061 * @param maxSize the max size of the rich-text. 0 if no max size 062 * @return the transformed rich-text 063 */ 064 public String richTextToString(RichText richText, int maxSize) 065 { 066 SAXParser saxParser = null; 067 try (InputStream inputStream = richText.getInputStream()) 068 { 069 RichTextHandler txtHandler = new RichTextHandler(maxSize); 070 saxParser = (SAXParser) _manager.lookup(SAXParser.ROLE); 071 saxParser.parse(new InputSource(inputStream), txtHandler); 072 return txtHandler.getValue().trim(); 073 } 074 catch (ServiceException e) 075 { 076 getLogger().error("Unable to get a SAX parser", e); 077 return null; 078 } 079 catch (IOException | SAXException e) 080 { 081 getLogger().error("Cannot parse inputstream", e); 082 return null; 083 } 084 finally 085 { 086 _manager.release(saxParser); 087 } 088 } 089}