Java Code Examples for org.openide.filesystems.FileUtil#createData()

The following examples show how to use org.openide.filesystems.FileUtil#createData() . 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: CopyOnSave.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Returns the destination (parent) directory needed to create file with relative path path under webBuilBase
 */
protected FileObject ensureDestinationFileExists(FileObject buildBase, String path, boolean isFolder) throws IOException {
    FileObject current = buildBase;
    StringTokenizer st = new StringTokenizer(path, "/"); //NOI18N
    while (st.hasMoreTokens()) {
        String pathItem = st.nextToken();
        FileObject newCurrent = current.getFileObject(pathItem);
        if (newCurrent == null) {
            // need to create it
            if (isFolder || st.hasMoreTokens()) {
                // create a folder
                newCurrent = FileUtil.createFolder(current, pathItem);
            } else {
                newCurrent = FileUtil.createData(current, pathItem);
            }
        }
        current = newCurrent;
    }
    return current;
}
 
Example 2
Source File: DataFolderPasteTypesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testUriFileListPasteTypes() throws ClassNotFoundException, IOException {
    DataFlavor flavor = new DataFlavor( "unsupported/flavor;class=java.lang.Object" );
    FileObject testFO = FileUtil.createData( testFileSystem.getRoot(), "testFile.txt" );
    File testFile = FileUtil.toFile( testFO );
    String uriList = Utilities.toURI(testFile) + "\r\n";
    Transferable t = new MockTransferable( new DataFlavor[] {new DataFlavor("text/uri-list;class=java.lang.String")}, uriList );

    DataFolder.FolderNode node = (DataFolder.FolderNode)folderNode;
    ArrayList list = new ArrayList();
    node.createPasteTypes( t, list );
    assertFalse( list.isEmpty() );
    PasteType paste = (PasteType)list.get( 0 );
    paste.paste();

    FileObject[] children = testFileSystem.getRoot().getFileObject( "testDir" ).getChildren();
    assertEquals( 1, children.length );
    assertEquals( children[0].getNameExt(), "testFile.txt" );
}
 
Example 3
Source File: GenerationUtilsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void initTemplates() throws Exception{
    FileObject interfaceTemplate = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Interface.java");
    interfaceTemplate.setAttribute("javax.script.ScriptEngine", "freemarker");
    TestUtilities.copyStringToFileObject(interfaceTemplate,
            "package ${package};" +
            "public interface ${name} {\n" +
            "}");
    FileObject classTemplate = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Class.java");
    classTemplate.setAttribute("javax.script.ScriptEngine", "freemarker");
    TestUtilities.copyStringToFileObject(classTemplate,
            "package ${package};" +
            "public class ${name} {\n" +
            "   public ${name}(){\n" +
            "   }\n" +
            "}");
}
 
Example 4
Source File: WhiteListSupportTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static FileObject createFile (
        final FileObject root,
        final String fqn,
        final String content) throws IOException {
    final FileObject file = FileUtil.createData(
            root,
            String.format("%s.java", fqn.replace('.', '/'))); //NOI18N
    final FileLock lck = file.lock();
    try {
        final PrintWriter out = new PrintWriter(new OutputStreamWriter(file.getOutputStream(lck)));
        try {
            out.print(content);
        } finally {
            out.close();
        }
    } finally {
        lck.releaseLock();
    }
    return file;
}
 
Example 5
Source File: ScriptingCreateFromTemplateTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void XtestCreateFromTemplateDocumentCreated() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.txt");
    OutputStream os = fo.getOutputStream();
    os.write("test".getBytes());
    os.close();
    fo.setAttribute ("template", Boolean.TRUE);
    fo.setAttribute(ScriptingCreateFromTemplateHandler.SCRIPT_ENGINE_ATTR, "js");

    MockServices.setServices(MockMimeLookup.class);
    MockMimeLookup.setInstances(MimePath.parse("content/unknown"), new TestEditorKit());
    
    DataObject obj = DataObject.find(fo);
    DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(root, "target"));
    
    assertFalse(TestEditorKit.createDefaultDocumentCalled);
    DataObject inst = obj.createFromTemplate(folder, "test");
    assertTrue(TestEditorKit.createDefaultDocumentCalled);
    
    String exp = "test";
    assertEquals(exp, inst.getPrimaryFile().asText());
}
 
