Java Code Examples for org.openide.filesystems.FileObject#getAttributes()

The following examples show how to use org.openide.filesystems.FileObject#getAttributes() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: netbeans   File: SaveAsTemplateAction.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns map of attributes for given FileObject. */ // XXX: copied from org.netbeans.modules.favorites.templates
private static Map<String, Object> getAttributes (FileObject fo) {
    HashMap<String, Object> attributes = new HashMap<String, Object> ();
    Enumeration<String> attributeNames = fo.getAttributes ();
    while (attributeNames.hasMoreElements ()) {
        String attrName = attributeNames.nextElement ();
        if (attrName == null) {
            continue;
        }
        Object attrValue = fo.getAttribute (attrName);
        if (attrValue != null) {
            attributes.put (attrName, attrValue);
        }
    }
    return attributes;
}
 
Example 2
Source Project: netbeans   File: OptionsCheck.java    License: Apache License 2.0 6 votes vote down vote up
public void testGetKeywords() throws Exception {
    FileObject fo = FileUtil.getConfigFile("OptionsDialog");
    assertNotNull("Dialog data found", fo);
    StringBuilder sb = new StringBuilder();
    Enumeration<? extends FileObject> en = fo.getChildren(true);
    while (en.hasMoreElements()) {
        FileObject f = en.nextElement();
        if (f.isFolder()) {
            continue;
        }
        Enumeration<String> attrs = f.getAttributes();
        while (attrs.hasMoreElements()) {
            String an = attrs.nextElement();
            if (an.startsWith("keywords")) {
                assertFalse("Should not contain dot: " + an, an.contains("."));
                final String kwds = getAttr(f, an);
                System.setProperty("nbkeywords." + an + "." + f.getPath(), kwds);
            }
        }
        System.setProperty("category.nbkeywords." + f.getPath(), getAttr(f, "keywordsCategory"));
        System.setProperty("displayName.nbkeywords." + f.getPath(), getAttr(f, "displayName"));
    }
    if (sb.length() > 0) {
        fail(sb.toString());
    }
}
 
Example 3
Source Project: netbeans   File: FrameworksPanel.java    License: Apache License 2.0 6 votes vote down vote up
private List<String> loadKeywords(AdvancedOption option) {
    OptionsPanelController controller = getController(option);
    JComponent panel = controller.getComponent(masterLookup);
    String id = "OptionsDialog/Keywords/" + panel.getClass().getName(); // NOI18N
    List<String> res = new ArrayList<>(20);
    FileObject keywordsFO = FileUtil.getConfigFile(id);
    if (keywordsFO != null) {
        Enumeration<String> attributes = keywordsFO.getAttributes();
        while (attributes.hasMoreElements()) {
            String attribute = attributes.nextElement();
            if (attribute.startsWith("keywords")) { // NOI18N
                String word = keywordsFO.getAttribute(attribute).toString();
                res.add(word.toUpperCase());
            }
        }
    }
    return res;
}
 
Example 4
Source Project: netbeans   File: SystemFileSystemTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testUserHasPreferenceOverFSs() throws Exception {
    FileObject global = FileUtil.createData(FileUtil.getConfigRoot(), "dir/file.txt");
    global.setAttribute("global", 3);
    write(global, "global");
    
    FileObject fo1 = FileUtil.createData(fs1.getRoot(), "dir/file.txt");
    fo1.setAttribute("one", 1);
    write(fo1, "fileone");
    
    FileObject fo2 = FileUtil.createData(fs2.getRoot(), "dir/file.txt");
    fo2.setAttribute("two", 2);
    write(fo2, "two");

    events.clear();
    
    MainLookup.register(fs1, this);
    MainLookup.register(fs2, this);
    
    Enumeration<String> en = global.getAttributes();
    TreeSet<String> t = new TreeSet<String>();
    while (en.hasMoreElements()) {
        t.add(en.nextElement());
    }
    
    assertEquals("three elements: " + t, 3, t.size());
    assertTrue(t.contains("two"));
    assertTrue(t.contains("one"));
    assertTrue(t.contains("global"));
    
    assertEquals(1, global.getAttribute("one"));
    assertEquals(2, global.getAttribute("two"));
    assertEquals(3, global.getAttribute("global"));

    assertEquals("contains global", 6, global.getSize());
    assertEquals("global", read(global));
    
    
    assertTrue("no events: " + events, events.isEmpty());
}
 
