Java Code Examples for org.openide.filesystems.FileObject.getOutputStream()

The following are Jave code examples for showing how to use getOutputStream() of the org.openide.filesystems.FileObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: ScriptingCreateFromTemplateTest.java   View Source Code Vote up 6 votes
public void testCreateFromTemplateEncodingProperty() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.txt");
    OutputStream os = fo.getOutputStream();
    os.write("${encoding}".getBytes());
    os.close();
    assertEquals("content/unknown", fo.getMIMEType());
    fo.setAttribute ("template", Boolean.TRUE);
    assertEquals("content/unknown", fo.getMIMEType());
    fo.setAttribute("javax.script.ScriptEngine", "freemarker");
    assertEquals("text/x-freemarker", fo.getMIMEType());
    
    DataObject obj = DataObject.find(fo);
    DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(root, "target"));
    
    Map<String,String> parameters = Collections.emptyMap();
    DataObject inst = obj.createFromTemplate(folder, "complex", parameters);
    FileObject instFO = inst.getPrimaryFile();
    
    Charset targetEnc = FileEncodingQuery.getEncoding(instFO);
    assertNotNull("Template encoding is null", targetEnc);
    assertEquals("Encoding in template doesn't match", targetEnc.name(), instFO.asText());
}
 
Example 2
Project: incubator-netbeans   File: J2SEProjectConfigurations.java   View Source Code Vote up 6 votes
private static void generateConfig(FileObject prjDir, String cfgFilePath, EditableProperties propsToWrite) throws IOException {
    
    if (propsToWrite == null) {
        // do not create anything if props is null
        return;
    }
    FileObject jwsConfigFO = FileUtil.createData(prjDir, cfgFilePath);
    Properties props = new Properties();
    InputStream is = jwsConfigFO.getInputStream();
    props.load(is);
    is.close();
    if (props.equals(propsToWrite)) {
        // file already exists and props are the same
        return;
    }
    OutputStream os = jwsConfigFO.getOutputStream();
    propsToWrite.store(os);
    os.close();
    
}
 
Example 3
Project: incubator-netbeans   File: EncodingTest.java   View Source Code Vote up 6 votes
private void copy(final String res, final FileObject data) throws Exception {
    final InputStream is = getClass ().getResourceAsStream ("data/"+res);   //NOI18N
    try {
        assertNotNull (res+" should exist", is);    //NOI18N
        FileLock lock = data.lock();
        try {
            OutputStream os = data.getOutputStream (lock);
            try {
                FileUtil.copy (is, os);
            } finally {
                os.close ();
            }
        } finally {
            lock.releaseLock ();
        }
    } finally {
        is.close ();
    }
}
 
Example 4
Project: incubator-netbeans   File: JavaSourceUtilImplTest.java   View Source Code Vote up 6 votes
private static void dump(
        final FileObject wd,
        final Map<String,byte[]> clzs) throws IOException {
    for (Map.Entry<String,byte[]> clz : clzs.entrySet()) {
        final String extName = FileObjects.convertPackage2Folder(clz.getKey());
        final FileObject data = FileUtil.createData(wd, String.format(
                "%s.class", //NOI18N
                extName));
        FileLock l = data.lock();
        try (final OutputStream out = data.getOutputStream(l)) {
            out.write(clz.getValue());
        }finally {
            l.releaseLock();
        }
    }
    System.out.printf("Dumped into: %s%n", FileUtil.getFileDisplayName(wd));
}
 
