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

The following are Jave code examples for showing how to use asText() 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.
Example 1
Project: incubator-netbeans   File: SourceMapTest.java   Source Code and License Vote up 6 votes
public void testGetAllMappings() throws IOException {
    System.out.println("\nALL Mappings:");
    FileObject grsm = getTestFile("sourcemaps/greeter.js.map");
    SourceMap sm = SourceMap.parse(grsm.asText());
    FileObject goldenDirectMappingFO = getTestFile("sourcemaps/greeter.dmapping");
    String goldenDirectMapping = goldenDirectMappingFO.asText();
    BufferedReader gdm = new BufferedReader(new StringReader(goldenDirectMapping));
    for (int l = 0; l < 100; l++) {
        List<Mapping> allLineMappings = sm.findAllMappings(l);
        if (allLineMappings != null) {
            for (Mapping m : allLineMappings) {
                String map = l+","+m.getColumn()+"->"+m.getOriginalLine()+","+m.getOriginalColumn();
                String line = gdm.readLine();
                if (line == null) {
                    throw new IOException("Golden file finished prematurely when processing line "+l+" and mapping: "+map);
                }
                assertEquals(line, map);
            }
        }
    }
    assertNull(gdm.readLine());
}
 
Example 2
Project: incubator-netbeans   File: SourceMapTest.java   Source Code and License Vote up 6 votes
public void testGetAllInverseMappings() throws IOException {
    System.out.println("\nALL Mappings:");
    FileObject grsm = getTestFile("sourcemaps/greeter.js.map");
    SourceMap sm = SourceMap.parse(grsm.asText());
    FileObject goldenInverseMappingFO = getTestFile("sourcemaps/greeter.imapping");
    String goldenInverseMapping = goldenInverseMappingFO.asText();
    BufferedReader gim = new BufferedReader(new StringReader(goldenInverseMapping));
    for (int l = 0; l < 100; l++) {
        List<Mapping> allLineMappings = sm.findAllInverseMappings("greeter.ts", l);
        if (allLineMappings != null) {
            for (Mapping m : allLineMappings) {
                String map = l+","+m.getColumn()+"->"+m.getOriginalLine()+","+m.getOriginalColumn();
                String line = gim.readLine();
                if (line == null) {
                    throw new IOException("Golden file finished prematurely when processing line "+l+" and mapping: "+map);
                }
                assertEquals(line, map);
            }
        }
    }
    assertNull(gim.readLine());
}
 
Example 3
Project: incubator-netbeans   File: Source.java   Source Code and License Vote up 6 votes
/**
 * 
 * @param url
 * @param content
 * @return a non-negative line shift of content of 'url' in 'content', or -1
 *         when content of 'url' is not a subset of 'content'.
 */
static int getContentLineShift(URL url, String content) {
    String origContent;
    FileObject fo = URLMapper.findFileObject(url);
    if (fo != null) {
        try {
            origContent = fo.asText();
        } catch (IOException ex) {
            return 0;
        }
    } else {
        return 0;
    }
    int index = content.indexOf(origContent);
    if (index < 0) {
        return -1;
    }
    String prep = content.substring(0, index);
    return countNewLines(prep);
}
 
Example 4
Project: incubator-netbeans   File: BaseFileObjectTestHid.java   Source Code and License Vote up 6 votes
public void testWriteRecreatedFile() throws Exception {
    FileObject fo = root.getFileObject("testdir/mountdir4/file.ext");
    assertNotNull("File found properly", fo);
    String txt = fo.asText("UTF-8");
    
    File f = FileUtil.toFile(fo);
    
    f.delete();
    
    fo.getParent().refresh();
    
    assertFalse("No longer valid", fo.isValid());
    
    f.createNewFile();
    
    OutputStream os = fo.getOutputStream();
    os.write("Ahoj".getBytes());
    os.close();
    
    String newTxt = fo.asText("UTF-8");
    assertEquals("Text read even the file object is not valid anymore", "Ahoj", newTxt);
    assertFalse("Still invalid", fo.isValid());
}
 
