Java Code Examples for org.openide.filesystems.FileUtil

The following examples show how to use org.openide.filesystems.FileUtil. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: netbeans   Source File: InterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testGetAttributeClonedPullWithCredentials() throws HgException, IOException {
    File folder = createFolder("folder");
    File file = createFile(folder, "file");

    commit(folder);
    File cloned = clone(getWorkTreeDir());

    String defaultPull = "http://so:[email protected]/away";
    String defaultPullReturned = "http://a.repository.far.far/away";

    new HgConfigFiles(cloned).setProperty(HgConfigFiles.HG_DEFAULT_PULL, defaultPull);
    HgRepositoryContextCache.getInstance().reset();

    FileObject fo = FileUtil.toFileObject(new File(new File(cloned, folder.getName()), file.getName()));
    String attr = (String) fo.getAttribute("ProvidedExtensions.RemoteLocation");
    assertNotNull(attr);
    assertEquals(defaultPullReturned, attr);
}
 
Example 2
Source Project: netbeans   Source File: DebuggerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test of debug method, of class Debugger.
 */
public void testStopAtBreakpoint()  throws Exception {
    FileObject scriptFo = createPHPTestFile("index.php");//NOI18N
    assertNotNull(scriptFo);
    Project dummyProject = DummyProject.create(scriptFo);
    assertNotNull(dummyProject);
    final SessionId sessionId = new SessionId(scriptFo, dummyProject);
    File scriptFile = FileUtil.toFile(scriptFo);
    assertNotNull(scriptFile);
    assertTrue(scriptFile.exists());
    final TestWrapper testWrapper = new TestWrapper(getTestForSuspendState(sessionId));
    addBreakpoint(scriptFo, 27, testWrapper, new RunContinuation(sessionId));
    startDebugging(sessionId, scriptFile);
    sessionId.isInitialized(true);
    // always fails
    // testWrapper.assertTested();
}
 
Example 3
Source Project: netbeans   Source File: JavaPluginUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Problem isSourceFile(FileObject fo, CompilationInfo info) {
    Problem preCheckProblem;
    if (fo == null || FileUtil.getArchiveFile(fo) != null) { //NOI18N
        preCheckProblem = new Problem(true, NbBundle.getMessage(
                JavaPluginUtils.class, "ERR_CannotRefactorLibraryClass",
                FileUtil.getFileDisplayName(fo)
                ));
        return preCheckProblem;
    }
    // RefactoringUtils.isFromLibrary already checked file for null
    if (!RefactoringUtils.isFileInOpenProject(fo)) {
        preCheckProblem =new Problem(true, NbBundle.getMessage(
                JavaPluginUtils.class,
                "ERR_ProjectNotOpened",
                FileUtil.getFileDisplayName(fo)));
        return preCheckProblem;
    }
    return null;
}
 
Example 4
Source Project: netbeans   Source File: DefaultReplaceTokenProvider.java    License: Apache License 2.0 6 votes vote down vote up
/** Finds the one source group, if any, which contains all of the listed files. */
private static @CheckForNull SourceGroup findGroup(SourceGroup[] groups, FileObject[] files) {
    SourceGroup selected = null;
    for (FileObject file : files) {
        for (SourceGroup group : groups) {
            FileObject root = group.getRootFolder();
            if (file == root || FileUtil.isParentOf(root, file)) { // or group.contains(file)?
                if (selected == null) {
                    selected = group;
                } else if (selected != group) {
                    return null;
                }
            }
        }
    }
    return selected;
}
 