Example 5
Source Project: netbeans   File: MenuBar.java    License: Apache License 2.0 5 votes vote down vote up
/** Constructor. */
public LazyMenu(final DataFolder df, boolean icon) {
    this.master = df;
    this.icon = icon;
    this.dynaModel = new DynaMenuModel();
    this.slave = new MenuFolder();
    
    setName(df.getName());
    final FileObject pf = df.getPrimaryFile();
    Object prefix = pf.getAttribute("property-prefix"); // NOI18N
    if (prefix instanceof String) {
        Enumeration<String> en = pf.getAttributes();
        while (en.hasMoreElements()) {
            String attrName = en.nextElement();
            if (attrName.startsWith((String)prefix)) {
                putClientProperty(
                    attrName.substring(((String)prefix).length()), 
                    pf.getAttribute(attrName)
                );
            }
        }
    }

    // Listen for changes in Node's DisplayName/Icon
    Node n = master.getNodeDelegate ();
    n.addNodeListener (org.openide.nodes.NodeOp.weakNodeListener (this, n));
    Mutex.EVENT.readAccess(this);
    getModel().addChangeListener(this);
}
 
Example 6
Source Project: netbeans   File: QuickSearchProvider.java    License: Apache License 2.0 5 votes vote down vote up
private void readKeywordsFromNewAnnotation() {
FileObject keywordsFOs = FileUtil.getConfigRoot().getFileObject(CategoryModel.OD_LAYER_KEYWORDS_FOLDER_NAME);

       for(FileObject keywordsFO : keywordsFOs.getChildren()) {
    String location = keywordsFO.getAttribute("location").toString(); //NOI18N
    String tabTitle = keywordsFO.getAttribute("tabTitle").toString(); //NOI18N
    Set<String> keywords = new HashSet<String>();
    Enumeration<String> attributes = keywordsFO.getAttributes();
    while (attributes.hasMoreElements()) {
	String attribute = attributes.nextElement();
	if (attribute.startsWith("keywords")) {
	    String word = keywordsFO.getAttribute(attribute).toString();
	    for (String s : word.split(",")) {
		keywords.add(s.trim());
	    }
	}
    }
    String path = location.concat("/").concat(tabTitle);
    Set<String> keywordsFromPath = path2keywords.get(path);
    if(keywordsFromPath != null) {
	for (String keyword : keywordsFromPath) {
	    if (!keywords.contains(keyword)) {
		keywords.add(keyword);
	    }
	}
    }
    path2keywords.put(path, keywords);
       }
   }
 
Example 7
Source Project: netbeans   File: OutputKeymapManager.java    License: Apache License 2.0 5 votes vote down vote up
private void storeShortCuts(String profileName) {
    FileObject root = FileUtil.getConfigRoot();
    try {
        FileObject actionsDir = FileUtil.createFolder(
                root, STORAGE_DIR + profileName);
        for (OutWinShortCutAction a : allActions) {
            FileObject data = actionsDir.getFileObject(a.getId());
            if (data == null) {
                data = actionsDir.createData(a.getId());
            } else if (data.isFolder()) {
                throw new IOException(data + " is a folder.");      //NOI18N
            }
            Enumeration<String> atts = data.getAttributes();
            while (atts.hasMoreElements()) {
                String attName = atts.nextElement();
                data.setAttribute(attName, null);
            }
            int index = 1;
            if (keymaps.get(profileName).get(a) == null) {
                continue;
            }
            for (String shortCut : keymaps.get(profileName).get(a)) {
                data.setAttribute(SHORTCUT_PREFIX + index++, shortCut);
            }
        }
    } catch (IOException e) {
        LOG.log(Level.WARNING, "Cannot create folder", e);          //NOI18N
    }
}
 
Example 8
Source Project: netbeans   File: OutputKeymapManager.java    License: Apache License 2.0 5 votes vote down vote up
private void loadShortCuts() {
    FileObject root = FileUtil.getConfigRoot();
    FileObject actionsDir = root.getFileObject(STORAGE_DIR);
    if (actionsDir == null) {
        return;
    }
    for (FileObject profileDir : actionsDir.getChildren()) {
        if (!profileDir.isFolder()) {
            continue;
        }
        Map<ShortcutAction, Set<String>> keymap =
                new HashMap<ShortcutAction, Set<String>>();
        keymaps.put(profileDir.getName(), keymap);
        for (OutWinShortCutAction a : allActions) {
            FileObject actionFile = profileDir.getFileObject(a.getId());
            if (actionFile == null || !actionFile.isData()) {
                keymap.put(a, Collections.<String>emptySet());
                continue;
            }
            Enumeration<String> atts = actionFile.getAttributes();
            Set<String> strokes = new HashSet<String>();
            while (atts.hasMoreElements()) {
                String att = atts.nextElement();
                if (att.startsWith(SHORTCUT_PREFIX)) {
                    strokes.add((String) actionFile.getAttribute(att));
                }
            }
            keymap.put(a, strokes);
        }
    }
}
 
