Java Code Examples for org.openide.loaders.DataObject#getCookie()

The following examples show how to use org.openide.loaders.DataObject#getCookie() . 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: JAXBWizardOpenXSDIntoEditorAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void performAction(Node[] nodes) {
    Node node = nodes[ 0 ];
    
    FileObject fo = node.getLookup().lookup(FileObject.class );
    try {
    if ( fo != null ) {
        DataObject dataObject = DataObject.find( fo );
        if ( dataObject != null ) {
            EditCookie ec = dataObject.getCookie(EditCookie.class );
            if ( ec != null ) {
                ec.edit();
            }
        }
    }
    } catch ( DataObjectNotFoundException donfe ) {
        donfe.printStackTrace();
    }
}
 
Example 2
Source File: DDUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void openEditorFor(DDDataObject dObj, String className) {
    if (className==null || className.length()==0) return;
    try {
        SourceGroup[] sourceGroups =  getJavaSourceGroups(dObj);
        String resource = className.trim().replace('.','/');
        for (int i=0;i<sourceGroups.length;i++) {
            FileObject fo = sourceGroups[i].getRootFolder();
            FileObject target = fo.getFileObject(resource+".java"); //NOI18N
            if (target!=null) {
                DataObject javaDo = DataObject.find(target);
                org.openide.cookies.OpenCookie cookie =
                        (org.openide.cookies.OpenCookie)javaDo.getCookie(org.openide.cookies.OpenCookie.class);
                if (cookie !=null) {
                    cookie.open();
                    return;
                }
            }
        }
    } catch (IOException ex) {
        LOG.log(Level.FINE, "ignored exception", ex); //NOI18N
    }
    org.openide.DialogDisplayer.getDefault().notify(new org.openide.NotifyDescriptor.Message(
            org.openide.util.NbBundle.getMessage(DDUtils.class,"MSG_sourceNotFound")));
}
 
Example 3
Source File: CatalogEntryNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void edit() {
    try {
        URI uri = new URI(getSystemID());
        File file = new File(uri);
        FileObject fo = FileUtil.toFileObject(file);
        boolean editPossible=false;
        if (fo!=null) {
            DataObject obj = DataObject.find(fo);
            EditCookie editCookie = obj.getCookie(EditCookie.class);
            if (editCookie!=null) {
                editPossible=true;
                editCookie.edit();
            }
        }
        if (!editPossible)
            org.openide.DialogDisplayer.getDefault().notify(
                    new NotifyDescriptor.Message(
                        NbBundle.getMessage(CatalogEntryNode.class, "MSG_CannotOpenURI",getSystemID()), //NOI18N
                        NotifyDescriptor.INFORMATION_MESSAGE));
    } catch (Throwable ex) {
        ErrorManager.getDefault().notify(ex);
    }
}
 
Example 4
Source File: WebFreeFormActionProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void openFile(String path) {
    FileObject file = helper.getProjectDirectory().getFileObject(path);
    if (file == null)
        return;
    
    DataObject fileDO;
    try {
        fileDO = DataObject.find(file);
    }
    catch (DataObjectNotFoundException e) {
        throw new AssertionError(e);
    }
    
    EditCookie edit = (EditCookie)fileDO.getCookie(EditCookie.class);
    if (edit != null) {
        edit.edit();
    }
}
 
Example 5
Source File: DTDWizardIterator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * This is where, the schema gets instantiated from the template.
 */
public Set instantiate (TemplateWizard wizard) throws IOException {        
    FileObject dir = Templates.getTargetFolder( wizard );        
    DataFolder df = DataFolder.findFolder( dir );
    FileObject template = Templates.getTemplate( wizard );        
    DataObject dTemplate = DataObject.find( template );                
    DataObject dobj = dTemplate.createFromTemplate(df, Templates.getTargetName(wizard));
    if (dobj == null)
        return Collections.emptySet();
        
    encoding = EncodingUtil.getProjectEncoding(df.getPrimaryFile());
    if(!EncodingUtil.isValidEncoding(encoding))
        encoding = "UTF-8"; //NOI18N
    EditCookie edit = dobj.getCookie(EditCookie.class);
    if (edit != null) {
        EditorCookie editorCookie = dobj.getCookie(EditorCookie.class);
        Document doc = (Document)editorCookie.openDocument();
        fixEncoding(doc, encoding);
        SaveCookie save = dobj.getCookie(SaveCookie.class);
        if (save!=null) save.save();
    }
    
    return Collections.singleton(dobj.getPrimaryFile());
}
 