Example 5
public void testQuery() throws Exception {
    JavaPlatform platform = JavaPlatform.getDefault();
    ClassPath cp = platform.getBootstrapLibraries();
    FileObject pfo = cp.getRoots()[0];
    URL u = URLMapper.findURL(pfo, URLMapper.EXTERNAL);
    URL urls[] = JavadocForBinaryQuery.findJavadoc(u).getRoots();
    assertEquals(1, urls.length);
    assertTrue(urls[0].toString(), urls[0].toString().startsWith("https://docs.oracle.com/"));

    List<URL> l = new ArrayList<URL>();
    File javadocFile = getBaseDir();
    File api = new File (javadocFile,"api");
    File index = new File (api,"index-files");
    FileUtil.toFileObject(index);
    index.mkdirs();
    l.add(Utilities.toURI(javadocFile).toURL());
    J2SEPlatformImpl platformImpl = (J2SEPlatformImpl)platform;
    platformImpl.setJavadocFolders(l);
    urls = JavadocForBinaryQuery.findJavadoc(u).getRoots();
    assertEquals(1, urls.length);
    assertEquals(Utilities.toURI(api).toURL(), urls[0]);
}
 
Example 6
Source Project: netbeans   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
public static String validateTestSources(PhpProject project, String testDirPath) {
    if (!StringUtils.hasText(testDirPath)) {
        return NbBundle.getMessage(Utils.class, "MSG_FolderEmpty");
    }

    File testSourcesFile = new File(testDirPath);
    if (!testSourcesFile.isAbsolute()) {
        return NbBundle.getMessage(Utils.class, "MSG_TestNotAbsolute");
    } else if (!testSourcesFile.isDirectory()) {
        return NbBundle.getMessage(Utils.class, "MSG_TestNotDirectory");
    }
    FileObject nbproject = project.getProjectDirectory().getFileObject("nbproject"); // NOI18N
    FileObject testSourcesFo = FileUtil.toFileObject(testSourcesFile);
    if (testSourcesFile.equals(FileUtil.toFile(ProjectPropertiesSupport.getSourcesDirectory(project)))) {
        return NbBundle.getMessage(Utils.class, "MSG_TestEqualsSources");
    } else if (FileUtil.isParentOf(nbproject, testSourcesFo)
            || nbproject.equals(testSourcesFo)) {
        return NbBundle.getMessage(Utils.class, "MSG_TestUnderneathNBMetadata");
    } else if (!FileUtils.isDirectoryWritable(testSourcesFile)) {
        return NbBundle.getMessage(Utils.class, "MSG_TestNotWritable");
    }
    return null;
}
 
Example 7
Source Project: netbeans   Source File: GSFPHPParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void parse(Snapshot snapshot, Task task, SourceModificationEvent event) throws ParseException {
    if (snapshot == null) {
        return;
    }

    long startTime = System.currentTimeMillis();
    FileObject fileObject = snapshot.getSource().getFileObject();
    if (!PARSE_BIG_FILES && fileIsTooBig(fileObject)) {
        createEmptyResult(snapshot);
        LOGGER.log(
                Level.INFO,
                "Parsing of big file cancelled. Size: {0} Name: {1}",
                new Object[] {fileObject.getSize(), FileUtil.getFileDisplayName(fileObject)});
    } else if (!isRegisteredPhpFile(fileObject)) {
        createEmptyResult(snapshot);
        LOGGER.log(
                Level.FINE,
                "Skipped file extension: {0}\nRegistered extensions: {1}",
                new Object[] {fileObject.getExt(), REGISTERED_PHP_EXTENSIONS.toString()});
    } else {
        processParsing(fileObject, snapshot, event);
    }
    long endTime = System.currentTimeMillis();
    LOGGER.log(Level.FINE, "Parsing took: {0}ms source: {1}", new Object[]{endTime - startTime, System.identityHashCode(snapshot.getSource())}); //NOI18N
}
 
Example 8
Source Project: netbeans   Source File: DDHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Created validation.xml deployment descriptor
 * @param j2eeProfile Java EE profile
 * @param dir Directory where validation.xml should be created
 * @param name name of configuration file to create;
 * @return validation.xml file as FileObject
 * @throws IOException
 * @since 1.52
 */
