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

The following examples show how to use org.openide.filesystems.FileObject#asText() . These examples are extracted from open source projects. 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 Project: netbeans   File: Source.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @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 2
Source Project: netbeans   File: SourceMapTest.java    License: Apache License 2.0 6 votes vote down vote up
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 3
Source Project: netbeans   File: BaseFileObjectTestHid.java    License: Apache License 2.0 6 votes vote down vote up
public void testReadRecreatedFile() 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());
    try {
        InputStream is = fo.getInputStream();
        fail("Should throw an exception: " + is);
    } catch (FileNotFoundException ex) {
        // ok
    }
    
    f.createNewFile();
    
    String newTxt = fo.asText("UTF-8");
    assertEquals("Empty text read even the file object is not valid anymore", "", newTxt);
    assertFalse("Still invalid", fo.isValid());
}
 
Example 4
Source Project: netbeans   File: ConvertAsBeanTest.java    License: Apache License 2.0 6 votes vote down vote up
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 5
Source Project: netbeans   File: ConvertAsBeanTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testReadWriteOnSubclass() throws Exception {
    HooFoo foo = new HooFoo();
    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", HooFoo.class, read.getClass());
    HooFoo readFoo = (HooFoo)read;
    assertEquals("property changed", "xxx", readFoo.getName());
}
 
Example 6
Source Project: netbeans   File: ModelTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testPersonRevert() throws Exception {
    FileObject fo = getTestFile("testfiles/model/person.js.model");
    BufferedReader reader = new BufferedReader(new InputStreamReader(fo.getInputStream()));
    try {
        Collection<JsObject> obj = Model.readModel(reader, null, null, null);
        assertEquals(1, obj.size());

        final StringWriter sw = new StringWriter();
        Model.Printer p = new Model.Printer() {
            @Override
            public void println(String str) {
                sw.append(str).append("\n");
            }
        };
        Model.writeObject(p, obj.iterator().next(), null);
        assertDescriptionMatches(fo, sw.toString(), false, ".revert", true);
    } finally {
        reader.close();
    }

    // bit hacky check that .model and .model.revert are the same
    String text = fo.asText();
    assertDescriptionMatches("testfiles/model/person.js.model", text, false, ".revert", true);
}
 
Example 7
Source Project: netbeans   File: ClassMetricsTest.java    License: Apache License 2.0 5 votes vote down vote up
private String code(String fileName) throws IOException {
    File f = getDataDir();
    FileObject dd = FileUtil.toFileObject(f);
    
    FileObject file = dd.getFileObject("hints/metrics/" + fileName);
    return file.asText();
}
 
Example 8
Source Project: netbeans   File: IntroduceClass.java    License: Apache License 2.0 5 votes vote down vote up
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 9
Source Project: netbeans   File: ElementsParserTest.java    License: Apache License 2.0 5 votes vote down vote up
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 10
Source Project: netbeans   File: MatchingObjectTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 11
Source Project: netbeans-mmd-plugin   File: MindMapLink.java    License: Apache License 2.0 5 votes vote down vote up
public String readUTF8Text() throws IOException {
  final FileObject foj = getFile();
  final FileLock flock = lock(foj);
  try {
    return foj.asText("UTF-8");
  } finally {
    flock.releaseLock();
  }
}
 
