KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > test > editor > indentation > programmatic > IndentCore


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.test.editor.indentation.programmatic;
21
22 import java.io.Writer JavaDoc;
23 import java.io.PrintWriter JavaDoc;
24 import java.io.StringWriter JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.net.MalformedURLException JavaDoc;
29
30 import javax.swing.JEditorPane JavaDoc;
31 import javax.swing.text.Document JavaDoc;
32 import javax.swing.text.StyledDocument JavaDoc;
33 import javax.swing.text.EditorKit JavaDoc;
34
35 import org.openide.text.CloneableEditorSupport;
36 import org.openide.text.IndentEngine;
37 import java.util.Map JavaDoc;
38 import java.lang.reflect.Method JavaDoc;
39 import java.beans.BeanInfo JavaDoc;
40 import java.beans.Introspector JavaDoc;
41 import java.beans.PropertyDescriptor JavaDoc;
42 import java.util.HashMap JavaDoc;
43 import java.beans.PropertyEditor JavaDoc;
44 import java.beans.PropertyEditorManager JavaDoc;
45 //import org.netbeans.modules.editor.java.JavaIndentEngine;//SPLIT-TEMP
46

47 /**<FONT COLOR="#CC3333" FACE="Courier New, Monospaced" SIZE="+1">
48  * <B>
49  * <BR> Editor module API test: indentation - programmatic
50  * </B>
51  * </FONT>
52  *
53  * <P>
54  * <B>What it tests:</B><BR>
55  * This test should test internals of indentation engine. It should not test
56  * indentation from user view. The principle is like java module is inserting
57  * the text.
58  * </P>
59  *
60  * <P>
61  * <B>How it works:</B><BR>
62  * An document with proper MIME type is created, it's indent engine is found,
63  * and text is written to it.
64  * </P>
65  *
66  * <P>
67  * <B>Settings:</B><BR>
68  * This test is not complete test, it's only stub, so for concrete test instance
69  * it's necessary to provide file with text and MIME type. There are no else
70  * settings needed, when executing on clean build.
71  * </P>
72  *
73  * <P>
74  * <B>Output:</B><BR>
75  * The output should be formatted text. If an exception occurs, result is this
76  * exception (it should not match any golden file!). If there is not enough
77  * parametrs, the error message is the result.
78  * </P>
79  *
80  * <P>
81  * <B>Possible reasons of failure:</B><BR>
82  * An exception when obtaining indent engine (for example if it doesn't exist).
83  * An exception when writting to indent engine.
84  * Possibly unrecognized MIME type.
85  * Indent engine error.
86  * </P>
87  *
88  * @author Jan Lahoda
89  * @version 1.0
90  */

