alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 *
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 *
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

/*
 * Common.java
 *
 * Created on May 19, 2000, 1:56 PM
 */

package org.netbeans.test.java;

import java.lang.reflect.Modifier;
import org.netbeans.api.java.classpath.ClassPath;
import org.openide.filesystems.*;
import org.openide.src.*;
import org.openide.loaders.DataObject;
import org.openide.cookies.SourceCookie;
import org.openide.filesystems.Repository;

/** Common static methods. Useful for creating new JavaElements
 * @author Jan Becicka
 * @version 1.1
 */

public class Common extends Object {
    
    private static final String cr=System.getProperty("line.separator");
    private static final String METHODS = "newMethod";
    private static final String FIELDS = "newField";
    private static final int DEFAULTMODIFIERS = Modifier.PUBLIC;
    private static final String DEFAULTBODY = "for (int i=0;i<100;i++){\n\tSystem.out.println(new Integer(i).toString());\n}\nreturn 0;\n";
    public  static final String DEFAULTINITIALIZERBODY = "\n/*somebody*/\n";
    
    /** int parameter1
     */
    public static MethodParameter[] PARS1=new MethodParameter[1];
    /** int parameter1, int parameter2
     */
    public static MethodParameter[] PARS2=new MethodParameter[2];
    /** float parameter1, float parameter2, float parameter 3
     */
    public static MethodParameter[] PARS3=new MethodParameter[3];
    
    
    /** int parameter1
     */
    public static Type[] TPARS1={Type.INT};
    /** int parameter1, int parameter2smnJm kjhklkj .k
     */
    public static Type[] TPARS2={Type.INT,Type.INT};
    /** float parameter1, float parameter2, float parameter 3
     */
    public static Type[] TPARS3={Type.FLOAT,Type.FLOAT, Type.INT};
    
    static {
        PARS1[0]=new MethodParameter("parameter1",Type.INT,false);
        PARS2[0]=new MethodParameter("parameter1",Type.INT,false);
        PARS2[1]=new MethodParameter("parameter2",Type.INT,false);
        PARS3[0]=new MethodParameter("parameter1",Type.FLOAT,false);
        PARS3[1]=new MethodParameter("parameter2",Type.FLOAT,false);
        PARS3[2]=new MethodParameter("parameter3",Type.INT,true);
    }
    
    private static java.io.PrintWriter pw = null;
    
    public static void setPrintWriter(java.io.PrintWriter pr){
        pw=pr;
    }
    
    private static Type getType(int i) throws Exception {
        switch (i){
            case 0x0001: return Type.BOOLEAN;
            case 0x0002: return Type.INT      ;
            case 0x0003: return Type.CHAR;
            case 0x0004: return Type.BYTE;
            case 0x0005: return Type.SHORT ;
            case 0x0006: return Type.LONG;
            case 0x0007: return Type.FLOAT;
            case 0x0008: return Type.DOUBLE;
            case 0x0009: return Type.VOID;
        }
        throw new Exception("unknown type");
    }
    
    
    public Common() {
    }
    
    /** returns string from in and int
     * @param s
     * @param i
     * @return Makes String from String and int
     */
    public static String concat(String s, int i){
        return s+new Integer(i).toString();
    }
    
    
    
    /**
     * @param i
     * @return for i=1 "newMethod1"
     */
    static public String getMethodName(int i){
        return concat(METHODS,i);
    }
    
    /** Concats String and int
     * @param name
     * @param i
     * @return
     */
    public static String getFieldName(String name,int i){
        return concat(name,i);
    }
    
    /**
     * @param i
     * @return for i=1 "newField1"
     */
    public static String getFieldName(int i){
        return concat(FIELDS,i);
    }
    
