Java Code Examples for org.openide.loaders.DataObject

The following are top voted examples for showing how to use org.openide.loaders.DataObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: LogAction.java   Source Code and License 6 votes vote down vote up
public static void openHistory (File repositoryRoot, File[] files, String revision) {
    List<Node> nodes = new ArrayList<Node>(files.length);
    for (File file : files) {
        FileObject fo = FileUtil.toFileObject(file);
        if(fo == null) continue;
        DataObject dao;
        try {
            dao = DataObject.find(fo);
        } catch (DataObjectNotFoundException ex) {
            Exceptions.printStackTrace(ex);
            continue;
        }
        nodes.add(dao.getNodeDelegate());
    }
    if(nodes.isEmpty()) return;
    
    String title = NbBundle.getMessage(
            LogAction.class, 
            "MSG_Log_TabTitle", // NOI18N
            Utils.getContextDisplayName(VCSContext.forNodes(nodes.toArray(new Node[nodes.size()]))));
    openHistory(repositoryRoot, files, title, revision);
}
 
Example 2
Project: incubator-netbeans   File: HtmlIndenterTest.java   Source Code and License 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 3
Project: incubator-netbeans   File: DiffSidebar.java   Source Code and License 6 votes vote down vote up
/**
 * Tries to obtain an {@code EditorCookie} representing the given file.
 * @param  fileObj  file to get an {@code EditorCookie} from
 * @return  {@code EditorCookie} representing the file, or {@code null}
 * @throws  java.io.IOException
 *          if there was some I/O error while reading the file's content
 */
private static EditorCookie getEditorCookie(FileObject fileObj) throws IOException {
    DataObject dao;
    try {
        dao = DataObject.find(fileObj);
    } catch (DataObjectNotFoundException ex) {
        return null;
    }

    if (dao instanceof MultiDataObject) {
        MultiDataObject.Entry entry = findEntryForFile((MultiDataObject) dao, fileObj);
        if ((entry != null) && (entry instanceof CookieSet.Factory)) {
            CookieSet.Factory factory = (CookieSet.Factory) entry;
            return factory.createCookie(EditorCookie.class);   //can be null
        }
    }

    return dao.getCookie(EditorCookie.class);                  //can be null
}
 
Example 4
Project: incubator-netbeans   File: SettingChildren.java   Source Code and License 6 votes vote down vote up
protected Node copyNode (Node node) {
    boolean filter = false;
    try {
        DataObject d = (DataObject) node.getCookie (DataObject.class);
        if (d != null) {
            InstanceCookie.Of inst = (InstanceCookie.Of)d.getCookie(InstanceCookie.Of.class);
            if (inst != null && (inst.instanceOf(Node.class) || inst.instanceOf(Node.Handle.class))) {
                // This is just a node, not a real setting. E.g. ModuleNode, LoaderPoolNode. As such,
                // it itself should not display any origin information, it would make no sense. However
                // its children might have a legitimate DataObject cookie from the SFS.
                d = null;
            }
        }
        DataFolder folder = (DataFolder) node.getCookie (DataFolder.class);
        FileSystem fs = d == null || folder != null ? null : d.getPrimaryFile ().getFileSystem ();
        filter = fs == null ? false : fs.isDefault();
    } catch (FileStateInvalidException e) {
        // ignore
    }

    return filter ? new SettingFilterNode (node) : 
        node.isLeaf() ? node.cloneNode() : new TrivialFilterNode(node);
}
 
Example 5
Project: incubator-netbeans   File: MatchingObjectTest.java   Source Code and License 6 votes vote down vote up
private MatchingObject prepareMatchingObject(int numTextDetails)
        throws IOException {
    ResultModel rm = new org.netbeans.modules.search.ResultModel(
            new BasicSearchCriteria(), null, null);
    FileObject fo = FileUtil.createMemoryFileSystem().getRoot()
            .createData("test.tst");
    List<TextDetail> details = new LinkedList<TextDetail>();
    for (int i = 0; i < numTextDetails; i++) {
        TextDetail td = new TextDetail(DataObject.find(fo),
                SearchPattern.create("test", false, false, false));
        details.add(td);
    }
    rm.objectFound(fo, Charset.defaultCharset(), details);
    MatchingObject mo = rm.getMatchingObjects().get(0);
    return mo;
}
 