Example 5
Project: incubator-netbeans   File: ConvertAsBeanTest.java   Source Code and License Vote up 6 votes
public void testReadWrite() throws Exception {
    AnnoFoo foo = new AnnoFoo();
    foo.setName("xxx");

    DataFolder test = DataFolder.findFolder(FileUtil.getConfigRoot());
    DataObject obj = InstanceDataObject.create(test, null, foo, null);
    final FileObject pf = obj.getPrimaryFile();
    final String content = pf.asText();
    if (content.indexOf("<string>xxx</string>") == -1) {
        fail(content);
    }
    obj.setValid(false);
    DataObject newObj = DataObject.find(pf);
    if (newObj == obj) {
        fail("Strange, objects shall differ");
    }
    InstanceCookie ic = newObj.getLookup().lookup(InstanceCookie.class);
    assertNotNull("Instance cookie found", ic);

    Object read = ic.instanceCreate();
    assertNotNull("Instance created", read);
    assertEquals("Correct class", AnnoFoo.class, read.getClass());
    AnnoFoo readFoo = (AnnoFoo)read;
    assertEquals("property changed", "xxx", readFoo.getName());
}
 
Example 6
Project: incubator-netbeans   File: MatchingObjectTest.java   Source Code and License Vote up 5 votes
/**
 * Helper method - create file, write its content, find it, replace in it
 * and return its new content.
 */
public String replaceInFilePreserveCase(String fileContent, String find,
        String replace) throws IOException, InterruptedException,
        InvocationTargetException {

    BasicSearchCriteria bsc = new BasicSearchCriteria();
    bsc.setTextPattern(find);
    bsc.setMatchType(SearchPattern.MatchType.BASIC);
    bsc.setReplaceExpr(replace);
    bsc.setPreserveCase(true);
    bsc.onOk();

    FileObject fo = createTestFile(fileContent);
    SearchScopeDefinition ss = new TempFileSearchScope(fo);
    SearchInfo si = ss.getSearchInfo();

    final SearchComposition<Def> sc =
            new BasicComposition(si,
            new DefaultMatcher(bsc.getSearchPattern()),
            bsc, null);
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            sc.getSearchResultsDisplayer().getVisualComponent(); // initialize model
            final SearchTask st = new SearchTask(sc, true);
            st.run();
        }
    });

    ReplaceTask rt = new ReplaceTask(
            ((ResultDisplayer) sc.getSearchResultsDisplayer()).getResultModel().getMatchingObjects(),
            null);
    rt.run();
    String result = fo.asText(TEST_FILE_ENC);
    return result;
}
 
Example 7
Project: incubator-netbeans   File: ConvertAsBeanTest.java   Source Code and License Vote up 5 votes
public void testReadWriteNotForSubclasses() throws Exception {
    NotFoo foo = new NotFoo();
    foo.setName("xxx");

    DataFolder test = DataFolder.findFolder(FileUtil.getConfigRoot());
    try {
        DataObject obj = InstanceDataObject.create(test, null, foo, null);
        final FileObject pf = obj.getPrimaryFile();
        final String content = pf.asText();
        fail(content);
    } catch (NotSerializableException ex) {
        // OK
    }
}
 
Example 8
Project: incubator-netbeans   File: ElementsParserTest.java   Source Code and License Vote up 5 votes
public void testPerformance() throws IOException {
    FileObject file = getTestFile("testfiles/huge.html");
    String content = file.asText();

    TokenHierarchy hi = TokenHierarchy.create(content, HTMLTokenId.language());
    ElementsParser parser = ElementsParser.forTokenIndex(content, hi.tokenSequence(HTMLTokenId.language()), 0);

    long start = System.currentTimeMillis();
    while (parser.hasNext()) {
        parser.next();
    }
    long end = System.currentTimeMillis();

    float diff1 = end - start;
    System.out.println("first iteration took " + diff1 + "ms.");

    //~2500ms

    //second attempt

    parser = ElementsParser.forTokenIndex(content, hi.tokenSequence(HTMLTokenId.language()), 0);
    start = System.currentTimeMillis();
    while (parser.hasNext()) {
        parser.next();
    }
    end = System.currentTimeMillis();

    float diff2 = end - start;
    System.out.println("second iteration took " + diff2 + "ms.");

    //~600ms

    float ratio = diff1 / diff2;
    System.out.println("first / second ratio = " + ratio);
}
 
Example 9
Project: incubator-netbeans   File: CachingPreventsFileTouchesTest.java   Source Code and License Vote up 5 votes
private static void assertFileDoesNotContain(File file, String text) throws IOException, PropertyVetoException {
    LocalFileSystem lfs = new LocalFileSystem();
    lfs.setRootDirectory(file.getParentFile());
    FileObject fo = lfs.findResource(file.getName());
    assertNotNull("file object for " + file + " found", fo);
    String content = fo.asText();
    if (content.contains(text)) {
        fail("File " + file + " seems to contain '" + text + "'!");
    }
}
 
