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

The following examples show how to use org.openide.loaders.DataObject#find() . 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: SCFTHandlerTest.java    From netbeans with 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 2
Source File: EarDataNodeTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testGetActions() throws Exception {
    File ddFile = new File(getWorkDir(), "application.xml");
    String ddContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<application version=\"1.4\" xmlns=\"http://java.sun.com/xml/ns/j2ee\" " +
            "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
            "xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee " +
            "http://java.sun.com/xml/ns/j2ee/application_1_4.xsd\">" +
            "</application>";
    EarDataNodeTest.dump(ddFile, ddContent);
    FileObject fo = FileUtil.toFileObject(ddFile);
    EarDataObject edo = (EarDataObject) DataObject.find(fo);
    Action[] action = edo.getNodeDelegate().getActions(false);
    for (int i = 0; i < action.length; i++) {
        assertFalse("OpenAction is not present yet", action[i] instanceof OpenAction);
    }
}
 
Example 3
Source File: MainWindow.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to find custom status line component on system file system.
 * @return status line component or <code>null</code> if no status line
 *         component is found on system file system.
 */
private static JComponent getCustomStatusLine() {
    try {
        String fileName = Constants.CUSTOM_STATUS_LINE_PATH;
        if (fileName == null) {
            return null;
        }
        FileObject fo = FileUtil.getConfigFile(fileName);
        if (fo != null) {
            DataObject dobj = DataObject.find(fo);
            InstanceCookie ic = (InstanceCookie)dobj.getCookie(InstanceCookie.class);
            if (ic != null) {
                return (JComponent)ic.instanceCreate();
            }
        }
    } catch (Exception e) {
        Exceptions.printStackTrace(e);
    }
    return null;
}
 
Example 4
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static List<PositionBounds> prepareSpansFor(FileObject file, Iterable<? extends int[]> spans) {
    List<PositionBounds> result = new ArrayList<PositionBounds>();

    try {
        DataObject d = DataObject.find(file);
        EditorCookie ec = d.getLookup().lookup(EditorCookie.class);
        CloneableEditorSupport ces = (CloneableEditorSupport) ec;

        result = new LinkedList<PositionBounds>();

        for (int[] span : spans) {
            PositionRef start = ces.createPositionRef(span[0], Bias.Forward);
            PositionRef end = ces.createPositionRef(span[1], Bias.Forward);

            result.add(new PositionBounds(start, end));
        }
    } catch (DataObjectNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    }

    return result;
}
 
Example 5
Source File: RecentFiles.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Icon findIconForPath(String path) {
    FileObject fo = RecentFiles.convertPath2File(path);
    final Icon i;
    if (fo == null) {
        i = null;
    } else {
        DataObject dObj;
        try {
            dObj = DataObject.find(fo);
        } catch (DataObjectNotFoundException e) {
            dObj = null;
        }
        i = dObj == null
                ? null
                : new ImageIcon(dObj.getNodeDelegate().getIcon(
                BeanInfo.ICON_COLOR_16x16));
    }
    return i;
}
 
Example 6
Source File: LatteIndenterTestBase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected BaseDocument getDocument(FileObject fo, String mimeType, Language language) {
    // for some reason GsfTestBase is not using DataObjects for BaseDocument construction
    // which means that for example Java formatter which does call EditorCookie to retrieve
    // document will get difference instance of BaseDocument for indentation
    try {
        DataObject dobj = DataObject.find(fo);
        assertNotNull(dobj);
        EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class);
        assertNotNull(ec);
        return (BaseDocument) ec.openDocument();
    } catch (Exception ex) {
        fail(ex.toString());
        return null;
    }
}
 
Example 7
Source File: ScriptingCreateFromTemplateTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void XtestCreateFromTemplateDocumentCreated() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.txt");
    OutputStream os = fo.getOutputStream();
    os.write("test".getBytes());
    os.close();
    fo.setAttribute ("template", Boolean.TRUE);
    fo.setAttribute("javax.script.ScriptEngine", "freemarker");

    MockServices.setServices(MockMimeLookup.class);
    MockMimeLookup.setInstances(MimePath.parse("content/unknown"), new TestEditorKit());
    
    DataObject obj = DataObject.find(fo);
    DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(root, "target"));
    
    assertFalse(TestEditorKit.createDefaultDocumentCalled);
    DataObject inst = obj.createFromTemplate(folder, "test");
    assertTrue(TestEditorKit.createDefaultDocumentCalled);
    
    String exp = "test";
    assertEquals(exp, inst.getPrimaryFile().asText());
}
 
Example 8
Source File: GitUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the file is binary.
 *
 * @param file file to check
 * @return true if the file cannot be edited in NetBeans text editor, false otherwise
 */