Example 6
Source File: ActionInvocationTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws IOException, Exception {
    try {
        super.setUp();
        f = FileUtil.createData(FileUtil.toFileObject(getWorkDir()), "test.txt");

        OutputStream outputStream = f.getOutputStream();
        outputStream.write("test".getBytes());
        outputStream.close();
        
        assertEquals(DD.class, Lookup.getDefault().lookup(DialogDisplayer.class).getClass());
    } catch (InterruptedException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 7
Source File: ConvertAnonymousToInnerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void performEnabledTest(String test, final boolean onlyHeader, final boolean golden) throws Exception {
    clearWorkDir();

    String[] parts = test.split(Pattern.quote("|"));
    final int start, end;

    if (parts.length == 2) {
        start = end = parts[0].length();
        test = parts[0] + parts[1];
    } else {
        start = parts[0].length();
        end   = start + parts[1].length();
        test = parts[0] + parts[1] + parts[2];
    }

    FileUtil.refreshFor(getWorkDir());

    FileObject wd = FileUtil.toFileObject(getWorkDir());
    FileObject src = FileUtil.createFolder(wd, "src");
    FileObject build = FileUtil.createFolder(wd, "build");
    FileObject cache = FileUtil.createFolder(wd, "cache");

    SourceUtilsTestUtil.prepareTest(src, build, cache);

    FileObject testFile = FileUtil.createData(src, "Test.java");

    TestUtilities.copyStringToFile(testFile, test);

    JavaSource testSource = JavaSource.forFileObject(testFile);
    Task task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);

            assertEquals(golden, ConvertAnonymousToInner.computeFix(workingCopy, start, end, onlyHeader) != null);
        }

    };
    testSource.runModificationTask(task).commit();
}
 
Example 8
Source File: DataEditorSupportMoveTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testModifiedMove() throws Exception {
    FileObject root = FileUtil.toFileObject(getWorkDir());
    FileObject data = FileUtil.createData(root, "someFolder/someFile.obj");
    
    DataObject obj = DataObject.find(data);
    assertEquals( MyDataObject.class, obj.getClass());
    assertEquals(MyLoader.class, obj.getLoader().getClass());
    
    EditorCookie ec = obj.getLookup().lookup(EditorCookie.class);
    assertNotNull("Editor cookie found", ec);
    ec.open();
    JEditorPane[] arr = openedPanes(ec);
    assertEquals("One pane is opened", 1, arr.length);
            
    StyledDocument doc = ec.openDocument();
    doc.insertString(0, "Ahoj", null);
    assertTrue("Modified", obj.isModified());
    Thread.sleep(100);
    
    FileObject newFolder = FileUtil.createFolder(root, "otherFolder");
    DataFolder df = DataFolder.findFolder(newFolder);
    
    obj.move(df);
    
    assertEquals(newFolder, obj.getPrimaryFile().getParent());
    
    assertEquals("Still one editor", 1, openedPanes(ec).length);
    DD.assertNoCalls();
}
 
Example 9
Source File: SourceFileObjectTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDeadlock() throws Exception {
    clearWorkDir();
    
    FileObject work = FileUtil.toFileObject(getWorkDir());
    FileObject data = FileUtil.createData(work, "test.java");
    Document doc = DataObject.find(data).getLookup().lookup(EditorCookie.class).openDocument();
    SourceFileObject sfo = new SourceFileObject(
        new AbstractSourceFileObject.Handle(data, work),
        new FilterImplementation(doc),
        null,
        true);
}
 