Example 6
Project: incubator-netbeans   File: CreateNewNonIndexedProperty.java   Source Code and License 6 votes vote down vote up
/** setUp method  */
public void setUp() {
    System.out.println("########  "+getName()+"  #######");
    
    OptionsOperator optionsOperator = OptionsOperator.invoke();
    optionsOperator.selectOption(Bundle.getString("org.netbeans.core.Bundle", "UI/Services/Editing")+"|"+Bundle.getString("org.netbeans.modules.beans.Bundle", "PROP_Option_Menu"));
    PropertySheetOperator propertySheetTabOperator = new PropertySheetOperator(optionsOperator);
    new Property(propertySheetTabOperator, Bundle.getString("org.netbeans.modules.beans.Bundle", "PROP_Option_Prop_Style")).setValue(Bundle.getString("org.netbeans.modules.beans.Bundle", "MSG_Option_Gen_This"));

    FileObject testFile = Repository.getDefault().findResource("gui/data/" + NAME_TEST_FILE + ".java");
    FileObject destination = Repository.getDefault().findFileSystem(sampleDir.replace('\\', '/')).getRoot();
    optionsOperator.close();
    try {
        DataObject.find(testFile).copy(DataFolder.findFolder(destination));
    } catch (IOException e) {
        fail(e);
    }
    new PropertiesAction().perform();
}
 
Example 7
Project: incubator-netbeans   File: ActionUtilsTest.java   Source Code and License 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    clearWorkDir();
    dir = FileUtil.toFileObject(getWorkDir());
    f1 = dir.createData("f1.data");
    f1form = dir.createData("f1.form");
    f2 = dir.createData("f2");
    subdir = dir.createFolder("sub");
    f3 = subdir.createData("f3.data");
    f3a = subdir.createData("f3a.data");
    subdir2 = dir.createFolder("subdir2");
    f4 = subdir2.createData("f3.nondata");
    subsubdir = subdir2.createFolder("sub");
    f5 = subdir2.createData("f1.data");
    f5a = subsubdir.createData("f3.data");
    fx = new XMLFileSystem().getRoot();
    d1 = DataObject.find(f1);
    d2 = DataObject.find(f2);
    d3 = DataObject.find(f3);
    dx = DataObject.find(fx);
    n1 = d1.getNodeDelegate();
    n2 = d2.getNodeDelegate();
    n3 = d3.getNodeDelegate();
    nx = dx.getNodeDelegate();
}
 
Example 8
Project: incubator-netbeans   File: TopComponentOperator.java   Source Code and License 6 votes vote down vote up
/** Closes all opened documents and waits until this top component is closed. */
public void closeAllDocuments() {
    DataObject[] modifs = DataObject.getRegistry().getModified();
    if (modifs.length != 0) {
        // some object modified => need to call in new thread because modal question dialog appears
        new Thread(new Runnable() {

            @Override
            public void run() {
                pushMenuOnTab(closeAllDocumentsItem);
            }
         ;
        }, "thread to closeAllDocuments").start();
    } else {
        // no object modified
        new CloseAllDocumentsAction().perform(this);
        waitComponentShowing(false);
    }
}
 
Example 9
Project: incubator-netbeans   File: CreateFromTemplateDecoratorTest.java   Source Code and License 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 10
Project: incubator-netbeans   File: SelectorUtils.java   Source Code and License 6 votes vote down vote up
private static List<Node> getRootNodes(Project prj,
                                       List<FileObject> roots, 
                                       FilteredNode.NodeFilter filter,
                                       boolean includeFiles) {
    List<Node> nodes = new ArrayList<Node>(roots.size());      
    for (FileObject rfo : roots) {
        try {
            if (includeFiles || (FileUtil.toFile(rfo)!=null)) {
                Project owner = org.netbeans.api.project.FileOwnerQuery.getOwner(rfo);
                Node origNode = DataObject.find(rfo).getNodeDelegate();
                FilteredNode node =  new FilteredNode(origNode,filter, getDisplayName(rfo, owner, prj!=owner));
                nodes.add(node);
            }
        } catch (org.openide.loaders.DataObjectNotFoundException ex) {}
    }
    return nodes;
}
 
