Java Code Examples for org.openide.loaders.DataObject

The following examples show how to use org.openide.loaders.DataObject. 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   Source File: JspHyperlinkProvider.java    License: Apache License 2.0 6 votes vote down vote up
private void openInEditor(FileObject fObj) {
    if (fObj != null) {
        DataObject dobj;
        try {
            dobj = DataObject.find(fObj);
        } catch (DataObjectNotFoundException e) {
            Exceptions.printStackTrace(e);
            return;
        }
        if (dobj != null) {
            Node.Cookie cookie = dobj.getLookup().lookup(EditCookie.class);
            if (cookie != null) {
                ((EditCookie) cookie).edit();
            }
        }
    }
}
 
Example 2
Source Project: netbeans   Source File: TemplateOperation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Set<FileObject> execute() {
    FileObject template = FileUtil.getConfigFile(templateName);
    if (template != null) {
        String targetName = target.getName();
        try {
            FileObject targetParent = FileUtil.createFolder(target.getParentFile());
            DataFolder targetFolder = DataFolder.findFolder(targetParent);
            DataObject o = DataObject.find(template);
            DataObject newData = o.createFromTemplate(targetFolder,targetName, tokens);
            return important ? Collections.singleton(newData.getPrimaryFile()) : null;
        } catch (IOException ex) {

        }
    }
    return null;
}
 
Example 3
Source Project: netbeans   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new PropertiesDataObject (properties file).
 * @param folder FileObject folder where to create the properties file
 * @param fileName String name of the file without the extension, can include
 *        relative path underneath the folder
 * @return created PropertiesDataObjet
 */
public static PropertiesDataObject createPropertiesDataObject(FileObject folder, String fileName)
    throws IOException
{
    int idx = fileName.lastIndexOf('/');
    if (idx > 0) {
        String folderPath = fileName.substring(0, idx);
        folder = FileUtil.createFolder(folder, folderPath);
        fileName = fileName.substring(idx + 1);
    }
    FileSystem defaultFS = Repository.getDefault().getDefaultFileSystem();
    FileObject templateFO = defaultFS.findResource("Templates/Other/properties.properties"); // NOI18N
    DataObject template = DataObject.find(templateFO);
    return (PropertiesDataObject)
           template.createFromTemplate(DataFolder.findFolder(folder), fileName);
}
 
Example 4
Source Project: netbeans   Source File: SCFTHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testCreateFromTemplateUsingFreemarker() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.txt");
    OutputStream os = fo.getOutputStream();
    String txt = "print('<html><h1>', title, '</h1></html>');";
    os.write(txt.getBytes());
    os.close();
    fo.setAttribute(ScriptingCreateFromTemplateHandler.SCRIPT_ENGINE_ATTR, "js");
    
    
    DataObject obj = DataObject.find(fo);
    
    DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(root, "target"));
    
    Map<String,String> parameters = Collections.singletonMap("title", "Nazdar");
    DataObject n = obj.createFromTemplate(folder, "complex", parameters);
    
    assertEquals("Created in right place", folder, n.getFolder());
    assertEquals("Created with right name", "complex.txt", n.getName());
    
    String exp = "<html><h1> Nazdar </h1></html>\n";
    assertEquals(exp, readFile(n.getPrimaryFile()));
    
}
 
Example 5
Source Project: netbeans   Source File: ConvertAsBeanTest.java    License: 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 6
Source Project: netbeans   Source File: FileActionTest.java    License: Apache License 2.0 6 votes vote down vote up
public boolean isActionEnabled( String command, Lookup context) throws IllegalArgumentException {
    
    if ( COMMAND.equals( command ) ) {
        Collection dobjs = context.lookupAll(DataObject.class);
        for ( Iterator it = dobjs.iterator(); it.hasNext();  ) {
            DataObject dobj = (DataObject)it.next();
            if ( !dobj.getPrimaryFile().getNameExt().endsWith( ".java" ) ) {
                return false;
            }                    
        }
        return true;
    }            
    else {
        throw new IllegalArgumentException();
    }
    
}
 