Example 9
Source Project: netbeans   File: ProjectTemplatesCheck.java    License: Apache License 2.0 5 votes vote down vote up
public void testCanGetWizardIteratorsForAllProjects() {
    FileObject root = FileUtil.getConfigFile("Templates/Project");
    assertNotNull("project is available (need to run in NbModuleTest mode)", root);
    Enumeration<? extends FileObject> en = root.getChildren(true);
    StringBuilder sb = new StringBuilder();
    int error = 0;
    while (en.hasMoreElements()) {
        FileObject fo = en.nextElement();
        if (Boolean.TRUE.equals(fo.getAttribute("template"))) {
            sb.append(fo);
            Object value = EnableStep.readWizard(fo);

            if (value == null) {
                error++;
                sb.append(" - failure\n");
                Enumeration<String> names = fo.getAttributes();
                while (names.hasMoreElements()) {
                    String n = names.nextElement();
                    sb.append("  name: " + n + " value: " + fo.getAttribute(n) + "\n");
                }
            } else {
                sb.append(" - OK\n");
            }
        }
    }
    if (error > 0) {
        fail(sb.toString());
    }
}
 
Example 10
Source Project: netbeans   File: SystemFileSystemTest.java    License: Apache License 2.0 4 votes vote down vote up
public void testUserHasPreferenceOverFSsButGeneratesAnEvent() throws Exception {
    FileObject fo1 = FileUtil.createData(fs1.getRoot(), "dir/file.txt");
    fo1.setAttribute("one", 1);
    write(fo1, "fileone");
    
    FileObject fo2 = FileUtil.createData(fs2.getRoot(), "dir/file.txt");
    fo2.setAttribute("two", 2);
    write(fo2, "two");

    events.clear();
    
    MainLookup.register(fs1, this);
    MainLookup.register(fs2, this);

    assertFalse("not empty", events.isEmpty());
    events.clear();
    
    FileObject global = FileUtil.createData(FileUtil.getConfigRoot(), "dir/file.txt");
    global.setAttribute("global", 3);
    write(global, "global");
    
    assertFalse("yet another set", events.isEmpty());
    
    Enumeration<String> en = global.getAttributes();
    TreeSet<String> t = new TreeSet<String>();
    while (en.hasMoreElements()) {
        t.add(en.nextElement());
    }

    
    
    assertEquals("three elements: " + t, 3, t.size());
    assertTrue(t.contains("two"));
    assertTrue(t.contains("one"));
    assertTrue(t.contains("global"));
    
    assertEquals(1, global.getAttribute("one"));
    assertEquals(2, global.getAttribute("two"));
    assertEquals(3, global.getAttribute("global"));

    assertEquals("contains global", 6, global.getSize());
    assertEquals("global", read(global));
}
 
Example 11
Source Project: netbeans   File: FolderPathLookup.java    License: Apache License 2.0 4 votes vote down vote up
/** get class name from specified file object*/
private static String getClassName(FileObject fo) {
    // first of all try "instanceClass" property of the primary file
    Object attr = fo.getAttribute ("instanceClass");
    if (attr instanceof String) {
        return BaseUtilities.translate((String) attr);
    } else if (attr != null) {
        LOG.warning(
            "instanceClass was a " + attr.getClass().getName()); // NOI18N
    }

    attr = fo.getAttribute("instanceCreate");
    if (attr != null) {
        return attr.getClass().getName();
    } else {
        Enumeration<String> attributes = fo.getAttributes();
        while (attributes.hasMoreElements()) {
            if (attributes.nextElement().equals("instanceCreate")) {
                // It was specified, just unloadable (usually a methodvalue).
                return null;
            }
        }
    }

    // otherwise extract the name from the filename
    String name = fo.getName ();

    int first = name.indexOf('[') + 1;
    if (first != 0) {
        LOG.log(Level.WARNING, "Cannot understand {0}", fo);
    }

    int last = name.indexOf (']');
    if (last < 0) {
        last = name.length ();
    }

    // take only a part of the string
    if (first < last) {
        name = name.substring (first, last);
    }

    name = name.replace ('-', '.');
    name = BaseUtilities.translate(name);

    return name;
}
 