Example 5
Project: incubator-netbeans   File: CreatedModifiedFilesTest.java   View Source Code Vote up 5 votes
/** @see "#64273" */
public void testCreateLayerEntryWithoutLocalizingBundle() throws Exception {
    NbModuleProject project = TestBase.generateStandaloneModule(getWorkDir(), "module");
    project.getProjectDirectory().getFileObject("src/org/example/module/resources/Bundle.properties").delete();
    FileObject mf = project.getProjectDirectory().getFileObject("manifest.mf");
    EditableManifest m;
    InputStream is = mf.getInputStream();
    try {
        m = new EditableManifest(is);
    } finally {
        is.close();
    }
    m.removeAttribute("OpenIDE-Module-Localizing-Bundle", null);
    OutputStream os = mf.getOutputStream();
    try {
        m.write(os);
    } finally {
        os.close();
    }
    CreatedModifiedFiles cmf = new CreatedModifiedFiles(project);
    Operation op = cmf.createLayerEntry("f", null, null, "F!", null);
    cmf.add(op);
    cmf.run();
    String[] supposedContent = new String[] {
        "<filesystem>",
        "<file name=\"f\"/>",
        "</filesystem>"
    };
    assertLayerContent(supposedContent, 
            new File(getWorkDir(), "module/src/org/example/module/resources/layer.xml"));
}
 
Example 6
Project: incubator-netbeans   File: DBSchemaManager.java   View Source Code Vote up 5 votes
/**
 * Writes the contents of <code>schemaElement</code> to the existing
 * <code>dbschemaFile</code>.
 */
private static void writeSchemaElement(SchemaElement schemaElement, FileObject dbschemaFile) throws IOException {
    FileLock lock = dbschemaFile.lock();
    try {
        OutputStream os = new BufferedOutputStream(dbschemaFile.getOutputStream(lock));
        try {
            schemaElement.save(os);
        } finally {
            os.close();
        }
    } finally {
        lock.releaseLock();
    }
}
 
Example 7
Project: incubator-netbeans   File: MasterDetailGenerator.java   View Source Code Vote up 5 votes
/**
 * Writes the content of the file.
 *
 * @param file file whose content should be written.
 * @param content new content of the file.
 * @throws IOException when the writing fails.
 */
private static void write(FileObject file, String content, String encoding) throws IOException {
    FileLock lock = file.lock();
    try {
        OutputStream os = file.getOutputStream(lock);
        os.write(content.getBytes(encoding));
        os.close();
    } finally {
        lock.releaseLock();
    }
}
 
Example 8
Project: incubator-netbeans   File: FreeformEvaluatorTest.java   View Source Code Vote up 5 votes
@RandomlyFails
public void testPropertyEvaluationChanges() throws Exception {
    FreeformProject simple2 = copyProject(simple);
    PropertyEvaluator eval = simple2.evaluator();
    assertEquals("right src.dir", "src", eval.getProperty("src.dir"));
    EditableProperties p = new EditableProperties();
    FileObject buildProperties = simple2.getProjectDirectory().getFileObject("build.properties");
    assertNotNull("have build.properties", buildProperties);
    InputStream is = buildProperties.getInputStream();
    try {
        p.load(is);
    } finally {
        is.close();
    }
    assertEquals("right original value", "src", p.getProperty("src.dir"));
    p.setProperty("src.dir", "somethingnew");
    TestPCL l = new TestPCL();
    eval.addPropertyChangeListener(l);
    final OutputStream os = buildProperties.getOutputStream();
    try {
        p.store(os);
    } finally {
        // close file under ProjectManager.readAccess so that events are fired synchronously
        ProjectManager.mutex().readAccess(new Mutex.ExceptionAction<Void>() {
            public Void run() throws Exception {
                os.close();
                return null;
            }
        });
    }
    assertEquals("got a change from properties file in src.dir", Collections.singleton("src.dir"), l.changed);
    l.reset();
    assertEquals("new value of src.dir", "somethingnew", eval.getProperty("src.dir"));
}
 
Example 9
Project: incubator-netbeans   File: SnapshotTest.java   View Source Code Vote up 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 10
Project: incubator-netbeans   File: TestUtilities.java   View Source Code Vote up 5 votes
public static final FileObject copyStringToFileObject(FileObject fo, String content) throws IOException {
    OutputStream os = fo.getOutputStream();
    try {
        InputStream is = new ByteArrayInputStream(content.getBytes("UTF-8"));
        FileUtil.copy(is, os);
        return fo;
    } finally {
        os.close();
    }
}
 