Example 6
Source File: XSLWizardIterator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * This is where, the schema gets instantiated from the template.
 */
public Set instantiate (TemplateWizard wizard) throws IOException {        
    FileObject dir = Templates.getTargetFolder( wizard );        
    DataFolder df = DataFolder.findFolder( dir );
    FileObject template = Templates.getTemplate( wizard );        
    DataObject dTemplate = DataObject.find( template );                
    DataObject dobj = dTemplate.createFromTemplate(df, Templates.getTargetName(wizard));
    if (dobj == null)
        return Collections.emptySet();
        
    encoding = EncodingUtil.getProjectEncoding(df.getPrimaryFile());
    if(!EncodingUtil.isValidEncoding(encoding))
        encoding = "UTF-8"; //NOI18N
    EditCookie edit = dobj.getCookie(EditCookie.class);
    if (edit != null) {
        EditorCookie editorCookie = dobj.getCookie(EditorCookie.class);
        Document doc = (Document)editorCookie.openDocument();
        fixEncoding(doc, encoding);
        SaveCookie save = dobj.getCookie(SaveCookie.class);
        if (save!=null) save.save();
    }
    
    return Collections.singleton(dobj.getPrimaryFile());
}
 
Example 7
Source File: LanguagesNavigator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void setDataObject (DataObject dataObject) {
    if (this.dataObject == dataObject) return;
    final EditorCookie ec = dataObject.getCookie (EditorCookie.class);    
    if (ec == null) return;
    LanguagesNavigatorModel model = (LanguagesNavigatorModel) tree.getModel ();
    try {
        NbEditorDocument document = (NbEditorDocument) ec.openDocument ();
        String mimeType = (String) document.getProperty ("mimeType");      
        if (mimeType == null) return;
        if (!LanguagesManager.getDefault ().isSupported (mimeType)) return;
        model.setContext (document);
    } catch (IOException ex) {
        model.setContext (null);
    }
    SwingUtilities.invokeLater(new Runnable() {
        public void run () {
            if (ec.getOpenedPanes () != null && 
                ec.getOpenedPanes ().length > 0
            ) 
                setCurrentEditor (ec.getOpenedPanes () [0]);
            else
                setCurrentEditor (null);
        }
    });
}
 
Example 8
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 9
Source File: GitUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void openInRevision (final File fileToOpen, final File originalFile, final int lineNumber, final String revision, boolean showAnnotations, ProgressMonitor pm) throws IOException {
    final FileObject fo = FileUtil.toFileObject(FileUtil.normalizeFile(fileToOpen));
    EditorCookie ec = null;
    org.openide.cookies.OpenCookie oc = null;
    try {
        DataObject dobj = DataObject.find(fo);
        ec = dobj.getCookie(EditorCookie.class);
        oc = dobj.getCookie(org.openide.cookies.OpenCookie.class);
    } catch (DataObjectNotFoundException ex) {
        Logger.getLogger(GitUtils.class.getName()).log(Level.FINE, null, ex);
    }
    if (ec == null && oc != null) {
        oc.open();
    } else {
        CloneableEditorSupport ces = org.netbeans.modules.versioning.util.Utils.openFile(fo, revision.substring(0, 7));
        if (showAnnotations && ces != null && !pm.isCanceled()) {
            final org.openide.text.CloneableEditorSupport support = ces;
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    javax.swing.JEditorPane[] panes = support.getOpenedPanes();
                    if (panes != null) {
                        if (lineNumber >= 0 && lineNumber < support.getLineSet().getLines().size()) {
                            support.getLineSet().getCurrent(lineNumber).show(Line.ShowOpenType.NONE, Line.ShowVisibilityType.FRONT);
                        }
                        SystemAction.get(AnnotateAction.class).showAnnotations(panes[0], originalFile, revision);
                    }
                }
            });
        }
    }
}
 
Example 10
Source File: FormEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void removeSaveCookie() {
    DataObject javaData = this.getDataObject();
    if (javaData.getCookie(SaveCookie.class) != null) {
        cookies.remove(saveCookie);
        javaData.setModified(false);
    }
}
 
Example 11
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the fo is binary.
 *
 * @param fo fileobject to check
 * @return true if the fileobject cannot be edited in NetBeans text editor, false otherwise
 */