Example 10
Source File: RepositoryUpdaterTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testFilesScannedAfterRenameOfFolder193243() throws Exception {
    final TestHandler handler = new TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests");
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);
    final FileObject testFo = FileUtil.createData(this.srcRootWithFiles1, "rename/A.foo");
    final MutableClassPathImplementation mcpi1 = new MutableClassPathImplementation ();
    mcpi1.addResource(this.srcRootWithFiles1);
    final ClassPath cp1 = ClassPathFactory.createClassPath(mcpi1);
    globalPathRegistry_register(SOURCES,new ClassPath[]{cp1});
    assertTrue (handler.await());
    indexerFactory.indexer.setExpectedFile(new URL[]{new URL(this.srcRootWithFiles1.toURL()+"renamed/A.foo")}, new URL[]{testFo.toURL()}, new URL[0]);
    eindexerFactory.indexer.setExpectedFile(new URL[0], new URL[]{testFo.toURL()}, new URL[0]);
    final FileObject parent = testFo.getParent();
    final FileLock lock = parent.lock();
    try {
        parent.rename(lock, "renamed", null);
    } finally {
        lock.releaseLock();
    }
    assertTrue(indexerFactory.indexer.awaitDeleted(TIME));
    assertTrue(eindexerFactory.indexer.awaitDeleted());
    assertTrue(indexerFactory.indexer.awaitIndex(TIME));
    assertTrue(eindexerFactory.indexer.awaitIndex());
    assertEquals(0, eindexerFactory.indexer.getIndexCount());
    assertEquals(1, eindexerFactory.indexer.getDeletedCount());
    assertEquals(0, eindexerFactory.indexer.getDirtyCount());
    assertEquals(1, indexerFactory.indexer.getIndexCount());
    assertEquals(1, indexerFactory.indexer.getDeletedCount());
    assertEquals(0, indexerFactory.indexer.getDirtyCount());
}
 
Example 11
Source File: EqualsHashCodeGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testEnabledFieldsWhenHashCodeExists() throws Exception {
    FileObject java = FileUtil.createData(fo, "X.java");
    String what1 = "class X {" +
        "  private int x;" +
        "  private int y;" +
        "  public int hashCode() {";
    
    String what2 = 
        "    return y;" +
        "  }" +
        "}";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);
    
    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);
    
    final JTextArea c = new JTextArea();
    c.getDocument().putProperty(JavaSource.class, new WeakReference<Object>(js));
    c.getDocument().insertString(0, what, null);
    c.setCaretPosition(what1.length());
    
    class Task implements org.netbeans.api.java.source.Task<CompilationController> {
        EqualsHashCodeGenerator generator;
        

        public void run(CompilationController cc) throws Exception {
            cc.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            Element el = cc.getElements().getTypeElement("X");
            generator = EqualsHashCodeGenerator.createEqualsHashCodeGenerator(c, cc, el);
        }
        
        
        public void post() throws Exception {
            assertNotNull("panel", generator);
            
            assertEquals("Two fields", 2, generator.description.getSubs().size());
            assertEquals("y field selected", true, generator.description.getSubs().get(1).isSelected());
            assertEquals("x field not selected", false, generator.description.getSubs().get(0).isSelected());
            assertEquals("generate hashCode", false, generator.generateHashCode);
            assertEquals("generate equals", true, generator.generateEquals);
        }
    }
    final Task t = new Task();
    
    js.runUserActionTask(t, false);
    t.post();
    
    
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            t.generator.invoke();
        }
    });
    
    //String text = c.getDocument().getText(0, c.getDocument().getLength());
    String text = GeneratorUtilsTest.readFromFile(java);
    
    int first = text.indexOf("hashCode");
    if (first < 0) {
        fail("There should be one hashCode mehtod:\n" + text);
    }
    int snd = text.indexOf("hashCode", first + 5);
    if (snd >= 0) {
        fail("Only one hashCode:\n" + text);
    }
}
 
