KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > htmlparser > parserapplications > filterbuilder > Filter


1 // HTMLParser Library $Name: v1_5_20050313 $ - A java-based parser for HTML
2
// http://sourceforge.org/projects/htmlparser
3
// Copyright (C) 2005 Derrick Oswald
4
//
5
// Revision Control Information
6
//
7
// $Source: /cvsroot/htmlparser/htmlparser/src/org/htmlparser/parserapplications/filterbuilder/Filter.java,v $
8
// $Author: derrickoswald $
9
// $Date: 2005/02/13 20:43:06 $
10
// $Revision: 1.1 $
11
//
12
// This library is free software; you can redistribute it and/or
13
// modify it under the terms of the GNU Lesser General Public
14
// License as published by the Free Software Foundation; either
15
// version 2.1 of the License, or (at your option) any later version.
16
//
17
// This library is distributed in the hope that it will be useful,
18
// but WITHOUT ANY WARRANTY; without even the implied warranty of
19
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20
// Lesser General Public License for more details.
21
//
22
// You should have received a copy of the GNU Lesser General Public
23
// License along with this library; if not, write to the Free Software
24
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25
//
26

27 package org.htmlparser.parserapplications.filterbuilder;
28
29 import java.awt.*;
30 import java.io.ByteArrayInputStream JavaDoc;
31 import java.io.ByteArrayOutputStream JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.io.ObjectInputStream JavaDoc;
34 import java.io.ObjectOutputStream JavaDoc;
35 import java.util.Hashtable JavaDoc;
36 import java.util.Vector JavaDoc;
37
38 import javax.swing.*;
39 import javax.swing.border.*;
40
41 import org.htmlparser.NodeFilter;
42 import org.htmlparser.Parser;
43 import org.htmlparser.parserapplications.filterbuilder.layouts.VerticalLayoutManager;
44
45 /**
46  * Base class for all filters.
47  * Provides common functionality applicable to all filters.
48  */