Example 10
Project: incubator-netbeans   File: CachingPreventsFileTouchesTest.java   Source Code and License Vote up 5 votes
private static void assertFileDoesNotContain(File file, String text) throws IOException, PropertyVetoException {
    LocalFileSystem lfs = new LocalFileSystem();
    lfs.setRootDirectory(file.getParentFile());
    FileObject fo = lfs.findResource(file.getName());
    assertNotNull("file object for " + file + " found", fo);
    String content = fo.asText();
    if (content.contains(text)) {
        fail("File " + file + " seems to contain '" + text + "'!");
    }
}
 
Example 11
Project: incubator-netbeans   File: Css3LexerTest.java   Source Code and License Vote up 5 votes
public void testIssue238864() throws Exception {
    FileObject testFile = getTestFile("testfiles/scss/large_empty.scss.txt");
    String source = testFile.asText();
     
    ExtCss3Lexer lexer = createLexer(source);
    
    assertANTLRToken(null, Css3Lexer.NL, lexer.nextToken());
    assertANTLRToken(null, Css3Lexer.EOF, lexer.nextToken());
}
 
Example 12
Project: incubator-netbeans   File: AntBuildExtender.java   Source Code and License Vote up 5 votes
private String assertMessage(FileObject extensionXml) {
    try {
        return "Extension file:" + extensionXml.asText() + " is owned by " + FileOwnerQuery.getOwner(extensionXml) +
                " but should be " + implementation.getOwningProject();
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
        return ex.getMessage();
    }
}
 
Example 13
Project: incubator-netbeans   File: ModelElementTest.java   Source Code and License Vote up 5 votes
public void testAcceptVisitorGeneric_speed() throws IOException {
    FileObject file = getTestFile("testfiles/bootstrap.css");
    String content = file.asText();

    System.out.println("Testing performance on " + file.getNameExt() + " ... ");

    long a = System.currentTimeMillis();
    CssParserResult result = TestUtil.parse(content);
    long b = System.currentTimeMillis();
    System.out.println("file parsing took " + (b - a) + "ms.");

    Model model = createModel(result);

    long c = System.currentTimeMillis();
    System.out.println("model creation took " + (c - b) + "ms.");

    StyleSheet s = getStyleSheet(model);
    assertNotNull(s);

    ModelVisitor visitor = new ModelVisitor.Adapter() {
        @Override
        public void visitRule(Rule rule) {
            //no-op
        }
    };

    s.accept(visitor);
    long d = System.currentTimeMillis();

    System.out.println("visiting took " + (d - c) + "ms.");

}
 
Example 14
Project: incubator-netbeans   File: TopComponentProcessorTest.java   Source Code and License Vote up 5 votes
public void testModeIsOK() throws Exception {
    FileObject set = FileUtil.getConfigFile("Windows2/Modes/output/my-tc.wstcref");
    assertNotNull("Mode file found", set);
    final String t = set.asText();
    assertValidate(t);
    assertEquals("not opened, no true in there", -1, t.indexOf("true"));
}
 
Example 15
Project: incubator-netbeans   File: TopComponentProcessorTest.java   Source Code and License Vote up 5 votes
public void testFactoryModeIsOK() throws Exception {
    FileObject set = FileUtil.getConfigFile("Windows2/Modes/explorer/factory-tc.wstcref");
    assertNotNull("Mode file found", set);
    final String t = set.asText();
    assertValidate(t);
    assertTrue("opened, no true in there", t.indexOf("true") > 0);
}
 
Example 16
Project: incubator-netbeans   File: IntroduceClass.java   Source Code and License Vote up 5 votes
String computeIntroduceClass(String className, FileObject fo) throws IOException {
    String fileText = fo.asText();
    StringBuilder textBuilder = new StringBuilder(fileText);
    String classText = ((this.staticContext) ? "static " : "") + "class "+className+" {\n"+
            "public "+className+"() {}\n"+
            this.methodBodyCode+"\n}";
    textBuilder.insert((int) this.classGeneratePosition, classText);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Inserted class: '"+classText+"'");
        LOG.fine("Updated full file content:\n'"+textBuilder.toString()+"'");
    }
    return textBuilder.toString();
}
 