Example 11
Project: incubator-netbeans   File: LayerNode.java   Source Code and License 6 votes vote down vote up
@Messages({"LBL_this_layer=<this layer>", "LBL_this_layer_in_context=<this layer in context>"})
@Override protected boolean createKeys(List<DataObject> keys) {
    handle.setAutosave(true);
    FileObject layer = handle.getLayerFile();
    if (layer == null) { // #180872, #212541
        return true;
    }
    Project p = FileOwnerQuery.getOwner(layer);
    if (p == null) { // #175861: inside JAR etc.
        return true;
    }
    FileSystem layerfs = handle.layer(false);
    try {
        if (layerfs != null) {
            keys.add(DataObject.find(badge(layerfs, handle.getLayerFile(), LBL_this_layer(), null).getRoot()));
        }
        LayerHandle h = LayerHandle.forProject(p);
        if (layer.equals(h.getLayerFile())) {
            h.setAutosave(true); // #135376
            keys.add(DataObject.find(badge(LayerUtils.getEffectiveSystemFilesystem(p), handle.getLayerFile(), LBL_this_layer_in_context(), handle.layer(false)).getRoot()));
        }
    } catch (IOException e) {
        Util.err.notify(ErrorManager.INFORMATIONAL, e);
    }
    return true;
}
 
Example 12
Project: netbeans-textlint-plugin   File: TextlintPushTaskScanner.java   Source Code and License 6 votes vote down vote up
public static List<Task> create(TextlintJsonResult[] results, FileObject fileObject) {
    List<Task> tasks = new ArrayList<>();
    final DataObject dataObject = getDataObject(fileObject);
    if (results != null && dataObject != null) {
        Line.Set lineSet = getLineSet(dataObject);
        if (lineSet != null) {
            for (TextlintJsonResult result : results) {
                result.getMessages().forEach((message) -> {
                    Line line = getCurrentLine(lineSet, message.getLine());
                    OpenAction defaultAction = line != null ? new OpenAction(line) : null;
                    Action[] popupActions = createPopupActions(dataObject, fileObject, message.getFix());
                    String description = String.format(MESSAGE_FORMAT,
                            message.getRuleId(),
                            message.getMessage(),
                            message.getLine(),
                            message.getIndex());
                    String groupName = message.getFix() != null ? TEXTLINT_FIXABLE_GROUP_NAME : TEXTLINT_GROUP_NAME;
                    tasks.add(Task.create(fileObject.toURL(), groupName, description, defaultAction, popupActions));
                });
            }
        }
    }
    return tasks;
}
 
Example 13
Project: incubator-netbeans   File: ImageNavigatorPanel.java   Source Code and License 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 14
Project: incubator-netbeans   File: ResourcePathCompleter.java   Source Code and License 6 votes vote down vote up
private void toCompletionItems(String folderName, Collection<FileObject> files) {
    for (FileObject f : files) {
        DataObject d;
        try {
            d = DataObject.find(f);
        } catch (DataObjectNotFoundException ex) {
            // ???
            continue;
        }
        String value = folderName == null ? f.getNameExt() : folderName + "/" + f.getNameExt();
        if (f.isFolder()) {
            value = value + "/";
        }
        if (resourceRef) {
            value = "@" + value;
        }
        if (context.isAttribute()) {
            value = "\"" + value  + "\"";
        }
        CompletionItem item = new ResourcePathItem(d, context, value, null);
        results.add(item);
    }
}
 