    /**
     * @param name Name of method
     * @param modifiers Modifiers
     * @param returntype Return Type
     * @param pars Parameters
     * @return
     */
    public static MethodElement createMethod(String name, int modifiers, Type returntype, MethodParameter[] pars) throws Exception {
        MethodElement me = new MethodElement();
        me.setName(Identifier.create(name));
        me.setParameters(pars);
        me.setReturn(returntype);
        me.setExceptions(new Identifier[] { Identifier.create("java.io.IOException") });
        me.setModifiers(modifiers);
        me.setBody("\n/*This is body of mehod"+name+"*/\n"+DEFAULTBODY);
        return me;
    }
    
    /** Creates method with empty body, return type is int.
     * @param name Name of method
     * @throws Exception
     * @return
     */
    public static MethodElement createEmptyMethod(String name) throws Exception {
        MethodElement me = createMethod(name);
        me.setBody(null);
        return me;
    }
    
    /** Creates method. Retrun type is int.
     * @param name Name of new method
     * @throws Exception
     * @return
     */
    public static MethodElement createMethod(String name) throws Exception{
        return createMethod(name,DEFAULTMODIFIERS,Type.INT);
    }
    
    /**
     * @param name Name of new method
     * @param modifiers Modifiers
     * @param returntype Return Type
     * @throws Exception
     * @return
     */
    public static MethodElement createMethod(String name,int modifiers,int returntype) throws Exception {
        return createMethod(name, modifiers, getType(returntype));
    }
    
    /**
     * @param name Name of new method
     * @param modifiers Modifiers
     * @param returntype Return Type
     * @throws Exception
     * @return
     */
    public static MethodElement createMethod(String name,int modifiers,Type returntype) throws Exception {
        return createMethod(name, modifiers, returntype, new MethodParameter[] { });
    }
    
    
    /** Creates public float name;
     * @param name
     * @throws Exception
     * @return
     */
    public static FieldElement createField(String name) throws Exception {
        return createField(name, DEFAULTMODIFIERS, Type.FLOAT);
    }
    
    /** creates new field
     */
    public static FieldElement createField(String name, int modifiers, int type) throws Exception {
        return createField(name, modifiers, getType(type));
    }
    
    /** creates new field
     * @param name
     * @param modifiers
     * @param type
     * @throws Exception
     * @return
     */
    public static FieldElement createField(String name, int modifiers, Type type) throws Exception {
        FieldElement fe = new FieldElement();
        fe.setName(Identifier.create(name));
        fe.setModifiers(modifiers);
        fe.setType(type);
        return fe;
    }
    
    /** Creates new constructor with parameters
     * @param name
     * @param pars parameters
     * @throws Exception
     * @return
     */
    public static ConstructorElement createConstructor(Identifier name,MethodParameter[] pars) throws Exception {
        ConstructorElement ce = new ConstructorElement();
        ce.setParameters(pars);
        ce.setName(name);
        return ce;
    }
    
    /** creates new default constructor
     * @param name
     * @throws Exception
     * @return
     */
    public static ConstructorElement createConstructor(String name) throws Exception {
        return createConstructor(Identifier.create(name));
    }
    
    
    /** creates new default constructor
     * @param name
     * @throws Exception
     * @return
     */
    public static ConstructorElement createConstructor(Identifier name) throws Exception {
        ConstructorElement ce = new ConstructorElement();
        ce.setName(name);
        return ce;
    }
    
    /** Creates new initializer
     * @throws Exception
     * @return
     */
    public static InitializerElement createInitializer(boolean isStatic) throws Exception {
        InitializerElement ie = new InitializerElement();
        ie.setBody(DEFAULTINITIALIZERBODY);
        ie.setStatic(isStatic);
        return ie;
    }
    
    /** Creates new static initializer
     * @throws Exception
     * @return
     */
    public static InitializerElement createInitializer() throws Exception {
        return createInitializer(true);
    }
    
    /** Creates new Class from package
     * @param packageName destination
     * @param className name
     * @throws Exception
     * @return
     */
    
