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-2002 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.examples.modules.unhardcode;

import java.io.*;
import java.lang.reflect.Modifier;
import java.util.*;
import org.openide.ErrorManager;
import org.openide.cookies.SourceCookie;
import org.openide.filesystems.*;
import org.openide.loaders.DataFolder;
import org.openide.loaders.DataObject;
import org.openide.nodes.Node;
import org.openide.src.*;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.util.actions.CookieAction;

/** Action which replaces hardcoded constants in source files
 * with references to a property file.
 * Demonstrates the Filesystems, Datasystems, Actions, Nodes, and Java Hierarchy APIs.
 */
public class UnHardCodeAction extends CookieAction {
    
    /** Cookies relevant to this action.
     * @return the cookie for source files and the cookie for folders
     */    
    protected Class[] cookieClasses() {
        return new Class[] {SourceCookie.class, DataFolder.class};
    }
    
    /** How many nodes we expect the cookies on.
     * @return every selected node
     */    
    protected int mode() {
        return MODE_ALL;
    }
    
    /** Run the action.
     * @param nodes the nodes which are currently selected
     */    
    protected void performAction(Node[] nodes) {
        if (nodes != null) {
            for (int i = 0; i < nodes.length; i++) {
                DataObject d = (DataObject)nodes[i].getCookie(DataObject.class);
                if (d != null) {
                    handle(d);
                }
            }
        }
    }
    
    /** Handle one folder or Java source file.
     * @param d the data object to look at
     */    
    private void handle(DataObject d) {
        if (d instanceof DataFolder) {
            DataObject[] children = ((DataFolder)d).getChildren();
            for (int i = 0; i < children.length; i++) {
                handle(children[i]);
            }
            return;
        }
        SourceCookie sc = (SourceCookie)d.getCookie(SourceCookie.class);
        if (sc == null) {
            return;
        }
        SourceElement se = sc.getSource();
        if (se.getPackage() == null) {
            return;
        }
        ClassElement[] classes = se.getAllClasses();
        Map hardCodedFields = new HashMap(); // Map
        for (int i = 0; i < classes.length; i++) {
            scanForHardCodedFields(classes[i], hardCodedFields);
        }
        if (hardCodedFields.isEmpty()) {
            return;
        }
        // XXX display confirmation first
        Properties p = createProperties(hardCodedFields, se);
        if (p == null) {
            // Unable to change source code.
            return;
        }
        write(p, d.getFolder().getPrimaryFile());
    }
    
    /** Look for hard-coded constants that could be replaced.
     * @param ce the Java source class to look in
     * @param hardCodedFields a map from FieldElements
     *                        to Integers or Strings
     */    
    private void scanForHardCodedFields(ClassElement ce, Map hardCodedFields) {
        FieldElement[] fields = ce.getFields();
        for (int j = 0; j < fields.length; j++) {
            int mods = fields[j].getModifiers();
            if (!Modifier.isStatic(mods) || !Modifier.isFinal(mods)) {
                continue;
            }
            Type type = fields[j].getType();
            String init = fields[j].getInitValue().trim();
            if (type.equals(Type.INT)) {
                try {
                    hardCodedFields.put(fields[j],
                        new Integer(Integer.parseInt(init)));
                } catch (NumberFormatException nfe) {
                    // OK, not an integer literal
                }
            } else if (type.equals(Type.createFromClass(String.class))) {
                if (init.startsWith("\"") && init.endsWith("\"")) {
                    // XXX handle "foo" + "bar", or "foo\"bar"
                    hardCodedFields.put(fields[j],
                        init.substring(1, init.length() - 1));
                }
            }
        }
    }
    
    /** Actually replace source fields with initializers, and create the
     * body of the resulting constants properties file.
     * @param hardCodedFields the map from field elements to values
     * @param se the source file to substitute
     * @return a properties mapping, or null if the substitutions failed
     */    
    private Properties createProperties(final Map hardCodedFields, SourceElement se) {
        final String pkg = se.getPackage().getFullName();
        final Properties p = new Properties();
        final boolean[] ok = {true};
        class CPAction implements Runnable {
            public void run() {
                Iterator it = hardCodedFields.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry entry = (Map.Entry)it.next();
                    FieldElement field = (FieldElement)entry.getKey();
                    Object value = entry.getValue();
                    String key = field.getDeclaringClass().getName().getFullName() +
                                 "." + field.getName();
                    if (key.startsWith(pkg + ".")) {
                        key = key.substring(pkg.length() + 1);
                    } else {
                        throw new IllegalStateException();
                    }
                    String bundleInit = "java.util.ResourceBundle.getBundle(\"" + pkg +
                                        ".constants\").getString(\"" + key + "\")";
                    try {
                        if (field.getType().equals(Type.INT)) {
                            field.setInitValue("Integer.parseInt(" + bundleInit + ")");
                        } else if (field.getType().equals(
                                Type.createFromClass(String.class))) {
                            field.setInitValue(bundleInit);
                        } else {
                            throw new IllegalStateException();
                        }
                    } catch (SourceException sx) {
                        ErrorManager.getDefault().notify(ErrorManager.WARNING, sx);
                        ok[0] = false;
                        return;
                    }
                    p.setProperty(key, value.toString());
                }
            }
        }
        try {
            se.runAtomicAsUser(new CPAction());
        } catch (SourceException sx) {
            // Attempted modification to guarded fields.
            ErrorManager.getDefault().notify(ErrorManager.WARNING, sx);
            return null;
        }
        return ok[0] ? p : null;
    }
    
    /** Write a generated constants properties file to disk.
     * @param p the properties to write
     * @param folder the folder in which a constants.properties file
     *               should be written
     */    
    private void write(final Properties p, final FileObject folder) {
        class WAction implements FileSystem.AtomicAction {
            public void run() throws IOException {
                FileObject propfile =
                    folder.getFileObject("constants", "properties");
                FileLock lock = null;
                try {
                    if (propfile != null) {
                        // Append to old file.
                        lock = propfile.lock();
                        InputStream is = propfile.getInputStream();
                        Properties old = new Properties();
                        try {
                            old.load(is);
                        } finally {
                            is.close();
                        }
                        old.putAll(p);
                        p.putAll(old);
                    } else {
                        // Create new file.
                        propfile = folder.createData("constants", "properties");
                        lock = propfile.lock();
                    }
                    OutputStream os = propfile.getOutputStream(lock);
                    try {
                        p.store(os, " Un-hardcoded constants");
                    } finally {
                        os.close();
                    }
                } finally {
                    if (lock != null) {
                        lock.releaseLock();
                    }
                }
            }
        }
        try {
            folder.getFileSystem().runAtomicAction(new WAction());
        } catch (IOException ioe) {
            ErrorManager.getDefault().notify(ioe);
        }
    }
    
    /** Get the display name of the action.
     * @return the localized name
     */    
    public String getName() {
        return NbBundle.getMessage(UnHardCodeAction.class, "LBL_un_hard_code");
    }
    
    /** Get an icon for the action.
     * @return a special icon
     */    
    protected String iconResource() {
        return "org/netbeans/examples/modules/unhardcode/unHardCode.gif";
    }
    
    /** Get any JavaHelp available for this action.
     * @return no special help
     */    
    public HelpCtx getHelpCtx() {
        return HelpCtx.DEFAULT_HELP;
    }
    
}
... 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.