KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > fop > layout > hyphenation > Hyphenator


1 /*
2  * $Id: Hyphenator.java,v 1.5.2.3 2003/02/25 14:07:10 jeremias Exp $
3  * ============================================================================
4  * The Apache Software License, Version 1.1
5  * ============================================================================
6  *
7  * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without modifica-
10  * tion, are permitted provided that the following conditions are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if any, must
20  * include the following acknowledgment: "This product includes software
21  * developed by the Apache Software Foundation (http://www.apache.org/)."
22  * Alternately, this acknowledgment may appear in the software itself, if
23  * and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "FOP" and "Apache Software Foundation" must not be used to
26  * endorse or promote products derived from this software without prior
27  * written permission. For written permission, please contact
28  * apache@apache.org.
29  *
30  * 5. Products derived from this software may not be called "Apache", nor may
31  * "Apache" appear in their name, without prior written permission of the
32  * Apache Software Foundation.
33  *
34  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
35  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
36  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
37  * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
38  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
39  * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
40  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
41  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  * ============================================================================
45  *
46  * This software consists of voluntary contributions made by many individuals
47  * on behalf of the Apache Software Foundation and was originally created by
48  * James Tauber <jtauber@jtauber.com>. For more information on the Apache
49  * Software Foundation, please see <http://www.apache.org/>.
50  */

51 package org.apache.fop.layout.hyphenation;
52
53 import java.io.*;
54 import java.util.HashMap JavaDoc;
55 import org.apache.fop.configuration.*;
56 import org.apache.fop.messaging.MessageHandler;
57
58 /**
59  * This class is the main entry point to the hyphenation package.
60  * You can use only the static methods or create an instance.
61  *
62  * @author Carlos Villegas <cav@uniscope.co.jp>
63  */

