Java Code Examples for org.openide.cookies.InstanceCookie#instanceCreate()

The following examples show how to use org.openide.cookies.InstanceCookie#instanceCreate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InstanceDataObjectLookupWarningTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** #28118, win sys relies that instance data object fires cookie 
 * changes when its settings file removed, it gets into corruped state otherwise. */
public void testNoWarnings() throws Exception {
    CharSequence log = Log.enable("org.openide.loaders", Level.WARNING);
    
    FileObject fo = FileUtil.createData(lfs.getRoot(), "x.instance");
    fo.setAttribute("instanceClass", "javax.swing.JButton");
    DataObject obj = DataObject.find(fo);
    assertEquals("IDO", InstanceDataObject.class, obj.getClass());
    
    InstanceCookie ic = obj.getLookup().lookup(InstanceCookie.class);
    assertNotNull("We have cookie", ic);
    
    Object o = ic.instanceCreate();
    assertNotNull("Obj created", o);
    
    assertEquals("button", JButton.class, o.getClass());
    
    if (log.length() > 0) {
        fail("No warnings, but: " + log);
    }
}
 
Example 2
Source File: ConvertAsBeanTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testReadWriteOnSubclass() throws Exception {
    HooFoo foo = new HooFoo();
    foo.setName("xxx");

    DataFolder test = DataFolder.findFolder(FileUtil.getConfigRoot());
    DataObject obj = InstanceDataObject.create(test, null, foo, null);
    final FileObject pf = obj.getPrimaryFile();
    final String content = pf.asText();
    if (content.indexOf("<string>xxx</string>") == -1) {
        fail(content);
    }
    obj.setValid(false);
    DataObject newObj = DataObject.find(pf);
    if (newObj == obj) {
        fail("Strange, objects shall differ");
    }
    InstanceCookie ic = newObj.getLookup().lookup(InstanceCookie.class);
    assertNotNull("Instance cookie found", ic);

    Object read = ic.instanceCreate();
    assertNotNull("Instance created", read);
    assertEquals("Correct class", HooFoo.class, read.getClass());
    HooFoo readFoo = (HooFoo)read;
    assertEquals("property changed", "xxx", readFoo.getName());
}
 
Example 3
Source File: MenuBar.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
           * Accepts only cookies that can provide <code>Menu</code>.
           * @param cookie an <code>InstanceCookie</code> to test
           * @return true if the cookie can provide accepted instances
           */
  	    protected @Override InstanceCookie acceptCookie(InstanceCookie cookie)
  	    throws IOException, ClassNotFoundException {
// [pnejedly] Don't try to optimize this by InstanceCookie.Of
// It will load the classes few ms later from instanceCreate
// anyway and more instanceOf calls take longer
          	Class c = cookie.instanceClass();
              boolean action = Action.class.isAssignableFrom (c);
              if (action) {
                  cookie.instanceCreate();
              }
          	boolean is =
              	Presenter.Menu.class.isAssignableFrom (c) ||
              	JMenuItem.class.isAssignableFrom (c) ||
              	JSeparator.class.isAssignableFrom (c) ||
                  action;
          	return is ? cookie : null;
  	    }
 
Example 4
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static Action findAction( String key ) {
    FileObject fo = FileUtil.getConfigFile(key);
    
    if (fo != null && fo.isValid()) {
        try {
            DataObject dob = DataObject.find(fo);
            InstanceCookie ic = dob.getCookie(InstanceCookie.class);
            
            if (ic != null) {
                Object instance = ic.instanceCreate();
                if (instance instanceof Action) {
                    Action a = (Action) instance;
                    return a;
                }
            }
        } catch (Exception e) {
            ErrorManager.getDefault().notify(ErrorManager.WARNING, e);
            return null;
        }
    }
    return null;
}
 
