Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/make/src/classes/build/tools/swingbeaninfo/GenSwingBeanInfo.java
32287 views
/*1* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package build.tools.swingbeaninfo;2627import java.beans.BeanInfo;28import java.beans.BeanDescriptor;29import java.beans.Introspector;30import java.beans.IntrospectionException;31import java.beans.PropertyDescriptor;3233import java.io.*;3435import java.util.Hashtable;36import java.util.HashMap;37import java.util.Iterator;3839/**40* A utlity for generating a BeanInfo source file from a template and a41* Hashtable with hints that were generated from a doclet.42* it's neccessary to write things like the per property descriptions43* by hand. To run the application:44* <pre>45* java GenSwingBeanInfo <class name>46* </pre>47* Code for a bean info class is written to out. If the class is48* swing package, you don't need to fully specify its name.49*50* @author Hans Muller51* @author Rich Schiavi52* @author Mark Davidson53*/54public class GenSwingBeanInfo {55private final static String BEANINFO_SUFFIX = "BeanInfo.java";5657// Tokens in @(...)58private final static String TOK_BEANPACKAGE = "BeanPackageName";59private final static String TOK_BEANCLASS = "BeanClassName";60private final static String TOK_BEANOBJECT = "BeanClassObject";61private final static String TOK_CLASSDESC = "ClassDescriptors";62private final static String TOK_BEANDESC = "BeanDescription";63private final static String TOK_PROPDESC = "BeanPropertyDescriptors";64private final static String TOK_ENUMVARS = "EnumVariables";6566private String enumcode; // Generated code for enumerated properties.6768private boolean DEBUG = false;6970private String fileDir;71private String templateFilename;7273/**74* Public constructor75* @param fileDir Location to put the generated source files.76* @param templateFilename Location of the BeanInfo template77* @param debug Flag to turn on debugging78*/79public GenSwingBeanInfo(String fileDir, String templateFilename, boolean debug) {80this.fileDir = fileDir;81this.templateFilename = templateFilename;82this.DEBUG = debug;83}8485/**86* Opens a BeanInfo PrintStream for the class.87*/88private PrintStream initOutputFile(String classname) {89try {90OutputStream out = new FileOutputStream(fileDir + File.separator + classname + BEANINFO_SUFFIX);91BufferedOutputStream bout = new BufferedOutputStream(out);92return new PrintStream(out);93} catch (IOException e){94// System.err.println("GenSwingBeanInfo: " + e.toString());95}96return null;97}9899private static void messageAndExit(String msg) {100System.err.println("\n" + msg);101System.exit(1);102}103104105/**106* Load the contents of the BeanInfo template into a string and107* return the string.108*/109private String loadTemplate() {110String template = "<no template>";111112try {113File file = new File(templateFilename);114DataInputStream stream = new DataInputStream(new FileInputStream(file));115BufferedReader reader = new BufferedReader(new InputStreamReader(stream));116StringBuffer buffer = new StringBuffer();117118int c;119while((c = reader.read()) != -1) {120buffer.append((char)c);121}122123template = buffer.toString();124reader.close();125} catch (IOException e) {126System.out.println(e.getMessage());127messageAndExit("GenSwingBeanInfo: Couldn't load template: " + templateFilename + e);128}129return template;130}131132133/**134* Generates a string for the BeanDescriptor135*/136private String genBeanDescriptor(DocBeanInfo dbi) {137String code = "";138int beanflags = dbi.beanflags;139140// we support export, hidden, preferred141if ((beanflags & DocBeanInfo.EXPERT) != 0)142code += " sun.swing.BeanInfoUtils.EXPERT, Boolean.TRUE,\n";143if ((beanflags & DocBeanInfo.HIDDEN) !=0)144code += " sun.swing.BeanInfoUtils.HIDDEN, Boolean.TRUE,\n";145/* 1.2 only - make sure build flag build using 1.2 */146if ((beanflags & DocBeanInfo.PREFERRED) !=0)147code += " sun.swing.BeanInfoUtils.PREFERRED, Boolean.TRUE,\n";148if (!(dbi.customizerclass.equals("null")))149code += " sun.swing.BeanInfoUtils.CUSTOMIZERCLASS, " + dbi.customizerclass + ".class,\n";150151if (dbi.attribs != null) {152code += genAttributes(dbi.attribs);153}154155return code;156}157158/**159* Generates the code for the attributes table.160*/161private String genAttributes(HashMap attribs) {162StringBuffer code = new StringBuffer();163String key;164String value;165166Iterator iterator = attribs.keySet().iterator();167while(iterator.hasNext()) {168key = (String)iterator.next();169value = (String)attribs.get(key);170171if (value.equals("true") || value.equals("false")) {172// Substitute the "true" and "false" for codegen Boolean values.173if(value.equals("true"))174value = "Boolean.TRUE";175else176value = "Boolean.FALSE";177178code.append(" \"").append(key).append("\", ").append(value).append(",\n");179} else {180code.append(" \"").append(key).append("\", \"").append(value).append("\",\n");181}182}183return code.toString();184}185186/**187* Generates the code for the enumeration.188* XXX - side effect: Modifies the enumcode field variable.189*/190private String genEnumeration(String propName, HashMap enums) {191String objectName = propName + "Enumeration";192String key;193String value;194195StringBuffer code = new StringBuffer("\n\t\tObject[] ");196code.append(objectName).append(" = new Object[] { \n");197198Iterator iterator = enums.keySet().iterator();199while(iterator.hasNext()) {200key = (String)iterator.next();201value = (String)enums.get(key);202203code.append("\t\t\t\"").append(key).append("\" , new Integer(");204code.append(value).append("), \"").append(value).append("\",\n");205}206// Close the statically initialized Object[]207code.replace(code.length() - 2, code.length(), "\n\t\t};\n");208209// Add this string to the enumeration code.210enumcode += code.toString();211212// Return the PropertyDescriptor init string;213return " \"enumerationValues\", " + objectName + ",\n";214}215216/**217* Generate the createPropertyDescriptor() calls, one per property.218* A fully specified createPropertyDescriptor() call looks like this:219* <pre>220* createPropertyDescriptor("contentPane", new Object[] {221* BOUND, Boolean.TRUE,222* CONSTRAINED, Boolean.TRUE,223* PROPERTYEDITORCLASS, package.MyEditor.cl224* WRITEMETHOD, "setContentPane",225* DISPLAYNAME, "contentPane",226* EXPERT, Boolean.FALSE,227* HIDDEN, Boolean.FALSE,228* PREFERRED, Boolean.TRUE,229* SHORTDESCRIPTION, "A top level window with a window manager border",230* "random attribute","random value"231* }232* );233* </pre>234*235* @param info The actual BeanInfo class generated from from the Intospector.236* @param dochash Set of DocBeanInfo pairs for each property. This information237* is used to suplement the instrospected properties.238* @return A snippet of source code which would construct all the PropertyDescriptors.239*/240private String genPropertyDescriptors(BeanInfo info, Hashtable dochash) {241String code = "";242enumcode = " "; // code for enumerated properties.243PropertyDescriptor[] pds = info.getPropertyDescriptors();244boolean hash_match = false;245DocBeanInfo dbi = null;246247for(int i = 0; i < pds.length; i++) {248if (pds[i].getReadMethod() != null) {249code += "\ncreatePropertyDescriptor(\"" + pds[i].getName() + "\", new Object[] {\n";250251if (DEBUG)252System.out.println("Introspected propertyDescriptor: " + pds[i].getName());253254if (dochash.size() > 0 && dochash.containsKey(pds[i].getName())) {255dbi = (DocBeanInfo)dochash.remove(pds[i].getName());256// override/set properties on this *introspected*257// BeanInfo pds using our DocBeanInfo class values258setDocInfoProps(dbi, pds[i]);259hash_match = true;260if (DEBUG)261System.out.println("DocBeanInfo class exists for propertyDescriptor: " + pds[i].getName() + "\n");262} else {263hash_match = false;264}265266// Do I need to do anything with this property descriptor267if (hash_match) {268if ((dbi.beanflags & DocBeanInfo.BOUND) != 0) {269code += " sun.swing.BeanInfoUtils.BOUND, Boolean.TRUE,\n";270} else {271code += " sun.swing.BeanInfoUtils.BOUND, Boolean.FALSE,\n";272}273}274275if (pds[i].isConstrained()) {276code += " sun.swing.BeanInfoUtils.CONSTRAINED, Boolean.TRUE,\n";277}278279if (pds[i].getPropertyEditorClass() != null) {280String className = pds[i].getPropertyEditorClass().getName();281code += " sun.swing.BeanInfoUtils.PROPERTYEDITORCLASS, " + className + ".class,\n";282} else if ((hash_match) && (!(dbi.propertyeditorclass.equals("null")))) {283code += " sun.swing.BeanInfoUtils.PROPERTYEDITORCLASS, " + dbi.propertyeditorclass + ".class,\n";284}285286if ((hash_match) && (!(dbi.customizerclass.equals("null")))) {287code += " sun.swing.BeanInfoUtils.CUSTOMIZERCLASS, " + dbi.customizerclass + ".class,\n";288}289290if ((hash_match) && (dbi.enums != null)) {291code += genEnumeration(pds[i].getName(), dbi.enums);292}293294if (!pds[i].getDisplayName().equals(pds[i].getName())) {295code += " sun.swing.BeanInfoUtils.DISPLAYNAME, \"" + pds[i].getDisplayName() + "\",\n";296}297298if (pds[i].isExpert()) {299code += " sun.swing.BeanInfoUtils.EXPERT, Boolean.TRUE,\n";300}301302if (pds[i].isHidden()) {303code += " sun.swing.BeanInfoUtils.HIDDEN, Boolean.TRUE,\n";304}305306if (pds[i].isPreferred()) {307code += " sun.swing.BeanInfoUtils.PREFERRED, Boolean.TRUE,\n";308}309310// user attributes311if (hash_match) {312if (dbi.attribs != null) {313code += genAttributes(dbi.attribs);314}315}316code += " sun.swing.BeanInfoUtils.SHORTDESCRIPTION, \"" + pds[i].getShortDescription() + "\",\n";317318// Print the closing brackets. If this is the last array initializer,319// don't print the trailing comma.320if (i == (pds.length - 1)) {321code += " }\n)\n";322} else {323code += " }\n),\n";324}325326} // end if ( readMethod != null )327} // end for328return code;329}330331/**332* Sets properties from the BeanInfo supplement on the333* introspected PropertyDescriptor334*/335private void setDocInfoProps(DocBeanInfo dbi, PropertyDescriptor pds) {336int beanflags = dbi.beanflags;337338if ((beanflags & DocBeanInfo.BOUND) != 0)339pds.setBound(true);340if ((beanflags & DocBeanInfo.EXPERT) != 0)341pds.setExpert(true);342if ((beanflags & DocBeanInfo.CONSTRAINED) != 0)343pds.setConstrained(true);344if ((beanflags & DocBeanInfo.HIDDEN) !=0)345pds.setHidden(true);346if ((beanflags & DocBeanInfo.PREFERRED) !=0)347pds.setPreferred(true);348349if (!(dbi.desc.equals("null"))){350pds.setShortDescription(dbi.desc);351}352if (!(dbi.displayname.equals("null"))){353pds.setDisplayName(dbi.displayname);354}355}356357/**358* Generates the BeanInfo source file using instrospection and a359* Hashtable full of hints. This the only public method in this class.360*361* @param classname Root name of the class. i.e., JButton362* @param dochash A hashtable containing the DocBeanInfo.363*/364public void genBeanInfo(String packageName, String classname, Hashtable dochash) {365// The following initial values are just examples. All of these366// fields are initialized below.367String beanClassName = "JInternalFrame";368String beanClassObject = "javax.swing.JInternalFrame.class";369String beanDescription = "<A description of this component>.";370String beanPropertyDescriptors = "<createSwingPropertyDescriptor code>";371String classPropertyDescriptors = "<createSwingClassPropertyDescriptor code>";372373Class cls = getClass(packageName, classname);374if (cls == null){375messageAndExit("Can't find class: " + classname);376}377378// Get the output stream.379PrintStream out = initOutputFile(classname);380381// Run the Introspector and initialize the variables382383BeanInfo beanInfo = null;384BeanDescriptor beanDescriptor = null;385386try {387if (cls == javax.swing.JComponent.class) {388// Go all the way up the heirarchy for JComponent389beanInfo = Introspector.getBeanInfo(cls);390} else {391beanInfo = Introspector.getBeanInfo(cls, cls.getSuperclass());392}393beanDescriptor = beanInfo.getBeanDescriptor();394beanDescription = beanDescriptor.getShortDescription();395} catch (IntrospectionException e) {396messageAndExit("Introspection failed for " + cls.getName() + " " + e);397}398399beanClassName = beanDescriptor.getName();400beanClassObject = cls.getName() + ".class";401402if (DEBUG){403System.out.println(">>>>GenSwingBeanInfo class: " + beanClassName);404}405// Generate the Class BeanDescriptor information first406if (dochash.size() > 0) {407if (dochash.containsKey(beanClassName)) {408DocBeanInfo dbi = (DocBeanInfo)dochash.remove(beanClassName);409classPropertyDescriptors = genBeanDescriptor(dbi);410if (DEBUG)411System.out.println("ClassPropertyDescriptors: " + classPropertyDescriptors);412if (!(dbi.desc.equals("null")))413beanDescription = dbi.desc;414} else415beanDescription = beanDescriptor.getShortDescription();416} else417beanDescription = beanDescriptor.getShortDescription();418419// Generate the Property descriptors420beanPropertyDescriptors = genPropertyDescriptors(beanInfo,dochash);421422// Dump the template to out, substituting values for423// @(token) tokens as they're encountered.424425int currentIndex = 0;426// not loading this to get around build issue for now427String template = loadTemplate();428429// This loop substitutes the "@(...)" tags in the template with the ones for the430// current class.431while (currentIndex < template.length()) {432// Find the Token433int tokenStart = template.indexOf("@(", currentIndex);434if (tokenStart != -1) {435out.print(template.substring(currentIndex, tokenStart));436437int tokenEnd = template.indexOf(")", tokenStart);438if (tokenEnd == -1) {439messageAndExit("Bad @(<token>) beginning at " + tokenStart);440}441String token = template.substring(tokenStart+2, tokenEnd);442443if (token.equals(TOK_BEANCLASS)) {444out.print(beanClassName);445} else if (token.equals(TOK_CLASSDESC)) {446if (!(classPropertyDescriptors.equals("<createSwingClassPropertyDescriptor code>"))) {447printDescriptors(out, classPropertyDescriptors, template, tokenStart);448}449} else if (token.equals(TOK_BEANPACKAGE)){450out.print(packageName);451} else if (token.equals(TOK_BEANOBJECT)) {452out.print(beanClassObject);453} else if (token.equals(TOK_BEANDESC)) {454out.print(beanDescription);455} else if (token.equals(TOK_ENUMVARS)){456out.print(enumcode);457} else if (token.equals(TOK_PROPDESC)) {458printDescriptors(out, beanPropertyDescriptors, template, tokenStart);459} else if (token.equals("#")) {460// Ignore the @(#) Version Control tag if it exists.461} else {462messageAndExit("Unrecognized token @(" + token + ")");463}464currentIndex = tokenEnd + 1;465} else {466// tokenStart == -1 - We are finsihed.467out.print(template.substring(currentIndex, template.length()));468break;469}470}471out.close();472}473474/**475* Returns the class from the package name and the class root name.476*477* @param packageName The name of the package of the containing class.478* @param rootname The root name of the class. i.e, JButton479* @return The class instance or null.480*/481private Class getClass(String packageName, String rootname) {482Class cls = null;483String classname = rootname;484485if (packageName != null || !packageName.equals("")) {486classname = packageName + "." + rootname;487}488489try {490cls = Class.forName(classname);491} catch (ClassNotFoundException e) {492// Fail silently.493}494return cls;495}496497/**498* Prints the formated descriptors to the PrintStream499* @param out Open PrintStream500* @param s String descriptor501* @param template Template502* @param tokenStart Index into the template503*/504private void printDescriptors(PrintStream out, String s,505String template, int tokenStart) {506String indent = "";507508// Find the newline that preceeds @(BeanPropertyDescriptors) to509// calculate the indent.510for (int i = tokenStart; i >= 0; i--) {511if (template.charAt(i) == '\n') {512char[] chars = new char[tokenStart - i];513for (int j = 0; j < chars.length; j++) {514chars[j] = ' ';515}516indent = new String(chars);517break;518}519}520521int i = 0;522while(i < s.length()) {523int nlIndex = s.indexOf('\n', i);524out.print(s.substring(i, nlIndex+1));525out.print(indent);526i = nlIndex + 1;527}528}529530531}532533534