Example 12
public void testAreAttributesFine () {
    List<String> errors = new ArrayList<String>();
    
    FileObject root = FileUtil.getConfigRoot();
    Enumeration<? extends FileObject> files = Enumerations.concat(Enumerations.singleton(root), root.getChildren(true));
    while (files.hasMoreElements()) {
        FileObject fo = files.nextElement();
        
        if (
            "Keymaps/NetBeans/D-BACK_QUOTE.shadow".equals(fo.getPath()) ||
            "Keymaps/NetBeans55/D-BACK_QUOTE.shadow".equals(fo.getPath()) ||
            "Keymaps/Emacs/D-BACK_QUOTE.shadow".equals(fo.getPath())
        ) {
            // #46753
            continue;
        }
        if (
            "Services/Browsers/FirefoxBrowser.settings".equals(fo.getPath()) ||
            "Services/Browsers/MozillaBrowser.settings".equals(fo.getPath()) ||
            "Services/Browsers/NetscapeBrowser.settings".equals(fo.getPath())
        ) {
            // #161784
            continue;
        }
        
        Enumeration<String> attrs = fo.getAttributes();
        while (attrs.hasMoreElements()) {
            String name = attrs.nextElement();

            if (isInstanceAttribute(name)) {
                continue;
            }
            
            if (name.indexOf('\\') != -1) {
                errors.add("File: " + fo.getPath() + " attribute name must not contain backslashes: " + name);
            }
            
            Object attr = fo.getAttribute(name);
            if (attr == null) {
                CharSequence warning = Log.enable("", Level.WARNING);
                if (
                    fo.getAttribute("class:" + name) != null &&
                    fo.getAttribute(name) == null &&
                    warning.length() == 0
                ) {
                    // ok, factory method returned null
                    continue;
                }

                errors.add("File: " + fo.getPath() + " attribute name: " + name);
            }

            if (attr instanceof URL) {
                URL u = (URL) attr;
                int read = -1;
                try {
                    read = u.openStream().read(new byte[4096]);
                } catch (IOException ex) {
                    errors.add(fo.getPath() + ": " + ex.getMessage());
                }
                if (read <= 0) {
                    errors.add("URL resource does not exist: " + fo.getPath() + " attr: " + name + " value: " + attr);
                }
            }

        }
    }
    
    assertNoErrors("Some attributes in files are unreadable", errors);
}
 
Example 13
Source Project: netbeans   File: DefaultSettingsContext.java    License: Apache License 2.0 4 votes vote down vote up
public BindingEnumeration(FileObject fo) {
    this.fo = fo;
    this.en = fo.getAttributes();
}
 
Example 14
Source Project: netbeans   File: RecognizeInstanceFiles.java    License: Apache License 2.0 4 votes vote down vote up
/** get class name from specified file object*/
private static String getClassName(FileObject fo) {
    // first of all try "instanceClass" property of the primary file
    Object attr = fo.getAttribute ("instanceClass");
    if (attr instanceof String) {
        return BaseUtilities.translate((String) attr);
    } else if (attr != null) {
        LOG.warning(
            "instanceClass was a " + attr.getClass().getName()); // NOI18N
    }

    attr = fo.getAttribute("instanceCreate");
    if (attr != null) {
        return attr.getClass().getName();
    } else {
        Enumeration<String> attributes = fo.getAttributes();
        while (attributes.hasMoreElements()) {
            if (attributes.nextElement().equals("instanceCreate")) {
                // It was specified, just unloadable (usually a methodvalue).
                return null;
            }
        }
    }

    // otherwise extract the name from the filename
    String name = fo.getName ();

    int first = name.indexOf('[') + 1;
    if (first != 0) {
        LOG.log(Level.WARNING, "Cannot understand {0}", fo);
    }

    int last = name.indexOf (']');
    if (last < 0) {
        last = name.length ();
    }

    // take only a part of the string
    if (first < last) {
        name = name.substring (first, last);
    }

    name = name.replace ('-', '.');
    name = BaseUtilities.translate(name);

    //System.out.println ("Original: " + getPrimaryFile ().getName () + " new one: " + name); // NOI18N
    return name;
}
 