Example 5
Source File: SerialDataNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void init() {
    try {
        InstanceCookie ic = (InstanceCookie) dobj.getCookie(InstanceCookie.class);
        if (ic == null) {
            bean = null;
            return;
        }
        Class<?> clazz = ic.instanceClass();
        if (BeanContext.class.isAssignableFrom(clazz)) {
            bean = ic.instanceCreate();
        } else if (BeanContextProxy.class.isAssignableFrom(clazz)) {
            bean = ((BeanContextProxy) ic.instanceCreate()).getBeanContextProxy();
        } else {
            bean = null;
        }
    } catch (Exception ex) {
        bean = null;
        Exceptions.printStackTrace(ex);
    }
    if (bean != null) {
        // attaches a listener to the bean
        ((BeanContext) bean).addBeanContextMembershipListener (contextL);
    }
    updateKeys();
}
 
Example 6
Source File: DatabaseConnectionConvertor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the file describing the specified database connection.
 */
public static void remove(DatabaseConnection dbconn) throws IOException {
    String name = dbconn.getName();
    FileObject fo = FileUtil.getConfigFile(CONNECTIONS_PATH); //NOI18N
    // If CONNECTIONS_PATH can't be found (getConfigFile returns null)
    // its useless to try to delete any connection
    if (fo == null) {
        return;
    }
    DataFolder folder = DataFolder.findFolder(fo);
    DataObject[] objects = folder.getChildren();
    
    for (int i = 0; i < objects.length; i++) {
        InstanceCookie ic = objects[i].getCookie(InstanceCookie.class);
        if (ic != null) {
            Object obj;
            try {
                obj = ic.instanceCreate();
            } catch (ClassNotFoundException e) {
                continue;
            }
            if (obj instanceof DatabaseConnection) {
                DatabaseConnection connection = (DatabaseConnection)obj;
                if (connection.getName().equals(name)) {
                    objects[i].delete();
                    break;
                }
            }
        }
    }
}
 