public static boolean isFileContentBinary (FileObject fo) {
    if (fo == null) return false;
    try {
        DataObject dao = DataObject.find(fo);
        return dao.getCookie(EditorCookie.class) == null;
    } catch (DataObjectNotFoundException e) {
        // not found, continue
    }
    return false;
}
 
Example 12
Source File: STSWizardCreator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void openFileInEditor(DataObject dobj){
    final EditorCookie ec = dobj.getCookie(EditorCookie.class);
    RequestProcessor.getDefault().post(new Runnable(){
        public void run(){
            ec.open();
        }
    }, 1000);
}
 
Example 13
Source File: JSFEditorUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Method that allows to find its
 * CloneableEditorSupport from given DataObject
 * @return the support or null if the CloneableEditorSupport 
 * was not found
 * This method is hot fix for issue #53309
 * this methd was copy/pasted from OpenSupport.Env class
 * @param dob an instance of DataObject
 */
public static CloneableEditorSupport findCloneableEditorSupport(DataObject dob) {
    Node.Cookie obj = dob.getCookie(org.openide.cookies.OpenCookie.class);
    if (obj instanceof CloneableEditorSupport) {
        return (CloneableEditorSupport)obj;
    }
    obj = dob.getCookie(org.openide.cookies.EditorCookie.class);
    if (obj instanceof CloneableEditorSupport) {
        return (CloneableEditorSupport)obj;
    }
    return null;
}
 
Example 14
Source File: BIEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void addSaveCookie() {
    DataObject javaData = this.getDataObject();
    if (javaData.getCookie(SaveCookie.class) == null) {
        if (this.saveCookie == null)
            this.saveCookie = new SaveSupport();
        this.cookieSet.add(this.saveCookie);
        javaData.setModified(true);
    }
}
 
Example 15
Source File: DefaultDataLoadersBridge.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public String getLine(Document doc, int lineNumber) {
    DataObject dObj = (DataObject) doc.getProperty(doc.StreamDescriptionProperty);
    LineCookie lc = dObj.getCookie(LineCookie.class);
    Line line = lc.getLineSet().getCurrent(lineNumber);

    return line.getText();
}
 
Example 16
Source File: AnnotationProviderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAnnotationProviderIsCalledCorrectly() throws Exception {              
    Object o = Lookup.getDefault().lookup(AnnotationProvider.class);
    if(o == null) {
        fail("No  annotation provider found");
    }
    
    FileObject fo = fs.getRoot().createData("test", "txt");

    DataObject data = DataObject.find(fo);
    
    EditorCookie ec = data.getCookie(EditorCookie.class);
    
    ConsistencyCheckProvider.setCalled(0);
    ec.open();
    
    CloneableEditorSupport ces = (CloneableEditorSupport)ec;
    
    assertEquals("Provider called exactly once", 1,ConsistencyCheckProvider.getCalled());
    assertEquals("Consistent lookup content", data.getPrimaryFile(),ConsistencyCheckProvider.getInLkp());

    Line l1 = ces.getLineSet().getCurrent(0);
    assertEquals("Exactly one annotation attached", 1, l1.getAnnotationCount());
    
    ec.close();
    // XXX
    Line l2 = ces.getLineSet().getCurrent(0);
    assertEquals ("Lines are the same", l1, l2);
    assertEquals("Exactly one annotation attached after close", 1, l2.getAnnotationCount());

    ConsistencyCheckProvider.setCalled(0);
    ec.open();
    // XXX
    assertEquals("Provider not called during reopen", 0,ConsistencyCheckProvider.getCalled());
    assertEquals("Exactly one annotation attached after reopen", 1, ces.getLineSet().getCurrent(0).getAnnotationCount());
}
 
Example 17
Source File: DatasourceSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Perform datasources graph changes defined by the jbossWeb modifier. Update editor
 * content and save changes, if appropriate.
 *
 * @param modifier
 */