    public static ClassElement createClass(FileObject target, String packageName, String className) throws Exception   {
        DataObject dob = getSystemDO("Templates/Classes", "Class", "java");
        DataObject mdob = dob.createFromTemplate(org.openide.loaders.DataFolder.findFolder(getFO(target,packageName,null,null)), className);
        SourceCookie cookie = (SourceCookie) mdob.getCookie(SourceCookie.class);
        ClassElement clazz = cookie.getSource().getClasses()[0];
        return clazz;
    }
    /*
    public static ClassElement createClass(String packageName, String className) throws Exception   {
        DataObject dob = getDO("Templates.Classes", "Class", "java");
        DataObject mdob = dob.createFromTemplate(org.openide.loaders.DataFolder.findFolder(getFO(packageName,null,null)),className);
        SourceCookie cookie = (SourceCookie) mdob.getCookie(SourceCookie.class);
        ClassElement clazz = cookie.getSource().getClasses()[0];
        return clazz;
    }*/
    
    /** Creates new Class from package
     * @param packageName destination
     * @throws Exception
     * @return
     */
    /*public static ClassElement createClass(String packageName) throws Exception   {
        DataObject dob = getDO("Templates.Classes", "Class", "java");
        DataObject mdob = dob.createFromTemplate(org.openide.loaders.DataFolder.findFolder(getFO(packageName,null,null)));
        SourceCookie cookie = (SourceCookie) mdob.getCookie(SourceCookie.class);
        ClassElement clazz = cookie.getSource().getClasses()[0];
        return clazz;
    }*/
    
    
    /** Creates new interface from package
     * @param packageName destination
     * @param interfaceName name of interface
     * @throws Exception
     * @return
     */
   /* public static ClassElement createInterface(String packageName, String interfaceName) throws Exception {
        DataObject dob = getDO("Templates.Classes", "Interface", "java");
        DataObject mdob = dob.createFromTemplate(org.openide.loaders.DataFolder.findFolder(getFO(packageName,null,null)),interfaceName);
        SourceCookie cookie = (SourceCookie) mdob.getCookie(SourceCookie.class);
        ClassElement iface = cookie.getSource().getClasses()[0];
        return iface;
    }*/
    
    
    /** Get a file object by name. */
    public static org.openide.filesystems.FileObject getFO(FileObject file, String pkg, String name, String ext) throws Exception {
        ClassPath cp=ClassPath.getClassPath(file, ClassPath.SOURCE);
        String nam=(pkg != null && pkg.length() > 0)?pkg:"";
        nam+=(name != null && name.length() > 0)?".":"";
        nam=nam.replace('.', '/');
        nam+=(name != null && name.length() > 0)?name:"";
        nam+=(ext != null && ext.length() > 0)?"."+ext:"";
        //check
        FileObject[] root=cp.getRoots();
        FileObject ret=cp.findResource(nam);
        return ret;
    }
    
    /** Get a data object by name. */
    public static DataObject getSystemDO(String pkg, String name, String ext) throws Exception {
        return DataObject.find(Repository.getDefault().getDefaultFileSystem().findResource(pkg+"/"+name+"."+ext));
    }
    