Example 15
Project: incubator-netbeans   File: SCFTHandlerTest.java   Source Code and License 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 16
Project: incubator-netbeans   File: PaletteItemTest.java   Source Code and License 6 votes vote down vote up
public void testFindItem() throws Exception {
    FileObject itemFile = createItemFileWithActiveEditorDrop();
    assertNotNull(itemFile);

    //create palette
    PaletteController pc = PaletteFactory.createPalette(PALETTE_ROOT, new DummyActions());
    
    //find node with ActiveEditorDrop impl in its lookup
    Node root = (Node)pc.getRoot().lookup(Node.class);
    Node[] cats = root.getChildren().getNodes(true);
    Node foundNode = null;
    Node foundCat = null;
    assertEquals("Too many categories", 1, cats.length);
    Node[] items = cats[0].getChildren().getNodes(true);
    assertEquals("Too many items", 1, items.length);
    
    assertTrue("Item not found.",
                DataObject.find(itemFile).getNodeDelegate().getLookup().lookup(ActiveEditorDrop.class) ==
                                                   items[0].getLookup().lookup(ActiveEditorDrop.class)
    ); 

}
 
Example 17
Project: incubator-netbeans   File: Selenium2Support.java   Source Code and License 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
 */
public static DataObject loadTestTemplate(String templateID) {
    // get the Test class template
    String path = 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 18
Project: incubator-netbeans   File: JavaRefactoringActionsProviderTest.java   Source Code and License 6 votes vote down vote up
public void test211193() throws Exception {
    writeFilesAndWaitForScan(src,
            new File("t/A.java", "package t;\n"
            + "public class A {\n"
            + "    public static void foo() {\n"
            + "        int someArray[] = {};\n"
            + "    }\n"
            + "}"));
    FileObject testFile = src.getFileObject("t/A.java");
    DataObject testFileDO = DataObject.find(testFile);
    EditorCookie ec = testFileDO.getLookup().lookup(EditorCookie.class);
    ec.open();
    ec.getOpenedPanes()[0].setCaretPosition(71);
    ec.getOpenedPanes()[0].moveCaretPosition(80);
    final AtomicInteger called = new AtomicInteger();
    ContextAnalyzer.SHOW = new ContextAnalyzer.ShowUI() {
        @Override
        public void show(RefactoringUI ui, TopComponent activetc) {
            assertNotNull(ui);
            called.incrementAndGet();
        }
    };
    int expectedCount = 0;
    new RefactoringActionsProvider().doRename(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
}
 
Example 19
Project: incubator-netbeans   File: HibernateEnvironmentImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a map of mapping file objects and list of names of Java classes (POJOs) that are defined in 
 * that mapping file for this configuration.
 * 
 * @param configFileObject the configuration FileObject.
 * @return Map of mapping FileObject with List of POJO class names.
 */
public Map<FileObject, List<String>> getAllPOJONamesFromConfiguration(FileObject configFileObject) {
    Map<FileObject, List<String>> mappingPOJOMap = new HashMap<FileObject, List<String>>();
    try {
        HibernateCfgDataObject hibernateCfgDO = (HibernateCfgDataObject) DataObject.find(configFileObject);
        for (String mappingFileName : getAllHibernateMappingsFromConfiguration(hibernateCfgDO.getHibernateConfiguration())) {
            for (FileObject mappingFO : getAllHibernateMappingFileObjects()) {
                if (mappingFileName.contains(mappingFO.getName())) {
                    List<String> l = getPOJONameFromMapping(mappingFO);
                    mappingPOJOMap.put(mappingFO, l);
                }
            }
        }
    } catch (DataObjectNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    }

    return mappingPOJOMap;
}
 
Example 20
Project: incubator-netbeans   File: BugtrackingOwnerSupport.java   Source Code and License 5 votes vote down vote up
private static FileObject getOpenFileObj() {
    TopComponent activatedTopComponent = TopComponent.getRegistry()
                                         .getActivated();
    if (activatedTopComponent == null) {
        return null;
    }

    DataObject dataObj = activatedTopComponent.getLookup()
                         .lookup(DataObject.class);
    if ((dataObj == null) || !dataObj.isValid()) {
        return null;
    }

    return dataObj.getPrimaryFile();
}
 
Example 21
Project: incubator-netbeans   File: CompatibilityUtilsTest.java   Source Code and License 5 votes vote down vote up
@Override
protected Node[] createNodes(FileObject key) {
    try {
        return new Node[]{new MockProjectNode(key, Lookups.singleton(DataObject.find(key)))};
    } catch (DataObjectNotFoundException ex) {
        fail("Cannot find data object " + key.getPath());
        return new Node[0];
    }
}
 
Example 22
Project: incubator-netbeans   File: AsciiMultiLineMappedMatcher.java   Source Code and License 5 votes vote down vote up
/**
 * Perform pattern matching inside the whole file.
 *
 * @param cb Character buffer.
 * @param fo File object.
 */
private List<TextDetail> matchWholeFile(CharSequence cb, FileObject fo)
        throws DataObjectNotFoundException {

    Matcher textMatcher = pattern.matcher(cb);
    DataObject dataObject = null;
    LineInfoHelper lineInfoHelper = new LineInfoHelper(cb);

    List<TextDetail> textDetails = null;

    while (textMatcher.find()) {
        if (textDetails == null) {
            textDetails = new LinkedList<TextDetail>();
            dataObject = DataObject.find(fo);
            fileMatches++;
        }
        itemMatches++;
        TextDetail ntd = new TextDetail(dataObject, searchPattern);
        lineInfoHelper.findAndSetPositionInfo(ntd, textMatcher.start(),
                textMatcher.end(), textMatcher.group());
        textDetails.add(ntd);
        if (fileMatches >= Constants.COUNT_LIMIT
                || itemMatches
                >= Constants.DETAILS_COUNT_LIMIT) {
            break;
        }
    }
    return textDetails;
}
 
Example 23
Project: incubator-netbeans   File: NbEditorToolBarTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests that the action context for the context-aware toolbar actions
 * is the DataObject corresponding to the current document if there is no
 * Lookup.Provider ancestor.
 */
public void testActionContextFallbackToDataObject() throws Exception {
    JPanel parent = new JPanel();
    JEditorPane editor = new JEditorPane();
    editor.setEditorKit(new NbEditorKit());
    parent.add(editor);
    DataObject docDataObject = createDataObject();
    assertNotNull(docDataObject);
    editor.getDocument().putProperty(Document.StreamDescriptionProperty, docDataObject);

    Lookup actionContext = NbEditorToolBar.createActionContext(editor);
    assertNotNull(actionContext.lookup(Node.class));
    assertNull(actionContext.lookup(Foo.class));
}
 
Example 24
Project: incubator-netbeans   File: ExternalReferenceDataNode.java   Source Code and License 5 votes vote down vote up
public String getPrefix() {
    
    if (prefix == null) {
        DataObject dobj = (DataObject) getLookup().lookup(DataObject.class);
        if( dobj !=null && !(dobj.getPrimaryFile().isFolder()) )
            prefix = decorator.generatePrefix(prefix, dobj);
        else
            prefix ="";
    }
    return prefix;
}
 
Example 25
Project: incubator-netbeans   File: DataEditorSupport.java   Source Code and License 5 votes vote down vote up
private DOEnvLookup (DataObject dobj, InstanceContent ic) {
    super (ic);
    this.ic = ic;
    this.dobj = dobj;
	dobj.addPropertyChangeListener(WeakListeners.propertyChange(this, dobj));
     
    updateLookup ();
}
 
Example 26
Project: incubator-netbeans   File: NbKeymap.java   Source Code and License 5 votes vote down vote up
/**
 * Traverses shadow files to origin.
 * Returns impl class name if that is obvious (common for SystemAction's);
 * else just returns file path (usual for more modern registrations).
 */
private static String idForFile(FileObject f) {
    if (f.hasExt(SHADOW_EXT)) {
        String path = (String) f.getAttribute("originalFile");
        if (path != null && f.getSize() == 0) {
            f = FileUtil.getConfigFile(path);
            if (f == null) {
                return path; // #169887: some race condition with layer init?
            }
        } else {
            try {
                DataObject d = DataObject.find(f);
                if (d instanceof DataShadow) {
                    f = ((DataShadow) d).getOriginal().getPrimaryFile();
                }
            } catch (DataObjectNotFoundException x) {
                LOG.log(Level.FINE, f.getPath(), x);
            }
        }
    }
    // Cannot actually load instanceCreate methodvalue=... attribute; just want to see if it is there.
    if (f.hasExt("instance") && !Collections.list(f.getAttributes()).contains("instanceCreate")) {
        String clazz = (String) f.getAttribute("instanceClass");
        if (clazz != null) {
            return clazz;
        } else {
            return f.getName().replace('-', '.');
        }
    }
    return f.getPath();
}
 
Example 27
Project: incubator-netbeans   File: DataEditorSupportEncodingTest.java   Source Code and License 5 votes vote down vote up
public void testIncompatibleCharacter() throws Exception {
    DataObject d = DataObject.find(testFileObject);
    
    encodingName = "ISO-8859-1"; // NOI18N
    
    EditorCookie o = d.getLookup().lookup(EditorCookie.class);
    StyledDocument doc = o.openDocument();
    doc.insertString(0, CZECH_STRING_UTF, null);
    
    try {
        o.saveDocument();
        
        // try to open the file
        InputStream istm = testFileObject.getInputStream();
        try {
            BufferedReader r = new BufferedReader(new InputStreamReader(istm, "ISO-8859-2")); // NOI18N
            String line = r.readLine();
            
            int questionMarkPos = line.indexOf('?'); // NOI18N
            
            assertTrue("Should save question marks", questionMarkPos != -1); // NOI18N
        } finally {
            istm.close();
        }
        //fail("Exception expected");
    } catch (UnmappableCharacterException ex) {
        // expected exceptiom
    }
}
 
Example 28
Project: incubator-netbeans   File: FormNode.java   Source Code and License 5 votes vote down vote up
@Override
public <T extends Node.Cookie> T getCookie(Class<T> type) {
    T cookie = super.getCookie(type);
    if (cookie == null
        && (DataObject.class.isAssignableFrom(type)
            || SaveCookie.class.isAssignableFrom(type)
            || CloseCookie.class.isAssignableFrom(type)
            || PrintCookie.class.isAssignableFrom(type)))
    {
        FormDataObject fdo = FormEditor.getFormDataObject(formModel);
        if (fdo != null)
            cookie = fdo.getCookie(type);
    }
    return cookie;
}
 
Example 29
Project: incubator-netbeans   File: LayersBridge.java   Source Code and License 5 votes vote down vote up
/**
 * Returns instance of GlobalAction encapsulating action, or null.
 */
private GlobalAction createAction (DataObject dataObject, String prefix, String name, boolean ignoreUserRemoves) {
    InstanceCookie ic = dataObject.getCookie(InstanceCookie.class);
    // handle any non-IC file as instruction to remove the action
    FileObject pf = dataObject.getPrimaryFile();
    if (ignoreUserRemoves && pf.canRevert()) {
        return null;
    }
    if (ic == null) {
        if (!EXT_REMOVED.equals(pf.getExt())) {
            LOG.log(Level.WARNING, "Invalid shortcut: {0}", dataObject);
            return null;
        }
        // ignore the 'remove' file, if there's a shadow (= real action) present
        if (FileUtil.findBrother(pf, "shadow") != null) {
            // handle redefinition + removal: ignore the removal.
            return null;
        }
        return REMOVED;
    }
    try {
        Object action = ic.instanceCreate ();
        if (action == null) return null;
        if (!(action instanceof Action)) return null;
        return createAction((Action) action, prefix, name);
    } catch (Exception ex) {
        ex.printStackTrace ();
        return null;
    }
}
 
Example 30
Project: incubator-netbeans   File: CookieManager.java   Source Code and License 5 votes vote down vote up
/**
 */
public CookieManager (DataObject dataObject, CookieSet cookieSet, Class clazz) {        
    if ( CookieFactoryCreator.class.isAssignableFrom (clazz) == false ) {
        throw new IllegalArgumentException ("Parameter class must extend CookieFactoryCreator class.");
    }

    this.dataObject = dataObject;
    this.cookieSet  = cookieSet;
    this.factoryMap = new HashMap<CookieFactoryCreator, CookieFactory>();

    register (clazz);

    addedToResult (getResult());
}
 
Example 31
Project: incubator-netbeans   File: FormatingTest.java   Source Code and License 5 votes vote down vote up
public void test177858() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
            "package hierbas.del.litoral;\n"
            + "\n"
            + "public class Test {\n"
            + "     {\n"
            + "         java.util.Set<String\n"
            + "     }\n"
            + "}\n");
    FileObject testSourceFO = FileUtil.toFileObject(testFile);
    DataObject testSourceDO = DataObject.find(testSourceFO);
    EditorCookie ec = (EditorCookie)testSourceDO.getCookie(EditorCookie.class);
    final Document doc = ec.openDocument();
    doc.putProperty(Language.class, JavaTokenId.language());
    String content =
            "package hierbas.del.litoral;\n\n"
            + "public class Test {\n\n"
            + "    {\n"
            + "        java.util.Set<String\n"
            + "    }\n"
            + "}\n";

    String golden =
            "package hierbas.del.litoral;\n\n"
            + "public class Test {\n\n"
            + "    {\n"
            + "        java.util.Set<String\n"
            + "    }\n"
            + "}\n";
    reformat(doc, content, golden);
}
 