public static FileObject createValidationXml(Profile j2eeProfile, FileObject dir, String name) throws IOException {
    String template = null;
    if (Profile.JAVA_EE_6_FULL == j2eeProfile || Profile.JAVA_EE_6_WEB == j2eeProfile ||
            Profile.JAVA_EE_7_FULL == j2eeProfile || Profile.JAVA_EE_7_WEB == j2eeProfile ||
            Profile.JAVA_EE_8_FULL == j2eeProfile || Profile.JAVA_EE_8_WEB == j2eeProfile) {
        template = "validation.xml"; //NOI18N
    }

    if (template == null)
        return null;

    MakeFileCopy action = new MakeFileCopy(RESOURCE_FOLDER + template, dir, name+".xml");
    FileUtil.runAtomicAction(action);
    if (action.getException() != null)
        throw action.getException();
    else
        return action.getResult();
}
 
Example 9
Source Project: netbeans   Source File: CustomizerSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the element at the specified position in this list.
 *
 * @param index The element position in the list.
 *
 * @return The element at the specified position in this list.
 */
@Override
public Object getElementAt(int index) {
    URL url = data.get(index);
    if ("jar".equals(url.getProtocol())) { // NOI18N
        URL fileURL = FileUtil.getArchiveFile(url);
        if (FileUtil.getArchiveRoot(fileURL).equals(url)) {
            // really the root
            url = fileURL;
        } else {
            // some subdir, just show it as is
            return url.toExternalForm();
        }
    }
    if ("file".equals(url.getProtocol())) { // NOI18N
        File f = new File(URI.create(url.toExternalForm()));
        return f.getAbsolutePath();
    }
    else {
        return url.toExternalForm();
    }
}
 
Example 10
Source Project: netbeans   Source File: OutputPanel.java    License: Apache License 2.0 6 votes vote down vote up
private void javadocBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_javadocBrowseActionPerformed
    JFileChooser chooser = new JFileChooser();
    FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
    chooser.setFileSelectionMode (JFileChooser.FILES_AND_DIRECTORIES);
    chooser.setMultiSelectionEnabled(false);
    if (lastChosenFile != null) {
        chooser.setSelectedFile(lastChosenFile);
    } else if (javadoc.getText().length() > 0) {
        chooser.setSelectedFile(new File(javadoc.getText()));
    } else {
        File files[] = model.getBaseFolder().listFiles();
        if (files != null && files.length > 0) {
            chooser.setSelectedFile(files[0]);
        } else {
            chooser.setSelectedFile(model.getBaseFolder());
        }
    }
    chooser.setDialogTitle(NbBundle.getMessage(OutputPanel.class, "LBL_Browse_Javadoc")); // NOI18N
    if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
        File file = chooser.getSelectedFile();
        file = FileUtil.normalizeFile(file);
        javadoc.setText(file.getAbsolutePath());
        lastChosenFile = file;
    }
}
 
Example 11
/**
 * @throws Exception
 */
public void testGenerate() throws Exception{

    File testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
            "package org.netbeans.test;\n\n" +
            "import java.util.*;\n\n" +
            "public class Test {\n" +
            "}"
            );
    GenerationOptions options = new GenerationOptions();
    options.setMethodName("create");
    options.setOperation(GenerationOptions.Operation.PERSIST);
    options.setParameterName("object");
    options.setParameterType("Object");
    options.setQueryAttribute("");
    options.setReturnType("Object");

    FileObject result = generate(FileUtil.toFileObject(testFile), options);
    assertFile(result);
}
 
Example 12
Source Project: netbeans   Source File: RenamePackagePlugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Problem fastCheckParameters() {
    final String newName = refactoring.getNewName();
    if (!IdentifiersUtil.isValidPackageName(newName)) {
        return createProblem("ERR_InvalidPackage", newName); //NOI18N
    }

    final ClassPath projectClassPath = ClassPath.getClassPath(folder, ClassPath.SOURCE);
    final FileObject fo = projectClassPath.findResource(newName.replace('.','/'));
    if (fo != null) {
        final FileObject ownerRoot = projectClassPath.findOwnerRoot(folder);
        if(ownerRoot != null && ownerRoot.equals(projectClassPath.findOwnerRoot(fo))) {
            if (fo.isFolder() && fo.getChildren().length == 1) {
                final FileObject parent = fo.getChildren()[0];
                final String relativePath = FileUtil.getRelativePath(parent, folder);
                if (relativePath != null) {
                    return null;
                }
            }
            return createProblem("ERR_PackageExists", newName); //NOI18N
        }
    }
    return null;
}
 