64 public class Hyphenator {
65     static HashMap JavaDoc hyphenTrees = new HashMap JavaDoc();
66
67     private HyphenationTree hyphenTree = null;
68     private int remainCharCount = 2;
69     private int pushCharCount = 2;
70     private static boolean errorDump = false;
71
72     public Hyphenator(String JavaDoc lang, String JavaDoc country, int leftMin,
73                       int rightMin) {
74         hyphenTree = getHyphenationTree(lang, country);
75         remainCharCount = leftMin;
76         pushCharCount = rightMin;
77     }
78
79     public static HyphenationTree getHyphenationTree(String JavaDoc lang,
80             String JavaDoc country) {
81         String JavaDoc key = lang;
82         // check whether the country code has been used
83
if (country != null &&!country.equals("none"))
84             key += "_" + country;
85             // first try to find it in the cache
86
if (hyphenTrees.containsKey(key))
87             return (HyphenationTree)hyphenTrees.get(key);
88         if (hyphenTrees.containsKey(lang))
89             return (HyphenationTree)hyphenTrees.get(lang);
90
91         HyphenationTree hTree = getFopHyphenationTree(key);
92         if (hTree == null) {
93             String JavaDoc hyphenDir =
94                 Configuration.getStringValue("hyphenation-dir");
95             if (hyphenDir != null) {
96                 hTree = getUserHyphenationTree(key, hyphenDir);
97             }
98         }
99         // put it into the pattern cache
100
if (hTree != null) {
101             hyphenTrees.put(key, hTree);
102         } else {
103             MessageHandler.errorln("Couldn't find hyphenation pattern "
104                                    + key);
105         }
106         return hTree;
107     }
108
109     private static InputStream getResourceStream(String JavaDoc key) {
110         InputStream is = null;
111         // Try to use Context Class Loader to load the properties file.
112
try {
113             java.lang.reflect.Method JavaDoc getCCL =
114                 Thread JavaDoc.class.getMethod("getContextClassLoader", new Class JavaDoc[0]);
115             if (getCCL != null) {
116                 ClassLoader JavaDoc contextClassLoader =
117                     (ClassLoader JavaDoc)getCCL.invoke(Thread.currentThread(),
118                                                new Object JavaDoc[0]);
119                 is = contextClassLoader.getResourceAsStream("hyph/" + key
120                                                             + ".hyp");
121             }
122         } catch (Exception JavaDoc e) {}
123
124         if (is == null) {
125             is = Hyphenator.class.getResourceAsStream("/hyph/" + key
126                                                       + ".hyp");
127         }
128
129         return is;
130     }
131
132     public static HyphenationTree getFopHyphenationTree(String JavaDoc key) {
133         HyphenationTree hTree = null;
134         ObjectInputStream ois = null;
135         InputStream is = null;
136         try {
137             is = getResourceStream(key);
138             if (is == null) {
139                 if (key.length() == 5) {
140                     is = getResourceStream(key.substring(0, 2));
141                     if (is != null) {
142                         MessageHandler.errorln("Couldn't find hyphenation pattern "
143                                                + key
144                                                + "\nusing general language pattern "
145                                                + key.substring(0, 2)
146                                                + " instead.");
147                     } else {
148                         if (errorDump) {
149                             MessageHandler.errorln("Couldn't find precompiled "
150                                                    + "fop hyphenation pattern "
151                                                    + key + ".hyp");
152                         }
153                         return null;
154                     }
155                 } else {
156                     if (errorDump) {
157                         MessageHandler.errorln("Couldn't find precompiled "
158                                                + "fop hyphenation pattern "
159                                                + key + ".hyp");
160                     }
161                     return null;
162                 }
163             }
164             ois = new ObjectInputStream(is);
165             hTree = (HyphenationTree)ois.readObject();
166         } catch (Exception JavaDoc e) {
167             e.printStackTrace();
168         }
169         finally {
170             if (ois != null) {
171                 try {
172                     ois.close();
173                 } catch (IOException e) {
174                     MessageHandler.errorln("can't close hyphenation object stream");
175                 }
176             }
177         }
178         return hTree;
179     }
180
181     /**
182      * load tree from serialized file or xml file
183      * using configuration settings
184      */

185     public static HyphenationTree getUserHyphenationTree(String JavaDoc key,
186             String JavaDoc hyphenDir) {
187         HyphenationTree hTree = null;
188         // I use here the following convention. The file name specified in
189
// the configuration is taken as the base name. First we try
190
// name + ".hyp" assuming a serialized HyphenationTree. If that fails
191
// we try name + ".xml", assumming a raw hyphenation pattern file.
192

193         // first try serialized object
194
File hyphenFile = new File(hyphenDir, key + ".hyp");
195         if (hyphenFile.exists()) {
196             ObjectInputStream ois = null;
197             try {
198                 ois = new ObjectInputStream(new FileInputStream(hyphenFile));
199                 hTree = (HyphenationTree)ois.readObject();
200             } catch (Exception JavaDoc e) {
201                 e.printStackTrace();
202             }
203             finally {
204                 if (ois != null) {
205                     try {
206                         ois.close();
207                     } catch (IOException e) {}
208                 }
209             }
210             return hTree;
211         } else {
212
213             // try the raw XML file
214
hyphenFile = new File(hyphenDir, key + ".xml");
215             if (hyphenFile.exists()) {
216                 hTree = new HyphenationTree();
217                 if (errorDump) {
218                     MessageHandler.errorln("reading " + hyphenDir + key
219                                            + ".xml");
220                 }
221                 try {
222                     hTree.loadPatterns(hyphenFile.getPath());
223                     if (errorDump) {
224                         System.out.println("Stats: ");
225                         hTree.printStats();
226                     }
227                     return hTree;
228                 } catch (HyphenationException ex) {
229                     if (errorDump) {
230                         MessageHandler.errorln("Can't load user patterns "
231                                                + "from xml file " + hyphenDir
232                                                + key + ".xml");
233                     }
234                     return null;
235                 }
236             } else {
237                 if (errorDump) {
238                     MessageHandler.errorln("Tried to load "
239                                            + hyphenFile.toString()
240                                            + "\nCannot find compiled nor xml file for "
241                                            + "hyphenation pattern" + key);
242                 }
243                 return null;
244             }
245         }
246     }
247
248     public static Hyphenation hyphenate(String JavaDoc lang, String JavaDoc country,
249                                         String JavaDoc word, int leftMin,
250                                         int rightMin) {
251         HyphenationTree hTree = getHyphenationTree(lang, country);
252         if (hTree == null) {
253             MessageHandler.errorln("Error building hyphenation tree for language "
254                                    + lang);
255             return null;
256         }
257         return hTree.hyphenate(word, leftMin, rightMin);
258     }
259
260     public static Hyphenation hyphenate(String JavaDoc lang, String JavaDoc country,
261                                         char[] word, int offset, int len,
262                                         int leftMin, int rightMin) {
263         HyphenationTree hTree = getHyphenationTree(lang, country);
264         if (hTree == null) {
265             MessageHandler.errorln("Error building hyphenation tree for language "
266                                    + lang);
267             return null;
268         }
269         return hTree.hyphenate(word, offset, len, leftMin, rightMin);
270     }
271
272     public void setMinRemainCharCount(int min) {
273         remainCharCount = min;
274     }
275
276     public void setMinPushCharCount(int min) {
277         pushCharCount = min;
278     }
279
280     public void setLanguage(String JavaDoc lang, String JavaDoc country) {
281         hyphenTree = getHyphenationTree(lang, country);
282     }
283
284     public Hyphenation hyphenate(char[] word, int offset, int len) {
285         if (hyphenTree == null)
286             return null;
287         return hyphenTree.hyphenate(word, offset, len, remainCharCount,
288                                     pushCharCount);
289     }
290
291     public Hyphenation hyphenate(String JavaDoc word) {
292         if (hyphenTree == null)
293             return null;
294         return hyphenTree.hyphenate(word, remainCharCount, pushCharCount);
295     }
296
297 }
298
Popular Tags