Example 7
public void testLineSeparator() throws Exception {
    File file = File.createTempFile("lineSeparator", ".txt", getWorkDir());
    file.deleteOnExit();
    FileObject fileObject = FileUtil.toFileObject(file);
    fileObject.setAttribute(FileObject.DEFAULT_LINE_SEPARATOR_ATTR, "\r");
    DataObject dataObject = DataObject.find(fileObject);
    EditorCookie editor = dataObject.getLookup().lookup(org.openide.cookies.EditorCookie.class);
    final StyledDocument doc = editor.openDocument();
    SwingUtilities.invokeAndWait(new Runnable() {

        @Override
        public void run() {
            try {
                doc.insertString(doc.getLength(), ".\n", null);
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
    
    editor.saveDocument();
    InputStream inputStream = fileObject.getInputStream();
    assertEquals('.',inputStream.read());
    assertEquals('\r',inputStream.read());
    inputStream.close();
}
 
Example 8
Source Project: netbeans   Source File: Actions.java    License: Apache License 2.0 6 votes vote down vote up
static DataObject createShadows(final DataFolder favourities, final List<DataObject> dos, final List<DataObject> listAdd) {
    DataObject createdDO = null;
    for (DataObject obj : dos) {
        try {
            DataShadow added = findShadow(favourities, obj);
            if (added != null) {
                if (createdDO == null) {
                    createdDO = added;
                }
            } else {
                if (createdDO == null) {
                    // Select only first node in array added to favorites
                    createdDO = obj.createShadow(favourities);
                    listAdd.add(createdDO);
                } else {
                    listAdd.add(obj.createShadow(favourities));
                }
            }
        } catch (IOException ex) {
            LOG.log(Level.WARNING, null, ex);
        }
    }
    return createdDO;
}
 
Example 9
Source Project: netbeans   Source File: DocumentTitlePropertyTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testDocumentId () throws IOException {
    FileUtil.createData(FileUtil.getConfigRoot(), "someFolder/someFile.obj");
    FileUtil.createData(FileUtil.getConfigRoot(), "someFolder/someFile.txt");
    
    DataObject obj = DataObject.find(FileUtil.getConfigFile("someFolder/someFile.obj"));
    DataObject txt = DataObject.find(FileUtil.getConfigFile("someFolder/someFile.txt"));
    assertEquals( MyDataObject.class, obj.getClass());
    assertTrue( "we need UniFileLoader", obj.getLoader() instanceof UniFileLoader );

    CloneableEditorSupport ecobj = (CloneableEditorSupport) obj.getCookie(EditorCookie.class);
    CloneableEditorSupport ectxt = (CloneableEditorSupport) txt.getCookie(EditorCookie.class);
    
    if (ecobj.documentID().equals(ectxt.documentID())) {
        fail("The same ID: " + ectxt.documentID());
    }
    assertEquals("Should be full name of the fileObj", obj.getPrimaryFile().getNameExt(), ecobj.documentID());
    assertEquals("Should be full name of the txtObj", txt.getPrimaryFile().getNameExt(), ectxt.documentID());
}
 
Example 10
Source Project: netbeans   Source File: ProjectFileExplorer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void addNotify() {
    super.addNotify();
    manager.addPropertyChangeListener(this);
    for (int i = 0; i < projects.length; i++) {
        try {
            Project project = projects[i];
            FileObject projectDir = project.getProjectDirectory();
            DataObject projectDirDObj = DataObject.find(projectDir);
            Node rootNode = projectDirDObj.getNodeDelegate();
            FilterNode node = new FilterNode(rootNode);
            projectNodeList.add(node);

        } catch (DataObjectNotFoundException ex) {
            ErrorManager.getDefault().notify(ex);
        }
    }
    Node[] projectNodes = new Node[projectNodeList.size()];
    projectNodeList.<Node>toArray(projectNodes);
    rootChildren.add(projectNodes);
    manager.setRootContext(explorerClientRoot);

    descriptor.setValid(false);
}
 
Example 11
Source Project: netbeans   Source File: WebFreeFormActionProvider.java    License: 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 12
Source Project: netbeans   Source File: NbKeymapTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testAcceleratorMapping() throws Exception {
    FileObject def1 = make("Actions/DummyAction1.instance");
    def1.setAttribute("instanceCreate", new DummyAction("one"));
    FileObject def2 = make("Actions/DummyAction2.instance");
    def2.setAttribute("instanceCreate", new DummyAction("two"));
    FileObject def3 = make("Actions/DummySystemAction1.instance");
    def3.setAttribute("instanceClass", DummySystemAction1.class.getName());
    FileObject def4 = make("Actions/" + DummySystemAction2.class.getName().replace('.', '-') + ".instance");
    DataFolder shortcuts = DataFolder.findFolder(makeFolder("Shortcuts"));
    DataShadow.create(shortcuts, "1", DataObject.find(def1)).getPrimaryFile();
    DataShadow.create(shortcuts, "2", DataObject.find(def2)).getPrimaryFile();
    DataShadow.create(shortcuts, "3", DataObject.find(def3)).getPrimaryFile();
    DataShadow.create(shortcuts, "C-4", DataObject.find(def4)).getPrimaryFile();
    DataFolder menu = DataFolder.findFolder(makeFolder("Menu/Tools"));
    FileObject menuitem1 = DataShadow.create(menu, "whatever1", DataObject.find(def1)).getPrimaryFile();
    FileObject menuitem2 = DataShadow.create(menu, "whatever2", DataObject.find(def2)).getPrimaryFile();
    FileObject menuitem3 = DataShadow.create(menu, "whatever3", DataObject.find(def3)).getPrimaryFile();
    FileObject menuitem4 = DataShadow.create(menu, "whatever4", DataObject.find(def4)).getPrimaryFile();
    NbKeymap km = new NbKeymap();
    assertMapping(km, KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), menuitem1, "one");
    assertMapping(km, KeyStroke.getKeyStroke(KeyEvent.VK_2, 0), menuitem2, "two");
    assertMapping(km, KeyStroke.getKeyStroke(KeyEvent.VK_3, 0), menuitem3, "DummySystemAction1");
    assertMapping(km, KeyStroke.getKeyStroke(KeyEvent.VK_4, KeyEvent.CTRL_MASK), menuitem4, "DummySystemAction2");
}
 
Example 13
Source Project: netbeans   Source File: EditQueryStringAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean enable (Node[] activatedNodes){
    if (activatedNodes.length == 0) {
        return false;
    }
    for (int i = 0; i < activatedNodes.length; i++){
        DataObject dObj = (DataObject)(activatedNodes[i]).getCookie(DataObject.class);
        QueryStringCookie qsc = (QueryStringCookie)activatedNodes[i].getCookie(QueryStringCookie.class);

        if (qsc == null || dObj == null)
            return false;
        
        if (dObj instanceof JspDataObject){
            String ext = dObj.getPrimaryFile().getExt();
            if (ext.equals(JspLoader.TAGF_FILE_EXTENSION) 
                || ext.equals(JspLoader.TAGX_FILE_EXTENSION)
                || ext.equals(JspLoader.TAG_FILE_EXTENSION))
                    return false;
        }
    }
    return true;
}
 
Example 14
Source Project: netbeans   Source File: MultiBundleStructureTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test of getOpenSupport method, of class MultiBundleStructure.
 */
@Test
public void testGetOpenSupport() throws Exception{
    System.out.println("getOpenSupport");
    String fileName1 = "foo.properties";
    String fileName2 = "foo_ru.properties";
    File propFile = new File(getWorkDir(), fileName1);
    propFile.createNewFile();
    File propFile2 = new File(getWorkDir(), fileName2);
    propFile2.createNewFile();
    DataObject propDO1 = DataObject.find(FileUtil.toFileObject(propFile));
    DataObject propDO2 = DataObject.find(FileUtil.toFileObject(propFile));
    DataObject.find(FileUtil.toFileObject(propFile2));
    assertTrue(propDO1 instanceof PropertiesDataObject);
    PropertiesDataObject dataObject = (PropertiesDataObject) propDO1;
    MultiBundleStructure instance = (MultiBundleStructure) dataObject.getBundleStructure();
    MultiBundleStructure instance2 = (MultiBundleStructure) ((PropertiesDataObject)propDO2).getBundleStructure();
    //instances should be the same
    assertEquals(instance, instance2);
    instance.updateEntries();
    PropertiesOpen result = instance.getOpenSupport();
    assertNotNull(result);
}
 
Example 15
public DataObject generate(FileObject targetFolder, String targetName) {
    try {
        DataFolder folder = (DataFolder) DataObject.find(targetFolder);
        FileObject fo = null;
        fo = FileUtil.getConfigFile("Templates/WebServices/DerivedKeyPasswordValidator.java"); // NOI18N
        if (fo != null) {
            DataObject template = DataObject.find(fo);
            DataObject obj = template.createFromTemplate(folder, targetName);            
            return obj;
        }
    } catch (IOException ex) {
        Logger.getLogger("global").log(Level.INFO, null, ex);
    }
    
    return null;
}
 
Example 16
Source Project: netbeans   Source File: ModuleLogicalViewTest.java    License: Apache License 2.0 6 votes vote down vote up
private Node find(LogicalViewProvider lvp, String path) throws Exception {
    FileObject f = FileUtil.toFileObject(file(path));
    assertNotNull("found " + path, f);
    Node root = new FilterNode(lvp.createLogicalView());
    
    lvp.findPath(root, f); // ping
    waitForNodesUpdate();
    
    DataObject d = DataObject.find(f);
    Node n = lvp.findPath(root, f);
    assertEquals("same result for DataObject as for FileObject", n, lvp.findPath(root, d));
    if (n != null) {
        assertEquals("right DataObject", d, n.getLookup().lookup(DataObject.class));
    }
    return n;
}
 
Example 17
Source Project: netbeans   Source File: ProjectTemplateAttributesLegacy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, ?> attributesFor(DataObject template, DataFolder target, String name) {
    FileObject targetF = target.getPrimaryFile();
    Project prj = FileOwnerQuery.getOwner(targetF);
    Map<String, Object> all = new HashMap<>();
    if (prj != null) {
        // call old providers
        Collection<? extends CreateFromTemplateAttributesProvider> oldProvs = prj.getLookup().lookupAll(CreateFromTemplateAttributesProvider.class);
        if (!oldProvs.isEmpty()) {
            for (CreateFromTemplateAttributesProvider attrs : oldProvs) {
                Map<String, ? extends Object> m = attrs.attributesFor(template, target, name);
                if (m != null) {
                    all.putAll(m);
                }
            }
        }
    }
    all.put(ProjectTemplateAttributesLegacy.class.getName(), Boolean.TRUE);
    return checkProjectAttrs(all, targetF);
}
 
Example 18
Source Project: netbeans   Source File: StrutsConfigHyperlinkProvider.java    License: Apache License 2.0 6 votes vote down vote up
public boolean isHyperlinkPoint(javax.swing.text.Document doc, int offset) {
    if (debug) debug(":: isHyperlinkSpan - offset: " + offset); //NOI18N
    
    // PENDING - this check should be removed, when
    // the issue #61704 is solved.
    DataObject dObject = NbEditorUtilities.getDataObject(doc);
    if (! (dObject instanceof StrutsConfigDataObject))
        return false;
    
    eav = getElementAttrValue(doc, offset);
    if (eav != null){
        if (hyperlinkTable.get(eav[0]+"#"+eav[1])!= null)
            return true;
    }
    return false;
}
 
Example 19
Source Project: netbeans   Source File: DefaultPlugin.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Loads a test template.
 * If the template loading fails, displays an error message.
 *
 * @param  templateID  bundle key identifying the template type
 * @return  loaded template, or <code>null</code> if the template
 *          could not be loaded
 */
private static DataObject loadTestTemplate(String templateID) {
    // get the Test class template
    String path = NbBundle.getMessage(DefaultPlugin.class,
                                      templateID);
    try {
        FileObject fo = FileUtil.getConfigFile(path);
        if (fo == null) {
            noTemplateMessage(path);
            return null;
        }
        return DataObject.find(fo);
    }
    catch (DataObjectNotFoundException e) {
        noTemplateMessage(path);
        return null;
    }
}
 
Example 20
Source Project: netbeans   Source File: DnDSupport.java    License: Apache License 2.0 6 votes vote down vote up
private boolean handleDropImpl(Transferable t) {       
    try {
        Object o;
        if( t.isDataFlavorSupported( actionDataFlavor ) ) {
            o = t.getTransferData( actionDataFlavor );
            if( o instanceof Node ) {
                DataObject dobj = ((Node)o).getLookup().lookup( DataObject.class );
                return addButton( dobj, dropTargetButtonIndex, insertBefore );
            }
        } else {
            o = t.getTransferData( buttonDataFlavor );
            if( o instanceof DataObject ) {
                return moveButton( (DataObject)o, dropTargetButtonIndex, insertBefore );
            }
        }
    } catch( UnsupportedFlavorException e ) {
        log.log( Level.INFO, null, e );
    } catch( IOException ioE ) {
        log.log( Level.INFO, null, ioE );
    }
    return false;
}
 
Example 21
Source Project: netbeans   Source File: TestSuiteWizardIterator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Set<DataObject> instantiate() throws IOException {
    saveSettings(wizard);
    
    /* collect and build necessary data: */
    String name = Templates.getTargetName(wizard);
    FileObject targetFolder = Templates.getTargetFolder(wizard);
    FileObject testRootFolder = findTestRootFolder(targetFolder);
    assert testRootFolder != null;
    
    /* create test class(es) for the selected source class: */
    DataObject suite = JUnitUtils.createSuiteTest(testRootFolder, targetFolder, name, JUnitTestUtil.getSettingsMap(true));
    if (suite != null) {
        return Collections.singleton(suite);
    } else {
        throw new IOException();
    }
}
 
Example 22
Source Project: netbeans   Source File: JerseyClientWizardIterator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Set<DataObject> instantiate() throws IOException {
    FileObject template = Templates.getTemplate(wizard);
    template.setAttribute("REST_RESOURCE_NAME", bottomPanel.getResourceName());
    DataObject dTemplate = DataObject.find( template );
    org.openide.filesystems.FileObject dir = Templates.getTargetFolder(wizard);
    DataFolder df = DataFolder.findFolder( dir );
    final DataObject dobj = dTemplate.createFromTemplate(df, Templates.getTargetName(wizard ));
    // generating client
    RequestProcessor.getDefault().post(new Runnable() {

        @Override
        public void run() {
            ClientJavaSourceHelper.generateJerseyClient(
                    bottomPanel.getResourceNode(), dobj.getPrimaryFile(), 
                    null, bottomPanel.getSecurity());
        }
    });
    return Collections.<DataObject>singleton(dobj);
}
 
Example 23
Source Project: netbeans   Source File: ImageNavigatorPanel.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void fileChanged(final FileEvent fe) {
    if (fe.getTime() > lastSaveTime) {
        lastSaveTime = System.currentTimeMillis();

        // Refresh image viewer
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                try {
                    currentDataObject = DataObject.find(fe.getFile());
                    setNewContent(currentDataObject);
                } catch (DataObjectNotFoundException ex) {
                    Logger.getLogger(ImageNavigatorPanel.class.getName()).info(NbBundle.getMessage(ImageNavigatorPanel.class, "ERR_DataObject"));
                }
            }
        });
    }
}
 
