Java Code Examples for org.openide.cookies.SaveCookie#save()
The following examples show how to use
org.openide.cookies.SaveCookie#save() .
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: WSUtils.java From netbeans with Apache License 2.0 | 6 votes |
private static void deleteFile(FileObject f) { FileLock lock = null; try { DataObject dObj = DataObject.find(f); if (dObj != null) { SaveCookie save = dObj.getCookie(SaveCookie.class); if (save!=null) save.save(); } lock = f.lock(); f.delete(lock); } catch(java.io.IOException e) { NotifyDescriptor ndd = new NotifyDescriptor.Message(NbBundle.getMessage(WSUtils.class, "MSG_Unable_Delete_File", f.getNameExt()), NotifyDescriptor.ERROR_MESSAGE); DialogDisplayer.getDefault().notify(ndd); } finally { if(lock != null) { lock.releaseLock(); } } }
Example 2
Source File: CreatedModifiedFiles.java From netbeans with Apache License 2.0 | 6 votes |
@Override public void run() throws IOException { //#65420 it can happen the manifest is currently being edited. save it // and cross fingers because it can be in inconsistent state try { DataObject dobj = DataObject.find(mfFO); SaveCookie safe = dobj.getLookup().lookup(SaveCookie.class); if (safe != null) { safe.save(); } } catch (DataObjectNotFoundException ex) { Util.err.notify(ErrorManager.WARNING, ex); } EditableManifest em = Util.loadManifest(mfFO); em.addSection(dataLoaderClass); em.setAttribute("OpenIDE-Module-Class", "Loader", dataLoaderClass); // NOI18N if (installBefore != null) { em.setAttribute("Install-Before", installBefore, dataLoaderClass); //NOI18N } Util.storeManifest(mfFO, em); }
Example 3
Source File: CatalogFileWrapperDOMImpl.java From netbeans with Apache License 2.0 | 5 votes |
boolean saveBySaveCookie(){ try { DataObject dobj = DataObject.find(backendCatalogFileObj); SaveCookie saveCookie = (SaveCookie) dobj.getCookie(SaveCookie.class); assert(saveCookie != null); saveCookie.save(); } catch (IOException ex) { return false; } return true; }
Example 4
Source File: ClientHandlerButtonListener.java From netbeans with Apache License 2.0 | 5 votes |
private static void saveFile(FileObject file) throws IOException { DataObject dataObject = DataObject.find(file); if (dataObject != null) { SaveCookie cookie = dataObject.getCookie(SaveCookie.class); if (cookie != null) { cookie.save(); } } }
Example 5
Source File: TestCatalogModel.java From netbeans with Apache License 2.0 | 5 votes |
public SchemaModel getSchemaModel(NamespaceLocation nl) throws Exception { if (nl.getResourceFile().exists()) { ModelSource source = singletonCatMod.getModelSource(nl.getLocationURI()); DataObject dobj = (DataObject) source.getLookup().lookup(DataObject.class); SaveCookie save = (SaveCookie) dobj.getCookie(SaveCookie.class); if (save != null) save.save(); FileObject fo = (FileObject) source.getLookup().lookup(FileObject.class); fo.delete(); } nl.refreshResourceFile(); return getSchemaModel(nl.getLocationURI()); }
Example 6
Source File: EjbModuleTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testChangeDescription() throws Exception { String descriptionName = "test New description"; getDetailPanel().getDescriptionTextArea().setText(descriptionName); // check DD beans assertEquals("DD bean isn't updated", descriptionName, DDProvider.getDefault().getDDRoot(ddFo).getDescription(null)); checkinXML("<description>" + descriptionName + "</description>"); //save ejb-jar.xml editor SaveCookie saveCookie = (SaveCookie) ddObj.getCookie(SaveCookie.class); assertNotNull("Save cookie is null, Data object isn't changed!", saveCookie); if (saveCookie != null) { saveCookie.save(); } }
Example 7
Source File: AddWsOperationHelper.java From netbeans with Apache License 2.0 | 5 votes |
private void saveFile(FileObject file) throws IOException { DataObject dataObject = DataObject.find(file); if (dataObject!=null) { SaveCookie cookie = dataObject.getCookie(SaveCookie.class); if (cookie!=null) cookie.save(); } }
Example 8
Source File: PropertiesDataObject.java From netbeans with Apache License 2.0 | 5 votes |
/** Moves primary and secondary files to a new folder. * Overrides superclass method. * @param df the new folder * @return the moved primary file object * @throws IOException if there was a problem moving * @throws UserCancelException if the user cancelled the move */ @Override protected FileObject handleMove(DataFolder df) throws IOException { if (LOG.isLoggable(FINER)) { LOG.finer("handleMove(" //NOI18N + FileUtil.getFileDisplayName(df.getPrimaryFile()) + ')'); } BundleStructure oldStructure = (MultiBundleStructure) bundleStructure; FileObject fo = this.getPrimaryFile(); // a simple fix of issue #92195 (impossible to save a moved prop. file): SaveCookie saveCookie = getCookie(SaveCookie.class); if (saveCookie != null) { saveCookie.save(); } PropertiesOpen openCookie = (PropertiesOpen) getCookie(OpenCookie.class); if (openCookie != null) { openCookie.removeModifiedListener(this); openCookie.close(); bundleStructure = null; openSupport = null; } // getCookieSet().remove(openCookie); try { // pasteSuffix = createPasteSuffix(df); return super.handleMove(df); } finally { //Here data object has old path still but in invalid state if (oldStructure!=null && oldStructure.getEntryCount()>1) { oldStructure.updateEntries(); oldStructure.notifyOneFileChanged(fo); } pasteSuffix = null; bundleStructure = null; openSupport = null; } }
Example 9
Source File: DocumentsDlg.java From netbeans with Apache License 2.0 | 5 votes |
private void saveDocuments(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveDocuments // Add your handling code here: Node[] selNodes = explorer.getSelectedNodes(); if (selNodes.length == 0) { return; } for (int i = 0; i < selNodes.length; i++) { TopComponent tc = ((TopComponentNode) selNodes[i]).getTopComponent(); Lookup l = tc.getLookup(); SaveCookie sc = (SaveCookie) l.lookup(SaveCookie.class); if (sc != null) { try { sc.save(); } catch (IOException exc) { Logger.getAnonymousLogger().log(Level.WARNING, "[WinSys.DocumentsDlg.saveDocuments]" // NOI18N + " Warning: Cannot save content of TopComponent: [" // NOI18N + WindowManagerImpl.getInstance().getTopComponentDisplayName(tc) + "]" // NOI18N + " [" + tc.getClass().getName() + "]", exc); // NOI18N } //Refresh name of node because TopComponent name is probably changed too //('*' is removed) ((TopComponentNode) selNodes[i]).refresh(); } } jButtonSave.setEnabled(false); }
Example 10
Source File: AddWsOperationHelper.java From netbeans with Apache License 2.0 | 5 votes |
private void saveFile(FileObject file) throws IOException { DataObject dataObject = DataObject.find(file); if (dataObject!=null) { SaveCookie cookie = dataObject.getCookie(SaveCookie.class); if (cookie!=null) cookie.save(); } }
Example 11
Source File: NbLifecycleManager.java From netbeans with Apache License 2.0 | 5 votes |
@Override public void saveAll() { ArrayList<DataObject> bad = new ArrayList<>(); DataObject[] modifs = DataObject.getRegistry().getModified(); if (modifs.length == 0) { // Do not show MSG_AllSaved return; } for (DataObject dobj : modifs) { try { SaveCookie sc = dobj.getLookup().lookup(SaveCookie.class); if (sc != null) { StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage(NbLifecycleManager.class, "CTL_FMT_SavingMessage", dobj.getName())); sc.save(); } } catch (IOException ex) { Logger.getLogger(NbLifecycleManager.class.getName()).log(Level.WARNING, null, ex); bad.add(dobj); } } NotifyDescriptor descriptor; //recode this part to show only one dialog? for (DataObject badDO : bad) { descriptor = new NotifyDescriptor.Message( NbBundle.getMessage(NbLifecycleManager.class, "CTL_Cannot_save", badDO.getPrimaryFile().getName())); DialogDisplayer.getDefault().notify(descriptor); } // notify user that everything is done StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(NbLifecycleManager.class, "MSG_AllSaved")); }
Example 12
Source File: GenerateDTDSupport.java From netbeans with Apache License 2.0 | 5 votes |
/** * Performs a dialog with a user and generates the DTD */ public void generate() { try { //save the XML document before DTD generation SaveCookie save = (SaveCookie)template.getCookie(SaveCookie.class); if (save!=null) save.save(); FileObject primFile = template.getPrimaryFile(); String name = primFile.getName(); FileObject folder = primFile.getParent(); //use same name as the XML for default DTD name FileObject generFile = (new SelectFileDialog(folder, name, DTD_EXT, Util.NONEMPTY_CHECK)).getFileObject(); //new name as per user name = generFile.getName(); // get project's encoding String encoding = EncodingUtil.getProjectEncoding(primFile); //generate DTD content generateDTDContent(encoding, name, generFile); GuiUtil.performDefaultAction(generFile); } catch (UserCancelException e) { } catch (Exception exc) { GuiUtil.notifyException(exc); } }
Example 13
Source File: I18nManager.java From netbeans with Apache License 2.0 | 5 votes |
/** Cancels current internationalizing session and re-layout top component to original layout. */ public void cancel() { if (replaceCount>0) { //Need to save resource DataObject resource = support.getResourceHolder().getResource(); if (resource != null) { SaveCookie save = resource.getCookie(SaveCookie.class); if (save!=null) { try { save.save(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } } } replaceCount = 0; // No memory leaks. support = null; if(LOG.isLoggable(Level.FINEST)) { LOG.logp(Level.FINEST, getClass().getName(), "cancel()", "Sets the I18nSupport to null"); // NOI18N } closeDialog(); }
Example 14
Source File: CompletionTestCase.java From netbeans with Apache License 2.0 | 5 votes |
private static void saveDocument(DataObject file) throws IOException { //!!!WARNING: if this exception is thrown, the test may be locked (the file in editor may be modified, but not saved. problems with IDE finishing are supposed in this case). SaveCookie sc = (SaveCookie) file.getCookie(SaveCookie.class); if (sc != null) { sc.save(); } }
Example 15
Source File: DataGetModifiedTest.java From netbeans with Apache License 2.0 | 4 votes |
private void doTestSavableRegistry(boolean save) throws Exception { class L implements ChangeListener { int cnt; @Override public void stateChanged(ChangeEvent e) { assertTrue(e.getSource() instanceof Collection); for (Object o : (Collection)e.getSource()) { assertTrue("DataObject is the value: " + o, o instanceof DataObject); } cnt++; } } L listener = new L(); DataObject.getRegistry().addChangeListener(listener); do1.getLookup().lookup(EditorCookie.class).openDocument().insertString(0, "Ahoj", null); String name = do1.getNodeDelegate().getDisplayName(); assertTrue("DataObject is modified", do1.isModified()); assertEquals("One change in registry", 1, listener.cnt); Savable savable = findSavable(name); assertNotNull("Savable for the do1 lookup found", savable); savable.save(); assertFalse("DataObject no longer modified", do1.isModified()); assertEquals("2nd change in registry", 2, listener.cnt); do1.getLookup().lookup(EditorCookie.class).openDocument().insertString(0, "Ahoj", null); assertTrue("DataObject is modified again", do1.isModified()); assertEquals("3rd change in registry", 3, listener.cnt); Savable another = findSavable(name); assertNotSame("It is different instance", savable, another); assertEquals("But it remains equals", savable, another); assertTrue("DataObject savables provide Icons", another instanceof Icon); savable.save(); assertTrue("Calling save on old savable has no impact", do1.isModified()); SaveCookie sc = do1.getLookup().lookup(SaveCookie.class); if (save) { sc.save(); } else { do1.setModified(false); } assertFalse("Unmodified", do1.isModified()); assertNull("No save cookie", do1.getLookup().lookup(SaveCookie.class)); Savable none = findSavable(name); assertNull("No savable for our dataobject found", none); }
Example 16
Source File: JSFConfigModelUtilities.java From netbeans with Apache License 2.0 | 4 votes |
/** * attempts to save the document model to disk. * if model is in transaction, the transaction is ended first, * then dataobject's SaveCookie is called. * * @param model * @throws java.io.IOException if saving fails. */ public static void saveChanges(DocumentModel<?> model) throws IOException { if (model.isIntransaction()) { try { model.endTransaction(); } catch (IllegalStateException ex) { IOException io = new IOException("Cannot save faces config", ex); throw Exceptions.attachLocalizedMessage(io, NbBundle.getMessage(JSFConfigModelUtilities.class, "ERR_Save_FacesConfig", Exceptions.findLocalizedMessage(ex))); } } model.sync(); DataObject dobj = model.getModelSource().getLookup().lookup(DataObject.class); if (dobj == null) { final Document doc = model.getModelSource().getLookup().lookup(Document.class); final File file = model.getModelSource().getLookup().lookup(File.class); LOGGER.log(Level.FINE, "saving changes in {0}", file); File parent = file.getParentFile(); FileObject parentFo = FileUtil.toFileObject(parent); if (parentFo == null) { parent.mkdirs(); FileUtil.refreshFor(parent); parentFo = FileUtil.toFileObject(parent); } final FileObject fParentFo = parentFo; if (fParentFo != null) { FileSystem fs = parentFo.getFileSystem(); fs.runAtomicAction(new FileSystem.AtomicAction() { @Override public void run() throws IOException { String text; try { text = doc.getText(0, doc.getLength()); } catch (BadLocationException x) { throw new IOException(x); } FileObject fo = fParentFo.getFileObject(file.getName()); if (fo == null) { fo = fParentFo.createData(file.getName()); } OutputStream os = fo.getOutputStream(); try { os.write(text.getBytes(FileEncodingQuery.getEncoding(fo))); } finally { os.close(); } } }); } } else { SaveCookie save = dobj.getLookup().lookup(SaveCookie.class); if (save != null) { LOGGER.log(Level.FINE, "saving changes in {0}", dobj); save.save(); } else { LOGGER.log(Level.FINE, "no changes in {0}", dobj); } } }
Example 17
Source File: AbstractTestUtil.java From netbeans with Apache License 2.0 | 4 votes |
/** Saves DataObject */ public static void saveDataObject(DataObject dataObject) throws IOException { SaveCookie cookie = (SaveCookie) dataObject.getCookie(SaveCookie.class); if (cookie == null) throw new IllegalStateException("Cannot save document without SaveCookie."); cookie.save(); }
Example 18
Source File: Util.java From netbeans with Apache License 2.0 | 4 votes |
/** * Create new DataObject with requested locale and notify that new locale was added * @param propertiesDataObject DataObject to add locale * @param locale * @param copyInitialContent */ public static void createLocaleFile(PropertiesDataObject propertiesDataObject, String locale, boolean copyInitialContent) { try { if(locale.length() == 0) { // It would mean default locale to create again. notifyError(locale); return; } if(propertiesDataObject != null) { // FileObject file = propertiesDataObject.getPrimaryFile(); FileObject file = propertiesDataObject.getBundleStructure().getNthEntry(0).getFile(); String extension = PropertiesDataLoader.PROPERTIES_EXTENSION; if (!file.hasExt(extension)) { if (file.getMIMEType().equalsIgnoreCase(PropertiesDataLoader.PROPERTIES_MIME_TYPE)) extension = file.getExt(); } //Default locale may be deleted final String newName = getBaseName(file.getName()) + PropertiesDataLoader.PRB_SEPARATOR_CHAR + locale; final FileObject folder = file.getParent(); // final PropertiesEditorSupport editor = (PropertiesEditorSupport)propertiesDataObject.getCookie(PropertiesEditorSupport.class); java.util.Iterator it = propertiesDataObject.secondaryEntries().iterator(); while (it.hasNext()) { FileObject f = ((FileEntry)it.next()).getFile(); if (newName.startsWith(f.getName()) && f.getName().length() > file.getName().length()) file = f; } if (file.getName().equals(newName)) { return; // do nothing if the file already exists } if (copyInitialContent) { if (folder.getFileObject(newName, extension) == null) { SaveCookie save = (SaveCookie) propertiesDataObject.getCookie(SaveCookie.class); if (save != null) { save.save(); } final FileObject templateFile = file; final String ext = extension; folder.getFileSystem().runAtomicAction(new FileSystem.AtomicAction() { public void run() throws IOException { templateFile.copy(folder, newName, ext); } }); //find just created DataObject PropertiesDataObject dataObject = (PropertiesDataObject) DataObject.find(folder.getFileObject(newName, extension)); dataObject.setBundleStructure(propertiesDataObject.getBundleStructure()); //update entries in BundleStructure propertiesDataObject.getBundleStructure().updateEntries(); //Add it to OpenSupport propertiesDataObject.getOpenSupport().addDataObject(dataObject); //Notify BundleStructure that one file changed propertiesDataObject.getBundleStructure().notifyOneFileChanged(folder.getFileObject(newName, extension)); } } else { // Create an empty file - creating from template via DataObject // API would create a separate DataObject for the locale file. // After creation force the DataObject to refresh its entries. DataObject.find(folder.createData(newName, extension)); //update entries in BundleStructure propertiesDataObject.getBundleStructure().updateEntries(); } } } catch(IOException ioe) { if(Boolean.getBoolean("netbeans.debug.exceptions")) // NOI18N ioe.printStackTrace(); notifyError(locale); } }
Example 19
Source File: MethodGenerator.java From netbeans with Apache License 2.0 | 4 votes |
@org.netbeans.api.annotations.common.SuppressWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") public static void deleteMethod(final FileObject implClass, final String operationName) throws IOException{ JavaSource targetSource = JavaSource.forFileObject(implClass); CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>() { @Override public void run(WorkingCopy workingCopy) throws java.io.IOException { workingCopy.toPhase(Phase.ELEMENTS_RESOLVED); //workingCopy.toPhase(Phase.ELEMENTS_RESOLVED); ClassTree javaClass = SourceUtils.getPublicTopLevelTree(workingCopy); if (javaClass!=null) { ExecutableElement method = new MethodVisitor(workingCopy). getMethod( operationName); TreeMaker make = workingCopy.getTreeMaker(); if(method != null){ MethodTree methodTree = workingCopy.getTrees().getTree( method); ClassTree modifiedJavaClass = make.removeClassMember( javaClass, methodTree); workingCopy.rewrite(javaClass, modifiedJavaClass); boolean removeImplementsClause = false; //find out if there are no more exposed operations, if so remove the implements clause if(! new MethodVisitor(workingCopy).hasPublicMethod()){ removeImplementsClause = true; } if(removeImplementsClause){ //TODO: need to remove implements clause on the SEI //for now all implements are being remove List<? extends Tree> implementeds = javaClass. getImplementsClause(); for(Tree implemented : implementeds) { modifiedJavaClass = make. removeClassImplementsClause(modifiedJavaClass, implemented); } workingCopy.rewrite(javaClass, modifiedJavaClass); } } } } //} public void cancel() { } }; targetSource.runModificationTask(task).commit(); DataObject dobj = DataObject.find(implClass); if (dobj!=null) { SaveCookie cookie = dobj.getCookie(SaveCookie.class); if (cookie!=null) cookie.save(); } }
Example 20
Source File: JavaSourceTest.java From netbeans with Apache License 2.0 | 4 votes |
public void testJavaSourceIsReclaimable() throws MalformedURLException, InterruptedException, IOException, BadLocationException { FileObject test = createTestFile ("Test1"); ClassPath bootPath = createBootPath (); ClassPath compilePath = createCompilePath (); ClassPath srcPath = createSourcePath(); JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, srcPath), test); DataObject dobj = DataObject.find(test); EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class); final StyledDocument[] doc = new StyledDocument[] {ec.openDocument()}; doc[0].putProperty(Language.class, JavaTokenId.language()); TokenHierarchy h = TokenHierarchy.get(doc[0]); TokenSequence ts = h.tokenSequence(JavaTokenId.language()); Thread.sleep(500); CountDownLatch[] latches = new CountDownLatch[] { new CountDownLatch (1), new CountDownLatch (1) }; AtomicInteger counter = new AtomicInteger (0); CancellableTask<CompilationInfo> task = new DiagnosticTask(latches, counter, Phase.PARSED); JavaSourceAccessor.getINSTANCE().addPhaseCompletionTask (js,task,Phase.PARSED,Priority.HIGH, TaskIndexingMode.ALLOWED_DURING_SCAN); assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch[] {latches[0]}, 15000)); Thread.sleep(500); //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it NbDocument.runAtomic (doc[0], new Runnable () { public void run () { try { String text = doc[0].getText(0,doc[0].getLength()); int index = text.indexOf(REPLACE_PATTERN); assertTrue (index != -1); doc[0].remove(index,REPLACE_PATTERN.length()); doc[0].insertString(index,"System.out.println();",null); } catch (BadLocationException ble) { ble.printStackTrace(System.out); } } }); assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch[] {latches[1]}, 15000)); JavaSourceAccessor.getINSTANCE().removePhaseCompletionTask (js,task); Reference jsWeak = new WeakReference(js); Reference testWeak = new WeakReference(test); SaveCookie sc = (SaveCookie) dobj.getCookie(SaveCookie.class); sc.save(); sc = null; js = null; test = null; dobj = null; ec = null; doc[0] = null; //give the worker thread chance to remove the task: //if the tests starts to fail randomly, try to increment the timeout Thread.sleep(1000); assertGC("JavaSource is reclaimable", jsWeak); //the file objects is held by the timers component //and maybe others: assertGC("FileObject is reclaimable", testWeak); }