Example 17
Project: incubator-netbeans   File: AntJUnitTestMethodNode.java   Source Code and License Vote up 4 votes
@NbBundle.Messages({
    "LBL_RerunTest=Run Again",
    "LBL_DebugTest=Debug"
})
@Override
public Action[] getActions(boolean context) {
    List<Action> actions = new ArrayList<Action>();
    Action preferred = getPreferredAction();
    if (preferred != null) {
        actions.add(preferred);
    }
    // Method node might belong to an inner class
    FileObject testFO = ((JUnitTestcase) testcase).getClassFileObject(true);
    if (testFO == null) {
        Logger.getLogger(AntJUnitTestMethodNode.class.getName()).log(Level.INFO, "Test running process was probably abnormally interrupted. Could not locate FileObject for {0}", testcase.toString());
        for (Action prefAction : actions) {
            prefAction.setEnabled(false);
        }
    } else {
        boolean parameterized = false;
        try {
            String text = testFO.asText();
            if (text != null) {
                text = text.replaceAll("\n", "").replaceAll(" ", "");
                if ((text.contains("@RunWith") || text.contains("@org.junit.runner.RunWith")) //NOI18N
                        && text.contains("Parameterized.class)")) {  //NOI18N
                    parameterized = true;
                }
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }

        if (!parameterized) {
            ActionProvider actionProvider = OutputUtils.getActionProvider(testFO);
            if (actionProvider != null) {
                List supportedActions = Arrays.asList(actionProvider.getSupportedActions());

                SingleMethod methodSpec = new SingleMethod(testFO, testcase.getName());
                Lookup nodeContext = Lookups.singleton(methodSpec);
                if (supportedActions.contains(COMMAND_RUN_SINGLE_METHOD)
                        && actionProvider.isActionEnabled(COMMAND_RUN_SINGLE_METHOD, nodeContext)) {
                    actions.add(new TestMethodNodeAction(actionProvider, nodeContext, COMMAND_RUN_SINGLE_METHOD, Bundle.LBL_RerunTest()));
                }
                if (supportedActions.contains(COMMAND_DEBUG_SINGLE_METHOD)
                        && actionProvider.isActionEnabled(COMMAND_DEBUG_SINGLE_METHOD, nodeContext)) {
                    actions.add(new TestMethodNodeAction(actionProvider, nodeContext, COMMAND_DEBUG_SINGLE_METHOD, Bundle.LBL_DebugTest()));
                }
            }
        }
    }
    actions.addAll(Arrays.asList(super.getActions(context)));

    return actions.toArray(new Action[actions.size()]);
}
 
Example 18
Project: incubator-netbeans   File: ElementsParserCacheTest.java   Source Code and License Vote up 2 votes
public void testPerformance() throws IOException {
    
    FileObject file = getTestFile("testfiles/huge.html");
    String content = file.asText();
    
    TokenHierarchy hi = TokenHierarchy.create(content, HTMLTokenId.language());
    ElementsParserCache cache = new ElementsParserCache(content, hi.tokenSequence(HTMLTokenId.language()));
    
    Iterator<Element> itr = cache.createElementsIterator();
    
    long start = System.currentTimeMillis();
    while(itr.hasNext()) {
        itr.next();
    }
    long end = System.currentTimeMillis();
    
    System.out.println("ElementsParserCache");
    System.out.println("========================");
    
    float diff1 = end - start;
    System.out.println("first iteration took " + diff1 + "ms.");
    
    //~2700ms versus the ~2500ms of the plain ElementsParser
    
    //second iteration - from cache
    
    itr = cache.createElementsIterator();
    
    start = System.currentTimeMillis();
    while(itr.hasNext()) {
        itr.next();
    }
    end = System.currentTimeMillis();
    
    float diff2 = end - start;
    System.out.println("second iteration took " + diff2 + "ms.");
    
    //~70ms versus 600ms of the second iteration of the plain parser
    
    float ratio = diff1 / diff2;
    System.out.println("first / second ratio = " + ratio);
    
    
}
 
Example 19
Project: incubator-netbeans   File: TestFileUtils.java   Source Code and License Vote up 2 votes
/**
 * Assert that the contents of a file (in UTF-8) include the specified text as a substring.
 * @param file an existing data file
 * @param contents a substring expected to be found in it
 */
public static void assertContains(FileObject file, String contents) throws IOException {
    String text = file.asText("UTF-8");
    assertTrue("Found '" + contents + "' in '" + text + "'", text.contains(contents));
}
 
Example 20
Project: incubator-netbeans   File: TestFileUtils.java   Source Code and License Vote up 2 votes
/**
 * Read the contents of a file as a single string.
 * @param a data file
 * @return its contents (in UTF-8 encoding)
 * @deprecated Use file.asText()
 */
@Deprecated
public static String readFile(FileObject file) throws IOException {
    return file.asText("UTF-8");
}