Example 12
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 13
Source Project: netbeans   File: ConvertAsBeanTest.java    License: Apache License 2.0 5 votes vote down vote up
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 14
private synchronized String deployFile(File file, File deployDir) throws IOException, InterruptedException {

        final long deployTime = file.lastModified();
        File statusFile = new File(deployDir, file.getName() + DEPLOYED); // NOI18N
        File failedFile = new File(deployDir, file.getName() + FAILED_DEPLOY); // NOI18N
        File dodeployFile = new File(deployDir, file.getName() + DO_DEPLOY); // NOI18N
        if (!dodeployFile.exists() && !isDeploymentInProgress(file, deployDir)) {
            dodeployFile.createNewFile(); // NOI18N
        }
        int i = 0;
        int limit = ((int) TIMEOUT / POLLING_INTERVAL);
        do {
            Thread.sleep(POLLING_INTERVAL);
            i++;
            // what this condition says
            // we are waiting and either there is progress file
            // or (there is not a new enough status file
            // and there is not a new enough failed file)
        } while (i < limit && isDeploymentInProgress(file, deployDir)
                || ((!statusFile.exists() || statusFile.lastModified() < deployTime)
                && (!failedFile.exists() || failedFile.lastModified() < deployTime)));

        if (failedFile.isFile()) {
            FileObject fo = FileUtil.toFileObject(failedFile);
            if (fo != null) {
                return fo.asText();
            }
            return NbBundle.getMessage(WildflyDeploymentStatus.class, "MSG_FAILED");
        } else if (!statusFile.isFile()) {
            return NbBundle.getMessage(WildflyDeploymentStatus.class, "MSG_TIMEOUT");
        }
        return null;
    }
 
Example 15
Source Project: netbeans   File: Css3LexerTest.java    License: Apache License 2.0 5 votes vote down vote up
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 16
Source Project: netbeans   File: KeepInitialComments.java    License: Apache License 2.0 4 votes vote down vote up
public void testKeepInitialComment() throws IOException, PersistenceException {
    FileObject file = FileUtil.createMemoryFileSystem()
                              .getRoot()
                              .createData("test.form");
    String code = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
                  "\n" +
                  "<!--Leading\n" +
                  "  - comment\n" +
                  "-->\n" +
                  "\n" +
                  "<Form version=\"1.3\" maxVersion=\"1.9\" type=\"org.netbeans.modules.form.forminfo.JPanelFormInfo\">\n" +
                  "  <AuxValues>\n" +
                  "    <AuxValue name=\"FormSettings_autoResourcing\" type=\"java.lang.Integer\" value=\"0\"/>\n" +
                  "    <AuxValue name=\"FormSettings_autoSetComponentName\" type=\"java.lang.Boolean\" value=\"false\"/>\n" +
                  "    <AuxValue name=\"FormSettings_generateFQN\" type=\"java.lang.Boolean\" value=\"true\"/>\n" +
                  "    <AuxValue name=\"FormSettings_generateMnemonicsCode\" type=\"java.lang.Boolean\" value=\"false\"/>\n" +
                  "    <AuxValue name=\"FormSettings_i18nAutoMode\" type=\"java.lang.Boolean\" value=\"false\"/>\n" +
                  "    <AuxValue name=\"FormSettings_layoutCodeTarget\" type=\"java.lang.Integer\" value=\"1\"/>\n" +
                  "    <AuxValue name=\"FormSettings_listenerGenerationStyle\" type=\"java.lang.Integer\" value=\"0\"/>\n" +
                  "    <AuxValue name=\"FormSettings_variablesLocal\" type=\"java.lang.Boolean\" value=\"false\"/>\n" +
                  "    <AuxValue name=\"FormSettings_variablesModifier\" type=\"java.lang.Integer\" value=\"2\"/>\n" +
                  "  </AuxValues>\n" +
                  "\n" +
                  "  <Layout>\n" +
                  "    <DimensionLayout dim=\"0\">\n" +
                  "      <Group type=\"103\" groupAlignment=\"0\" attributes=\"0\">\n" +
                  "          <EmptySpace min=\"0\" pref=\"400\" max=\"32767\" attributes=\"0\"/>\n" +
                  "      </Group>\n" +
                  "    </DimensionLayout>\n" +
                  "    <DimensionLayout dim=\"1\">\n" +
                  "      <Group type=\"103\" groupAlignment=\"0\" attributes=\"0\">\n" +
                  "          <EmptySpace min=\"0\" pref=\"300\" max=\"32767\" attributes=\"0\"/>\n" +
                  "      </Group>\n" +
                  "    </DimensionLayout>\n" +
                  "  </Layout>\n" +
                  "</Form>\n";
    try (OutputStream out = file.getOutputStream();
         Writer w = new OutputStreamWriter(out, "UTF-8")) {
        w.append(code);
    }

    FormModel form = loadForm(file);

    List<Throwable> errors = new ArrayList<Throwable>();

    new GandalfPersistenceManager().saveForm(file, form, errors);

    if (errors.size() > 0) {
        System.out.println("There were errors while loading the form: ");
        for (Throwable er : errors) {
            er.printStackTrace();
        }
    }

    String content = file.asText("UTF-8");

    assertEquals(code, content);
}
 