Example 13
Source Project: netbeans   Source File: PhpDeleteRefactoringUI.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doRefactoringBypass() throws IOException {
    RP.post(new Runnable() {

        @Override
        public void run() {
            try {
                // #172199
                FileUtil.runAtomicAction(new FileSystem.AtomicAction() {
                    @Override
                    public void run() throws IOException {
                        file.delete();
                    }
                });
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, null, ex);
            }
        }

    });
}
 
Example 14
Source Project: netbeans   Source File: CustomizerSources.java    License: Apache License 2.0 6 votes vote down vote up
private void configFilesFolderBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configFilesFolderBrowseActionPerformed
    JFileChooser chooser = new JFileChooser();
    FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    File fileName = new File(jTextFieldConfigFilesFolder.getText());
    File configFiles = fileName.isAbsolute() ? fileName : new File(projectFld, fileName.getPath());
    if (configFiles.isAbsolute()) {
        chooser.setSelectedFile(configFiles);
    } else {
        chooser.setSelectedFile(projectFld);
    }
    if ( JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
        File selected = FileUtil.normalizeFile(chooser.getSelectedFile());
        String newConfigFiles;
        if (CollocationQuery.areCollocated(projectFld, selected)) {
            newConfigFiles = PropertyUtils.relativizeFile(projectFld, selected);
        } else {
            newConfigFiles = selected.getPath();
        }
        jTextFieldConfigFilesFolder.setText(newConfigFiles);
    }
}
 
Example 15
public DataObject generate(FileObject targetFolder, String targetName) {
    try {
        DataFolder folder = (DataFolder) DataObject.find(targetFolder);
        FileObject fo = null;
        fo = FileUtil.getConfigFile("Templates/WebServices/DerivedKeyPasswordValidator.java"); // NOI18N
        if (fo != null) {
            DataObject template = DataObject.find(fo);
            DataObject obj = template.createFromTemplate(folder, targetName);            
            return obj;
        }
    } catch (IOException ex) {
        Logger.getLogger("global").log(Level.INFO, null, ex);
    }
    
    return null;
}
 
Example 16
Source Project: NBANDROID-V2   Source File: AndroidClassPathProvider.java    License: Apache License 2.0 6 votes vote down vote up
public void addAndroidLibraryDependencies(List<URL> roots, Map<URL, ArtifactData> libs, AndroidLibrary lib) {
    String name = lib.getName();
    URL url = FileUtil.urlForArchiveOrDir(FileUtil.normalizeFile(lib.getJarFile()));
    if (!roots.contains(url)) {
        roots.add(url);
        libs.put(url, new ArtifactData(lib, project));
    }
    List<? extends AndroidLibrary> libraryDependencies = lib.getLibraryDependencies();
    for (AndroidLibrary libraryDependencie : libraryDependencies) {
        addAndroidLibraryDependencies(roots, libs, libraryDependencie);
    }
    Iterator<File> localJars = lib.getLocalJars().iterator();
    if (localJars != null) {
        while (localJars.hasNext()) {
            File next = localJars.next();
            url = FileUtil.urlForArchiveOrDir(FileUtil.normalizeFile(next));
            if (!roots.contains(url)) {
                roots.add(url);
                libs.put(url, new ArtifactData(lib, project));
            }

        }
    }

}
 