Example 11
Project: incubator-netbeans   File: DBSchemaManager.java   View Source Code Vote up 5 votes
/**
 * Writes the contents of <code>schemaElement</code> to the existing
 * <code>dbschemaFile</code>.
 */
private static void writeSchemaElement(SchemaElement schemaElement, FileObject dbschemaFile) throws IOException {
    FileLock lock = dbschemaFile.lock();
    try {
        OutputStream os = new BufferedOutputStream(dbschemaFile.getOutputStream(lock));
        try {
            schemaElement.save(os);
        } finally {
            os.close();
        }
    } finally {
        lock.releaseLock();
    }
}
 
Example 12
Project: incubator-netbeans   File: TestUtilities.java   View Source Code Vote up 5 votes
public static final FileObject copyStringToFileObject(FileObject fo, String content) 
    throws IOException 
 {
    OutputStream os = fo.getOutputStream();
    try {
        InputStream is = new ByteArrayInputStream(content.getBytes("UTF-8"));
        FileUtil.copy(is, os);
        return fo;
    } finally {
        os.close();
    }
}
 
Example 13
Project: incubator-netbeans   File: NbKeymapTest.java   View Source Code Vote up 5 votes
public void testUnusualInstanceFileExtensions() throws Exception {
    MockServices.setServices(ENV.class);
    FileObject inst = make("Shortcuts/C-F11.xml");
    OutputStream os = inst.getOutputStream();
    os.write("<action/>".getBytes());
    os.close();
    assertMapping(new NbKeymap(), KeyStroke.getKeyStroke(KeyEvent.VK_F11, KeyEvent.CTRL_MASK), inst, "whatever");
}
 
Example 14
Project: incubator-netbeans   File: VCSInterceptorTest.java   View Source Code Vote up 5 votes
public void testChangedFile() throws IOException {
    File f = new File(dataRootDir, "workdir/root-test-versioned");
    FileObject fo = FileUtil.toFileObject(f);
    fo = fo.createData("deleteme.txt");
    File file = FileUtil.toFile(fo);
    OutputStream os = fo.getOutputStream();
    os.close();
    assertTrue(inteceptor.getBeforeCreateFiles().contains(file));
    assertTrue(inteceptor.getDoCreateFiles().contains(file));
    assertTrue(inteceptor.getCreatedFiles().contains(file));
    assertTrue(inteceptor.getBeforeChangeFiles().contains(file));
    assertTrue(inteceptor.getAfterChangeFiles().contains(file));
}
 
Example 15
Project: incubator-netbeans   File: ModuleListStartLevelTest.java   View Source Code Vote up 5 votes
private void initModule() throws IOException {
    FileObject fo = modulesfolder.createData("com-jcraft-jsch.xml");
    File mod = new File(new File(ud, "modules"), "com-jcraft-jsch.jar");
    final HashMap<String, String> man = new HashMap<String, String>();
    man.put("Bundle-SymbolicName", "com.jcraft.jsch");
    createJar(mod, new HashMap<String, String>(), man);
    
    InputStream is = ModuleListStartLevelTest.class.getResourceAsStream("ModuleList-com-jcraft-jsch.xml");
    assertNotNull("Module definition found", is);
    final OutputStream os = fo.getOutputStream();
    FileUtil.copy(is, os);
    os.close();
    is.close();
}
 
Example 16
Project: incubator-netbeans   File: CslTestBase.java   View Source Code Vote up 5 votes
public static final FileObject copyStringToFileObject(FileObject fo, String content) throws IOException {
    OutputStream os = fo.getOutputStream();
    try {
        InputStream is = new ByteArrayInputStream(content.getBytes("UTF-8"));
        try {
            FileUtil.copy(is, os);
            return fo;
        } finally {
            is.close();
        }
    } finally {
        os.close();
    }
}
 
Example 17
Project: incubator-netbeans   File: NbModuleProjectGenerator.java   View Source Code Vote up 5 votes
/**
 * Creates basic <em>build.xml</em> or whatever
 * <code>GeneratedFilesHelper.BUILD_XML_PATH</code> is pointing to.
 */