public static boolean isFileContentBinary(File file) {
    FileObject fo = FileUtil.toFileObject(file);
    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 9
Source File: BeanInstaller.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Recursive method scanning folders for classes (class files) that could
 * be JavaBeans. */
private static void scanFolderForBeans(FileObject folder, final Map<String,ItemInfo> beans, final ClassSource.Entry root) {
    JavaClassHandler handler = new JavaClassHandler() {
        @Override
        public void handle(String className, String problem) {
            if (problem == null) {
                ItemInfo ii = new ItemInfo();
                ii.classname = className;
                ii.entry = root;
                beans.put(ii.classname, ii);
            }
        }
    };
                
    FileObject[] files = folder.getChildren();
    for (int i=0; i < files.length; i++) {
        FileObject fo = files[i];
        if (fo.isFolder()) {
            scanFolderForBeans(fo, beans, root);
        }
        else try {
            if ("class".equals(fo.getExt()) // NOI18N
                 && (DataObject.find(fo) != null))
            {                   
                scanFileObject(folder, fo, handler);
            }
        }
        catch (org.openide.loaders.DataObjectNotFoundException ex) {} // should not happen
    }
}
 
Example 10
Source File: EditorConfigProcessorTest.java    From editorconfig-netbeans with MIT License 5 votes vote down vote up
@Test
public void itDoesNotLoopOnTrimTrailingWhiteSpaceOperation() throws Exception {
  // Setup test file
  DataObject dataObject = null;
  File file = null;

  String content = "alert('Hello World!'); ";

  try {
    file = File.createTempFile(this.getClass().getSimpleName(), ".js");
    Path path = Paths.get(Utilities.toURI(file));
    Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
    dataObject = DataObject.find(FileUtil.toFileObject(file));
  } catch (IOException ex) {
    Exceptions.printStackTrace(ex);
  }

  // Setup EditorConfig
  MappedEditorConfig config = new MappedEditorConfig();
  config.setEndOfLine(System.lineSeparator());
  config.setTrimTrailingWhiteSpace(true);

  // Run processor
  EditorConfigProcessor proc = new EditorConfigProcessor();
  FileInfo info = proc.excuteOperations(dataObject, config);
  assertEquals(true, info.isFileChangeNeeded());

  /* 
   Run the processor a second time and test that a file change is NOT 
   needed (because it has been already performed during the first run).
   */
  proc.flushFile(info);
  info = proc.excuteOperations(dataObject, config);
  assertEquals(false, info.isFileChangeNeeded());

  // Delete test file
  assertEquals(true, file.delete());
}
 
Example 11
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 12
Source File: TestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Document getDefaultDocument(FileObject fo) throws DataObjectNotFoundException, IOException {
    DataObject dobj = DataObject.find(fo);
    assertNotNull(dobj);

    EditorCookie cookie = dobj.getCookie(EditorCookie.class);
    assertNotNull(cookie);

    Document document = (Document) cookie.openDocument();
    return document;
}
 
Example 13
Source File: TransformPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void browseXSLTButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseXSLTButtonActionPerformed

        try {
            File selectedFile=getFileFromChooser(getXSL());
            if (selectedFile==null) return;
            FileObject fo = FileUtil.toFileObject(selectedFile);
            DataObject dObj = fo == null ? null : DataObject.find(fo);
            if (dObj==null || !TransformUtil.isXSLTransformation(dObj)) {
                NotifyDescriptor desc =  new NotifyDescriptor.Message(
                    NbBundle.getMessage(TransformPanel.class, "MSG_notXslFile", //NOI18N
                    selectedFile.getName()),NotifyDescriptor.ERROR_MESSAGE);
                DialogDisplayer.getDefault().notify(desc);
                return;
            }
            setXSL(TransformUtil.getURLName(fo));

            if ( ( userSetOutput == false ) && ( xmlHistory != null ) ) {
                setOutput(xmlHistory.getXSLOutput(data.xsl));
            }
            if ( userSetProcess == false ) {
                setProcessOutput(null);
            }
            updateXSLComboBoxModel(data.xsl);

            updateComponents();

            setCaretPosition(transformComboBox);
            
        } catch (IOException exc) { // TransformUtil.getURLName (...)
            // ignore it
            //Util.THIS.debug(exc);
        } finally {
            //Util.icons = null;
        }
    }
 
Example 14
Source File: SQLEditorSupportNormalTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    FileObject folder = FileUtil.toFileObject(getWorkDir()).createFolder("folder" + System.currentTimeMillis());
    fileObject = folder.createData("SQLFile", "sql");
    
    MockServices.setServices(Pool.class);
    assertEquals(Pool.class, Lookup.getDefault().lookup(DataLoaderPool.class).getClass());
    
    dataObject = DataObject.find(fileObject);
    support = (MySQLEditorSupport)dataObject.getCookie(OpenCookie.class);
}
 
Example 15
Source File: LoadScenarioTask.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
private DataObject loadPartialOrderScript(Scenario scenario) {
    if (scenario.getScriptPartialOrder() != null) {
        try {
            File partialOrderFile = new File(scenario.getScriptPartialOrder().getScriptFile());
            FileObject pofo = FileUtil.toFileObject(partialOrderFile);
            DataObject javascript = DataObject.find(pofo);
            return javascript;
        } catch (DataObjectNotFoundException e) {
            logger.warn(e.getMessage());
            logger.trace(e);
            status.setStatusText(Bundle.MSG_LoadError().concat(e.getLocalizedMessage()));
        }
    }
    return null;
}
 