Example 17
public void testBootClassPathImplementation () throws Exception {
    ClassPathImplementation cpImpl = ProjectClassPathSupport.createPropertyBasedClassPathImplementation(
            FileUtil.toFile(helper.getProjectDirectory()), evaluator, new String[] {PROP_NAME_1, PROP_NAME_2});
    ClassPath cp = ClassPathFactory.createClassPath(cpImpl);
    FileObject[] fo = cp.getRoots();
    List<FileObject> expected = new ArrayList<FileObject>();
    expected.addAll(Arrays.asList(cpRoots1));
    expected.addAll(Arrays.asList(cpRoots2));
    assertEquals ("Wrong ClassPath roots",expected, Arrays.asList(fo));   //NOI18N
    cpRoots1 = new FileObject[] {cpRoots1[0]};
    setClassPath(new String[] {PROP_NAME_1}, new FileObject[][]{cpRoots1});
    fo = cp.getRoots();
    expected = new ArrayList<FileObject>();
    expected.addAll(Arrays.asList(cpRoots1));
    expected.addAll(Arrays.asList(cpRoots2));
    assertEquals ("Wrong ClassPath roots",expected, Arrays.asList(fo));   //NOI18N
    cpRoots2 = new FileObject[] {cpRoots2[0]};
    setClassPath(new String[] {PROP_NAME_2}, new FileObject[][]{cpRoots2});
    fo = cp.getRoots();
    expected = new ArrayList<FileObject>();
    expected.addAll(Arrays.asList(cpRoots1));
    expected.addAll(Arrays.asList(cpRoots2));
    assertEquals ("Wrong ClassPath roots",expected, Arrays.asList(fo));   //NOI18N
}
 