49 public abstract class Filter
50     extends
51         JComponent
52     implements
53         NodeFilter
54 {
55     /**
56      * Create a new filter from the class name.
57      * @param class_name The class to instatiate.
58      * @return The constructed filter object.
59      */

60     public static Filter instantiate (String JavaDoc class_name)
61     {
62         Filter ret;
63         
64         ret = null;
65         try
66         {
67             Class JavaDoc cls = Class.forName (class_name);
68             ret = (Filter)cls.newInstance ();
69             mWrappers.put (ret.getNodeFilter ().getClass ().getName (), class_name);
70         }
71         catch (ClassNotFoundException JavaDoc cnfe)
72         {
73             System.out.println ("can't find class " + class_name);
74         }
75         catch (InstantiationException JavaDoc ie)
76         {
77             System.out.println ("can't instantiate class " + class_name);
78         }
79         catch (IllegalAccessException JavaDoc ie)
80         {
81             System.out.println ("class " + class_name + " has no public constructor");
82         }
83         catch (ClassCastException JavaDoc cce)
84         {
85             System.out.println ("class " + class_name + " is not a Filter");
86         }
87         
88         return (ret);
89     }
90
91     /**
92      * Map from cilter class to wrapper.
93      * Populated as part of each wrapper being loaded.
94      */

95     protected static Hashtable JavaDoc mWrappers = new Hashtable JavaDoc ();
96
97     /**
98      * Create a filter.
99      * Set up the default display.
100      * Only a border with the label of the filter name,
101      * returned by <code>getDescription()</code>,
102      * and an icon, returned by <code>getIcon()</code>.
103      */

104     public Filter ()
105     {
106         JLabel label;
107         Dimension dimension;
108         Insets insets;
109
110         setToolTipText (getDescription ());
111         // none of these quite does it:
112
// new BoxLayout (this, BoxLayout.Y_AXIS));
113
// new GridLayout (0, 1));
114
setLayout (new VerticalLayoutManager ());
115         setSelected (false);
116         label = new JLabel (getDescription (), getIcon (), SwingConstants.LEFT);
117         label.setBackground (Color.green);
118         label.setAlignmentX (Component.LEFT_ALIGNMENT);
119         label.setHorizontalAlignment (SwingConstants.LEFT);
120         add (label);
121         dimension = label.getMaximumSize ();
122         insets = getInsets ();
123         dimension.setSize (dimension.width + insets.left + insets.right, dimension.height + insets.top + insets.bottom);
124         setSize (dimension);
125     }
126
127     /**
128      * Get the name of the filter.
129      * @return A descriptive name for the filter.
130      */

131     public abstract String JavaDoc getDescription ();
132
133     /**
134      * Get the underlying node filter object.
135      * @return The node filter object suitable for serialization.
136      */

137     public abstract NodeFilter getNodeFilter ();
138
139     /**
140      * Assign the underlying node filter for this wrapper.
141      * @param filter The filter to wrap.
142      * @param context The parser to use for conditioning this filter.
143      * Some filters need contextual information to provide to the user,
144      * i.e. for tag names or attribute names or values,
145      * so the Parser context is provided.
146      */

147     public abstract void setNodeFilter (NodeFilter filter, Parser context);
148
149     /**
150      * Get the underlying node filter's subordinate filters.
151      * @return The node filter object's contained filters.
152      */

153     public abstract NodeFilter[] getSubNodeFilters ();
154
155     /**
156      * Assign the underlying node filter's subordinate filters.
157      * @param filters The filters to insert into the underlying node filter.
158      */

159     public abstract void setSubNodeFilters (NodeFilter[] filters);
160
161     /**
162      * Convert this filter into Java code.
163      * Output whatever text necessary and return the variable name.
164      * @param out The output buffer.
165      * @param context Three integers as follows:
166      * <li>indent level - the number of spaces to insert at the beginning of each line</li>
167      * <li>filter number - the next available filter number</li>
168      * <li>filter array number - the next available array of filters number</li>
169      * @return The variable name to use when referencing this filter (usually "filter" + context[1]++)
170      */

171     public abstract String JavaDoc toJavaCode (StringBuffer JavaDoc out, int[] context);
172
173     /**
174      * Get the icon for the filter.
175      * Loads the resource specified by
176      * <code>getIconSpec()</code> as an icon.
177      * @return The icon or null if it was not found.
178      */

179     public Icon getIcon ()
180     {
181         ImageIcon ret;
182         
183         ret = null;
184         try
185         {
186             ret = new ImageIcon (getClass ().getResource (getIconSpec ()));
187         }
188         catch (NullPointerException JavaDoc npe)
189         {
190             System.err.println ("can't find icon " + getIconSpec ());
191         }
192         
193         return (ret);
194     }
195     
196     /**
197      * Get the resource name for the icon.
198      * @return The icon resource specification.
199      */

200     public abstract String JavaDoc getIconSpec ();
201
202     //
203
// Component overrides
204
//
205

206     /**
207      * Returns a string representation of this component and its values.
208      * @return A string representation of this component.
209      */

210     public String JavaDoc toString ()
211     {
212         return (getDescription () + " [" + this.getClass ().getName () + "]");
213     }
214
215     //
216
// utilities
217
//
218

219     public static byte[] pickle (Object JavaDoc object)
220         throws
221             IOException JavaDoc
222     {
223         ByteArrayOutputStream JavaDoc bos;
224         ObjectOutputStream JavaDoc oos;
225         byte[] ret;
226
227         bos = new ByteArrayOutputStream JavaDoc ();
228         oos = new ObjectOutputStream JavaDoc (bos);
229         oos.writeObject (object);
230         oos.close ();
231         ret = bos.toByteArray ();
232
233         return (ret);
234     }
235
236     public static Object JavaDoc unpickle (byte[] data)
237         throws
238             IOException JavaDoc,
239             ClassNotFoundException JavaDoc
240     {
241         ByteArrayInputStream JavaDoc bis;
242         ObjectInputStream JavaDoc ois;
243         Object JavaDoc ret;
244
245         bis = new ByteArrayInputStream JavaDoc (data);
246         ois = new ObjectInputStream JavaDoc (bis);
247         ret = ois.readObject ();
248         ois.close ();
249
250         return (ret);
251     }
252
253     public static String JavaDoc serialize (byte[] data)
254     {
255         String JavaDoc string;
256         StringBuffer JavaDoc ret;
257         
258         ret = new StringBuffer JavaDoc (data.length * 2);
259
260         for (int i = 0; i < data.length; i++)
261         {
262             string = Integer.toString (0xff & data[i], 16);
263             if (string.length () < 2)
264                 ret.append ("0");
265             ret.append (string);
266         }
267         
268         return (ret.toString ());
269     }
270
271     public static byte[] deserialize (String JavaDoc string)
272     {
273         byte[] ret;
274         
275         ret = new byte[string.length () / 2];
276         
277         for (int i = 0; i < string.length (); i += 2)
278             ret[i/2] = (byte)Integer.parseInt (string.substring (i, i + 2), 16); // todo: hopelessly inefficient
279

280         return (ret);
281     }
282
283     /**
284      * Returns a string serialization of the filters.
285      * @return A string representation of the filters.
286      */

287     public static String JavaDoc deconstitute (Filter[] filters) throws IOException JavaDoc
288     {
289         StringBuffer JavaDoc ret;
290
291         ret = new StringBuffer JavaDoc (1024);
292         for (int i = 0; i < filters.length; i++)
293         {
294             ret.append ("[");
295             ret.append (serialize (pickle (filters[i].getNodeFilter ())));
296             ret.append ("]");
297         }
298
299         return (ret.toString ());
300     }
301
302     /**
303      * Returns the filters represented by the string.
304      * @param string The string with serialized node filters.
305      * @return The filters gleaned from the string.
306      */

307     public static Filter[] reconstitute (String JavaDoc string, Parser context)
308     {
309         Filter[] ret;
310         Vector JavaDoc vector;
311         int index;
312         String JavaDoc code;
313         Object JavaDoc object;
314         Filter filter;
315         
316         vector = new Vector JavaDoc ();
317         try
318         {
319             while (string.startsWith ("["))
320             {
321                 index = string.indexOf (']');
322                 if (-1 != index)
323                 {
324                     code = string.substring (1, index);
325                     string = string.substring (index + 1);
326                     object = unpickle (deserialize (code));
327                     if (object instanceof NodeFilter)
328                     {
329                         filter = wrap ((NodeFilter)object, context);
330                         if (null != filter)
331                             vector.addElement (filter);
332                     }
333                     else
334                         break;
335                 }
336                 else
337                     break;
338             }
339         }
340         catch (Exception JavaDoc e)
341         {
342             e.printStackTrace ();
343         }
344
345         ret = new Filter[vector.size ()];
346         vector.copyInto (ret);
347
348         return (ret);
349     }
350
351     /**
352      * Get the enclosed sub filter list if any.
353      * Todo: rationalize with FilterBuilder's method(s) of the same name.
354      * @param component The component that's supposedly enclosing the list.
355      * @return The enclosed component or <code>null</code> otherwise.
356      */

357     protected static SubFilterList getEnclosed (Component component)
358     {
359         Component[] list;
360
361         if (component instanceof Container)
362         {
363             list = ((Container)component).getComponents ();
364             for (int i = 0; i < list.length; i++)
365                 if (list[i] instanceof SubFilterList)
366                     return ((SubFilterList)list[i]);
367         }
368
369         return (null);
370     }
371
372     /**
373      * Returns a wrapped filter.
374      * @param filter A filter to be wrapped by GUI components.
375      * @param context The context within which to wrap the object.
376      * Some wrappers need context to set up useful choices for the user.
377      * @return The filter to wrap.
378      */

379     public static Filter wrap (NodeFilter filter, Parser context)
380     {
381         String JavaDoc class_name;
382         NodeFilter[] filters;
383         SubFilterList list;
384         Filter ret;
385
386         ret = null;
387         
388         class_name = filter.getClass ().getName ();
389         class_name = (String JavaDoc)mWrappers.get (class_name);
390         if (null != class_name)
391         {
392             try
393             {
394                 ret = Filter.instantiate (class_name);
395                 ret.setNodeFilter (filter, context);
396                 // recurse into subfilters
397
filters = ret.getSubNodeFilters ();
398                 if (0 != filters.length)
399                 {
400                     list = getEnclosed (ret);
401                     if (null != list)
402                     {
403                         ret.setSubNodeFilters (new NodeFilter[0]); // clean out the unwrapped filters
404
for (int i = 0; i < filters.length; i++)
405                             list.addFilter (wrap (filters[i], context));
406                     }
407                     else
408                         throw new IllegalStateException JavaDoc ("filter can't have subnodes without a SubFilterList on the wrapper");
409                 }
410             }
411             catch (Exception JavaDoc e)
412             {
413                 e.printStackTrace ();
414             }
415         }
416         else
417             System.out.println (class_name + " is not registered for wrapping.");
418         
419         return (ret);
420     }
421
422     /**
423      * Set the 'selected look' for the component.
424      * @param selected If <code>true</code>, 'select' this component,
425      * otherwise 'deselect' it.
426      */

427     public void setSelected (boolean selected)
428     {
429         if (selected)
430             setBorder (
431                 new CompoundBorder (
432                     new EtchedBorder (),
433                     new CompoundBorder (
434                         new LineBorder(Color.blue, 2),
435                         new EmptyBorder (1, 1, 1, 1))));
436         else
437             setBorder (
438                 new CompoundBorder (
439                     new EtchedBorder (),
440                     new EmptyBorder (3,3,3,3)));
441     }
442     
443     /**
444      * Set the expanded state for the component.
445      * This sets invisible all but the JLabel component in the
446      * comand component.
447      * @param expanded If <code>true</code>, 'expand' this component,
448      * otherwise 'collapse' it.
449      */

450     public void setExpanded (boolean expanded)
451     {
452         Component[] components;
453         
454         components = getComponents ();
455         for (int i = 0; i < components.length; i++)
456             if (!(components[i] instanceof JLabel))
457                 components[i].setVisible (expanded);
458     }
459     
460     public static void spaces (StringBuffer JavaDoc out, int count)
461     {
462         for (int i = 0; i < count; i++)
463             out.append (' ');
464     }
465     
466     public static void newline (StringBuffer JavaDoc out)
467     {
468         out.append ('\n');
469     }
470 }
471
Popular Tags