    /** Generates SimpleJavaTestSourceEtalon
     * @param clazz where to generate
     * @throws Exception
     */
    public static void simpleJavaSourceEtalonGenerator(ClassElement clazz) throws Exception {
        
        clazz.removeConstructors(clazz.getConstructors());
        clazz.addMethod(Common.createMethod("method1", Modifier.PUBLIC | Modifier.STATIC, Type.INT, PARS1));
        clazz.addField(Common.createField("field1",Modifier.PUBLIC | Modifier.STATIC, Type.FLOAT));
        clazz.addInitializer(Common.createInitializer());
        clazz.addMethod(Common.createMethod("method1", Modifier.PUBLIC | Modifier.STATIC, Type.INT, PARS2));
        clazz.addField(Common.createField("field2",Modifier.PUBLIC | Modifier.STATIC, Type.INT));
        clazz.addConstructor(Common.createConstructor(clazz.getName()));
        clazz.addConstructor(Common.createConstructor(clazz.getName(),PARS1));
        
        clazz.addMethod(Common.createMethod("method1", Modifier.PUBLIC | Modifier.STATIC, Type.INT, PARS3));
        clazz.addInitializer(Common.createInitializer());
        clazz.addMethod(Common.createMethod("method2", Modifier.PUBLIC | Modifier.STATIC, Type.INT, PARS1));
        clazz.addField(Common.createField("field3",Modifier.PUBLIC | Modifier.STATIC, Type.SHORT));
        clazz.addConstructor(Common.createConstructor(clazz.getName(),PARS2));
        clazz.addMethod(Common.createMethod("method2", Modifier.PUBLIC | Modifier.STATIC, Type.SHORT, PARS2));
        clazz.addInitializer(Common.createInitializer());
        clazz.addMethod(Common.createMethod("method2", Modifier.PUBLIC | Modifier.STATIC, Type.LONG, PARS3));
        
        ClassElement innerClass = new ClassElement();
        
        innerClass.addMethod(Common.createMethod("method2", Modifier.PUBLIC , Type.VOID, PARS3));
        
        //BUGY
        innerClass.setName(Identifier.create("InnerClass","InnerClass"));
        innerClass.addField(Common.createField("field2",Modifier.PUBLIC | Modifier.VOLATILE, Type.INT));
        
        
        ClassElement innerIface = new ClassElement();
        innerIface.setClassOrInterface(false);
        
        //BUGY
        innerIface.setName(Identifier.create("InnerInterface", "InnerInterface"));
        innerIface.addMethod(Common.createEmptyMethod("interfaceMethod"));
        
        clazz.addClass(innerClass);
        clazz.addClass(innerIface);
        
        
    }
    
    /** Compares two Arrays
     * @param l
     * @param r
     * @return
     */
    public static boolean arrayEquals(Object[] l,Object[] r) {
        if (l.length!=r.length) return false;
        for (int i=0; i < l.length; i++){
            if (!l[i].equals(r[i])) return false;
        }
        return true;
    }
    
    /** Removes time and author's name
     * @param result
     * @return
     */
    public static String unify(String result) {
        int left=result.indexOf("* Created on");
        int right=result.indexOf('\n',left);
        if (left > -1)
            result=result.substring(0,left+"* Created on".length())+result.substring(right);
        
        left=result.indexOf("@author");
        right=result.indexOf('\n',left);
        if (left > -1)
            result=result.substring(0,left+"@author".length())+result.substring(right);
        return result;
    }
    
    /**
     * @param str
     * @return
     */
    public static String firstCharToUpper(String str) {
        String    first, rest;
        
        if( str==null || str.equals("") )
            return str;
        
        first = str.substring(0, 1).toUpperCase();
        rest = str.substring( 1 );
        return first+rest;
    }
    
    /**
     * @param str
     * @return
     */
    public static String firstCharToLower(String str) {
        String first, rest;
        
        if( str==null || str.equals("") )
            return( str );
        
        first = str.substring(0, 1).toLowerCase();
        rest = str.substring( 1 );
        
        return first+rest;
    }
    
    /**
     * @param declaringClass
     * @return
     */
    public static MethodElement createEqualsMethod(ClassElement declaringClass) throws Exception {
        MethodParameter   parameter=new MethodParameter("obj", Type.createFromClass(java.lang.Object.class), false),
        parameters[]=new MethodParameter[1];
        FieldElement[]    fields=declaringClass.getFields();
        String            className=declaringClass.getName().getName(),
        methodName="equals",
        body=cr+"    if( obj==null ||"+
        cr+"        !this.getClass().equals(obj.getClass()) ) return( false );" + cr;
        Type              returnType=Type.BOOLEAN;
        
        //set body
        if( fields.length>0 )
            body += "    " + className + " o=(" + className + ") obj;" + cr;
        for( int i=0; i
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.