Example 17
Source Project: netbeans   File: FeaturesOffDemandTest.java    License: Apache License 2.0 4 votes vote down vote up
public void testFoDModuleFilesAreAnnotatedWithAttributes() throws Exception {
    FileObject sub = FileUtil.getConfigFile("Modules/org-netbeans-modules-java-kit.xml");
    assertNotNull("Module config file found", sub);

    String origContent = sub.asText("UTF-8");

    FileObject prjFO1 = root.getFileObject("1st");
    FileObject prjFO2 = root.getFileObject("2nd");

    assertTrue("Recognized as project", ProjectManager.getDefault().isProject(prjFO1));
    Project p = ProjectManager.getDefault().findProject(prjFO1);
    assertNotNull("Project found", p);

    long before = System.currentTimeMillis();
    Thread.sleep(1000);

    TestFactory.recognize.add(prjFO1);
    TestFactory.recognize.add(prjFO2);
    OpenProjects.getDefault().open(new Project[] { p }, false);

    Thread.sleep(1000);
    long after = System.currentTimeMillis();
    
    List<Project> arr = Arrays.asList(OpenProjects.getDefault().openProjects().get());
    assertEquals("However one instance is there", 1, arr.size());
    Project newP = arr.get(0).getLookup().lookup(Project.class);
    if (p == newP) {
        fail("New project is made available, not old: " + newP);
    }
    assertEquals("Right type", TestFactory.class, newP.getClass());

    OpenProjects.getDefault().close (new Project[] { newP });
    if (OpenProjects.getDefault().getOpenProjects().length != 0) {
        fail("All projects shall be closed: " + Arrays.asList(OpenProjects.getDefault().getOpenProjects()));
    }

    assertNotNull("File is found in userdir", FileUtil.toFile(sub));
    final Object when = sub.getAttribute("ergonomicsEnabled");
    final Object cnt = sub.getAttribute("ergonomicsUnused");
    assertNotNull("Not enabled manually", cnt);
    assertNotNull("Not enabled manually", when);
    assertEquals("Integer", Integer.class, cnt.getClass());
    assertEquals("Set to zero", Integer.valueOf(0), cnt);

    if (origContent.equals(sub.asText("UTF-8"))) {
        fail("The module shall be enabled right now:\n" + sub.asText("UTF-8"));
    }

    for (int i = 0; i < 2; i++) {
        FeatureManager.incrementUnused(OpenProjects.getDefault().getOpenProjects());
    }
    FeatureManager.disableUnused(2);

    assertTrue("Config file exists", sub.canRead());
    String newContent = sub.asText("UTF-8");

    assertEquals("The content is the same as originally was", origContent, newContent);
}
 
Example 18
Source Project: netbeans   File: Utils.java    License: Apache License 2.0 4 votes vote down vote up
public static void dumpTokens(FileObject file, Map<String, String> prefix2libraryMap, PrintStream out) throws IOException {
    String source = file.asText("UTF-8");
    
    
    JspParseData jspParseData = new JspParseData(prefix2libraryMap, true, true, true);

    InputAttributes inputAttributes = new InputAttributes();
    inputAttributes.setValue(JspTokenId.language(), JspParseData.class, jspParseData, false);
    
    TokenHierarchy th = TokenHierarchy.create(source, false, JspTokenId.language(), Collections.EMPTY_SET, inputAttributes);
    
    
    TokenSequence<JspTokenId> ts = th.tokenSequence(JspTokenId.language());
    dumpTokens(ts, out);
    
}
 
Example 19
Source Project: netbeans   File: TestFileUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 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");
}
 
Example 20
Source Project: netbeans   File: TestFileUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 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));
}