Example 24
Source Project: netbeans   Source File: CopyStyleAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    BaseDocument bdoc = Utilities.getDocument(target);
    if(bdoc == null) {
        return ; //no document?!?!
    }
    DataObject csso = NbEditorUtilities.getDataObject(bdoc);
    if(csso == null) {
        return ; //document not backuped by DataObject
    }
    
    String pi = createText(csso);
    StringSelection ss = new StringSelection(pi);
    ExClipboard clipboard = Lookup.getDefault().lookup(ExClipboard.class);
    clipboard.setContents(ss, null);
    StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage(CopyStyleAction.class, "MSG_Style_tag_in_clipboard"));  // NOI18N
    
}
 
Example 25
Source Project: netbeans   Source File: CreateFromTemplateDecoratorTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testPreCreateDecorator() throws Exception {
    MockLookup.setLayersAndInstances(new Deco() {
        @Override
        public boolean isBeforeCreation() {
            return true;
        }
        
        @Override
        public List<FileObject> decorate(CreateDescriptor desc, List<FileObject> createdFiles) throws IOException {
            assertSize("No files should have been created", createdFiles, 0);
            decorated = true;
            assertEquals(0, target.getChildren().length);
            return null;
        }
    });
    Map<String,String> parameters = Collections.singletonMap("type", "empty");
    DataObject n = obj.createFromTemplate(folder, "complex", parameters);
    assertTrue(decorated);
    assertNotNull(n);
}
 