Example 15
Source Project: netbeans   File: OptionsPanel.java    License: Apache License 2.0 4 votes vote down vote up
private void handlePanel(FileObject keywordsFO) {
       String location = keywordsFO.getAttribute("location").toString(); //NOI18N
       String tabTitle = keywordsFO.getAttribute("tabTitle").toString(); //NOI18N
       JTabbedPane pane = categoryid2tabbedpane.get(location);
       int tabIndex = pane == null ? -1 : pane.indexOfTab(tabTitle);

       Set<String> keywords = new HashSet<String>();
keywords.add(location.toUpperCase());
       keywords.add(tabTitle.toUpperCase());
Enumeration<String> attributes = keywordsFO.getAttributes();
while(attributes.hasMoreElements()) {
    String attribute = attributes.nextElement();
    if(attribute.startsWith("keywords")) {
	String word = keywordsFO.getAttribute(attribute).toString();
	keywords.add(word.toUpperCase());
    }
}

       ArrayList<String> words = categoryid2words.get(location);
       if (words == null) {
           words = new ArrayList<String>();
       }

       Set<String> newWords = new HashSet<String>();
       for (String keyword : keywords) {
           if (!words.contains(keyword)) {
               newWords.add(keyword);
            }
        }

       words.addAll(newWords);
       categoryid2words.put(location, words);

       if (!categoryid2tabs.containsKey(location)) {
           categoryid2tabs.put(location, new HashMap<Integer, TabInfo>());
       }
       HashMap<Integer, TabInfo> categoryTabs = categoryid2tabs.get(location);
       TabInfo tabInfo;
       if (!categoryTabs.containsKey(tabIndex)) {
           tabInfo = new TabInfo();
       } else {
           tabInfo = categoryTabs.get(tabIndex);
       }
       tabInfo.addWords(keywords);
       categoryTabs.put(tabIndex, tabInfo);
       categoryid2tabs.put(location, categoryTabs);
    }
 
Example 16
Source Project: netbeans   File: VerifyFullIDETest.java    License: Apache License 2.0 4 votes vote down vote up
public void testGetAllProjectTemplates() throws Exception {
    List<XMLFileSystem> all = new ArrayList<XMLFileSystem>();

    for (FeatureInfo fi : FeatureManager.features()) {
        XMLFileSystem xfs = new XMLFileSystem(fi.getLayerURL());
        all.add(xfs);
    }

    MultiFileSystem mfs = new MultiFileSystem(all.toArray(new FileSystem[0]));
    FileObject orig = FileUtil.getConfigFile("Templates/Project");
    Enumeration<? extends FileObject> allTemplates = orig.getChildren(true);
    while (allTemplates.hasMoreElements()) {
        FileObject fo = allTemplates.nextElement();
        if (fo.getPath().equals("Templates/Project/Import")) {
            continue;
        }
        if (fo.getPath().equals("Templates/Project/Samples")) {
            continue;
        }

        FileObject clone = mfs.findResource(fo.getPath());

        assertNotNull("Both files exist: " + fo, clone);

        Enumeration<String> allAttributes = fo.getAttributes();
        while (allAttributes.hasMoreElements()) {
            String name = allAttributes.nextElement();
            if ("templateWizardIterator".equals(name)) {
                name = "instantiatingIterator";
            }

            Object attr = clone.getAttribute(name);
            assertNotNull(
                "Attribute " + name + " present in clone on " + fo, attr
            );

            if (attr instanceof URL) {
                URL u = (URL)attr;
                int read = u.openStream().read(new byte[4096]);
                if (read <= 0) {
                    fail("Resource shall exist: " + fo + " attr: " + name + " value: " + attr);
                }
            }
        }
    }
}
 
Example 17
Source Project: netbeans   File: PayaraInstance.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Read Payara server instance data from persistent storage.
 * <p/>
 * @param instanceFO  Persistent storage file.
 * @param uriFragment Payara server URI fragment.
 * @return Payara server instance reconstructed from persistent storage.
 * @throws IOException 
 */