Example 18
Source Project: netbeans   Source File: ProjectFactorySupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether any of Eclipse source roots is already owned by a project.
 * If it is then abort import and tell user to open that project instead.
 * Internal source roots beneath the project directory do not pose this problem, as
 * {@link FileOwnerQuery} should consider the new project to be the default owner of anything
 * underneath it.
 * @param model a model of the project being considered for import
 * @param nbProjectDir the proposed directory to use as the NetBeans {@linkplain Project#getProjectDirectory project directory}
 * @param importProblems problems to append to in case this returns true
 * @return true if the import would be blocked by ownership issues; false normally
 */
public static boolean areSourceRootsOwned(ProjectImportModel model, File nbProjectDir, List<String> importProblems) {
    for (File sourceRootFile : model.getEclipseSourceRootsAsFileArray()) {
        if (sourceRootFile.getAbsolutePath().startsWith(nbProjectDir.getAbsolutePath())) {
            continue;
        }
        FileObject fo = FileUtil.toFileObject(sourceRootFile);
        if (fo == null) { // #148256
            continue;
        }
        Project p = FileOwnerQuery.getOwner(fo);
        if (p != null) {
            for (SourceGroup sg : ProjectUtils.getSources(p).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA)) {
                if (fo.equals(sg.getRootFolder())) {
                    importProblems.add(NbBundle.getMessage(EclipseProject.class, "MSG_SourceRootOwned", // NOI18N
                            model.getProjectName(), sourceRootFile.getPath(),
                            FileUtil.getFileDisplayName(p.getProjectDirectory())));
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 19
Source Project: netbeans   Source File: StartTask.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initialize JDK used to start Payara server.
 * <p/>
 * @return State change request data when JDK could not be initialized
 *         or <code>null</code> otherwise.
 */
private StateChange initJDK() {
    try {
        if (null == jdkHome) {
            jdkHome = getJavaPlatformRoot();
            File jdkHomeFile = FileUtil.toFile(jdkHome);
            if (!JavaUtils.isJavaPlatformSupported(instance, jdkHomeFile)) {
                jdkHome = JavaSEPlatformPanel.selectServerSEPlatform(
                        instance, jdkHomeFile);
            }
        }
        if (jdkHome == null) {
            return new StateChange(this, TaskState.FAILED,
                    TaskEvent.CMD_FAILED, "StartTask.initJDK.null",
                    instanceName);
        }
    } catch (IOException ex) {
        LOGGER.log(Level.INFO, null, ex); // NOI18N
        return new StateChange(this, TaskState.FAILED,
                TaskEvent.CMD_FAILED, "StartTask.initJDK.exception",
                new String[] {instanceName, ex.getLocalizedMessage()});
    }
    return null;
}
 
Example 20
Source Project: netbeans   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static FileObject copyResource(String path, FileObject destFolder) throws Exception {
    String filename = getFileName(path);
    
    FileObject dest = destFolder.getFileObject(filename);
    if (dest == null) {
        dest = destFolder.createData(filename);
    }
    FileLock lock = dest.lock();
    OutputStream out = dest.getOutputStream(lock);
    InputStream in = Util.class.getResourceAsStream(path);
    try {
        FileUtil.copy(in, out);
    } finally {
        out.close();
        in.close();
        if (lock != null) lock.releaseLock();
    }
    return dest;
}
 
Example 21
Source Project: netbeans   Source File: SingleModulePropertiesTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testGetPublicPackages() throws Exception {
    final NbModuleProject p = generateStandaloneModule("module1");
    FileUtil.createData(p.getSourceDirectory(), "org/example/module1/One.java");
    FileUtil.createData(p.getSourceDirectory(), "org/example/module1/resources/Two.java");
    
    // apply and save project
    boolean result = ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction<Boolean>() {
        public Boolean run() throws IOException {
            ProjectXMLManager pxm = new ProjectXMLManager(p);
            pxm.replacePublicPackages(Collections.singleton("org.example.module1"));
            return true;
        }
    });
    assertTrue("replace public packages", result);
    ProjectManager.getDefault().saveProject(p);
    
    SingleModuleProperties props = loadProperties(p);
    PublicPackagesTableModel pptm = props.getPublicPackagesModel();
    assertEquals("number of available public packages", 2, pptm.getRowCount());
    assertEquals("number of selected public packages", 1, pptm.getSelectedPackages().size());
}
 
Example 22
Source Project: netbeans   Source File: ProjectLibraryProvider.java    License: Apache License 2.0 6 votes vote down vote up
private static FileObject getSharedLibFolder(final File libBaseFolder, final Library lib) throws IOException {
    FileObject sharedLibFolder;
    try {
        sharedLibFolder = ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction<FileObject>() {
            public FileObject run() throws IOException {
                FileObject lf = FileUtil.toFileObject(libBaseFolder);
                if (lf == null) {
                    lf = FileUtil.createFolder(libBaseFolder);
                }
                return lf.createFolder(getUniqueName(lf, lib.getName(), null));
            }
        });
    } catch (MutexException ex) {
        throw (IOException)ex.getException();
    }
    return sharedLibFolder;
}
 
Example 23
Source Project: netbeans   Source File: SourceRoots.java    License: Apache License 2.0 6 votes vote down vote up
private List<FileObject> addPluginRoots(File pluginsDirFile, GrailsPluginSupport.FolderFilter filter) {
    if (pluginsDirFile == null) {
        return Collections.emptyList();
    }

    final FileObject pluginsDir = FileUtil.toFileObject(FileUtil.normalizeFile(pluginsDirFile));
    if (pluginsDir != null) {
        List<FileObject> result = new ArrayList<>();
        for(Enumeration<? extends FileObject> subfolders = pluginsDir.getFolders(false);
                subfolders.hasMoreElements();) {

            FileObject subFolder = subfolders.nextElement();
            if (filter == null || filter.accept(subFolder.getNameExt())) {
                addGrailsSourceRoots(subFolder, result);
            }
        }
        return result;
    }
    return Collections.emptyList();
}
 
Example 24
Source Project: netbeans   Source File: SnippetClassGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@NbBundle.Messages({
    "EXC_UnexpectedTemplateContents=Unexpected plain class template contents",
    "EXC_ShellTemplateMissing=Unexpected plain class template contents"
})
private FileObject createJavaFile() throws IOException {
    FileObject template = FileUtil.getConfigFile("Templates/Classes/ShellClass.java"); // NOI18N
    if (template == null) {
        throw new IOException(Bundle.EXC_ShellTemplateMissing());
    }
    FileBuilder builder = new FileBuilder(template, targetFolder);
    builder.name(className);
    builder.param("executables", executableContent.toString());
    builder.param("declaratives", declarativeConent.toString());
    
    Collection<FileObject> l = builder.build();
    if (l.size() != 1) {
        throw new IOException(Bundle.EXC_UnexpectedTemplateContents());
    }
    return l.iterator().next();
}
 
Example 25
Source Project: netbeans   Source File: FileObjectIndexable.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public URL getURL() {
    if (url == null) {
        try {
            FileObject f = getFileObject();
            if (f != null) {
                url = f.toURL();
                if (LOG.isLoggable(Level.FINEST)) {
                    LOG.log(
                        Level.FINEST,
                        "URL from existing FileObject: {0} = {1}",  //NOI18N
                        new Object[] {
                            FileUtil.getFileDisplayName(f),
                            url
                        });
                }
            } else {
                url = Util.resolveUrl(root.toURL(), relativePath, false);
                if (LOG.isLoggable(Level.FINEST)) {
                    LOG.log(
                        Level.FINEST,
                        "URL from non existing FileObject root: {0} ({1}), relative path: {2} = {3}",  //NOI18N
                        new Object[] {
                            FileUtil.getFileDisplayName(root),
                            root.toURL(),
                            relativePath,
                            url
                        });
                }
            }
        } catch (MalformedURLException ex) {
            url = ex;
        }
    }

    return url instanceof URL ? (URL) url : null;
}
 
Example 26
Source Project: netbeans   Source File: PHPCodeCompletion217990Test.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, ClassPath> createClassPathsForTest() {
    return Collections.singletonMap(
        PhpSourcePath.SOURCE_CP,
        ClassPathSupport.createClassPath(new FileObject[] {
            FileUtil.toFileObject(new File(getDataDir(), "/testfiles/completion/lib/test217990/"))
        })
    );
}
 
Example 27
Source Project: netbeans   Source File: OptionsDisplayerImpl.java    License: Apache License 2.0 5 votes vote down vote up
public OptionsDisplayerImpl (boolean modal) {
       this.modal = modal;
fcl = new DefaultFSListener();
       try {
           // 91106 - listen to default FS changes to update Advanced Options, Export and Import buttons
           FileUtil.getConfigRoot().getFileSystem().addFileChangeListener(fcl);
       } catch (FileStateInvalidException ex) {
           Exceptions.printStackTrace(ex);
       }
   }
 
Example 28
Source Project: netbeans   Source File: JavaEEMavenTestBase.java    License: Apache License 2.0 5 votes vote down vote up
protected Project createMavenEarProject(FileObject projectDir) {
    try {
        FileObject src = FileUtil.createFolder(projectDir, "src"); //NOI18N
        FileObject main = FileUtil.createFolder(src, "main"); //NOI18N
        FileObject application = FileUtil.createFolder(main, "application"); //NOI18N
        
        PomBuilder pomBuilder = new PomBuilder();
        pomBuilder.appendPomContent(NbMavenProject.TYPE_EAR);

        return createProject(projectDir, pomBuilder.buildPom());
    } catch (IOException ex) {
        return null;
    }
}
 
Example 29
Source Project: netbeans   Source File: Issue226152Test.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, ClassPath> createClassPathsForTest() {
    List<FileObject> cpRoots = new LinkedList<FileObject>(ClasspathProviderImplAccessor.getJsStubs());
    
    cpRoots.add(FileUtil.toFileObject(new File(getDataDir(), "/testfiles/navigation/226152")));
    return Collections.singletonMap(
        JS_SOURCE_ID,
        ClassPathSupport.createClassPath(cpRoots.toArray(new FileObject[cpRoots.size()]))
    );
}
 
Example 30
Source Project: netbeans   Source File: RefTestBase.java    License: Apache License 2.0 5 votes vote down vote up
private void prepareTest() throws Exception {
    FileObject workdir = SourceUtilsTestUtil.makeScratchDir(this);
    
    FileObject projectFolder = FileUtil.createFolder(workdir, "testProject");
    src = FileUtil.createFolder(projectFolder, "src");
    test = FileUtil.createFolder(projectFolder, "test");

    FileObject cache = FileUtil.createFolder(workdir, "cache");

    CacheFolder.setCacheFolder(cache);
}