Example 26
Source Project: netbeans   Source File: WildflyManagerNode.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void edit() {
    FileObject fo = FileUtil.toFileObject(new File(configFile));
    try {
        DataObject.find(fo).getLookup().lookup(OpenCookie.class).open();
    } catch (DataObjectNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 27
Source Project: netbeans   Source File: JavaActions.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isSingleJavaFileSelected(Lookup context) {
    Collection<? extends DataObject> selectedDO = context.lookupAll(DataObject.class);
    if (selectedDO.size() == 1 && selectedDO.iterator().next().getPrimaryFile().hasExt("java")) {
        return true;
    }
    return false;
}
 
Example 28
Source Project: netbeans   Source File: HyperlinkProviderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private FileObject getProjectDir(Document doc) {
    DataObject dObject = NbEditorUtilities.getDataObject(doc);
    if (dObject != null) {
        return dObject.getPrimaryFile().getParent();
    }
    return null;
}
 
Example 29
Source Project: netbeans   Source File: Utilities.java    License: Apache License 2.0 5 votes vote down vote up
public static void delete(String file) {
    FileObject fileObject = Repository.getDefault().findResource(file);
    if (fileObject==null) return;
    try {
        DataObject.find(fileObject).delete();
    } catch (java.io.IOException e) {
    }
}
 
Example 30
Source Project: nb-springboot   Source File: GlobalActionContextProxy.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Recursively searches the node hierarchy for the project that owns a node.
 *
 * @param node a node to test for a Project in its or its ancestor's lookup.
 * @return the Project that owns the node, or null if not found
 */
private static Project findProjectThatOwnsNode(Node node) {
    if (node != null) {
        Project project = node.getLookup().lookup(Project.class);
        if (project == null) {
            DataObject dataObject = node.getLookup().lookup(DataObject.class);
            if (dataObject != null) {
                project = FileOwnerQuery.getOwner(dataObject.getPrimaryFile());
            }
        }
        return (project == null) ? findProjectThatOwnsNode(node.getParentNode()) : project;
    } else {
        return null;
    }
}
 
Example 31
Source Project: constellation   Source File: SaveAsAction.java    License: Apache License 2.0 5 votes vote down vote up
private FileObject getCurrentFileObject() {
    TopComponent tc = TopComponent.getRegistry().getActivated();
    if (tc != null) {
        DataObject dob = tc.getLookup().lookup(DataObject.class);
        if (dob != null) {
            return dob.getPrimaryFile();
        }
    }
    return null;
}
 
Example 32
Source Project: netbeans   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Try to extract the URL from the given DataObject using reflection.
 * (The DataObject should be URLDataObject in most cases)
 */
public static String getUrlString(DataObject dob) {
    try {
        Method m = dob.getClass().getDeclaredMethod( "getURLString", new Class[] {} ); //NOI18N
        m.setAccessible( true );
        Object res = m.invoke( dob );
        if( null != res ) {
            return res.toString();
        }
    } catch (Exception ex) {
        //ignore
    }
    return null;
}
 
Example 33
Source Project: netbeans   Source File: EjbJarMultiViewDataObject.java    License: Apache License 2.0 5 votes vote down vote up
protected DataObject handleCopy(DataFolder f) throws IOException {
    DataObject dataObject = super.handleCopy(f);
    try {
        dataObject.setValid(false);
    } catch (PropertyVetoException e) {
        // should not occur
    }
    return dataObject;
}
 
Example 34
Source Project: netbeans   Source File: GotoBaseAction.java    License: Apache License 2.0 5 votes vote down vote up
private DataObject getDataObjectFromComponent(JTextComponent sourceComponent) {
    if (sourceComponent == null) {
        return null;
    }

    Document doc = sourceComponent.getDocument();
    if (doc == null) {
        return null;
    }
    return NbEditorUtilities.getDataObject(doc);
}
 
Example 35
Source Project: netbeans   Source File: NavigatorContent.java    License: Apache License 2.0 5 votes vote down vote up
private void openAndFocusElement(final TreeNodeAdapter selected, final boolean selectLineOnly) {
    BaseDocument bdoc = (BaseDocument)selected.getDocumentElement().getDocument();
    DataObject dobj = NbEditorUtilities.getDataObject(bdoc);
    if(dobj == null) return ;
    
    final EditorCookie.Observable ec = (EditorCookie.Observable)dobj.getCookie(EditorCookie.Observable.class);
    if(ec == null) return ;
    
    try {
        final Document doc = ec.openDocument(); //wait to editor to open
    }catch(IOException ioe) {
        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe);
    }
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JEditorPane[] panes = ec.getOpenedPanes();
            if (panes != null && panes.length > 0) {
                // editor already opened, so just select
                selectElementInPane(panes[0], selected, !selectLineOnly);
            } else if(!selectLineOnly) {
                // editor not opened yet
                ec.open();
                panes = ec.getOpenedPanes();
                if (panes != null && panes.length > 0) {
                    selectElementInPane(panes[0], selected, true);
                }
            }
        }
    });
}
 
