Java Code Examples for org.openide.filesystems.FileObject#getOutputStream()
The following examples show how to use
org.openide.filesystems.FileObject#getOutputStream() .
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: DefaultCreationNoTest.java From netbeans with Apache License 2.0 | 6 votes |
/** * Checks that a file without CreateFromTemplate handler creates OK as copy of the template * @throws Exception */ public void testCreateNoHandler() throws Exception { FileObject root = FileUtil.createMemoryFileSystem().getRoot(); FileObject templ = FileUtil.createData(root, "simpleTemplate.txt"); String txt = "{a}"; OutputStream os = templ.getOutputStream(); os.write(txt.getBytes()); os.close(); DataObject obj = DataObject.find(templ); DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(root, "target")); Map m = new HashMap(); m.put("a", "eeee"); DataObject x = obj.createFromTemplate(folder, "nue", m); assertEquals(txt + "\n", x.getPrimaryFile().asText()); }
Example 2
Source File: ReferencesCountTest.java From netbeans with Apache License 2.0 | 6 votes |
private FileObject createSource( @NonNull final FileObject root, @NonNull final String fqn, @NonNull final String content) throws IOException { final FileObject file = FileUtil.createData(root, fqn.replace('.', '/')+"."+JavaDataLoader.JAVA_EXTENSION); //NOI18N final FileLock lck = file.lock(); try { final PrintWriter out = new PrintWriter(new OutputStreamWriter(file.getOutputStream(lck),"UTF-8")); //NOI18N try { out.print(content); } finally { out.close(); } } finally { lck.releaseLock(); } return file; }
Example 3
Source File: LanguagesDataObject.java From netbeans with Apache License 2.0 | 6 votes |
private static void copyAndSubstituteTokens(final URL content, final FileLock lock, final FileObject targetFO, final Map<String,String> tokens) throws IOException { OutputStream os = targetFO.getOutputStream(lock); try { PrintWriter pw = new PrintWriter(os); try { InputStream is = content.openStream(); try { Reader r = new InputStreamReader(is); BufferedReader br = new BufferedReader(r); String line; while ((line = br.readLine()) != null) { pw.println(tokens == null ? line : replaceTokens(tokens, line)); } } finally { is.close(); } } finally { pw.close(); } } finally { os.close(); } }
Example 4
Source File: SourceTest.java From netbeans with Apache License 2.0 | 6 votes |
private void writeToFileObject(FileObject f, String documentContent, String eol) throws IOException { assertTrue("No UTF-8 available", Charset.isSupported("UTF-8")); OutputStream os = f.getOutputStream(); try { byte [] eolBytes = eol.getBytes("UTF-8"); byte [] bytes = documentContent.getBytes("UTF-8"); for(byte b : bytes) { if (b == '\n') { os.write(eolBytes); } else { os.write(b); } } } finally { os.close(); } }
Example 5
Source File: FileUtil.java From jeddict with Apache License 2.0 | 6 votes |
public static void expandTemplate(InputStream template, FileObject toFile, Map<String, Object> values) throws IOException { Charset targetEncoding = FileEncodingQuery.getEncoding(toFile); if (toFile.isLocked()) { LOG.log(Level.SEVERE, "File {0} is locked", new Object[]{toFile.getName()}); return; } FileLock lock = toFile.lock(); try (Writer writer = new OutputStreamWriter(toFile.getOutputStream(lock), targetEncoding)) { expandTemplate(new InputStreamReader(template), writer, values, targetEncoding); } finally { lock.releaseLock(); } DataObject dob = DataObject.find(toFile); if (dob != null) { reformat(dob); } }
Example 6
Source File: CopyTest.java From netbeans with Apache License 2.0 | 5 votes |
private static void writeTo (FileSystem fs, String res, String content) throws java.io.IOException { FileObject fo = org.openide.filesystems.FileUtil.createData (fs.getRoot (), res); org.openide.filesystems.FileLock lock = fo.lock (); java.io.OutputStream os = fo.getOutputStream (lock); os.write (content.getBytes ()); os.close (); lock.releaseLock (); }
Example 7
Source File: WLTrustHandler.java From netbeans with Apache License 2.0 | 5 votes |
public static synchronized void removeFromTrustStore(String url) throws GeneralSecurityException, IOException { FileObject root = FileUtil.getConfigRoot(); FileObject ts = root.getFileObject(TRUST_STORE_PATH); if (ts == null) { return; } char[] password = Keyring.read(TRUST_PASSWORD_KEY); KeyStore keystore = KeyStore.getInstance("JKS"); // NOI18N InputStream is = new BufferedInputStream(ts.getInputStream()); try { keystore.load(is, password); } catch (IOException ex) { LOGGER.log(Level.INFO, null, ex); return; } finally { is.close(); } keystore.deleteEntry(url); OutputStream out = new BufferedOutputStream(ts.getOutputStream()); try { keystore.store(out, password); } finally { out.close(); } }
Example 8
Source File: TextmateLexerTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testNETBEANS2430() throws Exception { FileObject grammar = FileUtil.createData(FileUtil.getConfigRoot(), "Editors/text/test/grammar.json"); try (OutputStream out = grammar.getOutputStream(); Writer w = new OutputStreamWriter(out)) { w.write("{ \"scopeName\": \"test\", " + " \"patterns\": [\n" + " { \"name\": \"string.test\",\n" + " \"begin\": \"x([^x]+)x\",\n" + " \"end\": \"x\\\\1x\"\n" + " },\n" + " { \"name\": \"whitespace.test\",\n" + " \"match\": \" +\"\n" + " }\n" + "]}\n"); } grammar.setAttribute(LanguageHierarchyImpl.GRAMMAR_MARK, "test"); Document doc = new PlainDocument(); doc.insertString(0, " xaax xbbx\nxccx xaax ", null); doc.putProperty(Language.class, new LanguageHierarchyImpl("text/test", "test").language()); TokenHierarchy hi = TokenHierarchy.get(doc); TokenSequence<?> ts = hi.tokenSequence(); LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " "); assertTokenProperties(ts, "test", "whitespace.test"); //do not fully lex doc.insertString(3, "a", null); ts = hi.tokenSequence(); LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " "); assertTokenProperties(ts, "test", "whitespace.test"); LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaaax"); assertTokenProperties(ts, "test", "string.test"); LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " xbbx\n"); assertTokenProperties(ts, "test", "string.test"); LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xccx xaax \n"); assertFalse(ts.moveNext()); }
Example 9
Source File: AndroidProjectTemplateWizardIterator.java From NBANDROID-V2 with Apache License 2.0 | 5 votes |
private static void filterProjectXML(FileObject fo, ZipInputStream str, String name) throws IOException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileUtil.copy(str, baos); Document doc = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false, false, null, null); NodeList nl = doc.getDocumentElement().getElementsByTagName("name"); if (nl != null) { for (int i = 0; i < nl.getLength(); i++) { Element el = (Element) nl.item(i); if (el.getParentNode() != null && "data".equals(el.getParentNode().getNodeName())) { NodeList nl2 = el.getChildNodes(); if (nl2.getLength() > 0) { nl2.item(0).setNodeValue(name); } break; } } } try (OutputStream out = fo.getOutputStream()) { XMLUtil.write(doc, out, "UTF-8"); } } catch (Exception ex) { Exceptions.printStackTrace(ex); writeFile(str, fo); } }
Example 10
Source File: SCFTHandlerTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testBasePropertiesAlwaysPresent() throws Exception { FileObject root = FileUtil.createMemoryFileSystem().getRoot(); FileObject fo = FileUtil.createData(root, "simpleObject.txt"); OutputStream os = fo.getOutputStream(); String txt = "print('<html><h1>'); print(name); print('</h1>');" + "print('<h2>'); print(date); print('</h2>');" + "print('<h3>'); print(time); print('</h3>');" + "print('<h4>'); print(user); print('</h4>');" + "print('<h4>'); print(dateTime.getTime()); print('</h4>');" + "print('</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 res = readFile(n.getPrimaryFile()); if (res.indexOf("date") >= 0) fail(res); if (res.indexOf("time") >= 0) fail(res); if (res.indexOf("user") >= 0) fail(res); if (res.indexOf("name") >= 0) fail(res); if (res.indexOf("dateTime") >= 0) fail(res); }
Example 11
Source File: DataFolderTimeOrderTest.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected void setUp () throws Exception { clearWorkDir(); MockServices.setServices(Pool.class); String fsstruct [] = new String [] { "AA/X.txt", "AA/Y.txt", }; lfs = TestUtilHid.createLocalFileSystem (getWorkDir (), fsstruct); final FileObject x = lfs.findResource("AA/X.txt"); assertNotNull("X.txt", x); Thread.sleep(5); final FileObject y = lfs.findResource("AA/Y.txt"); assertNotNull("Y.txt", y); OutputStream os = y.getOutputStream(); os.write("Ahoj".getBytes()); os.close(); org.openide.filesystems.test.TestFileUtils.touch(y, x); aa = DataFolder.findFolder (lfs.findResource ("AA")); aa.addPropertyChangeListener (this); }
Example 12
Source File: Utilities.java From netbeans with Apache License 2.0 | 5 votes |
@NonNull static FileObject copyBuildScript (@NonNull final Project project) throws IOException { final FileObject projDir = project.getProjectDirectory(); FileObject rpBuildScript = projDir.getFileObject(BUILD_SCRIPT_PATH); if (rpBuildScript != null && !isBuildScriptUpToDate(project)) { // try to close the file just in case the file is already opened in editor DataObject dobj = DataObject.find(rpBuildScript); CloseCookie closeCookie = dobj.getLookup().lookup(CloseCookie.class); if (closeCookie != null) { closeCookie.close(); } final FileObject nbproject = projDir.getFileObject("nbproject"); //NOI18N final FileObject backupFile = nbproject.getFileObject(BUILD_SCRIPT_BACK_UP, "xml"); //NOI18N if (backupFile != null) { backupFile.delete(); } FileUtil.moveFile(rpBuildScript, nbproject, BUILD_SCRIPT_BACK_UP); rpBuildScript = null; } if (rpBuildScript == null) { if (LOG.isLoggable(Level.FINE)) { LOG.log( Level.FINE, "Updating remote build script in project {0} ({1})", //NOI18N new Object[]{ ProjectUtils.getInformation(project).getDisplayName(), FileUtil.getFileDisplayName(projDir) }); } rpBuildScript = FileUtil.createData(project.getProjectDirectory(), BUILD_SCRIPT_PATH); try( final InputStream in = new BufferedInputStream(RemotePlatformProjectSaver.class.getResourceAsStream(BUILD_SCRIPT_PROTOTYPE)); final OutputStream out = new BufferedOutputStream(rpBuildScript.getOutputStream())) { FileUtil.copy(in, out); } } return rpBuildScript; }
Example 13
Source File: SaasUtil.java From netbeans with Apache License 2.0 | 5 votes |
public static FileObject extractWadlFile(WadlSaas saas) throws IOException { InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(saas.getUrl()); if (in == null) { return null; } OutputStream out = null; FileObject wadlFile; try { FileObject dir = saas.getSaasFolder(); FileObject catalogDir = dir.getFileObject("catalog"); // NOI18N if (catalogDir == null) { catalogDir = dir.createFolder(CATALOG); } String wadlFileName = deriveFileName(saas.getUrl()); wadlFile = catalogDir.getFileObject(wadlFileName); if (wadlFile == null) { wadlFile = catalogDir.createData(wadlFileName); } out = wadlFile.getOutputStream(); FileUtil.copy(in, out); } finally { in.close(); if (out != null) { out.close(); } } return wadlFile; }
Example 14
Source File: J2SEDeployProperties.java From netbeans with Apache License 2.0 | 5 votes |
static FileObject copyBuildNativeTemplate(@NonNull final Project project) throws IOException { Parameters.notNull("project", project); //NOI18N final FileObject buildExFoBack = project.getProjectDirectory().getFileObject(String.format( "%s~", //NOI18N EXTENSION_BUILD_SCRIPT_PATH)); if (buildExFoBack != null) { closeInEditor(buildExFoBack); buildExFoBack.delete(); } FileObject buildExFo = project.getProjectDirectory().getFileObject(EXTENSION_BUILD_SCRIPT_PATH); FileLock lock; if (buildExFo != null) { closeInEditor(buildExFo); lock = buildExFo.lock(); try { buildExFo.rename( lock, buildExFo.getName(), String.format( "%s~", //NOI18N buildExFo.getExt())); } finally { lock.releaseLock(); } } buildExFo = FileUtil.createData(project.getProjectDirectory(), EXTENSION_BUILD_SCRIPT_PATH); lock = buildExFo.lock(); try (final InputStream in = J2SEDeployProperties.class.getClassLoader().getResourceAsStream(BUILD_SCRIPT_PROTOTYPE); final OutputStream out = buildExFo.getOutputStream(lock)) { FileUtil.copy(in, out); } finally { lock.releaseLock(); } return buildExFo; }
Example 15
Source File: ReferenceHelperTest.java From netbeans with Apache License 2.0 | 5 votes |
private void writeProperties(FileObject prop, String[] keys, String[] values) throws Exception { EditableProperties p = new EditableProperties(false); for (int cntr = 0; cntr < keys.length; cntr++) { p.setProperty(keys[cntr], values[cntr]); } OutputStream os = prop.getOutputStream(); try { p.store(os); } finally { os.close(); } }
Example 16
Source File: SnapshotTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testSnapshotEmbedding166592 () throws IOException { clearWorkDir (); FileObject workDir = FileUtil.toFileObject (getWorkDir ()); FileObject testFile = FileUtil.createData (workDir, "bla"); OutputStream outputStream = testFile.getOutputStream (); OutputStreamWriter writer = new OutputStreamWriter (outputStream); writer.append ("Toto je testovaci file, na kterem se budou delat hnusne pokusy!!!"); writer.close (); Source source = Source.create (testFile); Snapshot originalSnapshot = source.createSnapshot (); Embedding languageJednaEmbedding = Embedding.create (Arrays.asList (new Embedding[] { originalSnapshot.create (18, 4, "text/jedna"), originalSnapshot.create (33, 15, "text/jedna"), })); assertEquals ("text/jedna", languageJednaEmbedding.getMimeType ()); Snapshot languageJednaSnapshot = languageJednaEmbedding.getSnapshot (); assertEquals ("text/jedna", languageJednaSnapshot.getMimeType ()); assertEquals ("file se budou delat", languageJednaSnapshot.getText ().toString ()); assertEquals (18, languageJednaSnapshot.getOriginalOffset (0)); assertEquals (21, languageJednaSnapshot.getOriginalOffset (3)); assertEquals (33, languageJednaSnapshot.getOriginalOffset (4)); assertEquals (43, languageJednaSnapshot.getOriginalOffset (14)); assertEquals (48, languageJednaSnapshot.getOriginalOffset (19)); assertEquals (-1, languageJednaSnapshot.getOriginalOffset (20)); assertEquals (-1, languageJednaSnapshot.getEmbeddedOffset (0)); assertEquals (-1, languageJednaSnapshot.getEmbeddedOffset (17)); assertEquals (0, languageJednaSnapshot.getEmbeddedOffset (18)); assertEquals (3, languageJednaSnapshot.getEmbeddedOffset (21)); assertEquals (4, languageJednaSnapshot.getEmbeddedOffset (22)); assertEquals (-1, languageJednaSnapshot.getEmbeddedOffset (23)); assertEquals (-1, languageJednaSnapshot.getEmbeddedOffset (32)); assertEquals (4, languageJednaSnapshot.getEmbeddedOffset (33)); assertEquals (5, languageJednaSnapshot.getEmbeddedOffset (34)); assertEquals (-1, languageJednaSnapshot.getEmbeddedOffset (32)); }
Example 17
Source File: LanguageStorageTest.java From netbeans with Apache License 2.0 | 4 votes |
public void testStore() throws IOException { clearWorkDir(); FileObject root = FileUtil.toFileObject(getWorkDir()); FileObject config = root.createFolder("config"); FileObject data = root.createFolder("data"); FileSystem testWriteFS = new FileSystem() { @Override public String getDisplayName() { throw new UnsupportedOperationException("Not supported."); } @Override public boolean isReadOnly() { throw new UnsupportedOperationException("Not supported."); } @Override public FileObject getRoot() { throw new UnsupportedOperationException("Not supported."); } @Override public FileObject findResource(String name) { return config.getFileObject(name); } }; Repository repo = new Repository(testWriteFS); MockLookup.setInstances(repo); assertSame(repo, Repository.getDefault()); assertNull(MimeLookup.getLookup("text/x-ext-t").lookup(Language.class)); FileObject grammar = FileUtil.createData(data, "any.json"); try (OutputStream out = grammar.getOutputStream()) { out.write("{ \"scopeName\" : \"test\" }".getBytes("UTF-8")); } FileObject testFO = FileUtil.createData(root, "test.txt"); assertEquals("content/unknown", FileUtil.getMIMEType(testFO)); DataObject testDO = DataObject.find(testFO); assertEquals("org.openide.loaders.DefaultDataObject", testDO.getClass().getName()); LanguageStorage.store(Arrays.asList(new LanguageDescription("t", "txt", FileUtil.toFile(grammar).getAbsolutePath(), null, "txt", null))); assertEquals("text/x-ext-t", FileUtil.getMIMEType(testFO)); DataObject recognized = DataObject.find(testFO); assertEquals(GenericDataObject.class, recognized.getClass()); assertEquals("org.openide.loaders.DefaultDataObject", testDO.getClass().getName()); //ensure the DO cannot be GCed Image icon = recognized.getNodeDelegate().getIcon(BeanInfo.ICON_COLOR_16x16); String url = ((URL) icon.getProperty("url", null)).getFile(); assertTrue(url.contains("/org/openide/nodes/defaultNode.png")); Language l = MimeLookup.getLookup("text/x-ext-t").lookup(Language.class); assertNotNull(l); LanguageStorage.store(Arrays.asList(new LanguageDescription("t", "txt", FileUtil.toFile(grammar).getAbsolutePath(), null, "txt", null))); LanguageStorage.store(Collections.emptyList()); assertEquals("content/unknown", FileUtil.getMIMEType(testFO)); assertEquals("org.openide.loaders.DefaultDataObject", DataObject.find(testFO).getClass().getName()); assertEquals(GenericDataObject.class, recognized.getClass()); //ensure the DO cannot be GCed }
Example 18
Source File: JavaI18nFinderTest.java From netbeans with Apache License 2.0 | 4 votes |
private void writeFile(String content, FileObject file) throws Exception { OutputStream os = file.getOutputStream(); os.write(content.getBytes("UTF-8")); os.close(); }
Example 19
Source File: RecursiveListenerOnOffTest.java From netbeans with Apache License 2.0 | 4 votes |
public void testRecursiveListenerInsideRenamedFolder() throws Exception { final FileObject wd = FileUtil.toFileObject(getWorkDir()); final FileObject prj = wd.createFolder("prj"); //NOI18N final FileObject src = prj.createFolder("src"); //NOI18N final FileObject pkg = src.createFolder("pkg"); //NOI18N final FileObject file = pkg.createData("Test","java"); //NOI18N class FL extends FileChangeAdapter { private final Semaphore sem = new Semaphore(0); private final Queue<File> waitFor = new ArrayDeque<File>(); public synchronized void expect(final File... files) { waitFor.addAll(Arrays.asList(files)); } public boolean await() throws InterruptedException { final int size; synchronized (this) { size = waitFor.size(); } return sem.tryAcquire(size, TIMEOUT, TimeUnit.SECONDS); } @Override public void fileChanged(FileEvent fe) { final File f = FileUtil.toFile(fe.getFile()); final boolean remove; synchronized (this) { remove = waitFor.remove(f); } if (remove) { sem.release(); } } } final FL fl = new FL(); final File srcDir = FileUtil.toFile(src); FileUtil.addRecursiveListener(fl, srcDir); FileLock lck = prj.lock(); try { prj.rename(lck, "prj2", null); //NOI18N } finally { lck.releaseLock(); } FileUtil.removeRecursiveListener(fl, srcDir); final File newSrcDir = FileUtil.toFile(src); FileUtil.addRecursiveListener(fl, newSrcDir); fl.expect(FileUtil.toFile(file)); lck = file.lock(); try { final OutputStream out = file.getOutputStream(lck); out.write(1); out.close(); } finally { lck.releaseLock(); } assertTrue(fl.await()); }
Example 20
Source File: FileObjTest.java From netbeans with Apache License 2.0 | 4 votes |
/** #165406 - tests that only one event is fired for single change. */ public void testChangeEvents165406() throws Exception { clearWorkDir(); File workdir = getWorkDir(); File file = new File(workdir, "testfile"); file.createNewFile(); final FileObject fo = FileUtil.toFileObject(file); fo.refresh(); // to set lastModified field final long beforeModification = fo.lastModified().getTime(); Thread.sleep(1000); Handler handler = new Handler() { @Override public void publish(LogRecord record) { if (record.getMessage().equals("getOutputStream-close")) { // wait for physical change of timestamp after stream was closed while (beforeModification == fo.lastModified().getTime()) { try { Thread.sleep(10); } catch (InterruptedException ex) { ex.printStackTrace(); } } // call concurrent refresh fo.refresh(); } } @Override public void flush() { } @Override public void close() throws SecurityException { } }; Logger logger = Logger.getLogger(FileObj.class.getName()); logger.addHandler(handler); logger.setLevel(Level.FINEST); TestFileChangeListener listener = new TestFileChangeListener(); fo.addFileChangeListener(listener); OutputStream os = fo.getOutputStream(); os.write("Ahoj everyone!\n".getBytes("UTF-8")); os.close(); assertEquals("Only one change event should be fired.", 1, listener.check(EventType.CHANGED)); }