Java Code Examples for org.openide.filesystems.FileObject

The following are top voted examples for showing how to use org.openide.filesystems.FileObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: DefaultProjectOperationsImplementationTest.java   View source code 6 votes vote down vote up
public void testMoveWithInnerProjectComplex() throws Exception {
    TestUtil.createFileFromContent(DefaultProjectOperationsImplementationTest.class.getResource("data/test.txt"), projdir, "lib/test.txt");
    FileObject projdir2 = projdir.getFileObject("lib").createFolder("proj2");
    
    createProject(projdir2);
    
    ProgressHandle handle = ProgressHandleFactory.createHandle("test-handle");
    handle.start(DefaultProjectOperationsImplementation.MAX_WORK);
    
    FileObject oldProject     = prj.getProjectDirectory();
    File       oldProjectFile = FileUtil.toFile(oldProject);
    FileObject newTarget      = oldProject.getParent();
    
    DefaultProjectOperationsImplementation.doMoveProject(handle, prj, "projMove", "projMove", newTarget, "ERR_Cannot_Move");
    
    File newProject = new File(FileUtil.toFile(newTarget), "projMove");
    
    assertTrue(newProject.isDirectory());
    assertTrue(new File(newProject, "nbproject").isDirectory());
    assertTrue(new File(newProject, "src").isDirectory());
    assertTrue(new File(newProject, "lib").isDirectory());
    assertTrue(new File(new File(newProject, "lib"), "proj2").isDirectory());
    assertFalse(new File(new File(oldProjectFile, "lib"), "proj2").exists());
}
 
Example 2
Project: incubator-netbeans   File: OptionsDisplayerImpl.java   View source code 6 votes vote down vote up
/** Returns true if some non hidden files are registered under OptionsExport
 * folder.
 * @return true if something is registered under OptionsExport, false otherwise
 */