public static PayaraInstance readInstanceFromFile(
        FileObject instanceFO, boolean autoregistered) throws IOException {
    PayaraInstance instance = null;

    String installRoot
            = org.netbeans.modules.payara.common.utils.ServerUtils
            .getStringAttribute(instanceFO,
            PayaraModule.INSTALL_FOLDER_ATTR);
    String payaraRoot
            = org.netbeans.modules.payara.common.utils.ServerUtils
            .getStringAttribute(instanceFO,
            PayaraModule.PAYARA_FOLDER_ATTR);
    
    // Existing installs may lack "installRoot", but payaraRoot and 
    // installRoot are the same in that case.
    if(installRoot == null) {
        installRoot = payaraRoot;
    }
    // TODO: Implement better folders content validation.
    if(org.netbeans.modules.payara.common.utils.ServerUtils
            .isValidFolder(installRoot)
            && org.netbeans.modules.payara.common.utils.ServerUtils
            .isValidFolder(payaraRoot)) {
        // collect attributes and pass to create()
        Map<String, String> ip = new HashMap<>();
        Enumeration<String> iter = instanceFO.getAttributes();
        while(iter.hasMoreElements()) {
            String name = iter.nextElement();
            String value
                    = org.netbeans.modules.payara.common.utils
                    .ServerUtils.getStringAttribute(instanceFO, name);
            ip.put(name, value);
        }
        ip.put(INSTANCE_FO_ATTR, instanceFO.getName());
        fixImportedAttributes(ip, instanceFO);
        instance = create(ip,PayaraInstanceProvider.getProvider(), autoregistered);
    } else {
        LOGGER.log(Level.FINER,
                "Payara folder {0} is not a valid install.",
                instanceFO.getPath()); // NOI18N
        instanceFO.delete();
    }
    return instance;
}
 
Example 18
Source Project: netbeans   File: RootNode.java    License: Apache License 2.0 4 votes vote down vote up
static void enableActionsOnExpand(ServerRegistry registry) {
    FileObject fo = FileUtil.getConfigFile(registry.getPath()+"/Actions"); // NOI18N
    Enumeration<String> en;
    if (fo != null) {
        for (FileObject o : fo.getChildren()) {
            en = o.getAttributes();
            while (en.hasMoreElements()) {
                String attr = en.nextElement();
                boolean enable = false;
                final String prefix = "property-"; // NOI18N
                if (attr.startsWith(prefix)) {
                    attr = attr.substring(prefix.length());
                    if (System.getProperty(attr) != null) {
                        enable = true;
                    }
                } else {
                    final String config = "config-"; // NOI18N
                    if (attr.startsWith(config)) {
                        attr = attr.substring(config.length());
                        FileObject configFile = FileUtil.getConfigFile(attr);
                        if (configFile != null) {
                            if (!configFile.isFolder() || configFile.getChildren().length > 0) {
                                enable = true;
                            }
                        }
                    }
                }

                if (enable) {
                    Lookup l = Lookups.forPath(registry.getPath()+"/Actions"); // NOI18N
                    for (Lookup.Item<Action> item : l.lookupResult(Action.class).allItems()) {
                        if (item.getId().contains(o.getName())) {
                            Action a = item.getInstance();
                            a.actionPerformed(new ActionEvent(getInstance(), 0, "noui")); // NOI18N
                        }
                    }
                }
            }
        }
    }
}
 
Example 19
Source Project: netbeans   File: GlassfishInstance.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Read GlassFish server instance data from persistent storage.
 * <p/>
 * @param instanceFO  Persistent storage file.
 * @param uriFragment GlassFish server URI fragment.
 * @return GlassFish server instance reconstructed from persistent storage.
 * @throws IOException 
 */