Example 36
Source Project: netbeans   Source File: PaletteEnvironmentProvider.java    License: Apache License 2.0 5 votes vote down vote up
public Lookup getEnvironment(DataObject obj) {
    if (!FileUtil.isParentOf(
                FileUtil.getConfigRoot(), obj.getPrimaryFile())) {
        return Lookup.EMPTY;
    }
    PaletteItemNodeFactory nodeFactory = new PaletteItemNodeFactory((XMLDataObject)obj);
    return nodeFactory.getLookup();
}
 
Example 37
Source Project: netbeans   Source File: FastMatcher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Perform pattern matching in individual lines of the file.
 */
private List<TextDetail> matchLines(CharSequence cs, FileObject fo)
        throws DataObjectNotFoundException, IOException {

    List<TextDetail> dets = null;
    DataObject dataObject = null;
    int count = 0;
    int limit = Constants.DETAILS_COUNT_LIMIT;
    boolean canRun = true;

    LineReader nelr = new LineReader(cs);
    LineInfo line;
    while ((line = nelr.readNext()) != null && canRun
            && count < limit) {
        Matcher m = pattern.matcher(line.getString());
        while (m.find() && canRun) {
            if (dets == null) {
                dets = new ArrayList<TextDetail>();
                dataObject = DataObject.find(fo);

            }
            TextDetail det = createLineMatchTextDetail(dataObject,
                    line.getNumber(), m, line.getString(), line.start);
            dets.add(det);
            count++;
        }
        if ((line.getNumber() % 50) == 0) {
            synchronized (this) {
                // TODO terminate
                canRun = true;
            }
        }
    }
    return dets;
}
 