Example 16
Source File: AbstractTestUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the template with the given name.
 */
public static DataObject getTemplate(String tname) throws DataObjectNotFoundException {
    FileObject fileObject = Repository.getDefault().findResource("Templates/" + tname);
    if (fileObject == null) {
        throw new IllegalArgumentException("Cannot find template: " + tname);
    }
    return DataObject.find(fileObject);
}
 
Example 17
Source File: MemoryTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Object [] findEditorCookies(File f) throws IOException {
    //System.out.println("f = " + f.getPath());
    FileObject ff1 = FileUtil.toFileObject(f);
    //System.out.println("ff = " + ff1);
    DataObject dd1 = DataObject.find(ff1);
    //System.out.println("dd = " + dd1);
    return new Object [] {
        dd1.getCookie(EditCookie.class),
        dd1.getCookie(OpenCookie.class),
        dd1.getCookie(EditorCookie.class),
    };
}
 
Example 18
Source File: JavaDataObject.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected DataObject handleCopyRename(DataFolder df, String name, String ext) throws IOException {
    FileObject fo = getPrimaryEntry ().copyRename (df.getPrimaryFile (), name, ext);
    DataObject dob = DataObject.find( fo );
    //TODO invoke refactoring here (if needed)
    return dob;
}
 
Example 19
Source File: JaxWsServiceCreator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void generateWebServiceFromEJB(String wsName, FileObject pkg, 
        ProjectInfo projectInfo, Node[] nodes) 
        throws IOException, ServiceAlreadyExistsExeption, PropertyVetoException 
{

    if (nodes != null && nodes.length == 1) {

        EjbReference ejbRef = nodes[0].getLookup().lookup(EjbReference.class);
        if (ejbRef != null) {

            DataFolder df = DataFolder.findFolder(pkg);
            FileObject template = Templates.getTemplate(wiz);
            FileObject templateParent = template.getParent();
            if ((Boolean)wiz.getProperty(WizardProperties.IS_STATELESS_BEAN)) { //EJB Web Service
                template = templateParent.getFileObject("EjbWebServiceNoOp", 
                        "java"); //NOI18N
            } else {
                template = templateParent.getFileObject("WebServiceNoOp", 
                        "java"); //NOI18N
            }
            DataObject dTemplate = DataObject.find(template);
            DataObject dobj = dTemplate.createFromTemplate(df, wsName);
            FileObject createdFile = dobj.getPrimaryFile();
            createdFile.setAttribute("jax-ws-service", java.lang.Boolean.TRUE);     // NOI18N
            dobj.setValid(false);
            dobj = DataObject.find(createdFile);

            ClassPath classPath = getClassPathForFile(projectInfo.getProject(), 
                    createdFile);
            if (classPath != null) {
                String serviceImplPath = classPath.getResourceName(createdFile, 
                        '.', false);
                generateDelegateMethods(createdFile, ejbRef);

                final JaxWsModel jaxWsModel = projectInfo.getProject().
                    getLookup().lookup(JaxWsModel.class);
                if (jaxWsModel != null) {
                    jaxWsModel.addService(wsName, serviceImplPath);
                    ProjectManager.mutex().writeAccess(new Runnable() {

                        public void run() {
                            try {
                                jaxWsModel.write();
                            } catch (IOException ex) {
                                ErrorManager.getDefault().notify(ex);
                            }
                        }
                    });
                }
            }
            JaxWsUtils.openFileInEditor(dobj);
            displayDuplicityWarning(createdFile);
        }
    }
}
 
Example 20
Source File: EvaluationSpanTaskTest.java    From netbeans with Apache License 2.0 3 votes vote down vote up
private void prepareTest(String fileName, String code) throws Exception {
    clearWorkDir();
    File wdFile = getWorkDir();
    FileUtil.refreshFor(wdFile);

    FileObject wd = FileUtil.toFileObject(wdFile);
    assertNotNull(wd);
    sourceRoot = FileUtil.createFolder(wd, "src");
    FileObject buildRoot = FileUtil.createFolder(wd, "build");
    FileObject cache = FileUtil.createFolder(wd, "cache");

    FileObject data = FileUtil.createData(sourceRoot, fileName);
    File dataFile = FileUtil.toFile(data);

    assertNotNull(dataFile);

    TestUtilities.copyStringToFile(dataFile, code);

    SourceUtilsTestUtil.prepareTest(sourceRoot, buildRoot, cache);

    DataObject od = DataObject.find(data);
    EditorCookie ec = od.getLookup().lookup(EditorCookie.class);

    assertNotNull(ec);

    doc = ec.openDocument();
    doc.putProperty(Language.class, JavaTokenId.language());
    doc.putProperty("mimeType", "text/x-java");

    JavaSource js = JavaSource.forFileObject(data);

    assertNotNull(js);

    info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);

    assertNotNull(info);
}