Example 12
Source File: EqualsHashCodeGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testEnabledFieldsWhenEqualsExists() throws Exception {
    FileObject java = FileUtil.createData(fo, "X.java");
    String what1 = "class X {" +
        "  private int x;" +
        "  private int y;" +
        "  public Object equals(Object snd) {" +
        "    if (snd instanceof X) {" +
        "       X x2 = (X)snd;";
    
    String what2 = 
        "       return this.x == x2.x;" +
        "    }" +
        "    return false;" +
        "  }" +
        "}";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);
    
    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);
    
    class Task implements CancellableTask<CompilationController> {
        EqualsHashCodeGenerator generator;
        
        public void cancel() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        public void run(CompilationController cc) throws Exception {
            cc.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            Element el = cc.getElements().getTypeElement("X");
            generator = EqualsHashCodeGenerator.createEqualsHashCodeGenerator(null, cc, el);
        }
        
        
        public void post() throws Exception {
            assertNotNull("panel", generator);
            
            assertEquals("Two fields", 2, generator.description.getSubs().size());
            assertEquals("x field selected", true, generator.description.getSubs().get(0).isSelected());
            assertEquals("y field not selected", false, generator.description.getSubs().get(1).isSelected());
            assertEquals("generate hashCode", true, generator.generateHashCode);
            assertEquals("generate equals", false, generator.generateEquals);
        }
    }
    Task t = new Task();
    
    js.runUserActionTask(t, false);
    t.post();
}
 
Example 13
Source File: ActionProviderImplTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private FileObject createFile(String file) throws IOException {
    FileObject wd = FileUtil.toFileObject(getWorkDir());
    return FileUtil.createData(wd, file);
}
 
Example 14
Source File: GoToSupportTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String performTest(String sourceCode, String auxiliaryCode, int offset, final UiUtilsCaller validator, boolean tooltip, boolean doCompileRecursively) throws Exception {

        GoToSupport.CALLER = validator;
        
        if (offset == (-1)) {
            offset = sourceCode.indexOf('|');

            assertNotSame(-1, offset);

            sourceCode = sourceCode.replace("|", "");
        }

        clearWorkDir();
        FileUtil.refreshFor(getWorkDir());

        FileObject wd = FileUtil.toFileObject(getWorkDir());
        FileObject sourceDir = FileUtil.createFolder(wd, "src");
        FileObject buildDir = FileUtil.createFolder(wd, "build");
        FileObject cacheDir = FileUtil.createFolder(wd, "cache");
        
        source = FileUtil.createData(sourceDir, "test/Test.java");
        
        FileObject auxiliarySource = FileUtil.createData(sourceDir, "test/Auxiliary.java");

        TestUtilities.copyStringToFile(source, sourceCode);
        TestUtilities.copyStringToFile(auxiliarySource, auxiliaryCode);

        SourceUtilsTestUtil.setSourceLevel(source, sourceLevel);
        SourceUtilsTestUtil.setSourceLevel(auxiliarySource, sourceLevel);
        
        SourceUtilsTestUtil.prepareTest(sourceDir, buildDir, cacheDir, new FileObject[0]);

        if (doCompileRecursively) {
            SourceUtilsTestUtil.compileRecursively(sourceDir);
        }
        
        DataObject od = DataObject.find(source);
        EditorCookie ec = od.getCookie(EditorCookie.class);
        Document doc = ec.openDocument();

        doc.putProperty(Language.class, JavaTokenId.language());
        doc.putProperty("mimeType", "text/x-java");
        
        if (tooltip)
            return GoToSupport.getGoToElementTooltip(doc, offset, false, null);
        else
            GoToSupport.goTo(doc, offset, false);
        
        return null;
    }
 