private static void createNetBeansOrgBuildXML(FileObject projectDir, String cnb,
        File nborg) throws IOException {
    FileObject buildScript = NbModuleProjectGenerator.createFileObject(
            projectDir, GeneratedFilesHelper.BUILD_XML_PATH);
    Document prjDoc = XMLUtil.createDocument("project", null, null, null); // NOI18N
    Element prjEl = prjDoc.getDocumentElement();
    prjEl.setAttribute("name", PropertyUtils.relativizeFile(nborg, // NOI18N
            FileUtil.toFile(projectDir)));
    prjEl.setAttribute("default", "netbeans"); // NOI18N
    prjEl.setAttribute("basedir", "."); // NOI18N
    
    Element el = prjDoc.createElement("description"); // NOI18N
    el.appendChild(prjDoc.createTextNode("Builds, tests, and runs the " + // NOI18N
            "project " + cnb)); // NOI18N
    prjEl.appendChild(el);
    
    el = prjDoc.createElement("import"); // NOI18N
    el.setAttribute("file", PropertyUtils.relativizeFile(FileUtil.toFile(projectDir), // NOI18N
            new File(nborg, "nbbuild/templates/projectized.xml"))); // NOI18N
    prjEl.appendChild(el);
    
    // store document to disk
    OutputStream os = buildScript.getOutputStream();
    try {
        XMLUtil.write(prjDoc, os, "UTF-8"); // NOI18N
    } finally {
        os.close();
    }
}
 
Example 18
Project: incubator-netbeans   File: XMLPropertiesConvertorTest.java   View Source Code Vote up 4 votes
public void testChangeSettings() throws Exception {
FileObject dtdFO = Repository.getDefault().getDefaultFileSystem().
	findResource("/xml/lookups/xyz/x.instance");
assertNotNull("Provider not found", dtdFO);
Convertor c = XMLPropertiesConvertor.create(dtdFO);
assertNotNull("Convertor created", c);
StringWriter w = new StringWriter();
Change sampleChange = new Change();
sampleChange.value = "new value";
c.write(w, sampleChange);

DataFolder folder = DataFolder.findFolder(root);

String filename = "testChangeSettings";
FileObject fo = folder.getPrimaryFile().createData(filename + ".settings");
OutputStream os = fo.getOutputStream();
os.write(("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
	+ "<!DOCTYPE settings PUBLIC \"-//NetBeans//DTD Session settings 1.0//EN\" \"http://www.netbeans.org/dtds/sessionsettings-1_0.dtd\">\n"
	+ "<settings version=\"1.0\">\n"
	+ "  <instance class=\"" + Change.class.getName() + "\"/>\n"
	+ "</settings>\n").getBytes("UTF-8"));
os.close();

DataObject ido = DataObject.find(fo);
assertNotNull("InstanceDataObject.create cannot return null!", ido);

InstanceCookie ic = ido.getLookup().lookup(InstanceCookie.class);
assertNotNull("Cookie found", ic);

Change ch = (Change) ic.instanceCreate();
assertNotNull("Change found", ch);
assertEquals("Default value in value", "", ch.value);

os = ido.getPrimaryFile().getOutputStream();
os.write(w.toString().getBytes("UTF-8"));
os.close();

InstanceCookie icNew = ido.getCookie(InstanceCookie.class);
assertNotNull("Cookie is still found", icNew);

Change newCh = (Change) icNew.instanceCreate();
assertNotNull("Change instance still found", newCh);
assertEquals("It has the new value", sampleChange.value, newCh.value);

   }
 