private boolean optionsExportNotEmpty() {
    FileObject optionsExportFO = doGetConfigFile("OptionsExport");  //NOI18N
    if(optionsExportFO != null) {
        FileObject[] categories = optionsExportFO.getChildren();
        for (FileObject category : categories) {
            Object hiddenCategory = category.getAttribute("hidden");  //NOI18N
            if (hiddenCategory != null && (Boolean)hiddenCategory) {
                // skip hidden category folder
                continue;
            }
            FileObject[] items = category.getChildren();
            for (FileObject item : items) {
                Object hiddenItem = item.getAttribute("hidden");  //NOI18N
                if(hiddenItem == null || !(Boolean)hiddenItem) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 3
Project: NBANDROID-V2   File: GradleAndroidManifest.java   View source code 6 votes vote down vote up
@Override
public FileObject get() {
    if (aProject != null) {
        File manifestFile = aProject.getDefaultConfig().getSourceProvider().getManifestFile();

        BuildTypeContainer buildTypeContainer = buildConfig.getCurrentBuildTypeContainer();
        File buildManifestFile = buildTypeContainer != null
                ? buildTypeContainer.getSourceProvider().getManifestFile()
                : null;
        File m = Iterables.find(Lists.newArrayList(manifestFile, buildManifestFile), Predicates.notNull(), null);
        if (m != null) {
            return FileUtil.toFileObject(m);
        }
    }
    return null;
}
 
Example 4
Project: incubator-netbeans   File: CPWhereUsedQueryPlugin.java   View source code 6 votes vote down vote up
public static Collection<RefactoringElement> findMixins(RefactoringElementContext context) throws IOException, ParseException {
    Collection<RefactoringElement> elements = new ArrayList<>();
    String mixinName = context.getElementName();

    //all files linked from the base file with their CP models
    Map<FileObject, CPCssIndexModel> indexModels = CPUtils.getIndexModels(context.getFileObject(), DependencyType.REFERRING_AND_REFERRED, false);
    for (Map.Entry<FileObject, CPCssIndexModel> entry : indexModels.entrySet()) {
        CPCssIndexModel im = entry.getValue();
        FileObject file = entry.getKey();
        CPModel cpModel = CPModel.getModel(file);
        for (CPElementHandle var : im.getMixins()) {
            //change both declarations and usages
            if (var.getName().equals(mixinName)) {
                CPElement cpElement = var.resolve(cpModel);
                if (cpElement != null) {
                    OffsetRange elementRange = cpElement.getRange();
                    elements.add(new RefactoringElement(file, elementRange, mixinName));
                }
            }
        }
    }
    
    return elements;
}
 
Example 5
Project: incubator-netbeans   File: HtmlEditorSupport.java   View source code 6 votes vote down vote up
private boolean canDecodeFile(FileObject fo, String encoding) {
    CharsetDecoder decoder = Charset.forName(encoding).newDecoder().onUnmappableCharacter(CodingErrorAction.REPORT).onMalformedInput(CodingErrorAction.REPORT);
    try {
        BufferedInputStream bis = new BufferedInputStream(fo.getInputStream());
        //I probably have to create such big buffer since I am not sure
        //how to cut the file to smaller byte arrays so it cannot happen
        //that an encoded character is divided by the arrays border.
        //In such case it might happen that the method woult return
        //incorrect value.
        byte[] buffer = new byte[(int) fo.getSize()];
        bis.read(buffer);
        bis.close();
        decoder.decode(ByteBuffer.wrap(buffer));
        return true;
    } catch (CharacterCodingException ex) {
        //return false
    } catch (IOException ioe) {
        Logger.getLogger("global").log(Level.WARNING, "Error during charset verification", ioe);
    }
    return false;
}
 
Example 6
Project: incubator-netbeans   File: CPExtenderTest.java   View source code 6 votes vote down vote up
@RandomlyFails // frequently fails in NB-Core-Build; [CPExtender] checkLibraryForPoms on Library[Stuff] -> true and [Utilities] WORKDIR/o.n.m.m.c.C/testAddRemovePomLib/[email protected]:2: CHILD_REMOVED:[email protected] yet [Utilities] no changes in [email protected][WORKDIR/o.n.m.m.c.C/testAddRemovePomLib/[email protected]:2] where modified=true
public void testAddRemovePomLib() throws Exception {
    Library lib = LibraryManager.getDefault().createLibrary("j2se", "Stuff", Collections.singletonMap("maven-pom", Collections.singletonList(new URL("http://repo1.maven.org/maven2/grp/stuff/1.0/stuff-1.0.pom"))));
    Library lib2 = LibraryManager.getDefault().createLibrary("j2se", "Stuff2", Collections.singletonMap("maven-pom", Collections.singletonList(new URL("http://repo1.maven.org/maven2/grp/stuff/2.0/stuff-2.0.pom"))));
    FileObject d = FileUtil.toFileObject(getWorkDir());
    TestFileUtils.writeFile(d, "pom.xml", "<project><modelVersion>4.0.0</modelVersion>"
            + "<groupId>test</groupId><artifactId>prj</artifactId>"
            + "<packaging>jar</packaging><version>1.0</version></project>");
    FileObject java = TestFileUtils.writeFile(d, "src/main/java/p/C.java", "package p; class C {}");
    Project p = ProjectManager.getDefault().findProject(d);
    NbMavenProject mp = p.getLookup().lookup(NbMavenProject.class);
    assertEquals("[]", mp.getMavenProject().getDependencies().toString());
    assertTrue(ProjectClassPathModifier.addLibraries(new Library[] {lib}, java, ClassPath.COMPILE));
    assertFalse(ProjectClassPathModifier.addLibraries(new Library[] {lib}, java, ClassPath.COMPILE));
    NbMavenProject.fireMavenProjectReload(p); // XXX why is this necessary?
    assertEquals("[Dependency {groupId=grp, artifactId=stuff, version=1.0, type=jar}]", mp.getMavenProject().getDependencies().toString());
    assertFalse(ProjectClassPathModifier.removeLibraries(new Library[] {lib2}, java, ClassPath.COMPILE));
    assertTrue(ProjectClassPathModifier.removeLibraries(new Library[] {lib}, java, ClassPath.COMPILE));
    assertFalse(ProjectClassPathModifier.removeLibraries(new Library[] {lib}, java, ClassPath.COMPILE));
    NbMavenProject.fireMavenProjectReload(p);
    assertEquals("[]", mp.getMavenProject().getDependencies().toString());
}
 
Example 7
Project: incubator-netbeans   File: ProcessorTest.java   View source code 6 votes vote down vote up
public void testShowItIsPossibleToPassInBeansWrappedObject() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.txt");
    OutputStream os = fo.getOutputStream();
    String txt = "<#if (classInfo.getMethods().size() > 0) >The size is greater than 0.</#if>";
    os.write(txt.getBytes());
    os.close();       
    
    
    StringWriter w = new StringWriter();
                    
    Map<String,Object> parameters = Collections.<String,Object>singletonMap(
        "classInfo", BeansWrapper.getDefaultInstance().wrap(new ClassInfo())
    );
    apply(fo, w, parameters);
    assertEquals("The size is greater than 0.", w.toString());
}
 
Example 8
Project: incubator-netbeans   File: RecognizeInstanceObjectsOnModuleEnablementTest.java   View source code 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    clearWorkDir();
    f = new File(getWorkDir(), "m.jar");
    
    Manifest man = new Manifest();
    Attributes attr = man.getMainAttributes();
    attr.putValue("OpenIDE-Module", "m.test");
    attr.putValue("OpenIDE-Module-Public-Packages", "-");
    attr.putValue("Manifest-Version", "1.0");
    JarOutputStream os = new JarOutputStream(new FileOutputStream(f), man);
    os.putNextEntry(new JarEntry("META-INF/namedservices/ui/javax.swing.JComponent"));
    os.write("javax.swing.JButton\n".getBytes("UTF-8"));
    os.closeEntry();
    os.close();
    
    FileObject fo = FileUtil.createData(FileUtil.getConfigRoot(), "ui/ch/my/javax-swing-JPanel.instance");
}
 
Example 9
Project: incubator-netbeans   File: ModuleOraculumTest.java   View source code 6 votes vote down vote up
@NonNull
private static FileObject writeFile(
        @NonNull final FileObject root,
        @NonNull final String folder,
        @NonNull final String name,
        @NonNull final String content) throws IOException {
    final FileObject fld;
    if (!folder.isEmpty()) {
        fld = FileUtil.createFolder(root, folder);
    } else {
        fld = root;
    }
    final FileObject file = FileUtil.createData(fld, name);
    try(PrintWriter out = new PrintWriter(new OutputStreamWriter(file.getOutputStream(), "UTF-8"))) {   //NOI18N
        out.println(content);
    }
    return file;
}
 
Example 10
Project: incubator-netbeans   File: UICommonUtils.java   View source code 6 votes vote down vote up
/**
 * Grabs and checks a <code>FileObject</code> from the given node.
 * If either the file could not be grabbed or the file does not pertain
 * to any project, a message is displayed.
 *
 * @param  node  node to get a <code>FileObject</code> from.
 * @return  the grabbed <code>FileObject</code>,
 *          or <code>null</code> in case of failure
 */
@NbBundle.Messages({"# {0} - selected node's display name",
    "MSG_file_from_node_failed=File cannot be found for selected node: {0}.",
    "# {0} - source file",
    "MSG_no_project=Source file {0} does not belong to any project."})
private static FileObject getFileObject(final Node node, boolean justLogIt) {
    final FileObject fo = getFileObjectFromNode(node);
    if (fo == null) {
        if(justLogIt) {
            LOG.info(Bundle.MSG_file_from_node_failed(node.getDisplayName()));
        } else {
            notifyUser(Bundle.MSG_file_from_node_failed(node.getDisplayName()));
        }
        return null;
    }
    Project owner = FileOwnerQuery.getOwner(fo);
    if (owner == null) {
        if(justLogIt) {
            LOG.info(Bundle.MSG_no_project(fo));
        } else {
            notifyUser(Bundle.MSG_no_project(fo));
        }
        return null;
    }
    return fo;
}
 
Example 11
Project: incubator-netbeans   File: LayerUtilsTest.java   View source code 6 votes vote down vote up
public void testCachedMultiFS() throws Exception {
    clearWorkDir();
    LayerCacheManager m = LayerCacheManager.manager(true);
    // b-layer.xml overrides a-layer.xml now and then:
    List<File> files = new ArrayList<File>(Arrays.asList(
            new File(getDataDir(), "layers/b-layer.xml"),
            new File(getDataDir(), "layers/a-layer.xml")
            ));

    FileSystem cfs = memoryStoreAndLoad(m, files);
    assertNotNull(cfs.findResource("Menu/File"));
    assertNotNull(cfs.findResource("Menu/A Folder"));
    assertNull(cfs.findResource("Menu/A Folder/org-example-a-AAction.shadow"));  // hidden by b-layer
    FileObject mf = cfs.findResource("Actions/File");
    assertEquals(2, mf.getChildren().length);
    FileObject ba = cfs.findResource("Actions/File/org-example-b-BAction.instance");
    assertEquals("BBBBB", ba.getAttribute("displayName"));
    FileObject aa = cfs.findResource("Actions/File/org-example-a-AAction.instance");
    assertEquals("AAAA", aa.getAttribute("displayName"));
}
 
Example 12
Project: incubator-netbeans   File: FileObjSymlinkTest.java   View source code 6 votes vote down vote up
/**
 * Test isRecursiveSymbolicLink method. Use this folder tree:
 * <pre>
 * - workdir
 *   - a
 *     - b
 *       - c (symlink to d)
 *   - d (symlink to a)
 * </pre>
 *
 * @throws java.io.IOException
 */
public void testIsRecursiveSymbolicLinkIndirect() throws IOException {
    if (!checkSymlinksSupported()) {
        return;
    }
    File dir = getWorkDir();
    File a = new File(dir, "a");
    File b = new File(a, "b");
    File c = new File(b, "c");
    File d = new File(dir, "d");
    b.mkdirs();
    Files.createSymbolicLink(d.toPath(), a.toPath());
    Files.createSymbolicLink(c.toPath(), d.toPath());
    FileObject dirFO = FileUtil.toFileObject(dir);
    FileObject cFO = dirFO.getFileObject("a/b/c");
    assertTrue(FileUtil.isRecursiveSymbolicLink(cFO));
}
 
Example 13
Project: incubator-netbeans   File: SourcePathProviderImpl.java   View source code 6 votes vote down vote up
private static ClassPath createClassPath(URL[] urls) {
    List<PathResourceImplementation> pris = new ArrayList<PathResourceImplementation> ();
    for (URL url : urls) {
        FileObject fo = URLMapper.findFileObject(url);
        if (fo != null && fo.canRead()) {
            try {
                pris.add(ClassPathSupport.createResource(url));
            } catch (IllegalArgumentException iaex) {
                // Can be thrown from ClassPathSupport.createResource()
                // Ignore - bad source root
                //logger.log(Level.INFO, "Invalid source root = "+fo, iaex);
                logger.warning(iaex.getLocalizedMessage());
            }
        }
    }
    return ClassPathSupport.createClassPath(pris);
}
 
Example 14
Project: incubator-netbeans   File: CommonUtilities.java   View source code 6 votes vote down vote up
/**
     * Close Memory Toolbar.
     */
    public static void closeMemoryToolbar(){
        // View|Toolbars|Memory        
        try {  // workaround for Issue #213828
            FileObject fo = FileUtil.getConfigFile("Toolbars/Memory");
            if (fo!=null) {
                fo.delete();
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }        
//        closeToolbar(Bundle.getStringTrimmed("org.openide.actions.Bundle","View") + "|" +
//                Bundle.getStringTrimmed("org.netbeans.core.windows.actions.Bundle", "CTL_ToolbarsListAction") + "|" +
//                "Memory");
        maximizeWholeNetbeansWindow();
    }
 
Example 15
Project: incubator-netbeans   File: SuiteProjectGenerator.java   View source code 6 votes vote down vote up
private static void initApplication(FileObject dirFO, String platformID) throws IOException  {
    SuiteProject project = (SuiteProject) ProjectManager.getDefault().findProject(dirFO);
    SuiteProperties suiteProps = new SuiteProperties(project, project.getHelper(), project.getEvaluator(), Collections.<NbModuleProject>emptySet());
    BrandingModel branding = suiteProps.getBrandingModel();
    branding.setBrandingEnabled(true);
    branding.setName(branding.getName());
    branding.setTitle(branding.getTitle());
    branding.store();
    NbPlatform plaf = NbPlatform.getPlatformByID(platformID);
    if (plaf != null) {
        ModuleEntry bootstrapModule = plaf.getModule("org.netbeans.bootstrap");
        if (bootstrapModule != null) {
            if (plaf.getHarnessVersion().compareTo(HarnessVersion.V65) <= 0) {
                // Will be stripped of version suffix if appropriate for the platform.
                suiteProps.setEnabledClusters(new String[] {bootstrapModule.getClusterDirectory().getName()});
            } else {
                suiteProps.setClusterPath(Collections.singletonList(
                        ClusterInfo.create(bootstrapModule.getClusterDirectory(), true, true)));
            }
        }
    }
    suiteProps.setDisabledModules(SuiteCustomizerLibraries.DISABLED_PLATFORM_MODULES.toArray(new String[0]));
    suiteProps.storeProperties();
}
 
Example 16
Project: incubator-netbeans   File: FixActionProvider.java   View source code 6 votes vote down vote up
private Set<FileObject> getSourceRootsFO(SourcePathProvider sp) {
    if (sp instanceof SourcePathProviderImpl) {
        return ((SourcePathProviderImpl) sp).getSourceRootsFO();
    } else {
        String[] sourceRoots = sp.getSourceRoots();
        Set<FileObject> fos = new HashSet<FileObject>();
        for (String root : sourceRoots) {
            FileObject fo;
            int jarIndex = root.indexOf("!/");
            if (jarIndex > 0) {
                fo = FileUtil.toFileObject(new java.io.File(root.substring(0, jarIndex)));
                fo = fo.getFileObject(root.substring(jarIndex + 2));
            } else {
                fo = FileUtil.toFileObject(new java.io.File(root));
            }
            if (fo != null) {
                fos.add(fo);
            }
        }
        return fos;
    }
}
 
Example 17
Project: incubator-netbeans   File: SuiteUtilsTest.java   View source code 6 votes vote down vote up
public void testGeneratingOfUniqAntProperty_62819() throws Exception {
    SuiteProject suite1 = generateSuite("suite1");
    NbModuleProject module1 = generateStandaloneModule("module1");
    NbModuleProject module2 = generateStandaloneModule("module2");

    SuiteUtils.addModule(suite1, module1);
    FileObject propsFO = suite1.getProjectDirectory().getFileObject("nbproject/project.properties");
    EditableProperties props = Util.loadProperties(propsFO);
    assertEquals("modules property", "${project.org.example.module1}", props.getProperty("modules"));
    assertEquals("module1 property", "../module1", props.getProperty("project.org.example.module1"));

    // user is free to do this, although in more sensible way
    assertEquals("module1 project removed (sanity check)", "../module1", props.remove("project.org.example.module1"));
    props.setProperty("modules", "${project.org.example.module2}");
    props.setProperty("project.org.example.module2", "../module1");
    Util.storeProperties(propsFO, props);

    SuiteUtils.addModule(suite1, module2);
    SubprojectProvider spp = SuitePropertiesTest.getSubProjectProvider(suite1);
    assertEquals("one module suite component", 2, spp.getSubprojects().size());

    SuiteProvider suiteProvider = module1.getLookup().lookup(SuiteProvider.class);
    assertNotNull("module1 became suite component - has valid SuiteProvider", suiteProvider.getSuiteDirectory());
    suiteProvider = module2.getLookup().lookup(SuiteProvider.class);
    assertNotNull("module2 became suite component - has valid SuiteProvider", suiteProvider.getSuiteDirectory());
}
 
Example 18
Project: incubator-netbeans   File: SimpleSearchInfoDefinition.java   View source code 6 votes vote down vote up
/**
 * Return sub-array of filters that are nice to a file.
 */
private static SearchFilterDefinition[] niceFilters(FileObject fo,
        SearchFilterDefinition[] allFilters) {

    boolean[] mask = new boolean[allFilters.length]; // mask for bad filters
    if (fo.isFolder()) {
        for (int i = 0; i < allFilters.length; i++) {
            FolderResult result = allFilters[i].traverseFolder(fo);
            mask[i] = (result != FolderResult.DO_NOT_TRAVERSE);
        }
    } else {
        assert fo.isData();
        for (int i = 0; i < allFilters.length; i++) {
            mask[i] = allFilters[i].searchFile(fo);
        }
    }
    SearchFilterDefinition[] nice =
            new SearchFilterDefinition[countTrues(mask)];
    int niceIndex = 0;
    for (int i = 0; i < allFilters.length; i++) {
        if (mask[i]) {
            nice[niceIndex++] = allFilters[i];
        }
    }
    return nice;
}
 
Example 19
Project: incubator-netbeans   File: TreePathHandleTest.java   View source code 6 votes vote down vote up
public void testEquals() throws Exception {
    FileObject file = FileUtil.createData(sourceRoot, "test/test.java");
    final String code = "package test; public class test {}";

    writeIntoFile(file, code);

    JavaSource js = JavaSource.forFileObject(file);

    js.runUserActionTask(new  Task<CompilationController>() {
        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(Phase.RESOLVED);
            
            TreePath tp = parameter.getTreeUtilities().pathFor(code.indexOf("{}") + 1);
            TreePathHandle handle = TreePathHandle.create(tp, parameter);

            assertFalse(handle.equals(null));
            assertFalse(handle.equals((Object) ""));
            assertTrue(handle.equals(handle));

        }
    }, true);
}
 
Example 20
Project: incubator-netbeans   File: ProjectHelper.java   View source code 5 votes vote down vote up
public static void removeModelListner(Project prj, FileChangeListener l){
    // WeakChangeListener will return true for its proxy.
    FileObject fo = getFOForBindingConfigFile(prj);
    if (fo != null) {
        fo.removeFileChangeListener(l);
    }

    fo = getFOForNBProjectDir(prj);
    if (fo != null) {
        fo.removeFileChangeListener(l);
    }
}
 
Example 21
Project: incubator-netbeans   File: JavaSourceHelper.java   View source code 5 votes vote down vote up
public static JavaSource createJavaSource(String template, FileObject targetFolder, String packageName, String className) {
    try {
        FileObject fobj = targetFolder.getFileObject(className, Constants.JAVA_EXT);
        if (fobj == null) {
            fobj = createDataObjectFromTemplate(template, targetFolder, packageName, className).getPrimaryFile();
        }
        return JavaSource.forFileObject(fobj);
    } catch (IOException ex) {
        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
    }

    return null;
}
 
Example 22
Project: incubator-netbeans   File: PropertiesStorage.java   View source code 5 votes vote down vote up
private OutputStream outputStream() throws IOException {
    FileObject fo = toPropertiesFile(true);
    final FileLock lock = fo.lock();
    final OutputStream os = fo.getOutputStream(lock);
    return new FilterOutputStream(os) {
        public void close() throws IOException {
            super.close();
            lock.releaseLock();
        }
    };
}
 
Example 23
Project: incubator-netbeans   File: PersistenceManager.java   View source code 5 votes vote down vote up
/** @return Local folder for TopComponents. Do not cache ti because it can change
 * during project switch. */
public FileObject getComponentsLocalFolder () throws IOException {
    try {
        FileObject compsLocalFolder = FileUtil.createFolder(
            getRootLocalFolder(), COMPS_FOLDER
        );
        return compsLocalFolder;
    } catch (IOException exc) {
        String annotation = NbBundle.getMessage(PersistenceManager.class,
            "EXC_CompsFolder", COMPS_FOLDER);
        Exceptions.attachLocalizedMessage(exc, annotation);
        throw exc;
    }
}
 
Example 24
Project: incubator-netbeans   File: ModifyElementRulesPanel.java   View source code 5 votes vote down vote up
private void updateResultCodeSample() {
    FileObject file = (FileObject) styleSheetCB.getSelectedItem();
    Collection<String> classesInFile = files2classes.get(file);
    Collection<String> idsInFile = files2ids.get(file);
    
    boolean classExistInSS = classesInFile != null && classesInFile.contains(clzName);
    boolean idExistInSS = idsInFile != null && idsInFile.contains(idName);

    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    sb.append("&lt;");
    sb.append(sourceHandle.getOpenTag().name());

    appendCode(sb, "id", originalIdName, idName, idExistInSS);
    appendCode(sb, "class", originalClzName, clzName, classExistInSS);

    sb.append("&gt;");
    if(!isClassNameOK()) {
        sb.append("<br><div><font color=\"bb5555\">");
        sb.append(Bundle.class_selector_error(clzName));
        sb.append("</font>");
    }
    if(!isIdNameOK()) {
        sb.append("<br><div><font color=\"bb5555\">");
        sb.append(Bundle.id_selector_error(idName));
        sb.append("</font>");
    }
    
    sb.append("</html>");

    resultCodeLabel.setText(sb.toString());
}
 
Example 25
Project: NBANDROID-V2   File: AndroidSdkProvider.java   View source code 5 votes vote down vote up
private synchronized FileObject getStorage() {
    if (storageCache == null) {
        storageCache = FileUtil.getConfigFile(PLATFORM_STORAGE);
        if (storageCache != null) {
            storageCache.addFileChangeListener(this);
            removePathListener();
        } else {
            final String[] path = PLATFORM_STORAGE.split("/");  //NOI18N
            FileObject lastExist = FileUtil.getConfigRoot();
            String expected = null;
            for (String pathElement : path) {
                expected = pathElement;
                FileObject current = lastExist.getFileObject(expected);
                if (current == null) {
                    break;
                }
                lastExist = current;
            }
            assert lastExist != null;
            assert expected != null;
            removePathListener();
            final String expectedFin = expected;
            pathListener = new FileChangeAdapter() {
                @Override
                public void fileFolderCreated(FileEvent fe) {
                    if (expectedFin.equals(fe.getFile().getName())) {
                        firePropertyChange();
                    }
                }
            };
            lastFound = lastExist;
            lastFound.addFileChangeListener(pathListener);
        }
    }
    return storageCache;
}
 
Example 26
Project: incubator-netbeans   File: RepositoryComboSupport.java   View source code 5 votes vote down vote up
private void pingNBRepository(FileObject referenceFile) {
    String url = VersioningQuery.getRemoteLocation(referenceFile.toURI());
    if (url != null) {
        if(NBBugzillaUtils.isNbRepository(url)) {
            BugtrackingUtil.findNBRepository(); // ensure repository exists 
        }
    }
}
 
Example 27
Project: incubator-netbeans   File: ModuleClassPathsTest.java   View source code 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();
    clearWorkDir();
    final FileObject workDir = FileUtil.toFileObject(FileUtil.normalizeFile(getWorkDir()));
    MockLookup.setInstances(TestProject.createProjectType(), new MockCompilerOptions(), new MockClassPathProvider());
    final FileObject prjDir = FileUtil.createFolder(workDir, "TestProject");    //NOI18N
    assertNotNull(prjDir);
    final FileObject srcDir = FileUtil.createFolder(prjDir, "src");    //NOI18N
    assertNotNull(srcDir);
    final Project prj = TestProject.createProject(prjDir, srcDir, null);
    assertNotNull(prj);
    setSourceLevel(prj, "9");   //NOI18N
    tp = prj.getLookup().lookup(TestProject.class);
    assertNotNull(tp);
    src = ClassPathFactory.createClassPath(ClassPathSupportFactory.createSourcePathImplementation (
                        tp.getSourceRoots(),
                        tp.getUpdateHelper().getAntProjectHelper(),
                        tp.getEvaluator()));
    systemModules = Optional.ofNullable(TestUtilities.getJava9Home())
            .map((jh) -> TestJavaPlatform.createModularPlatform(jh))
            .map((jp) -> jp.getBootstrapLibraries())
            .orElse(null);
    final FileObject libs = FileUtil.createFolder(workDir, "libs"); //NOI18N
    automaticModuleRoot = createJar(libs,"automatic.jar");  //NOI18N
    assertNotNull(automaticModuleRoot);
    jarFileRoot = createJar(libs,"legacy.jar"); //NOI18N
    assertNotNull(jarFileRoot);
}
 
Example 28
Project: incubator-netbeans   File: SettingsType.java   View source code 5 votes vote down vote up
@Override
protected FileObject getLegacyMimeFolder(FileObject baseFolder, String mimeType) {
    if (mimeType == null || mimeType.length() == 0) {
        return baseFolder.getFileObject(Utils.TEXT_BASE_MIME_TYPE);
    } else {
        return super.getMimeFolder(baseFolder, mimeType);
    }
}
 
Example 29
Project: incubator-netbeans   File: MavenSourcesImpl.java   View source code 5 votes vote down vote up
GeneratedGroup(NbMavenProjectImpl p, FileObject rootFold, String nm, String displayNm/*,
                Icon icn, Icon opened*/) {
            project = p;
            rootFolder = rootFold;
            name = nm;
            displayName = displayNm != null ? displayNm : SG_Root_not_defined();
//            icon = icn;
//            openedIcon = opened;
        }
 
Example 30
Project: incubator-netbeans   File: UnitTestForSourceQueryImplTest.java   View source code 5 votes vote down vote up
public void testFindUnitTestMultiRoots () throws Exception {
    FileObject newRoot = SourceRootsTest.addSourceRoot(helper,projdir,"src.other.dir","other");
    URL[] urls = UnitTestForSourceQuery.findSources(tests);
    assertNotNull(urls);
    assertEquals(2,urls.length);
    assertEquals(sources.toURL(), urls[0]);
    assertEquals(newRoot.toURL(), urls[1]);
}
 
Example 31
Project: incubator-netbeans   File: LocalizedBundleInfo.java   View source code 5 votes vote down vote up
/** Use factory method instead. */
private LocalizedBundleInfo(FileObject[] bundleFOs) throws IOException {
    if (bundleFOs == null || bundleFOs.length == 0) {
        throw new IllegalArgumentException();
    }
    props = new EditableProperties[bundleFOs.length];
    paths = new File[bundleFOs.length];
    for (int i = 0; i < bundleFOs.length; i++) {
        InputStream bundleIS = bundleFOs[i].getInputStream();
        try {
            props[i] = new EditableProperties(true);
            props[i].load(bundleIS);
        } finally {
            bundleIS.close();
        }
        paths[i] = FileUtil.toFile(bundleFOs[i]);
        bundleFOs[i].addFileChangeListener(new FileChangeAdapter() {
            public void fileChanged(FileEvent fe) {
                try {
                    LocalizedBundleInfo.this.reload();
                } catch (IOException e) {
                    Util.err.log(ErrorManager.WARNING,
                            "Cannot reload localized bundle info " + // NOI18N
                            FileUtil.getFileDisplayName(fe.getFile()));
                }
            }
        });
    }
}
 
Example 32
Project: incubator-netbeans   File: TodoTaskScanner.java   View source code 5 votes vote down vote up
private String getContent( FileObject fileObject ) throws IOException {
    InputStream input = null;
    try {
        input = fileObject.getInputStream();
    } catch( FileNotFoundException fnfE ) {
        //file was deleted
    }
    if( null == input )
        return "";
    char[] buf = new char[1024*64];
    StringBuffer sb = new StringBuffer();
    Charset charset = FileEncodingQuery.getEncoding( fileObject );
    Reader r = new BufferedReader( new InputStreamReader( input, charset ) );
    int len;
    try {
        while (true) {
            len = r.read(buf);
            if (len == -1) break;
            sb.append(buf, 0, len);
        }
    } catch(IllegalArgumentException ex) { // reading of extra characters into the specified character buffer failed
        Logger.getLogger(TodoTaskScanner.class.getName()).log(Level.INFO, "Reading failed for {0}, with charset: {1}.", new Object[]{FileUtil.toFile(fileObject).getPath(), charset}); //NOI18N;
        r.close();
        return "";
    } finally {
        r.close();
    }
    return sb.toString();
}
 
Example 33
Project: incubator-netbeans   File: FolderPathLookup.java   View source code 5 votes vote down vote up
private static Class<? extends Object> findTypeFor(FileObject f) {
    String clazz = getClassName(f);
    if (clazz == null) {
        return null;
    }
    try {
        return Class.forName(clazz, false, loader());
    } catch (ClassNotFoundException ex) {
        LOG.log(Level.FINE, ex.getMessage(), ex);
        return null;
    }
}
 
Example 34
Project: incubator-netbeans   File: BeanNavigatorJavaSourceFactory.java   View source code 5 votes vote down vote up
public synchronized CancellableTask<CompilationInfo> createTask(FileObject file) {
    // System.out.println("CREATE TASK FOR " + file.getNameExt() );
    if ( ui == null) {
        return EMPTY_TASK;
    }
    else {
        return ui.getTask();
    }
}
 
Example 35
Project: incubator-netbeans   File: VisibilityFilter.java   View source code 5 votes vote down vote up
/**
 */
@Override
public boolean searchFile(FileObject file)
        throws IllegalArgumentException {
    if (file.isFolder()) {
        throw new java.lang.IllegalArgumentException(
                "file (not folder) expected");                      //NOI18N
    } else {
        return isPermittedByQuery(file) && isPrimaryFile(file);
    }
}
 
Example 36
Project: incubator-netbeans   File: RetrieverImpl.java   View source code 5 votes vote down vote up
public FileObject retrieveResource(FileObject destinationDir, 
        URI relativePathToCatalogFile, URI resourceToRetrieve, 
        boolean save2singleFolder) 
        throws UnknownHostException, URISyntaxException, IOException {
    Project prj = FileOwnerQuery.getOwner(destinationDir);
    if(relativePathToCatalogFile == null){
        assert(prj != null);
        //check if this project has XMLCatalogProvider in its lookup
        XMLCatalogProvider catProvider = (XMLCatalogProvider) prj.getLookup().
                lookup(XMLCatalogProvider.class);
        if(catProvider == null){
            //there is no catalog provider so just use the legacy projectwide catalog approach
            return retrieveResourceImpl(destinationDir, resourceToRetrieve, null, save2singleFolder);
        }
        relativePathToCatalogFile = catProvider.getProjectWideCatalog();
        if(relativePathToCatalogFile == null){
            //somehow this provider does not give me this info. So follow legacy.
            return retrieveResourceImpl(destinationDir, resourceToRetrieve, null, save2singleFolder);
        }
        //use this relativePathToCatalogFile for the new catalog file.
    }
    URI cfuri = null;
    if(!relativePathToCatalogFile.isAbsolute()){
        if (prj != null) {
            FileObject prjRtFO = prj.getProjectDirectory();
            cfuri = FileUtil.toFile(prjRtFO).toURI().resolve(relativePathToCatalogFile);
        } else {
            // For Maven based projects the project directory doesn't contain cached catalogs. 
            //  In these cases should be used catalog.xml within destination directory.
            cfuri = destinationDir.getParent().getURL().toURI().resolve(Utilities.PRIVATE_CATALOG_URI_STR);
        }
    }else{
        cfuri = relativePathToCatalogFile;
    }
    File cffile = new File(cfuri);
    if(!cffile.isFile())
        cffile.createNewFile();
    FileObject catalogFileObject = FileUtil.toFileObject(FileUtil.normalizeFile(cffile));
    return retrieveResourceImpl(destinationDir, resourceToRetrieve, catalogFileObject, save2singleFolder);
}
 
Example 37
Project: incubator-netbeans   File: SpringConfigFileModelManager.java   View source code 5 votes vote down vote up
private void notify(Document document) {
    FileObject fo = NbEditorUtilities.getFileObject(document);
    if (fo == null){
        return;
    }
    if (!SpringConstants.CONFIG_MIME_TYPE.equals(fo.getMIMEType())) {
        return;
    }
    File file = FileUtil.toFile(fo);
    if (file == null) {
        return;
    }
    notifyFileChanged(fo, file);
}
 
Example 38
Project: Pogamut3   File: ExampleBotProjectWizardIterator.java   View source code 5 votes vote down vote up
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;
                }
            }
        }
        OutputStream out = fo.getOutputStream();
        try {
            XMLUtil.write(doc, out, "UTF-8");
        } finally {
            out.close();
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        writeFile(str, fo);
    }

}
 
Example 39
Project: incubator-netbeans   File: FileDeletePlugin.java   View source code 5 votes vote down vote up
@Override
public Problem prepare(RefactoringElementsBag elements) {
    for (FileObject fo: refactoring.getRefactoringSource().lookupAll(FileObject.class)) {
            elements.addFileChange(refactoring, new DeleteFile(fo, elements));
        }
    return null;
}
 
Example 40
Project: incubator-netbeans   File: RepositoryUpdaterTest.java   View source code 5 votes vote down vote up
public void registerInvisibles (final Collection<? extends FileObject> invisibles) {
    synchronized (invisible) {
        invisible.clear();
        invisible.addAll(invisibles);
    }
    changeSupport.fireChange();
}