1.1 restoration
[mir.git] / source / mircoders / localizer / basic / MirBasicProducerAssistantLocalizer.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30 package mircoders.localizer.basic;
31
32 import mir.config.MirPropertiesConfiguration;
33 import mir.entity.adapter.EntityAdapter;
34 import mir.entity.adapter.EntityIteratorAdapter;
35 import mir.generator.Generator;
36 import mir.generator.GeneratorExc;
37 import mir.generator.GeneratorFailure;
38 import mir.log.LoggerWrapper;
39 import mir.misc.StringUtil;
40 import mir.util.*;
41 import mir.util.generator.ReflectionGeneratorFunctionsAdapter;
42 import mircoders.global.MirGlobal;
43 import mircoders.localizer.MirLocalizerExc;
44 import mircoders.localizer.MirLocalizerFailure;
45 import mircoders.localizer.MirProducerAssistantLocalizer;
46 import org.w3c.dom.Document;
47 import org.w3c.dom.NamedNodeMap;
48 import org.w3c.dom.Node;
49 import org.w3c.dom.NodeList;
50 import org.w3c.tidy.Tidy;
51 import org.w3c.tidy.Configuration;
52
53 import java.io.ByteArrayInputStream;
54 import java.io.IOException;
55 import java.io.StringWriter;
56 import java.util.GregorianCalendar;
57 import java.util.HashMap;
58 import java.util.Iterator;
59 import java.util.List;
60 import java.util.Map;
61
62 public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer {
63   protected LoggerWrapper logger;
64
65   public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure  {
66     try {
67       Iterator i;
68
69       Map configMap = new HashMap();
70
71       logger = new LoggerWrapper("Localizer.ProducerAssistant");
72
73 // obsolete:
74       configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot"));
75       configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot"));
76       configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost"));
77       configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction"));
78       configMap.put("docRoot", MirGlobal.config().getString("RootUri"));
79       configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir");
80       configMap.put("now", new GeneratorFormatAdapters.DateFormatAdapter(new GregorianCalendar().getTime(), MirGlobal.config().getString("Mir.DefaultTimezone")));
81       configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host"));
82       configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host"));
83       configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host"));
84       configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path"));
85       configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version"));
86       configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding"));
87
88 // "new":
89       configMap.putAll(MirPropertiesConfiguration.instance().allSettings());
90
91       aValueSet.put("config", configMap);
92
93       aValueSet.put("utility", new Utility()); 
94
95       aValueSet.put("languages",
96         new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language"));
97
98       aValueSet.put("topics",
99         new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
100
101       Map articleTypeMap = new HashMap();
102       articleTypeMap.put("openposting", "0");
103       articleTypeMap.put("newswire", "1");
104       articleTypeMap.put("feature", "2");
105       articleTypeMap.put("topicspecial", "3");
106       articleTypeMap.put("startspecial", "4");
107
108       i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType");
109       while (i.hasNext()) {
110         EntityAdapter articleType = (EntityAdapter) i.next();
111
112         articleTypeMap.put(articleType.get("name"), articleType.get("id"));
113       }
114       aValueSet.put("articletype", articleTypeMap);
115
116       Map commentStatusMap = new HashMap();
117       i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus");
118       while (i.hasNext()) {
119         EntityAdapter commentStatus = (EntityAdapter) i.next();
120
121         commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id"));
122       }
123       aValueSet.put("commentstatus", commentStatusMap);
124       aValueSet.put("languageCodeToId", new getLanguageIdFunction());
125     }
126     catch (Throwable t) {
127       logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage());
128       throw new RuntimeException(t.getMessage());
129     }
130
131   };
132   public static class getLanguageIdFunction implements Generator.Function {
133     private Map languageCodeToId;
134     private String otherLanguageId;
135     private LoggerWrapper logger = new LoggerWrapper("Localizer.Earth.getLanguageIdFunction");
136
137     public getLanguageIdFunction() throws MirLocalizerFailure {
138       try {
139         otherLanguageId = "";
140         languageCodeToId = new HashMap();
141
142         Iterator i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language");
143         while (i.hasNext()) {
144           EntityAdapter language = (EntityAdapter) i.next();
145           if (language.get("code").equals("ot"))
146             otherLanguageId = (String) language.get("id");
147
148           languageCodeToId.put(language.get("code"), language.get("id"));
149         }
150       }
151       catch (Throwable t) {
152         logger.error(t.toString());
153
154         throw new MirLocalizerFailure(t);
155       }
156     }
157
158     public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
159       try {
160         if (aParameters.size() != 1)
161           throw new GeneratorExc("getLanguageIdFunction: 1 parameter expected: language-code");
162
163         String result = (String) languageCodeToId.get(aParameters.get(0));
164         if (result == null)
165           result = otherLanguageId;
166
167         return result;
168       }
169       catch (GeneratorExc e) {
170         throw e;
171       }
172       catch (Throwable t) {
173         throw new GeneratorFailure("getLanguageIdFunction: " + t.getMessage(), t);
174       }
175     };
176   }
177
178
179   public String filterNonHTMLText(String aText) {
180
181     logger.debug("about to filter non HTML Text of length " + aText.length());
182     try {
183       String result =
184           StringUtil.createHTML(
185           StringUtil.removeHTMLTags(aText),
186           MirGlobal.config().getString("Producer.ImageRoot"),
187           MirGlobal.config().getString("Producer.MailLinkName"),
188           MirGlobal.config().getString("Producer.ExtLinkName"),
189           MirGlobal.config().getString("Producer.IntLinkName")
190           );
191       logger.debug("done filtering non-HTML text ");
192       return result;
193     }
194     catch (Throwable t) {
195       logger.error("error while filtering non-HTML text: " + t.toString());
196
197       throw new RuntimeException(t.toString());
198     }
199   }
200   public String filterHTMLText(String aText) {
201     try {
202       StringWriter out = new StringWriter();
203       Tidy tidy = new Tidy();
204       ByteArrayInputStream in = new ByteArrayInputStream(aText.getBytes("UTF8"));
205       tidy.setMakeClean(true);
206       tidy.setCharEncoding(Configuration.UTF8);
207       tidy.setErrout(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
208       print(tidy.parseDOM(in, null), out);
209       
210       return out.toString();
211     }
212     catch (IOException e) {
213       return e.getMessage();
214     }
215   }
216
217   private boolean checkAttr(String attrName) {
218     if (attrName.equals("onLoad") || attrName.equals("onClick") || attrName.equals("onFocus") || attrName.equals("onBlur") || attrName.equals("onMouseOver") || attrName.equals("onMouseOut") || attrName.equals("style") || attrName.equals("STYLE") || attrName.equals("height") || attrName.equals("width") || attrName.equals("HEIGHT") || attrName.equals("WIDTH"))
219       return false;
220     else
221       return true;
222
223   }
224
225   private boolean checkNode(String nodeName) {
226     if (nodeName.equals("a") ||
227         nodeName.equals("img") ||
228         nodeName.equals("h1") ||
229         nodeName.equals("h2") ||
230         nodeName.equals("h3") ||
231         nodeName.equals("h4") ||
232         nodeName.equals("h5") ||
233         nodeName.equals("h6") ||
234         nodeName.equals("br") ||
235         nodeName.equals("form") ||
236         nodeName.equals("input") ||
237         nodeName.equals("hr") ||
238         nodeName.equals("strong") ||
239         nodeName.equals("font") ||
240         nodeName.equals("b") ||
241         nodeName.equals("i") ||
242         nodeName.equals("em") ||
243         nodeName.equals("p") ||
244         nodeName.equals("table") ||
245         nodeName.equals("tr") ||
246         nodeName.equals("td") ||
247         nodeName.equals("th") ||
248         nodeName.equals("ul") ||
249         nodeName.equals("ol") ||
250         nodeName.equals("li")
251     ) {
252       return true;
253     } else {
254
255       return false;
256     }
257   }
258
259   private void print(Node node, StringWriter out) throws IOException {
260     if (node == null) {
261       return;
262     }
263     int type = node.getNodeType();
264     boolean canOutput = checkNode(node.getNodeName());
265
266     switch (type) {
267
268       case Node.DOCUMENT_NODE:
269
270         print(((Document) node).getDocumentElement(), out);
271         out.flush();
272         break;
273
274       case Node.ELEMENT_NODE:
275         if (canOutput) {
276           out.write('<');
277
278           out.write(node.getNodeName());
279           NamedNodeMap attrs = node.getAttributes();
280
281           for (int i = 0; i < attrs.getLength(); i++) {
282             String attrName = attrs.item(i).getNodeName();
283             if (checkAttr(attrName)) {
284               out.write(' ');
285               out.write(attrs.item(i).getNodeName());
286               out.write("=\"");
287
288               out.write(attrs.item(i).getNodeValue());
289               out.write('"');
290             }
291           }
292
293           if (node.getChildNodes()==null || node.getChildNodes().getLength()==0) {
294             out.write("/");
295           }
296           out.write('>');
297         }
298         NodeList children = node.getChildNodes();
299         if (children != null) {
300           int len = children.getLength();
301           for (int i = 0; i < len; i++) {
302             print(children.item(i), out);
303           }
304         }
305         break;
306
307       case Node.TEXT_NODE:
308         out.write(node.getNodeValue());
309         break;
310
311     }
312
313     if (type == Node.ELEMENT_NODE && canOutput && node.getChildNodes()!=null && node.getChildNodes().getLength()>0) {
314       out.write("</");
315       out.write(node.getNodeName());
316       out.write('>');
317     }
318
319     out.flush();
320   }
321
322   public static class Utility extends ReflectionGeneratorFunctionsAdapter {
323     public Utility () {
324       super(new MirBasicUtilityFunctions());
325     }
326     public Object getDatetime() {
327       return new GeneratorDateTimeFunctions.DateTimeFunctions(
328         MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"));
329     }
330
331     public Object getCompressWhitespace() {
332       return new freemarker.template.utility.CompressWhitespace();
333     }
334   }
335 }