private JBossDatasource modifyDSResource(DSResourceModifier modifier) 
throws ConfigurationException, DatasourceAlreadyExistsException {

    JBossDatasource ds = null;
    
    try {
        ensureResourceDirExists();
        ensureDatasourcesFileExists();
        
        DataObject datasourcesDO = DataObject.find(datasourcesFO);

        EditorCookie editor = (EditorCookie)datasourcesDO.getCookie(EditorCookie.class);
        StyledDocument doc = editor.getDocument();
        if (doc == null)
            doc = editor.openDocument();

        Datasources newDatasources = null;
        try {  // get the up-to-date model
            // try to create a graph from the editor content
            byte[] docString = doc.getText(0, doc.getLength()).getBytes();
            newDatasources = Datasources.createGraph(new ByteArrayInputStream(docString));
        } catch (RuntimeException e) {
            Datasources oldDatasources = getDatasourcesGraph(true);
            if (oldDatasources == null) {
                // neither the old graph is parseable, there is not much we can do here
                // TODO: should we notify the user?
                throw new ConfigurationException(
                        NbBundle.getMessage(DatasourceSupport.class, "MSG_datasourcesXmlCannotParse", DS_RESOURCE_NAME)); // NOI18N
            }
            // current editor content is not parseable, ask whether to override or not
            NotifyDescriptor notDesc = new NotifyDescriptor.Confirmation(
                    NbBundle.getMessage(DatasourceSupport.class, "MSG_datasourcesXmlNotValid", DS_RESOURCE_NAME),       // NOI18N
                    NotifyDescriptor.OK_CANCEL_OPTION);
            Object result = DialogDisplayer.getDefault().notify(notDesc);
            if (result == NotifyDescriptor.CANCEL_OPTION) {
                // keep the old content
                return null;
            }
            // use the old graph
            newDatasources = oldDatasources;
        }

        // perform changes
        ds = modifier.modify(newDatasources);

        // save if appropriate
        boolean modified = datasourcesDO.isModified();
        ResourceConfigurationHelper.replaceDocument(doc, newDatasources);
        if (!modified) {
            SaveCookie cookie = (SaveCookie)datasourcesDO.getCookie(SaveCookie.class);
            cookie.save();
        }

        datasources = newDatasources;

    } catch(DataObjectNotFoundException donfe) {
        Exceptions.printStackTrace(donfe);
    } catch (BadLocationException ble) {
        // this should not occur, just log it if it happens
        Exceptions.printStackTrace(ble);
    } catch (IOException ioe) {
        String msg = NbBundle.getMessage(DatasourceSupport.class, "MSG_CannotUpdateFile", datasourcesFile.getAbsolutePath());
        throw new ConfigurationException(msg, ioe);
    }
    
    return ds;
}
 