Example 7
Source File: WebBrowsersOptionsModel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void findPropertyPanel() {
    
    try {
        
        InstanceCookie cookie = browserSettings.getCookie(InstanceCookie.class);
        PropertyDescriptor[] propDesc = Introspector.getBeanInfo(cookie.instanceClass()).getPropertyDescriptors();
        
        PropertyDescriptor fallbackProp = null;
        
        for (PropertyDescriptor pd : propDesc ) {
            
            if (fallbackProp == null && !pd.isExpert() && !pd.isHidden()) {
                fallbackProp = pd;
            }
            
            if (pd.isPreferred() && !pd.isExpert() && !pd.isHidden()) {
                propertyPanel = new PropertyPanel(cookie.instanceCreate(), 
                        pd.getName(), PropertyPanel.PREF_CUSTOM_EDITOR);
                propertyPanelID = "PROPERTY_PANEL_" + propertyPanelIDCounter++;
                propertyPanel.setChangeImmediate(false);
                break;
            }
            
        }
        
        if (propertyPanel == null) {
            propertyPanel = new PropertyPanel(cookie.instanceCreate(),
                    fallbackProp.getName(), PropertyPanel.PREF_CUSTOM_EDITOR);
            propertyPanelID = "PROPERTY_PANEL_" + propertyPanelIDCounter++;
        }
        
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
    
}
 
Example 8
Source File: InstanceDataObjectTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Test whether instances survive garbage collection.
 */
public void testSameWithGC () throws Exception {
    Object ser = new Button();
    
    FileObject prim = InstanceDataObject.create (folder, "MyName", ser, null).getPrimaryFile ();
    String name = prim.getName ();
    String ext = prim.getExt ();
    prim = null;

    System.gc ();
    System.gc ();
    System.gc ();
    System.gc ();
    System.gc ();
    System.gc ();
    System.gc ();
    System.gc ();
    System.gc ();
    
    FileObject fo = folder.getPrimaryFile ().getFileObject (name, ext);
    assertTrue ("MyName.settings not found", fo != null);
    
    DataObject obj = DataObject.find (fo);
    
    InstanceCookie ic = (InstanceCookie)getCookie (obj, InstanceCookie.class);
    assertTrue ("Object: " + obj + " does not have instance cookie", ic != null);
    
    Object value = ic.instanceCreate ();
    if (value != ser) {
        fail ("Value is different than serialized: " + System.identityHashCode (ser) + " value: " + System.identityHashCode (value));
    }
    
    obj.delete ();
}
 
Example 9
Source File: ToolbarPoolDeadlockTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Object writeInstance (final FileObject folder, final String name, final Object inst) throws IOException {
    class W implements FileSystem.AtomicAction {
        public Object create;
        
        public void run () throws IOException {
            FileObject fo = FileUtil.createData (folder, name);
            FileLock lock = fo.lock ();
            ObjectOutputStream oos = new ObjectOutputStream (fo.getOutputStream (lock));
            oos.writeObject (inst);
            oos.close ();
            lock.releaseLock ();
            
            DataObject obj = DataObject.find (fo);
            InstanceCookie ic = obj.getCookie(InstanceCookie.class);
            
            assertNotNull ("Cookie created", ic);
            try {
                create = ic.instanceCreate ();
                assertEquals ("The same instance class", inst.getClass(), create.getClass ());
            } catch (ClassNotFoundException ex) {
                fail (ex.getMessage ());
            }
        }
    }
    W w = new W ();
    folder.getFileSystem ().runAtomicAction (w);
    return w.create;
}
 
Example 10
Source File: InstanceDataObjectRefreshesOnFileChangeTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void assertInstance(Lookup lkp, Object instance) throws Exception {
    InstanceCookie ic = lkp.lookup(InstanceCookie.class);
    assertNotNull("InstanceCookie found", ic);
    Object o = ic.instanceCreate();
    assertNotNull("Instance created", o);
    assertEquals("Same as expected", instance, o);
}
 
Example 11
Source File: InstanceSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Find context help for some instance.
* Helper method useful in nodes or data objects that provide an instance cookie;
* they may choose to supply their own help context based on this.
* All API classes which can provide help contexts will be tested for
* (including <code>HelpCtx</code> instances themselves).
* <code>JComponent</code>s are checked for an attached help ID property,
* as with {@link HelpCtx#findHelp(java.awt.Component)} (but not traversing parents).
* <p>Also, partial compliance with the JavaHelp section on JavaBeans help is implemented--i.e.,
* if a Bean in its <code>BeanInfo</code> provides a <code>BeanDescriptor</code> which
* has the attribute <code>helpID</code>, this will be returned. The value is not
* defaulted (because it would usually be nonsense and would mask a useful default
* help for the instance container), nor is the help set specification checked,
* since someone should have installed the proper help set anyway, and the APIs
* cannot add a new reference to a help set automatically.
* See <code>javax.help.HelpUtilities.getIDStringFromBean</code> for details.
* <p>Special IDs are added, corresponding to the class name, for all standard visual components.
* @param instance the instance to check for help (it is permissible for the {@link InstanceCookie#instanceCreate} to return <code>null</code>)
* @return the help context found on the instance or inferred from a Bean,
* or <code>null</code> if none was found (or it was {@link HelpCtx#DEFAULT_HELP})
 *
 *
 * @deprecated use org.openide.util.HelpCtx.findHelp (Object)
*/
@Deprecated
public static HelpCtx findHelp (InstanceCookie instance) {
    try {
        Class<?> clazz = instance.instanceClass();
        // [a.n] I have moved the code here as those components's BeanInfo do not contain helpID
        // - it is faster
        // Help on some standard components. Note that borders/layout managers do not really work here.
        if (java.awt.Component.class.isAssignableFrom (clazz) || java.awt.MenuComponent.class.isAssignableFrom (clazz)) {
            String name = clazz.getName ();
            String[] pkgs = new String[] { "java.awt.", "javax.swing.", "javax.swing.border." }; // NOI18N
            for (int i = 0; i < pkgs.length; i++) {
                if (name.startsWith (pkgs[i]) && name.substring (pkgs[i].length ()).indexOf ('.') == -1)
                    return new HelpCtx (name);
            }
        }
        Object o = instance.instanceCreate();
        if (o != null && o != instance) {
            HelpCtx h = HelpCtx.findHelp(o);
            if (h != HelpCtx.DEFAULT_HELP) {
                return h;
            }
        }
    } catch (Exception e) {
        // #63238: Ignore - generally not important context for us to be checking errors.
    }
    return null;
}
 
Example 12
Source File: InstanceNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void propertyChange(PropertyChangeEvent evt) {
    if (evt != null && !evt.getPropertyName().equals(InstanceDataObject.PROP_COOKIE)) return;
    
    if (contextL != null && bean != null) {
        ((BeanContext) bean).removeBeanContextMembershipListener(contextL);
    }
    
    try {
        InstanceCookie ic = dobj.getCookie(InstanceCookie.class);
        if (ic == null) {
            bean = null;
            return;
        }
        Class<?> clazz = ic.instanceClass();
        if (BeanContext.class.isAssignableFrom(clazz)) {
            bean = ic.instanceCreate();
        } else if (BeanContextProxy.class.isAssignableFrom(clazz)) {
            bean = ((BeanContextProxy) dobj.instanceCreate()).getBeanContextProxy();
        } else {
            bean = null;
        }
    } catch (Exception ex) {
        bean = null;
        Exceptions.printStackTrace(ex);
    }
    if (bean != null) {
        // attaches a listener to the bean
        ((BeanContext) bean).addBeanContextMembershipListener (contextL);
    }
    updateKeys();
}
 
Example 13
Source File: AnnotationViewDataImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void computeInstances() {
    ArrayList<MarkProviderCreator> newCreators = new ArrayList<MarkProviderCreator>();
    ArrayList<UpToDateStatusProviderFactory> newFactories = new ArrayList<UpToDateStatusProviderFactory>();
    
    for(FileObject f : instanceFiles) {
        if (!f.isValid() || !f.isData()) {
            continue;
        }
        
        try {
            DataObject d = DataObject.find(f);
            InstanceCookie ic = d.getLookup().lookup(InstanceCookie.class);
            if (ic != null) {
                if (MarkProviderCreator.class.isAssignableFrom(ic.instanceClass())) {
                    MarkProviderCreator creator = (MarkProviderCreator) ic.instanceCreate();
                    newCreators.add(creator);
                } else if (UpToDateStatusProviderFactory.class.isAssignableFrom(ic.instanceClass())) {
                    UpToDateStatusProviderFactory factory = (UpToDateStatusProviderFactory) ic.instanceCreate();
                    newFactories.add(factory);
                }
            }
        } catch (Exception e) {
            LOG.log(Level.WARNING, null, e);
        }
    }
    
    this.creators = newCreators;
    this.factories = newFactories;
}
 
Example 14
Source File: SerialDataNodeTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDisplayName() throws Exception {
    String res = "Settings/org-netbeans-modules-settings-convertors-testDisplayName.settings";
    FileObject fo = FileUtil.getConfigFile(res);
    assertNotNull(res, fo);
    assertNull("name", fo.getAttribute("name"));
    
    DataObject dobj = DataObject.find (fo);
    Node n = dobj.getNodeDelegate();
    assertNotNull(n);
    assertEquals("I18N", n.getDisplayName());
    
    // property sets have to be initialized otherwise the change name would be
    // propagated to the node after some delay (~2s)
    Object garbage = n.getPropertySets();
    
    InstanceCookie ic = (InstanceCookie) dobj.getCookie(InstanceCookie.class);
    assertNotNull (dobj + " does not contain instance cookie", ic);
    
    FooSetting foo = (FooSetting) ic.instanceCreate();
    String newName = "newName";
    foo.setName(newName);
    assertEquals(n.toString(), newName, n.getDisplayName());
    
    newName = "newNameViaNode";
    n.setName(newName);
    assertEquals(n.toString(), newName, n.getDisplayName());
    assertEquals(n.toString(), newName, foo.getName());
}
 
Example 15
Source File: LayersBridge.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns instance of GlobalAction encapsulating action, or null.
 */
private GlobalAction createAction (DataObject dataObject, String prefix, String name, boolean ignoreUserRemoves) {
    InstanceCookie ic = dataObject.getCookie(InstanceCookie.class);
    // handle any non-IC file as instruction to remove the action
    FileObject pf = dataObject.getPrimaryFile();
    if (ignoreUserRemoves && pf.canRevert()) {
        return null;
    }
    if (ic == null) {
        if (!EXT_REMOVED.equals(pf.getExt())) {
            LOG.log(Level.WARNING, "Invalid shortcut: {0}", dataObject);
            return null;
        }
        // ignore the 'remove' file, if there's a shadow (= real action) present
        if (FileUtil.findBrother(pf, "shadow") != null) {
            // handle redefinition + removal: ignore the removal.
            return null;
        }
        return REMOVED;
    }
    try {
        Object action = ic.instanceCreate ();
        if (action == null) return null;
        if (!(action instanceof Action)) return null;
        return createAction((Action) action, prefix, name);
    } catch (Exception ex) {
        ex.printStackTrace ();
        return null;
    }
}
 
Example 16
Source File: DefaultJavaPlatformProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public JavaPlatform[] getInstalledPlatforms() {
    final List<JavaPlatform> platforms = new ArrayList<JavaPlatform>();
    final FileObject storage = getStorage();
    if (storage != null) {
        for (FileObject platformDefinition : storage.getChildren()) {
            try {
                final DataObject dobj = DataObject.find(platformDefinition);
                final InstanceCookie ic = dobj.getCookie(InstanceCookie.class);
                if (ic == null) {
                    LOG.log(
                        Level.WARNING,
                        "The file: {0} has no InstanceCookie",  //NOI18N
                        platformDefinition.getNameExt());
                    continue;
                } else  if (ic instanceof InstanceCookie.Of) {
                    if (((InstanceCookie.Of)ic).instanceOf(JavaPlatform.class)) {
                        platforms.add((JavaPlatform) ic.instanceCreate());
                    } else {
                        LOG.log(
                            Level.WARNING,
                            "The file: {0} is not an instance of JavaPlatform", //NOI18N
                            platformDefinition.getNameExt());
                    }
                } else {
                    Object instance = ic.instanceCreate();
                    if (instance instanceof JavaPlatform) {
                        platforms.add((JavaPlatform) instance);
                    } else {
                        LOG.log(
                            Level.WARNING,
                            "The file: {0} is not an instance of JavaPlatform", //NOI18N
                            platformDefinition.getNameExt());
                    }
                }
            } catch (ClassNotFoundException | IOException e) {
                Exceptions.printStackTrace(e);
            }
        }
    }
    return platforms.toArray(new JavaPlatform[platforms.size()]);
}
 
Example 17
Source File: InstanceNode.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** try to initialize display name.
*/
public void run() {
    try {
        InstanceCookie ic = ic();
        if (ic == null) {
            return;
        }
        Class<?> clazz = ic.instanceClass();
    
    String className = clazz.getName ();
    if (className.equals ("javax.swing.JSeparator") || // NOI18N
        className.equals ("javax.swing.JToolBar$Separator")) { // NOI18N
            
        setDisplayName (NbBundle.getMessage (InstanceDataObject.class,
            "LBL_separator_instance")); // NOI18N
        return;
    }
    // Also specially handle action instances.
    if (Action.class.isAssignableFrom(clazz)) {
        Action action = (Action)ic.instanceCreate();
        // Set node's display name.
        String name = action != null ? (String)action.getValue(Action.NAME) : null;
        
        // #31227 - some action does not implement its name properly.
        // Throw exception with the name of the class.
        if (name == null) {
            DataObject.LOG.warning(
                "Please attach following information to the issue " + // NOI18N
                "<http://www.netbeans.org/issues/show_bug.cgi?id=31227>: " + // NOI18N
                "action " + className + " does not implement SystemAction.getName() or Action.getValue(NAME) properly. It returns null!"); // NOI18N
            setDisplayName(className);
            return;
        }
        
        int amper = name.indexOf ('&');
        if (amper != -1) {
            name = name.substring (0, amper) + name.substring (amper + 1);
        }
        if (name.endsWith ("...")) {// NOI18N
            name = name.substring (0, name.length () - 3);
        }
        name = name.trim ();
        setDisplayName (name);
        return;
    }
    } catch (Exception e) {
        Logger.getLogger(InstanceNode.class.getName()).log(Level.WARNING, null, e);
        setDisplayName(getDataObject().getName());
        return;
    }
}
 
Example 18
Source File: ExplorerContextMenuFactory.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
private List<Action>[] getActions(FileObject actionsFO, boolean allowDefaultActions) {
    // Init caches for default and regular context menu actions
    List<Action> defaultActions = new ArrayList();
    List<Action> actions = new ArrayList();
    
    if (actionsFO != null) {
        
        DataFolder actionsDF = DataFolder.findFolder(actionsFO);
        DataObject[] menuItems = actionsDF.getChildren();
        
        for (DataObject menuItemDO : menuItems) {
            
            FileObject fobj = menuItemDO.getPrimaryFile();
            
            if (fobj.isFolder()) {
                LOGGER.log(Level.WARNING, "Nested menus not supported for Applications context menu: " + fobj, fobj);   // NOI18N
            } else {
                InstanceCookie menuItemCookie = (InstanceCookie)menuItemDO.getCookie(InstanceCookie.class);
                try {
                    Object menuItem = menuItemCookie.instanceCreate();
                    
                    boolean isDefaultAction = false;
                    Object isDefaultActionObj = fobj.getAttribute("default");   // NOI18N
                    if (isDefaultActionObj != null) try {
                        isDefaultAction = (Boolean)isDefaultActionObj;
                        if (!allowDefaultActions && isDefaultAction)
                            LOGGER.log(Level.WARNING, "Default actions not supported for " + actionsFO.getPath() + ": " + menuItem, menuItem);  // NOI18N
                    } catch (Exception e) {
                        LOGGER.log(Level.WARNING, "Cannot determine whether context menu action is default: " + isDefaultActionObj, isDefaultActionObj);    // NOI18N
                    }
    
                    List<Action> actionsList = isDefaultAction ? defaultActions : actions;
    
                    if (menuItem instanceof Action) {
                        Action action = (Action)menuItem;
                        if (action.isEnabled()) actionsList.add(action);
                    } else if (menuItem instanceof JSeparator) {
                        if (isDefaultAction) {
                            LOGGER.log(Level.WARNING, "Separator cannot be added to default actions " + menuItem, menuItem);    // NOI18N
                        } else {
                            actionsList.add(null);
                        }
                    } else {
                        LOGGER.log(Level.WARNING, "Unsupported context menu item: " + menuItem, menuItem);  // NOI18N
                    }
                } catch (Exception ex) {
                    LOGGER.log(Level.SEVERE, "Unable to resolve context menu action: " + menuItemDO, menuItemDO);   // NOI18N
                }
            }
        }
    
    }
    
    // Return actions
    return new List[] { cleanupActions(defaultActions), cleanupActions(actions) };
}
 
Example 19
Source File: ActionsList.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static Pair convertImpl(List<FileObject> keys, boolean ignoreFolders,
        boolean prohibitSeparatorsAndActionNames)
{
    List<Object> all = new ArrayList<Object>();
    List<Action> actions = new ArrayList<Action>();

    for (FileObject item : keys) {
        DataObject dob;
        try {
            dob = DataObject.find(item);
            if (dob == null && prohibitSeparatorsAndActionNames) {
                if (LOG.isLoggable(Level.INFO)) {
                    LOG.info("ActionsList: DataObject is null for item=" + item + "\n"); //NOI18N
                }
            }
        } catch (DataObjectNotFoundException dnfe) {
            if (prohibitSeparatorsAndActionNames) {
                if (LOG.isLoggable(Level.INFO)) {
                    LOG.info("ActionsList: DataObject not found for item=" + item + "\n"); //NOI18N
                }
            } else {
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.log(Level.FINE, "DataObject not found for action fileObject=" + item); //NOI18N
                }
            }
            continue; // ignore
        }

        Object toAdd = null;
        InstanceCookie ic = dob.getLookup().lookup(InstanceCookie.class);
        if (prohibitSeparatorsAndActionNames && ic == null) {
            if (LOG.isLoggable(Level.INFO)) {
                LOG.info("ActionsList: InstanceCookie not found for item=" + item + "\n"); //NOI18N
            }
            continue;
        }
        if (ic != null) {
            try {
                if (!isSeparator(ic)) {
                    toAdd = ic.instanceCreate();
                    if (toAdd == null && prohibitSeparatorsAndActionNames) {
                        if (LOG.isLoggable(Level.INFO)) {
                            LOG.info("ActionsList: InstanceCookie.instanceCreate() null for item=" + item + "\n"); //NOI18N
                        }
                    }
                }
            } catch (Exception e) {
                LOG.log(Level.INFO, "Can't instantiate object", e); //NOI18N
                continue;
            }
        } else if (dob instanceof DataFolder) {
            toAdd = dob;
        } else {
            toAdd = dob.getName();
        }

        // Filter out the same succeding items
        if (all.size() > 0) {
            Object lastOne = all.get(all.size() - 1);
            if (Utilities.compareObjects(lastOne, toAdd)) {
                continue;
            }
            if (isSeparator(lastOne) && isSeparator(toAdd)) {
                continue;
            }
        }
        
        if (toAdd instanceof Action) {
            Action action = (Action) toAdd;
            actions.add(action);
            AcceleratorBinding.setAccelerator(action, item);
        } else if (isSeparator(toAdd)) {
            if (prohibitSeparatorsAndActionNames) {
                if (LOG.isLoggable(Level.INFO)) {
                    LOG.info("ActionsList: Separator for item=" + item + "\n"); //NOI18N
                }
            }
            actions.add(null);
        }
        all.add(toAdd);
    }

    Pair p = new Pair();
    p.all = all.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(all);
    p.actions = actions.isEmpty() ? Collections.<Action>emptyList() : Collections.unmodifiableList(actions);
    return p;
}
 
Example 20
Source File: ValidateLayerConsistencyTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testActionInstancesOnlyInActionsFolder() {
    List<String> errors = new ArrayList<String>();

    Enumeration<? extends FileObject> files = FileUtil.getConfigRoot().getChildren(true);
    FILE: while (files.hasMoreElements()) {
        FileObject fo = files.nextElement();

        if (skipFile(fo)) {
            continue;
        }

        try {
            DataObject obj = DataObject.find (fo);
            InstanceCookie ic = obj.getLookup().lookup(InstanceCookie.class);
            if (ic == null) {
                continue;
            }
            Object o;
            try {
                o = ic.instanceCreate();
            } catch (ClassNotFoundException ok) {
                // wrong instances are catched by another test
                continue;
            }
            if (!(o instanceof Action)) {
                continue;
            }
            if (fo.hasExt("xml")) {
                continue;
            }
            if (fo.getPath().startsWith("Actions/")) {
                continue;
            }
            if (fo.getPath().startsWith("Editors/")) {
                // editor is a bit different world
                continue;
            }
            if (fo.getPath().startsWith("Databases/Explorer/")) {
                // db explorer actions shall not influence start
                // => let them be for now.
                continue;
            }
            if (fo.getPath().startsWith("WelcomePage/")) {
                // welcome screen actions are not intended for end user
                continue;
            }
            if (fo.getPath().startsWith("Projects/org-netbeans-modules-mobility-project/Actions/")) {
                // I am not sure what mobility is doing, but
                // I guess I do not need to care
                continue;
            }
            if (fo.getPath().startsWith("NativeProjects/Actions/")) {
                // XXX should perhaps be replaced
                continue;
            }
            if (fo.getPath().startsWith("contextmenu/uml/")) {
                // UML is not the most important thing to fix
                continue;
            }
            if (fo.getPath().equals("Menu/Help/org-netbeans-modules-j2ee-blueprints-ShowBluePrintsAction.instance")) {
                // action included in some binary blob
                continue;
            }
            if (Boolean.TRUE.equals(fo.getAttribute("misplaced.action.allowed"))) {
                // it seems necessary some actions to stay outside
                // of the Actions folder
                continue;
            }
            if (fo.hasExt("shadow")) {
                o = fo.getAttribute("originalFile");
                if (o instanceof String) {
                    String origF = o.toString().replaceFirst("\\/*", "");
                    if (origF.startsWith("Actions/")) {
                        continue;
                    }
                    if (origF.startsWith("Editors/")) {
                        continue;
                    }
                }
            }
            errors.add("File " + fo.getPath() + " represents an action which is not in Actions/ subfolder. Provided by " + Arrays.toString((Object[])fo.getAttribute("layers")));
        } catch (Exception ex) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            ex.printStackTrace(ps);
            ps.flush();
            errors.add ("File " + fo.getPath() + " threw: " + baos);
        }
    }

    assertNoErrors(errors.size() + " actions is not registered properly", errors);
}