public static GlassfishInstance readInstanceFromFile(
        FileObject instanceFO, boolean autoregistered) throws IOException {
    GlassfishInstance instance = null;

    String installRoot
            = org.netbeans.modules.glassfish.common.utils.ServerUtils
            .getStringAttribute(instanceFO,
            GlassfishModule.INSTALL_FOLDER_ATTR);
    String glassfishRoot
            = org.netbeans.modules.glassfish.common.utils.ServerUtils
            .getStringAttribute(instanceFO,
            GlassfishModule.GLASSFISH_FOLDER_ATTR);
    
    // Existing installs may lack "installRoot", but glassfishRoot and 
    // installRoot are the same in that case.
    if(installRoot == null) {
        installRoot = glassfishRoot;
    }
    // TODO: Implement better folders content validation.
    if(org.netbeans.modules.glassfish.common.utils.ServerUtils
            .isValidFolder(installRoot)
            && org.netbeans.modules.glassfish.common.utils.ServerUtils
            .isValidFolder(glassfishRoot)) {
        // collect attributes and pass to create()
        Map<String, String> ip = new HashMap<>();
        Enumeration<String> iter = instanceFO.getAttributes();
        while(iter.hasMoreElements()) {
            String name = iter.nextElement();
            String value
                    = org.netbeans.modules.glassfish.common.utils
                    .ServerUtils.getStringAttribute(instanceFO, name);
            ip.put(name, value);
        }
        ip.put(INSTANCE_FO_ATTR, instanceFO.getName());
        fixImportedAttributes(ip, instanceFO);
        instance = create(ip,GlassfishInstanceProvider.getProvider(), autoregistered);
    } else {
        LOGGER.log(Level.FINER,
                "GlassFish folder {0} is not a valid install.",
                instanceFO.getPath()); // NOI18N
        instanceFO.delete();
    }
    return instance;
}
 
Example 20
Source Project: netbeans   File: GlassfishInstance.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Write GlassFish server instance data into persistent storage.
 * <p/>
 * @param instance GlassFish server instance to be written.
 * @throws IOException 
 */
public static void writeInstanceToFile(
        GlassfishInstance instance) throws IOException {
    String glassfishRoot = instance.getGlassfishRoot();
    if(glassfishRoot == null) {
        LOGGER.log(Level.SEVERE,
                NbBundle.getMessage(GlassfishInstanceProvider.class,
                "MSG_NullServerFolder")); // NOI18N
        return;
    }

    String url = instance.getDeployerUri();

    // For GFV3 managed instance files
    {
        FileObject dir
                = org.netbeans.modules.glassfish.common.utils.ServerUtils
                .getRepositoryDir(GlassfishInstanceProvider.getProvider()
                .getInstancesDirFirstName(), true);
        FileObject[] instanceFOs = dir.getChildren();
        FileObject instanceFO = null;

        for (int i = 0; i < instanceFOs.length; i++) {
            if (url.equals(instanceFOs[i].getAttribute(GlassfishModule.URL_ATTR))
                    && !instanceFOs[i].getName().startsWith(GlassfishInstanceProvider.GLASSFISH_AUTOREGISTERED_INSTANCE)) {
                instanceFO = instanceFOs[i];
            }
        }

        if(instanceFO == null) {
            String name = FileUtil.findFreeFileName(dir, "instance", null); // NOI18N
            instanceFO = dir.createData(name);
        }

        Map<String, String> attrMap = instance.getProperties();
        for(Map.Entry<String, String> entry: attrMap.entrySet()) {
            String key = entry.getKey();
            if(!filterKey(key)) {
                Object currentValue = instanceFO.getAttribute(key);
                if (null != currentValue && currentValue.equals(entry.getValue())) {
                    // do nothing
                } else {
                    if (key.equals(GlassfishModule.PASSWORD_ATTR)) {
                        String serverName = attrMap.get(GlassfishModule.DISPLAY_NAME_ATTR);
                        String userName = attrMap.get(GlassfishModule.USERNAME_ATTR);
                        Keyring.save(GlassfishInstance.passwordKey(
                                serverName, userName),
                                entry.getValue().toCharArray(),
                                "GlassFish administrator user password");
                        LOGGER.log(Level.FINEST,
                                "{0} attribute stored in keyring: {1}",
                                new String[] {instance.getDisplayName(),
                                    key});
                    } else {
                        instanceFO.setAttribute(key, entry.getValue());
                        LOGGER.log(Level.FINEST,
                                "{0} attribute stored: {1} = {2}",
                                new String[] {instance.getDisplayName(),
                                    key, entry.getValue()});
                    }
                }
            }
        }
        // Remove FO attributes that are no more stored in server instance.
        for (Enumeration<String> foAttrs = instanceFO.getAttributes(); foAttrs.hasMoreElements(); ) {
            String foAttr = foAttrs.nextElement();
            if (!attrMap.containsKey(foAttr)) {
                instanceFO.setAttribute(foAttr, null);
                LOGGER.log(Level.FINEST,
                        "{0} attribute deleted: {1}",
                        new String[]{instance.getDisplayName(),
                    foAttr});
            }
        }
        
        instance.putProperty(INSTANCE_FO_ATTR, instanceFO.getName());
        instance.getCommonSupport().setFileObject(instanceFO);
    }
}