Example 15
Source File: HtmlDataObjectTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testConstructorHasToRunWithoutChildrenLockBeingNeeded() throws Exception {
    MockServices.setServices(HtmlLoader.class);

    class Block implements Runnable {

        @Override
        public void run() {
            if (!Children.MUTEX.isReadAccess()) {
                Children.MUTEX.readAccess(this);
                return;
            }
            synchronized (this) {
                try {
                    notifyAll();

                    wait();
                } catch (InterruptedException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
    }
    Block b = new Block();

    synchronized (b) {
        RequestProcessor.getDefault().post(b);
        b.wait();
    }

    try {

        FileObject fo = FileUtil.createData(FileUtil.getConfigRoot(), "my.html");
        DataObject obj = DataObject.find(fo);
        assertEquals("Successfully created html object", obj.getClass(), HtmlDataObject.class);
        assertNotNull("File encoding query is in the object's lookup", obj.getLookup().lookup(FileEncodingQueryImplementation.class));
    } finally {
        synchronized (b) {
            b.notifyAll();
        }
    }
}
 
Example 16
Source File: HtmlDataObjectTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testModifySave() throws IOException, BadLocationException {
    FileObject fo = FileUtil.createData(FileUtil.getConfigRoot(), "test1.html");
    assertNotNull(fo);
    final DataObject obj = DataObject.find(fo);

    assertNotNull(obj);
    assertFalse(obj.isModified());
    assertNull(obj.getLookup().lookup(SaveCookie.class));
    final StyledDocument doc = obj.getLookup().lookup(EditorCookie.class).openDocument();
    assertTrue(doc instanceof BaseDocument);

    //listen on DO's lookup for the savecookie
    final Lookup.Result<SaveCookie> saveCookieResult = obj.getLookup().lookupResult(SaveCookie.class);
    saveCookieResult.addLookupListener(new LookupListener() {

        @Override
        public void resultChanged(LookupEvent ev) {
            //change - save cookie should appear upon the modification
            Collection<? extends SaveCookie> allInstances = saveCookieResult.allInstances();
            assertNotNull(allInstances);
            assertEquals(1, allInstances.size());

            //remove the listener
            saveCookieResult.removeLookupListener(this);

            assertTrue(obj.isModified());
            SaveCookie sc = allInstances.iterator().next();
            try {
                sc.save();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            assertFalse(obj.isModified());

            assertNull(obj.getLookup().lookup(SaveCookie.class));

        }

    });

    ((BaseDocument) doc).runAtomic(new Runnable() {
        @Override
        public void run() {
            try {
                //the document modification synchronously triggers the DataObject's lookup change  - SaveCookie added
                doc.insertString(0, "hello", null);
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });

}
 
Example 17
Source File: MultiModuleUnitTestForSourceQueryImplTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testFindUnitTests() throws IOException {
    assertNotNull(impl);
    assertNull(impl.findUnitTests(src1));
    assertNull(impl.findUnitTests(src2));
    assertEquals(
            Arrays.stream(new FileObject[]{mod1aTests})
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()),
            Arrays.stream(impl.findUnitTests(mod1a))
                .map((url) -> URLMapper.findFileObject(url))
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()));

    final FileObject javaFile = FileUtil.createData(mod1a, "org/me/Foo.java");  //NOI18N
    assertEquals(
            Arrays.stream(new FileObject[]{mod1aTests})
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()),
            Arrays.stream(impl.findUnitTests(javaFile))
                .map((url) -> URLMapper.findFileObject(url))
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()));
    assertEquals(
            Arrays.stream(new FileObject[]{mod1bTests})
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()),
            Arrays.stream(impl.findUnitTests(mod1b))
                .map((url) -> URLMapper.findFileObject(url))
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()));
    assertEquals(
            Arrays.stream(new FileObject[]{mod2cTests})
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()),
            Arrays.stream(impl.findUnitTests(mod2c))
                .map((url) -> URLMapper.findFileObject(url))
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()));
    assertEquals(
            Arrays.stream(new FileObject[]{mod1dTests, mod2dTests})
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()),
            Arrays.stream(impl.findUnitTests(mod1d))
                .map((url) -> URLMapper.findFileObject(url))
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()));
    assertEquals(
            Arrays.stream(new FileObject[]{mod1dTests, mod2dTests})
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()),
            Arrays.stream(impl.findUnitTests(mod2d))
                .map((url) -> URLMapper.findFileObject(url))
                .map((fo) -> fo.getPath())
                .sorted()
                .collect(Collectors.toList()));
}
 