Example 38
Source Project: netbeans   Source File: PackageViewTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testReducedTreeCut() throws Exception { // #210314
    SourceGroup g = sampleGroup();
    Node r = new TreeRootNode(g, true);
    Node n = NodeOp.findPath(r, new String[] {"org.netbeans", "modules.stuff"});
    Transferable t = n.clipboardCut();
    DataObject moving = LoaderTransfer.getDataObject(t, LoaderTransfer.MOVE);
    assertEquals(g.getRootFolder().getFileObject("org/netbeans/modules"), moving.getPrimaryFile());
    n = NodeOp.findPath(r, new String[] {"org.netbeans", "spi.stuff", "support"});
    t = n.clipboardCut();
    moving = LoaderTransfer.getDataObject(t, LoaderTransfer.MOVE);
    assertEquals(g.getRootFolder().getFileObject("org/netbeans/spi/stuff/support"), moving.getPrimaryFile());
}
 
Example 39
Source Project: netbeans   Source File: ContextAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * utility method to perform enable/disable logic for refactoring actions
 * @param lookup
 * @param notOnlyFile action is disabled when the selection is on File
 * @param onlyFromEditor action is enabled only in editor
 * @return 
 */
public static boolean canRefactorSingle(Lookup lookup, boolean notOnlyFile, boolean onlyFromEditor) {
    Collection<? extends Node> nodes = new HashSet<Node>(lookup.lookupAll(Node.class));
    if(nodes.size() != 1) {
        return false;
    }
    Node node = nodes.iterator().next();
    TreePathHandle tph = node.getLookup().lookup(TreePathHandle.class);
    if (tph != null) {
        if(JavaRefactoringUtils.isRefactorable(tph.getFileObject())) {
            return !onlyFromEditor || RefactoringUtils.isFromEditor(lookup.lookup(EditorCookie.class));
        } else {
            return false;
        }
    }
    DataObject dObj = node.getLookup().lookup(DataObject.class);
    if(null == dObj) {
        return false;
    }
    FileObject fileObj = dObj.getPrimaryFile();
    if(null == fileObj || !JavaRefactoringUtils.isRefactorable(fileObj)) {
        return false;
    }

    EditorCookie ec = lookup.lookup(EditorCookie.class);
    if (RefactoringUtils.isFromEditor(ec)) {
        return true;
    }
    return !notOnlyFile;
}
 