91 public class IndentCore extends java.lang.Object JavaDoc {
92
93     /** Creates new IndentCore */
94     public IndentCore() {
95     }
96
97     private static void setProperties(IndentEngine engine, Map JavaDoc indentationProperties) throws Exception JavaDoc {
98         System.err.println(engine.getClass());
99
100         BeanInfo JavaDoc info = Introspector.getBeanInfo(engine.getClass());
101         PropertyDescriptor JavaDoc[] descriptors = info.getPropertyDescriptors();
102
103         System.err.println(descriptors.length);
104
105         for (int cntr = 0; cntr < descriptors.length; cntr++) {
106             System.err.println("testing property=" + descriptors[cntr].getName());
107
108             Object JavaDoc value = indentationProperties.get(descriptors[cntr].getName());
109         
110         if (value == null)
111         continue;
112             
113             if (value.getClass() == String JavaDoc.class && descriptors[cntr].getPropertyType() != String JavaDoc.class) {
114                 PropertyEditor JavaDoc editor = PropertyEditorManager.findEditor(descriptors[cntr].getPropertyType());
115                 
116                 editor.setAsText((String JavaDoc )value);
117                 value = editor.getValue();
118             }
119
120         System.err.println("setting property=" + descriptors[cntr].getName());
121         Method JavaDoc write = descriptors[cntr].getWriteMethod();
122         
123         write.invoke(engine, new Object JavaDoc[] {value});
124         }
125
126 // System.err.println("spacesPerTab=" + ((JavaIndentEngine) engine).getSpacesPerTab()); //SPLIT-TEMP
127
}
128     
129     /** Finds the appropriate indentation writer for the java sources.
130      * @param doc The document where it will be inserted in
131      * @param offset The position in the document
132      * @param writer The encapsulated writer
133      */

134     private static Writer JavaDoc findIndentWriter(Document JavaDoc doc, int offset, Writer JavaDoc writer, Map JavaDoc indentationProperties) throws Exception JavaDoc {
135         IndentEngine engine = IndentEngine.find(doc); // NOI18N
136
// IndentEngine engineClone = (IndentEngine) engine.createClone();
137

138         setProperties(engine/*Clone*/, indentationProperties);
139
140         Writer JavaDoc indentWriter = engine/*Clone*/.createWriter(doc, offset, writer);
141
142         return indentWriter;
143     }
144     
145     private static EditorKit JavaDoc createEditorKit(String JavaDoc mimeType) {
146         return CloneableEditorSupport.getEditorKit(mimeType);
147     }
148     
149     private static StyledDocument JavaDoc createDocument(EditorKit JavaDoc kit) {
150         Document JavaDoc doc = kit.createDefaultDocument();
151         
152         if (doc instanceof StyledDocument JavaDoc) {
153             return (StyledDocument JavaDoc)doc;
154         } else {
155             return new org.openide.text.FilterDocument(doc);
156         }
157     }
158     
159     private static String JavaDoc formatText(StyledDocument JavaDoc doc, int pos, String JavaDoc text, Map JavaDoc indentationProperties) throws Exception JavaDoc {
160         StringWriter JavaDoc stringWriter = new StringWriter JavaDoc();
161         Writer JavaDoc indentWriter = findIndentWriter(doc, pos, stringWriter, indentationProperties);
162         indentWriter.write(text);
163         indentWriter.close();
164         
165         return stringWriter.toString();
166     }
167     
168     /**This method does text formatting.
169      *
170      * @param what to format
171      * @param mimeType MIME type of the text - how it should be formated
172      */

173     public static String JavaDoc indent(String JavaDoc what, String JavaDoc mimeType, Map JavaDoc indentationProperties) throws Exception JavaDoc {
174         Map JavaDoc oldProperties = saveIndentEngineProperties(mimeType);
175         EditorKit JavaDoc kit = createEditorKit(mimeType);
176         StyledDocument JavaDoc doc = createDocument(kit);
177         
178         String JavaDoc result = formatText(doc, 0, what, indentationProperties);
179         
180         loadIndentEngineProperties(mimeType, oldProperties);
181         return result;
182     }
183     
184     private static Map JavaDoc saveIndentEngineProperties(String JavaDoc mimeType) throws Exception JavaDoc {
185         IndentEngine engine = IndentEngine.find(createDocument(createEditorKit(mimeType)));
186         
187         if (engine == null)
188             throw new NullPointerException JavaDoc("No indent engine for MIMEType=" + mimeType + " found.");
189         
190         BeanInfo JavaDoc info = Introspector.getBeanInfo(engine.getClass());
191         PropertyDescriptor JavaDoc[] descriptor = info.getPropertyDescriptors();
192         Map JavaDoc result = new HashMap JavaDoc();
193         
194         for (int cntr = 0; cntr < descriptor.length; cntr++) {
195             Method JavaDoc read = descriptor[cntr].getReadMethod();
196             Object JavaDoc value = read.invoke(engine, new Object JavaDoc[] {});
197             
198 // System.err.println("getPropertyType()=" + descriptor[cntr].getPropertyType() + ", value.getClass()=" + value.getClass());
199
result.put(descriptor[cntr].getName(), value);
200         }
201         
202         return result;
203     }
204     
205     private static void loadIndentEngineProperties(String JavaDoc mimeType, Map JavaDoc properties) throws Exception JavaDoc {
206         IndentEngine engine = IndentEngine.find(createDocument(createEditorKit(mimeType)));
207         
208         if (engine == null)
209             throw new NullPointerException JavaDoc("No indent engine for MIMEType=" + mimeType + " found.");
210         
211         setProperties(engine, properties);
212     }
213
214     /**Entry point for test testing. Log is created fromm System.err, ref is
215      * created from System.out, agruments are passed to run directly. @see run
216      *
217      * @param args arguments for method run.
218      */

219     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
220         IndentCore eng = new IndentCore();
221
222         Map JavaDoc indentationProperties = new HashMap JavaDoc();
223         indentationProperties.put("expandTabs", "true");
224         indentationProperties.put("spacesPerTab", "11");
225         indentationProperties.put("javaFormatSpaceBeforeParenthesis", "true");
226         indentationProperties.put("javaFormatLeadingStarInComment", "true");
227         indentationProperties.put("javaFormatNewlineBeforeBrace", "true");
228
229         eng.run(new PrintWriter JavaDoc(System.err),
230                 new PrintWriter JavaDoc(System.out),
231                 "data/testfiles/wholeMethod.txt",
232                 "text/x-java",
233                 indentationProperties);
234         System.err.flush();
235         System.out.flush();
236     }
237     
238     /**Runs test. Test data are given via args.
239      *
240      * @param args in args[0] is given file with text to format (if the file
241      * is not found, this string is treated instead of it)
242      * in args[1] is given MIME type to format
243      * @param log log writer
244      * @param ref ref writer
245      * @return formatted text.
246      */

247     public void run(PrintWriter JavaDoc log,
248                     PrintWriter JavaDoc ref,
249                     String JavaDoc testFileName,
250                     String JavaDoc testFileMIMEType,
251                     Map JavaDoc indentationProperties) throws Exception JavaDoc {
252         try {
253             StringBuffer JavaDoc result = new StringBuffer JavaDoc();
254             InputStream JavaDoc in = null;
255             
256             try {
257                 int read;
258                 
259                 in = this.getClass().getResourceAsStream(testFileName);
260                 
261                 while ((read = in.read()) != (-1)) {
262                     result.append((char)read);
263                 }
264             } finally {
265                 if (in != null) {
266                     try {
267                         in.close();
268                     } catch (IOException JavaDoc e) {
269                     }
270                 }
271             }
272             ref.print(indent(result.toString(), testFileMIMEType, indentationProperties));
273         } catch (Exception JavaDoc e) {
274             e.printStackTrace(log);
275             throw e;
276         }
277     }
278
279 }
280
Popular Tags