Example 18
Source File: PatternResourcesIterator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Set instantiate(ProgressHandle pHandle) throws IOException {
    final Set<FileObject> result = new HashSet<FileObject>();
    try {
        Project project = Templates.getProject(wizard);
        
        final RestSupport restSupport = project.getLookup().lookup(RestSupport.class);
        String restAppPackage = (String) wizard.getProperty(WizardProperties.APPLICATION_PACKAGE);
        String restAppClass = (String) wizard.getProperty(WizardProperties.APPLICATION_CLASS);
        
        pHandle.start();
        
        pHandle.progress(NbBundle.getMessage(PatternResourcesIterator.class,
                "MSG_EnableRestSupport"));                  // NOI18N     
        
        boolean useJersey = Boolean.TRUE.equals(wizard.getProperty(WizardProperties.USE_JERSEY));
        if (!useJersey) {
            RestSupport.RestConfig.IDE.setAppClassName(restAppPackage+"."+restAppClass); //NOI18N
        }
        if ( restSupport!= null ){
            restSupport.ensureRestDevelopmentReady(useJersey ?
                    RestSupport.RestConfig.DD : RestSupport.RestConfig.IDE);
        }
        
        FileObject tmpTargetFolder = Templates.getTargetFolder(wizard);

        SourceGroup sourceGroup = (SourceGroup) wizard.getProperty(WizardProperties.SOURCE_GROUP);
        if (tmpTargetFolder == null) {
            String targetPackage = (String) wizard.getProperty(WizardProperties.TARGET_PACKAGE);
            tmpTargetFolder = SourceGroupSupport.getFolderForPackage(sourceGroup, targetPackage, true);
        }

        final FileObject targetFolder = tmpTargetFolder;
        final GenericResourceBean[] resourceBeans = getResourceBeans(wizard);

        // create application config class if required
        final FileObject restAppPack = restAppPackage == null ? null :  
            SourceGroupSupport.getFolderForPackage(sourceGroup, restAppPackage, true);
        final String appClassName = restAppClass;
        
        try {
            for (GenericResourceBean bean : resourceBeans) {
                result.addAll(new GenericResourceGenerator(targetFolder, 
                        bean).generate(pHandle));
            }
            if (restSupport != null && restAppPack != null && appClassName != null && !useJersey) {
                FileObject fo = RestUtils.createApplicationConfigClass(restSupport, restAppPack, appClassName);
                if (fo != null) {
                    // open generated Application subclass too:
                    result.add(fo);
                }
            }
            if (restSupport != null) {
                restSupport.configure(
                        wizard.getProperty(
                                WizardProperties.RESOURCE_PACKAGE).toString());
            }
            for (FileObject fobj : result) {
                DataObject dobj = DataObject.find(fobj);
                EditorCookie cookie = dobj.getCookie(EditorCookie.class);
                cookie.open();
            }
        } catch(Exception iox) {
            Exceptions.printStackTrace(iox);
        } finally {
            pHandle.finish();
        }

        // logging usage of wizard
        Object[] params = new Object[5];
        params[0] = LogUtils.WS_STACK_JAXRS;
        params[1] = project.getClass().getName();
        J2eeModule j2eeModule = RestUtils.getJ2eeModule(project);
        params[2] = j2eeModule == null ? null : j2eeModule.getModuleVersion()+"(WAR)"; //NOI18N
        params[3] = "REST FROM PATTERNS"; //NOI18N
        params[4] = ((Pattern)wizard.getProperty(WizardProperties.PATTERN_SELECTION)).toString();
        LogUtils.logWsWizard(params);

    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
    return result;
}
 
Example 19
Source File: BookmarkList.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private BookmarkList(final Document document) {
    if (document == null) {
        throw new NullPointerException ("Document cannot be null"); // NOI18N
    }
    this.document = document;
    this.bookmarks = new ArrayList<Bookmark> ();
    this.info2bookmark = new HashMap<BookmarkInfo, Bookmark>();

    BookmarkUtils.postTask(new Runnable() {
        @Override
        public void run() {
            BookmarkManager lockedBookmarkManager = BookmarkManager.getLocked();
            try {
                fileBookmarks = lockedBookmarkManager.getFileBookmarks(document);
                if (fileBookmarks != null) {
                    ProjectBookmarks projectBookmarks = fileBookmarks.getProjectBookmarks();
                    projectBookmarks.activeClientNotify(this);
                    for (BookmarkInfo bookmarkInfo : fileBookmarks.getBookmarks()) {
                        try {
                            addBookmarkForInfo(bookmarkInfo, -1);
                        } catch (IndexOutOfBoundsException ex) {
                            // line does not exists now (some external changes)
                        }
                    }
                }
                // Passing lockedBookmarkManager as "source" parameter is unclean
                lockedBookmarkManager.addBookmarkManagerListener(WeakListeners.create(
                        BookmarkManagerListener.class, bmListener, lockedBookmarkManager));
            } finally {
                lockedBookmarkManager.unlock();
            }
        }
    });

    DataObject dataObject = NbEditorUtilities.getDataObject (document);
    if (dataObject != null) {
        Observable observable = dataObject.getCookie (Observable.class);
        if (observable != null) {
            if (!observedObservables.contains (observable)) {
                observable.addPropertyChangeListener (documentModifiedListener);
                observedObservables.add (observable);
            }
        }
    }
}
 
Example 20
Source File: SuspiciousNamesCombinationTest.java    From netbeans with Apache License 2.0 3 votes vote down vote up
protected void prepareTest(String code) throws Exception {
    FileObject workFO = makeScratchDir(this);
    
    assertNotNull(workFO);
    
    FileObject sourceRoot = workFO.createFolder("src");
    FileObject buildRoot  = workFO.createFolder("build");
    FileObject cache = workFO.createFolder("cache");

    FileObject data = FileUtil.createData(sourceRoot, "test/Test.java");
    
    writeIntoFile(data, code);
    
    SourceUtilsTestUtil.prepareTest(sourceRoot, buildRoot, cache);
    
    DataObject od = DataObject.find(data);
    EditorCookie ec = od.getCookie(EditorCookie.class);
    
    assertNotNull(ec);
    
    ec.openDocument();
    
    JavaSource js = JavaSource.forFileObject(data);
    
    assertNotNull(js);
    
    info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);
    
    assertNotNull(info);
}