Example 19
Project: incubator-netbeans   File: CompilationUnitTest.java   View Source Code Vote up 4 votes
public void test196276() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package zoo;\n" +
        "\n" +
        "public class A {\n" +
        "}\n"
    );

    FileObject emptyJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Empty.java");
    emptyJava.setAttribute("template", Boolean.TRUE);
    FileObject classJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Class.java");
    classJava.setAttribute("template", Boolean.TRUE);
    Writer w = new OutputStreamWriter(classJava.getOutputStream(), "UTF-8");
    w.write("package zoo;\npublic class Template {\n    public Template() {}\n}");
    w.close();
    FileObject testSourceFO = FileUtil.toFileObject(testFile);
    assertNotNull(testSourceFO);
    ClassPath sourcePath = ClassPath.getClassPath(testSourceFO, ClassPath.SOURCE);
    assertNotNull(sourcePath);
    FileObject[] roots = sourcePath.getRoots();
    assertEquals(1, roots.length);
    final FileObject sourceRoot = roots[0];
    assertNotNull(sourceRoot);
    ClassPath compilePath = ClassPath.getClassPath(testSourceFO, ClassPath.COMPILE);
    assertNotNull(compilePath);
    ClassPath bootPath = ClassPath.getClassPath(testSourceFO, ClassPath.BOOT);
    assertNotNull(bootPath);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, compilePath, sourcePath);

    String golden1 =
        "package zoo;\n" +
        "\n" +
        "\n" + //XXX
        "public class Krtek {\n" +
        "    public Krtek() {}\n" +
        "}\n";

    JavaSource javaSource = JavaSource.create(cpInfo, FileUtil.toFileObject(testFile));

    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void cancel() {
        }

        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree newTree = make.CompilationUnit(
                    sourceRoot,
                    "zoo/Krtek.java",
                    Collections.<ImportTree>emptyList(),
                    Collections.<Tree>emptyList()
            );
            MethodTree constr = make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), "Krtek", null, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}", null);
            newTree = make.addCompUnitTypeDecl(newTree, make.Class(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), "Krtek", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>singletonList(constr)));
            workingCopy.rewrite(null, newTree);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/Krtek.java"));
    System.err.println(res);
    assertEquals(res, golden1);
}
 
Example 20
Project: incubator-netbeans   File: IndexerCache.java   View Source Code Vote up 4 votes
private void writeLastKnownIndexers(Map<String, Set<IndexerInfo<T>>> lki) {
    Properties props = new Properties();
    for(String indexerName : lki.keySet()) {
        Set<IndexerInfo<T>> iinfos = lki.get(indexerName);
        int indexerVersion = -1;
        Set<String> mimeTypes = new HashSet<String>();
        for(IndexerInfo<T> iinfo : iinfos) {
            if (indexerVersion == -1) {
                indexerVersion = iinfo.getIndexerVersion();
            } else if (indexerVersion != iinfo.getIndexerVersion()) {
                LOG.warning(iinfo.getIndexerFactory() + " has different version then other instances of the same factory: version=" + iinfo.getIndexerVersion() + ", others=" + indexerVersion);
                continue;
            }
            mimeTypes.addAll(iinfo.getMimeTypes());
        }

        StringBuilder sb = new StringBuilder();
        sb.append(indexerVersion);
        if (mimeTypes.size() > 0) {
            sb.append(",");//NOI18N
            for(Iterator<? extends String> i = mimeTypes.iterator(); i.hasNext(); ) {
                String mimeType = i.next();
                if (mimeType.length() == 0) {
                    sb.append("<all>"); //NOI18N
                    break;
                } else {
                    sb.append(mimeType);
                    if (i.hasNext()) {
                        sb.append(","); //NOI18N
                    }
                }
            }
        }

        props.put(indexerName, sb.toString());
    }

    FileObject cacheFolder = CacheFolder.getCacheFolder();
    try {
        FileObject infoFile = FileUtil.createData(cacheFolder, infoFileName);
        OutputStream os = infoFile.getOutputStream();
        try {
            props.store(os, "Last known indexer " + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(new Date())); //NOI18N
        } finally {
            os.close();
        }
    } catch (IOException ioe) {
        LOG.log(Level.FINE, "Can't write " + infoFileName + " file in " + cacheFolder.getPath(), ioe); //NOI18N
    }
}