Example 32
Project: incubator-netbeans   File: TestDataDirsNodeFactory.java   Source Code and License 5 votes vote down vote up
private Node findPathPlain(FileObject fo, FileObject groupRoot, Node rootNode) {
    FileObject folder = fo.isFolder() ? fo : fo.getParent();
    String relPath = FileUtil.getRelativePath(groupRoot, folder);
    List<String> path = new ArrayList<String>();
    StringTokenizer strtok = new StringTokenizer(relPath, "/"); // NOI18N
    while (strtok.hasMoreTokens()) {
        String token = strtok.nextToken();
       path.add(token);
    }
    try {
        Node folderNode =  folder.equals(groupRoot) ? rootNode : NodeOp.findPath(rootNode, Collections.enumeration(path));
        if (fo.isFolder()) {
            return folderNode;
        } else {
            Node[] childs = folderNode.getChildren().getNodes(true);
            for (int i = 0; i < childs.length; i++) {
               DataObject dobj = childs[i].getLookup().lookup(DataObject.class);
               if (dobj != null && dobj.getPrimaryFile().getNameExt().equals(fo.getNameExt())) {
                   return childs[i];
               }
            }
        }
    } catch (NodeNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 33
Project: incubator-netbeans   File: CssModuleTestBase.java   Source Code and License 5 votes vote down vote up
protected Document getDocumentForFileObject(FileObject file) {
    try {
        DataObject d = DataObject.find(file);
        EditorCookie ec = d.getLookup().lookup(EditorCookie.class);
        if (ec == null) {
            return null;
        }
        return ec.openDocument();
    } catch (IOException e) {
        throw new AssertionError("Cann't load document", e);
    }

}
 
Example 34
Project: incubator-netbeans   File: JavaElementFoldManager.java   Source Code and License 5 votes vote down vote up
public synchronized void initFolds(FoldHierarchyTransaction transaction) {
    Document doc = operation.getHierarchy().getComponent().getDocument();
    Object od = doc.getProperty(Document.StreamDescriptionProperty);
    
    if (od instanceof DataObject) {
        FileObject file = ((DataObject)od).getPrimaryFile();

        task = JavaElementFoldTask.getTask(file);
        task.setJavaElementFoldManager(JavaElementFoldManager.this, file);
    }
}
 
Example 35
Project: incubator-netbeans   File: XMLDataObjectTest.java   Source Code and License 5 votes vote down vote up
public void testLookup() throws Exception {
    MockLookup.setInstances(XMLDataLoader.getLoader(XMLDataLoader.class));

    FileObject document = FileUtil.toFileObject(
            FileUtil.normalizeFile(getDataDir())).getFileObject("dummyXMLDocument.xml");

    assertNotNull(document);

    DataObject object = DataObject.find(document);
    assertTrue(object instanceof XMLDataObject);

    XMLDataObject dataObject = (XMLDataObject) object;
    assertNotNull(dataObject.getLookup().lookup(FileObject.class));

    EditCookie ec = (EditCookie)dataObject.getCookie(EditCookie.class);
    assertNotNull("Editor cookie found", ec);

    EditCookie lkp = dataObject.getLookup().lookup(EditCookie.class);
    assertEquals("Cookies are the same", ec, lkp);

    OpenCookie lkp2 = dataObject.getLookup().lookup(OpenCookie.class);

    lkp.edit();
    lkp2.open();

    Set<?> all = null;
    for (int i = 0; i < 10; i++) {
        Thread.sleep(1000);
        all = WindowManager.getDefault().getRegistry().getOpened();
        if (all.size() > 0) {
            break;
        }
    }

    assertEquals("There is just one TC: " + all, 1, all.size());

    assertEquals("Cookies are the same", lkp, lkp2);
}
 
Example 36
Project: incubator-netbeans   File: NodeUtils.java   Source Code and License 5 votes vote down vote up
/**
 * open pom file for given FileObject, for items from local repository creates a read-only FO.
 * @param fo 
 * @since 2.67
 */
public static void openPomFile(FileObject fo) {
    DataObject dobj;
    try {
        dobj = DataObject.find(NodeUtils.readOnlyLocalRepositoryFile(fo));
        EditCookie edit = dobj.getLookup().lookup(EditCookie.class);
        if (edit != null) {
            edit.edit();
        }
    } catch (DataObjectNotFoundException ex) {
        LOG.log(Level.FINE, "Cannot find dataobject", ex);
    }
}
 
Example 37
Project: incubator-netbeans   File: BrowseFolders.java   Source Code and License 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    String command = e.getActionCommand();

    if (COMMAND_SELECT.equals(command)) {
        Node selection[] = browsePanel.getExplorerManager().getSelectedNodes();

        if (selection != null && selection.length > 0) {
            DataObject dobj = (DataObject) selection[0].getLookup().lookup(DataObject.class);
            result = dobj.getPrimaryFile();
        }
    }
}
 
Example 38
Project: incubator-netbeans   File: TemplatesPanelTest.java   Source Code and License 5 votes vote down vote up
public void testDuplicateTemplate () {
    DataObject dobj = TemplatesPanel.createTemplateFromFile (popural, f);
    DataObject dupl = TemplatesPanel.createDuplicateFromNode (dobj.getNodeDelegate ());
    assertNotNull ("Duplicate DataObject found.", dobj);
    assertTrue ("Duplicate is template.", dobj.isTemplate ());
    assertEquals ("Template is in same folder as original.", dobj.getFolder (), dupl.getFolder ());
    assertTrue ("Name is derived from original.", dupl.getNodeDelegate ().getName ().startsWith (dobj.getNodeDelegate ().getName ()));
}
 
Example 39
Project: incubator-netbeans   File: FormEditor.java   Source Code and License 5 votes vote down vote up
private void attachDataObjectListener() {
    if (dataObjectListener != null)
        return;

    dataObjectListener = new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent ev) {
            if (DataObject.PROP_NAME.equals(ev.getPropertyName())) {
                // FormDataObject's name has changed
                String name = formDataObject.getName();
                formModel.setName(name);
                formRootNode.updateName(name);
                // multiview updated by FormEditorSupport
                // code regenerated by FormRefactoringUpdate
            }
            else if (DataObject.PROP_COOKIE.equals(ev.getPropertyName())
                     && formDesigner != null) {
                for (Node node : formDesigner.getSelectedNodes()) {
                    if (node instanceof FormNode) { // Issue 181709
                        ((FormNode)node).updateCookies();
                    }
                }
            }
        }
    };

    formDataObject.addPropertyChangeListener(dataObjectListener);
}
 
Example 40
Project: incubator-netbeans   File: SafeDeleteUI.java   Source Code and License 5 votes vote down vote up
@Override
public void doRefactoringBypass() throws IOException {
    RequestProcessor.getDefault().post(new Runnable() {

        @Override
        public void run() {
            try {
                // #172199
                FileUtil.runAtomicAction(new FileSystem.AtomicAction() {

                    @Override
                    public void run() throws IOException {
                        for (FileObject file : getRefactoring().getRefactoringSource().lookupAll(FileObject.class)) {
                            if(file.isValid()) {
                                DataObject.find(file).delete();
                            }
                        }
                        NonRecursiveFolder f = (NonRecursiveFolder) getRefactoring().getRefactoringSource().lookup(NonRecursiveFolder.class);
                        if (f != null) {
                            deletePackage(f.getFolder());
                        }
                    }
                });
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        
    });

}