Example 18
Source File: IndexTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Test basic functionality of Index on FavoritesNode node.
 */
@RandomlyFails
public void testReorder () throws Exception {
    FileObject folder = FileUtil.createFolder (
        FileUtil.getConfigRoot(),
        "FavoritesTest"
    );
    FileObject fo1 = FileUtil.createData(folder,"Test1");
    FileObject fo2 = FileUtil.createData(folder,"Test2");
    
    DataObject dObj1 = DataObject.find(fo1);
    DataObject dObj2 = DataObject.find(fo2);
    
    DataFolder favorites = FavoritesNode.getFolder();
    
    dObj1.createShadow(favorites);
    dObj2.createShadow(favorites);
    
    Node n = FavoritesNode.getNode();
    
    Node n1 = n.getChildren().findChild("Test1");
    assertNotNull("Node must exist", n1);
    Node n2 = n.getChildren().findChild("Test2");
    assertNotNull("Node must exist", n2);
    
    Index ind = n.getCookie(Index.class);
    assertNotNull("Index must exist", ind);
    
    int i;
    i = ind.indexOf(n1);
    assertEquals("Node index must be 1", i, 1);
    i = ind.indexOf(n2);
    assertEquals("Node index must be 2", i, 2);
    
    ind.reorder(new int [] {0,2,1});
    
    i = ind.indexOf(n1);
    assertEquals("Node index must be 2", i, 2);
    i = ind.indexOf(n2);
    assertEquals("Node index must be 1", i, 1);
}
 
Example 19
Source File: GoToImplementationTest.java    From netbeans with Apache License 2.0 3 votes vote down vote up
private void prepareTest(String fileName, String code) throws Exception {
    FileObject workFO = FileUtil.toFileObject(getWorkDir());
    
    assertNotNull(workFO);
    
    FileObject sourceRoot = workFO.createFolder("src");
    FileObject buildRoot  = workFO.createFolder("build");
    FileObject cacheFO = workFO.createFolder("cache");
    
    SourceUtilsTestUtil.prepareTest(sourceRoot, buildRoot, cacheFO);
    
    testSource = FileUtil.createData(sourceRoot, fileName);
    
    assertNotNull(testSource);
    
    try (OutputStream out = testSource.getOutputStream()) {
        out.write(code.getBytes());
    }
    
    js = JavaSource.forFileObject(testSource);
    
    assertNotNull(js);
    
    info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);
    
    assertNotNull(info);
}
 
Example 20
Source File: SCFTHandlerTest.java    From netbeans with Apache License 2.0 3 votes vote down vote up
public void testUTF8() throws Exception {
    FileObject root = FileUtil.getConfigRoot();
    FileObject xmldir = FileUtil.createFolder(root, "xml");
    FileObject xml = FileUtil.createData(xmldir, "class.txt");
    OutputStream os = xml.getOutputStream();
    FileUtil.copy(getClass().getResourceAsStream("utf8.xml"), os);
    xml.setAttribute(ScriptingCreateFromTemplateHandler.SCRIPT_ENGINE_ATTR, "js");
    os.close();
    
    DataObject obj = DataObject.find(xml);
    
    
    FileObject target = FileUtil.createFolder(FileUtil.createMemoryFileSystem().getRoot(), "dir");
    DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(target, "target"));
    
    
    
    Charset set = Charset.forName("iso-8859-2");
    FEQI.fs = target.getFileSystem();
    FEQI.result = set;
    
    
    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 read = readChars(n.getPrimaryFile(), set).replaceAll("print\\('", "").replaceAll("'\\);", "");
    String exp = readChars(xml, Charset.forName("utf-8")).replaceAll("print\\('", "").replaceAll("'\\);", "");
    assertEquals(exp, read);
    
}