Example 40
Source Project: netbeans   Source File: CopyPathToClipboardActionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws IOException, PropertyVetoException {

    // create projects
    projects.add(createProject("projectDir1"));
    projects.add(createProject("projectDir2"));

    List l = new LinkedList<DataObject>();
    clearWorkDir();
    FileObject root = FileUtil.toFileObject(getWorkDir());
    FileObject test1 = root.createFolder("test1");
    FileObject test2 = root.createFolder("test2");
    FileObject test1a = test1.createFolder("A");
    FileObject test1aTestClassJava = test1a.createData("TestClass.java");
    FileObject test2DataTxt = test2.createData("data.txt");
    createZipFile(test2);
    DataObject shadowFile = createShadowFile(test2DataTxt);

    FileObject archiveZip = test2.getFileObject("archive.zip");
    assertTrue(FileUtil.isArchiveFile(archiveZip));
    FileObject archiveRoot = FileUtil.getArchiveRoot(archiveZip);
    assertNotNull(archiveRoot);
    FileObject test2ArchiveZipBTxt = archiveRoot.getFileObject("b.txt");

    // test1/A/TestClass.java
    l.add(DataObject.find(test1aTestClassJava));
    // test2/data.txt
    l.add(DataObject.find(test2DataTxt));
    // test2/archive.zip:b.txt
    l.add(DataObject.find(test2ArchiveZipBTxt));
    // /testDataShadows/testShadowFile -> test2/data.txt
    l.add(shadowFile);
    dataObjects = l;
    List<Lookup.Provider> context = new LinkedList<Lookup.Provider>();
    context.addAll(projects);
    context.addAll(dataObjects);
    action = new CopyPathToClipboardAction(context);
}