Java Code Examples for org.openide.filesystems.FileUtil

The following are top voted examples for showing how to use org.openide.filesystems.FileUtil. 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: ExternalTouchTest.java   Source Code and License 6 votes vote down vote up
public void testFindResourceDoesNotRefresh() throws Exception {
    FileObject fileObject1 = testFolder.createData("fileObject1");
    FileObject[] arr = testFolder.getChildren();
    assertEquals("One child", 1, arr.length);
    assertEquals("Right child", fileObject1, arr[0]);
    
    File testFile = FileUtil.toFile(testFolder);
    assertNotNull("Folder File found", testFile);
    final String path = testFolder.getPath() + "/file1.txt";
    final FileSystem fs = testFolder.getFileSystem();
    
    File newCh = new File(testFile, "file1.txt");
    newCh.createNewFile();
    
    FileObject fromResource = fs.findResource(path);
    FileObject fromToFO = FileUtil.toFileObject(newCh);
    FileObject fromSndResource = fs.findResource(path);
    
    assertNotNull("toFileObject does refresh", fromToFO);
    assertNull("fromResource does not refresh", fromResource);
    assertEquals("after refresh the result reflects reality", fromToFO, fromSndResource);
}
 
Example 2
Project: incubator-netbeans   File: TargetChooserPanelGUI.java   Source Code and License 6 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    if ( browseButton == e.getSource() ) {
        FileObject fo=null;
        // Show the browse dialog 
        if (getPanel().getSourceGroups()!=null) fo = BrowseFolders.showDialog(
                getPanel().getSourceGroups(),
                org.openide.loaders.DataFolder.class,
                folderTextField.getText().replace( File.separatorChar, '/' ) );
        else {                 
            Sources sources = ProjectUtils.getSources(getPanel().getProject());
            fo = BrowseFolders.showDialog( sources.getSourceGroups( 
                    Sources.TYPE_GENERIC ),DataFolder.class,
                    folderTextField.getText().replace( File.separatorChar, '/' ) );
        }
        
        if ( fo != null && fo.isFolder() ) {
            FileObject root = ((LocationItem)locationCB.getSelectedItem()).
                getFileObject();
            folderTextField.setText( FileUtil.getRelativePath( root, fo ) );
        }
                    
    }
}
 
Example 3
Project: incubator-netbeans   File: CodeTemplatesLocatorTest.java   Source Code and License 6 votes vote down vote up
public void testFullCodeTemplatesLegacyLayout() throws Exception {
    String [] files = new String [] {
        "Editors/Defaults/abbreviations.xml",
        "Editors/abbreviations.xml",
    };
    
    LocatorTest.createOrderedFiles(files, CT_CONTENTS);
    
    FileObject baseFolder = FileUtil.getConfigFile("Editors");
    Map<String, List<Object []>> results = new HashMap<String, List<Object []>>();
    LocatorTest.scan(CodeTemplatesStorage.ID, baseFolder, null, null, true, true, true, results);
    
    assertNotNull("Scan results should not null", results);
    assertEquals("Wrong number of profiles", 1, results.size());
    
    List<Object []> profileFiles = results.get(null);
    LocatorTest.checkProfileFiles(files, null, profileFiles, null);
}
 
Example 4
Project: incubator-netbeans   File: ProcessorTest.java   Source Code and License 6 votes vote down vote up
public void testFailTwice() throws Exception {
    FileObject template = FileUtil.createData(root, "some.txt");
    OutputStream os = template.getOutputStream();
    String txt = "<html><h1>${unknown}</h1></html>";
    os.write(txt.getBytes());
    os.close();

    StringWriter w1 = new StringWriter();
    TestFailTemplateExceptionHandler tfeh1 = new TestFailTemplateExceptionHandler();
    apply(template, w1, tfeh1);

    StringWriter w2 = new StringWriter();
    TestFailTemplateExceptionHandler tfeh2 = new TestFailTemplateExceptionHandler();
    apply(template, w2, tfeh2);

    String expText = "Expression unknown is undefined on line 1, column 13 in some.txt.";
    String exp = "<html><h1>"+expText+"</h1></html>";
    assertEquals(exp, w1.toString());
    assertEquals(exp, w2.toString());

    assertNotNull("An expected exception was reported:", tfeh1.getExceptions());
    assertEquals("Just two exception reported:", 2, tfeh1.getExceptions().size());
    assertEquals("The expected exception was reported:", expText, tfeh1.getExceptions().get(0).getMessage());
    assertEquals("The expected exception was reported:", expText, tfeh1.getExceptions().get(1).getMessage());
}
 
Example 5
Project: incubator-netbeans   File: SpecialSearchGroupTest.java   Source Code and License 6 votes vote down vote up
public void testFindCommonPathObject() throws IOException {
        
        FileObject root = FileUtil.createMemoryFileSystem().getRoot();
        
        FileObject a = root.createFolder("a");
        FileObject b = a.createFolder("b");
        FileObject c = b.createData("c");
        
        FileObject b1 = a.createFolder("b1");
        FileObject b1c = b1.createData("b1c");
        
//        SpecialSearchGroup.CommonSearchRoot csr = new SpecialSearchGroup.CommonSearchRoot(1);
//
//        csr.update(c);
//        csr.update(b1c);
//
//        assertEquals(a, csr.getFileObject());
    }
 
Example 6
Project: incubator-netbeans   File: ModuleOperationsTest.java   Source Code and License 6 votes vote down vote up
public void testOperationActions() throws Exception { // #72397
    final NbModuleProject project = generateStandaloneModule("module");
    cgpi.setProject(project);
    DialogDisplayerImpl dd = (DialogDisplayerImpl) Lookup.getDefault().lookup(DialogDisplayer.class);
    FileObject lock = FileUtil.createData(project.getProjectDirectory(), "build/testuserdir/lock");
    RandomAccessFile raf = new RandomAccessFile(FileUtil.toFile(lock), "rw");
    FileLock lck = raf.getChannel().lock();
    EventQueue.invokeAndWait(new Runnable() {
        @Override public void run() {
            ((ContextAwareAction) CommonProjectActions.deleteProjectAction()).createContextAwareInstance(Lookups.singleton(project)).actionPerformed(null);
        }
    });
    assertNotNull("warning message emitted", dd.getLastNotifyDescriptor());
    assertEquals("warning message emitted", dd.getLastNotifyDescriptor().getMessage(),
            Bundle.ERR_ModuleIsBeingRun());
    dd.reset();
    lck.release();
    raf.close();
    lock.delete();
    EventQueue.invokeAndWait(new Runnable() {
        @Override public void run() {
            CommonProjectActions.deleteProjectAction().actionPerformed(null);
        }
    });
    assertNull("no warning message", dd.getLastNotifyDescriptor());
}
 
Example 7
Project: incubator-netbeans   File: SnapshotSizeTest.java   Source Code and License 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    MockMimeLookup.setLookup(MimePath.get(MIME),
        Lookups.fixed(
            new FooEmbeddingProviderFactory(),
            new FooParserFactory()));
    FileUtil.setMIMEType(EXT, MIME);
    file1 = FileUtil.toFileObject(TestFileUtils.writeFile(
        new File(getWorkDir(),"test1.foo"),  //NOI18N
        FILE_CONTENT));
    file2 = FileUtil.toFileObject(TestFileUtils.writeFile(
        new File(getWorkDir(),"test2.foo"),  //NOI18N
        FILE_CONTENT+FILE_CONTENT));
    setBigFileSize(FILE_CONTENT.length());
}
 
Example 8
Project: incubator-netbeans   File: MIMEResolverImpl.java   Source Code and License 6 votes vote down vote up
/** Lists registered MIMEResolver instances in reverse order,
 * i.e. first are ones with lower priority (position attribute higher)
 * and last are ones with highest prority (position attribute lower).
 * @return list of all registered MIMEResolver instances in reverse order
 */
public static Collection<? extends FileObject> getOrderedResolvers() {
    // scan resolvers and order them to be able to assign extension to mime type from resolver with the lowest position
    FileObject[] resolvers = FileUtil.getConfigFile(MIME_RESOLVERS_PATH).getChildren();
    TreeMap<Integer, FileObject> orderedResolvers = new TreeMap<Integer, FileObject>(Collections.reverseOrder());
    for (FileObject mimeResolverFO : resolvers) {
        Integer position = (Integer) mimeResolverFO.getAttribute("position");  //NOI18N
        if (position == null) {
            position = Integer.MAX_VALUE;
        }
        while (orderedResolvers.containsKey(position)) {
            position--;
        }
        orderedResolvers.put(position, mimeResolverFO);
    }
    return orderedResolvers.values();
}
 
Example 9
Project: Pogamut3   File: ExampleBotProjectPanelVisual.java   Source Code and License 6 votes vote down vote up
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
    String command = evt.getActionCommand();
    if ("BROWSE".equals(command)) {
        JFileChooser chooser = new JFileChooser();
        FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
        chooser.setDialogTitle("Select Project Location");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        String path = this.projectLocationTextField.getText();
        if (path.length() > 0) {
            File f = new File(path);
            if (f.exists()) {
                chooser.setSelectedFile(f);
            }
        }
        if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
            File projectDir = chooser.getSelectedFile();
            projectLocationTextField.setText(FileUtil.normalizeFile(projectDir).getAbsolutePath());
        }
        panel.fireChangeEvent();
    }

}
 
Example 10
Project: incubator-netbeans   File: LookupSensitiveActionUILogTest.java   Source Code and License 6 votes vote down vote up
protected void setUp() throws Exception {
    super.setUp();
    clearWorkDir();
    dir = FileUtil.toFileObject(getWorkDir());
    f1 = dir.createData("f1.java");
    f2 = dir.createData("f2.java");
    f3 = dir.createData("f3.properties");
    f4 = dir.createData("f4.xml");          
    d1 = DataObject.find(f1);
    d2 = DataObject.find(f2);
    d3 = DataObject.find(f3);
    d4 = DataObject.find(f4);
    
    my = new MyHandler();
    Logger.getLogger("org.netbeans.ui.actions").addHandler(my);
    Logger.getLogger("org.netbeans.ui.actions").setLevel(Level.FINE);
}
 
Example 11
Project: incubator-netbeans   File: DependenciesNode.java   Source Code and License 6 votes vote down vote up
private HashSet<DependencyWrapper> create(Set<Artifact> arts, boolean longLiving, Function<Artifact, Boolean> accept) {
    HashSet<DependencyWrapper> lst = new HashSet<>();
    for (Artifact a : arts) {
        if (accept.apply(a)) {
            URL url = FileUtil.urlForArchiveOrDir(a.getFile());
            String name = url != null ? SourceUtils.getModuleName(url) : null;
            if(name != null) {
                LOG.log(Level.FINE, "Artifact {0} has module name ''{1}''", new Object[]{url, name}); // NOI18N
                lst.add(new DependencyWrapper(a, longLiving, () -> moduleInfoSupport != null ? moduleInfoSupport.canAddToModuleInfo(name) : false));
            } else {
                LOG.log(Level.WARNING, "Could not determine module name for artifact {0}", new Object[]{url}); // NOI18N
            }
        }
    }
    return lst;
}
 
Example 12
Project: incubator-netbeans   File: LocatorTest.java   Source Code and License 6 votes vote down vote up
public void testFullFontsColorsLegacyLayout() throws Exception {
    String [] files = new String [] {
        "Editors/NetBeans/Defaults/defaultColoring.xml",
        "Editors/NetBeans/Defaults/coloring.xml",
        "Editors/NetBeans/Defaults/editorColoring.xml",
        "Editors/NetBeans/coloring.xml",
        "Editors/NetBeans/editorColoring.xml",
    };
    
    createOrderedFiles(files, FC_CONTENTS);
    
    FileObject baseFolder = FileUtil.getConfigFile("Editors");
    Map<String, List<Object []>> results = new HashMap<>();
    scan(ColoringStorage.ID, baseFolder, null, null, true, true, true, results);
    
    assertNotNull("Scan results should not null", results);
    assertEquals("Wrong number of profiles", 1, results.size());
    
    List<Object []> profileFiles = results.get("NetBeans");
    checkProfileFiles(files, null, profileFiles, "NetBeans");
}
 
Example 13
Project: incubator-netbeans   File: TakeSnapshotProfilingPoint.java   Source Code and License 6 votes vote down vote up
private String takeHeapdumpHit(long time) {
        try {
            File heapdumpFile = constructHeapDumpFile(time);

            if (heapdumpFile.exists()) {
                File fixedHeapdumpFile = constructHeapDumpFile(Utils.getTimeInMillis(time));
                heapdumpFile.renameTo(fixedHeapdumpFile);
                FileObject folder = FileUtil.toFileObject(fixedHeapdumpFile.getParentFile());
                SnapshotsWindow.instance().refreshFolder(folder, true);
//                if (ProfilerControlPanel2.hasDefault())
//                    ProfilerControlPanel2.getDefault().refreshSnapshotsList();

                return fixedHeapdumpFile.toURI().toURL().toExternalForm();
            }
        } catch (IOException ex) {
            ErrorManager.getDefault().notify(ErrorManager.ERROR, ex);

            return Bundle.TakeSnapshotProfilingPoint_NoDataAvailableMsg();
        }

        return Bundle.TakeSnapshotProfilingPoint_NoDataAvailableMsg();
    }
 
Example 14
Project: incubator-netbeans   File: SQLEditorSupport.java   Source Code and License 6 votes vote down vote up
@Override
public void saveAs(FileObject folder, String fileName) throws IOException {
    String fn = FileUtil.getFileDisplayName(folder) + File.separator + fileName; 
    File existingFile = FileUtil.normalizeFile(new File(fn));
    if (existingFile.exists()) {
        NotifyDescriptor confirm = new NotifyDescriptor.Confirmation(
                NbBundle.getMessage(SQLEditorSupport.class,
                "MSG_ConfirmReplace", fileName),
                NbBundle.getMessage(SQLEditorSupport.class,
                "MSG_ConfirmReplaceFileTitle"),
                NotifyDescriptor.YES_NO_OPTION);
        DialogDisplayer.getDefault().notify(confirm);
        if (!confirm.getValue().equals(NotifyDescriptor.YES_OPTION)) {
            return;
        }
    }
    if (isConsole()) {
        // #166370 - if console, need to save document before copying
        saveDocument();
    }
    super.saveAs(folder, fileName);
}
 
Example 15
Project: incubator-netbeans   File: ValidateModulesTest.java   Source Code and License 6 votes vote down vote up
public void testAutomaticDependenciesUnused() throws Exception {
    List<URL> urls = new ArrayList<URL>();
    for (FileObject kid : FileUtil.getConfigFile("ModuleAutoDeps").getChildren()) {
        urls.add(kid.toURL());
    }
    StringBuilder problems = new StringBuilder();
    AutomaticDependencies ad = AutomaticDependencies.parse(urls.toArray(new URL[urls.size()]));
    for (Manifest m : loadManifests()) {
        String cnb = findCNB(m);
        AutomaticDependencies.Report r = ad.refineDependenciesAndReport(cnb,
                Dependency.create(Dependency.TYPE_MODULE, m.getMainAttributes().getValue("OpenIDE-Module-Module-Dependencies")));
        if (r.isModified()) {
            problems.append('\n').append(r);
        }
    }
    if (problems.length() > 0) {
        fail("Some modules need to upgrade their dependencies" + problems);
    }
}
 
Example 16
Project: incubator-netbeans   File: FileObjects.java   Source Code and License 6 votes vote down vote up
@CheckForNull
static Pair<String,List<URL>> parseModulePatches(@NonNull final Iterator<? extends String> tail) {
    if (tail.hasNext()) {
        //<module>=<file>(:<file>)*
        final Matcher m = MATCHER_PATCH.matcher(tail.next());
        if (m.matches() && m.groupCount() == 2) {
            final String module = m.group(1);
            final List<URL> patches = Arrays.stream(m.group(2).split(File.pathSeparator))
                    .map((p) -> FileUtil.normalizeFile(new File(p)))
                    .map(FileUtil::urlForArchiveOrDir)
                    .collect(Collectors.toList());
            return Pair.of(module, patches);
        }
    }
    return null;
}
 
Example 17
Project: incubator-netbeans   File: ImportAnalysisTest.java   Source Code and License 6 votes vote down vote up
public void testAddImportThroughMethod2() throws IOException {
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree node = (MethodTree) clazz.getMembers().get(0);
            int offset = (int) (workingCopy.getTrees().getSourcePositions().getStartPosition(workingCopy.getCompilationUnit(), node) + 1);
            TreePath context = workingCopy.getTreeUtilities().pathFor(offset);
            try {
                assertEquals("List", SourceUtils.resolveImport(workingCopy, context, "java.util.List"));
                assertEquals("java.awt.List", SourceUtils.resolveImport(workingCopy, context, "java.awt.List"));
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertFiles("testAddImportThroughMethod2.pass");
}
 
Example 18
Project: incubator-netbeans   File: TestNGOutputReader.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new instance of TestNGOutputReader
 */
TestNGOutputReader(final AntSession session,
        final AntSessionInfo sessionInfo,
        final Project project,
        final Properties props) {
    CommonUtils.getInstance().setTestingFramework(CommonUtils.TESTNG_TF);
    this.project = project;
    this.sessionType = sessionInfo.getSessionType();
    this.antScript = FileUtil.normalizeFile(session.getOriginatingScript());
    this.timeOfSessionStart = sessionInfo.getTimeOfTestTaskStart();
    if (project == null) {
        FileObject fileObj = FileUtil.toFileObject(antScript);
        this.project = FileOwnerQuery.getOwner(fileObj);
    }
    CoreManager testngManager = getManagerProvider();
    if(testngManager != null) {
        testngManager.registerNodeFactory();
    }
    this.testSession = new TestNGTestSession(sessionInfo.getSessionName(), this.project, sessionType);
    testSession.setRerunHandler(new TestNGExecutionManager(session, testSession, props));
    reports = new HashMap<String, Report>();
}
 
Example 19
Project: nb-clojure   File: ClojureTemplatePanelVisual.java   Source Code and License 6 votes vote down vote up
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
    String command = evt.getActionCommand();
    if ("BROWSE".equals(command)) {
        JFileChooser chooser = new JFileChooser();
        FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
        chooser.setDialogTitle("Select Project Location");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        String path = this.projectLocationTextField.getText();
        if (path.length() > 0) {
            File f = new File(path);
            if (f.exists()) {
                chooser.setSelectedFile(f);
            }
        }
        if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
            File projectDir = chooser.getSelectedFile();
            projectLocationTextField.setText(FileUtil.normalizeFile(projectDir).getAbsolutePath());
        }
        panel.fireChangeEvent();
    }

}
 
Example 20
Project: incubator-netbeans   File: NetigsoLayerTest.java   Source Code and License 5 votes vote down vote up
public void testOSGiCanProvideLayer() throws Exception {
    FileObject fo;
    Module m2;
    try {
        mgr.mutexPrivileged().enterWriteAccess();
        String mfBar = "Bundle-SymbolicName: org.bar\n" +
            "Bundle-Version: 1.1.0\n" +
            "Bundle-ManifestVersion: 2\n" +
            "Import-Package: org.foo\n" +
            "Export-Package: org.bar\n" +
            "OpenIDE-Module-Layer: org/bar/layer.xml\n" +
            "\n\n";

        File j2 = changeManifest(new File(jars, "depends-on-simple-module.jar"), mfBar);
        m2 = mgr.create(j2, null, false, false, false);
        mgr.enable(m2);
    } finally {
        mgr.mutexPrivileged().exitWriteAccess();
    }
    try {
        mgr.mutexPrivileged().enterWriteAccess();
        fo = FileUtil.getConfigFile("TestFolder");
        assertNotNull("Folder found", fo);

        URL u = mgr.getClassLoader().getResource("org/bar/layer.xml");
        assertNotNull("System ClassLoader can load resources", u);
    } finally {
        mgr.disable(m2);
        mgr.mutexPrivileged().exitWriteAccess();
    }
}
 
Example 21
Project: incubator-netbeans   File: DefaultProjectOperationsImplementation.java   Source Code and License 5 votes vote down vote up
private static FileObject createFolder(File parent, String name) throws IOException {
    FileObject path = FileUtil.toFileObject(parent);
    if (path != null) {
        return path.createFolder(name);
    } else {
        return createFolder(parent.getParentFile(), parent.getName()).createFolder(name);
    }
}
 
Example 22
Project: incubator-netbeans   File: ALT_ParallelPosition15Test.java   Source Code and License 5 votes vote down vote up
public ALT_ParallelPosition15Test(String name) {
    super(name);
    try {
 className = this.getClass().getName();
 className = className.substring(className.lastIndexOf('.') + 1, className.length());	    
        startingFormFile = FileUtil.toFileObject(new File(url.getFile() + goldenFilesPath + className + "-StartingForm.form").getCanonicalFile());
    } catch (IOException ioe) {
        fail(ioe.toString());
    }
}
 
Example 23
Project: incubator-netbeans   File: IgnoreListPanel.java   Source Code and License 5 votes vote down vote up
@Override
boolean isIgnored(FileObject obj) {
    File file = FileUtil.toFile(obj);
    if (file != null) {
        return p.matcher(file.getPath()).find();
    } else {
        return p.matcher(obj.getPath()).find();
    }
}
 
Example 24
Project: incubator-netbeans   File: NetigsoLayerDoesNotActivateTest.java   Source Code and License 5 votes vote down vote up
public void testOSGiCanProvideImpl() throws Exception {
    FileObject fo;
    Module m2;
    try {
        mgr.mutexPrivileged().enterWriteAccess();
        String mfBar = "Bundle-SymbolicName: org.kuk\n" +
            "Bundle-Version: 1.1.0\n" +
            "Bundle-ManifestVersion: 2\n" +
            "Import-Package: org.foo\n" +
            "OpenIDE-Module-Layer: org/bar/impl/layer.xml\n" +
            "\n\n";
        File j2 = changeManifest(new File(jars, "depends-on-simple-module.jar"), mfBar);
        m2 = mgr.create(j2, null, false, false, false);
        mgr.enable(m2);
    } finally {
        mgr.mutexPrivileged().exitWriteAccess();
    }
    try {
        mgr.mutexPrivileged().enterWriteAccess();
        fo = FileUtil.getConfigFile("TestImplFolder");
        assertNotNull("Layer found and its entries registered", fo);

        Bundle b = NetigsoServicesTest.findBundle(m2.getCodeNameBase());
        assertNotNull("Bundle for m2 found", b);
        assertEquals("It still remains in installed state only", Bundle.INSTALLED, b.getState());
    } finally {
        mgr.disable(m2);
        mgr.mutexPrivileged().exitWriteAccess();
    }
}
 
Example 25
Project: incubator-netbeans   File: DerbyDatabasesImpl.java   Source Code and License 5 votes vote down vote up
public  List<String> getDatabases() {
    String databaseHome = DerbyOptions.getDefault().getSystemHome();
    if (databaseHome == null || databaseHome.length() == 0) {
        Logger.getLogger(DerbyServerNode.class.getName()).fine("No JavaDB location set.");
        return Collections.emptyList();
    }
    File databaseHomeFile = new File(databaseHome);
    if (! databaseHomeFile.exists()) {
        Logger.getLogger(DerbyServerNode.class.getName()).log(Level.WARNING, "No JavaDB location found on " + databaseHomeFile);
        return Collections.emptyList();
    }
    FileObject databaseHomeFO = FileUtil.toFileObject(databaseHomeFile);
    try {
        databaseHomeFO.getFileSystem().refresh(false);
    } catch (FileStateInvalidException ex) {
        // This should be part of the real filesystem - it is doubtful, that
        // this case is ever reached - just log it
        LOG.log(Level.FINE, "Failed to refresh filesystem", ex);
    }
    Enumeration<? extends FileObject> children = databaseHomeFO.getChildren(false);
    List<String> res = new ArrayList<String>();
    while (children.hasMoreElements()) {
        FileObject candidate = children.nextElement();
        if (Util.isDerbyDatabase(candidate)) {
            Logger.getLogger(DerbyServerNode.class.getName()).fine(candidate.getName() + " added into Databases in " + databaseHome);
            res.add(candidate.getName());
        }
    }
    return res;
}
 
Example 26
Project: incubator-netbeans   File: ProfileSupport.java   Source Code and License 5 votes vote down vote up
@Override
@CheckForNull
protected URL map(@NonNull final FileObject fo) {
    final String relative = FileObjects.convertFolder2Package(
            FileObjects.stripExtension(FileObjects.getRelativePath(cacheRoot, FileUtil.toFile(fo))), File.separatorChar);
    final FileObject sourceFile = SourceUtils.getFile(
        ElementHandleAccessor.getInstance().create(ElementKind.CLASS, relative),
        resolveCps);
    return sourceFile == null ? null : sourceFile.toURL();
}
 
Example 27
Project: incubator-netbeans   File: ProjectActionTest.java   Source Code and License 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    System.setProperty("sync.project.execution", "true");
    MockServices.setServices(TestSupport.TestProjectFactory.class);
    clearWorkDir();
    FileObject workDir = FileUtil.toFileObject(getWorkDir());

    
    p1 = TestSupport.createTestProject( workDir, "project1" );
    f1_1 = p1.createData("f1_1.java");
    f1_2 = p1.createData("f1_2.krava");
    d1_1 = DataObject.find(f1_1);
    d1_2 = DataObject.find(f1_2);
           
    project1 = (TestSupport.TestProject)ProjectManager.getDefault().findProject( p1 );
    tap1 = new TestActionProvider();
    project1.setLookup(Lookups.singleton(tap1));
    
    p2 = TestSupport.createTestProject( workDir, "project2" );
    f2_1 = p2.createData("f2_1.java");
    f2_2 = p2.createData("f2_2.krava");
    d2_1 = DataObject.find(f2_1);
    d2_2 = DataObject.find(f2_2);
           
    project2 = (TestSupport.TestProject)ProjectManager.getDefault().findProject( p2 );                
}
 
Example 28
Project: incubator-netbeans   File: TaskProcessorTest.java   Source Code and License 5 votes vote down vote up
public void testWarningWhenRunUserTaskCalledFromAWT() throws Exception {
    this.clearWorkDir();
    final File _wd = this.getWorkDir();
    final FileObject wd = FileUtil.toFileObject(_wd);

    FileUtil.setMIMEType("foo", "text/foo");
    final FileObject foo = wd.createData("file.foo");
    final LogRecord[] warning = new LogRecord[1];
    final String msgTemplate = "ParserManager.parse called in AWT event thread by: {0}";  //NOI18N

    MockMimeLookup.setInstances(MimePath.parse("text/foo"), new FooParserFactory());
    Logger.getLogger(TaskProcessor.class.getName()).addHandler(new Handler() {
        public @Override void publish(LogRecord record) {
            if (record.getMessage().startsWith(msgTemplate)) {
                warning[0] = record;
            }
        }

        public @Override void flush() {
        }

        public @Override void close() throws SecurityException {
        }
    });

    final StackTraceUserTask stackTraceUserTask = new StackTraceUserTask();
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            try {
                ParserManager.parse(Collections.singleton(Source.create(foo)), stackTraceUserTask);
            } catch (ParseException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });

    assertNotNull("No warning when calling ParserManager.parse from AWT", warning[0]);
    assertEquals("Wrong message", msgTemplate, warning[0].getMessage());
    assertEquals("Suspiciosly wrong warning message (is the caller identified correctly?)", stackTraceUserTask.caller, warning[0].getParameters()[0]);
}
 
Example 29
Project: incubator-netbeans   File: J2SESampleProjectGenerator.java   Source Code and License 5 votes vote down vote up
private static void unzip(InputStream source, FileObject targetFolder) throws IOException {
    //installation
    ZipInputStream zip=new ZipInputStream(source);
    try {
        ZipEntry ent;
        while ((ent = zip.getNextEntry()) != null) {
            if (ent.isDirectory()) {
                FileUtil.createFolder(targetFolder, ent.getName());
            } else {
                FileObject destFile = FileUtil.createData(targetFolder,ent.getName());
                FileLock lock = destFile.lock();
                try {
                    OutputStream out = destFile.getOutputStream(lock);
                    try {
                        FileUtil.copy(zip, out);
                    } finally {
                        out.close();
                    }
                } finally {
                    lock.releaseLock();
                }
            }
        }
    } finally {
        zip.close();
    }
}
 
Example 30
Project: incubator-netbeans   File: HeapDumpAction.java   Source Code and License 5 votes vote down vote up
private String getCurrentHeapDumpFilename(String targetFolder) {
    try {
        String fileName = ResultsManager.getDefault().getDefaultHeapDumpFileName(System.currentTimeMillis());
        FileObject folder = (targetFolder == null)
                            ? ProfilerStorage.getProjectFolder(NetBeansProfiler.getDefaultNB().getProfiledProject(), true)
                            : FileUtil.toFileObject(FileUtil.normalizeFile(new File(targetFolder)));

        return FileUtil.toFile(folder).getAbsolutePath() + File.separator
               + FileUtil.findFreeFileName(folder, fileName, ResultsManager.HEAPDUMP_EXTENSION) + "."
               + ResultsManager.HEAPDUMP_EXTENSION; // NOI18N
    } catch (IOException e) {
        return null;
    }
}
 
Example 31
Project: incubator-netbeans   File: DeleteCreateTestAnnotationProvider.java   Source Code and License 5 votes vote down vote up
private Set<FileSystem> getRootFilesystems() {
    Set<FileSystem> filesystems = new HashSet<FileSystem>();
    File [] roots = File.listRoots();
    for (int i = 0; i < roots.length; i++) {
        File root = roots[i];
        FileObject fo = FileUtil.toFileObject(FileUtil.normalizeFile(root));
        if (fo == null) continue;
        try {
            filesystems.add(fo.getFileSystem());
        } catch (FileStateInvalidException e) {
            // ignore invalid filesystems
        }
    }
    return filesystems;
}
 
Example 32
Project: incubator-netbeans   File: NbRepositoryTest.java   Source Code and License 5 votes vote down vote up
public void testUserDirIsWriteableEvenInstallDirDoesNotExists() throws IOException {
    System.getProperties().remove("netbeans.home");
    System.setProperty("netbeans.user", getWorkDirPath());
    
    FileObject ahoj = FileUtil.createData(FileUtil.getConfigRoot(), "ahoj.jardo");
    
    OutputStream os = ahoj.getOutputStream();
    os.write("Ahoj".getBytes());
    os.close();
    
    File af = new File(new File(getWorkDir(), "config"), "ahoj.jardo");
    assertTrue("File created", af.exists());
    assertEquals("4 bytes", 4, af.length());
}
 
Example 33
Project: incubator-netbeans   File: ApisupportAntUtils.java   Source Code and License 5 votes vote down vote up
public static URL[] findURLs(final String path) {
    if (path == null) {
        return new URL[0];
    }
    String[] pieces = PropertyUtils.tokenizePath(path);
    URL[] urls = new URL[pieces.length];
    for (int i = 0; i < pieces.length; i++) {
        // XXX perhaps also support http: URLs somehow?
        urls[i] = FileUtil.urlForArchiveOrDir(FileUtil.normalizeFile(new File(pieces[i])));
    }
    return urls;
}
 
Example 34
Project: incubator-netbeans   File: JavaFXSampleProjectGenerator.java   Source Code and License 5 votes vote down vote up
private static File createPrivateProperties(FileObject fo) throws IOException {
    String[] nameElements = AntProjectHelper.PRIVATE_PROPERTIES_PATH.split("/"); // NOI18N
    for (int i = 0; i < nameElements.length - 1; i++) {
        FileObject tmp = fo.getFileObject(nameElements[i]);
        if (tmp == null) {
            tmp = fo.createFolder(nameElements[i]);
        }
        fo = tmp;
    }
    fo = fo.createData(nameElements[nameElements.length - 1]);
    return FileUtil.toFile(fo);
}
 
Example 35
Project: incubator-netbeans   File: AntProjectHelper.java   Source Code and License 5 votes vote down vote up
private void change(FileEvent fe) {
    synchronized (saveActions) {
        for (AtomicAction a : saveActions) {
            if (fe.firedFrom(a)) {
                return;
            }
        }
    }
    String path;
    File f = FileUtil.toFile(fe.getFile());
    synchronized (modifiedMetadataPaths) {
        if (f.equals(resolveFile(PROJECT_XML_PATH))) {
            if (modifiedMetadataPaths.contains(PROJECT_XML_PATH)) {
                //#68872: don't do anything if the given file has non-saved changes:
                return ;
            }
            path = PROJECT_XML_PATH;
            projectXmlValid = false;
        } else if (f.equals(resolveFile(PRIVATE_XML_PATH))) {
            if (modifiedMetadataPaths.contains(PRIVATE_XML_PATH)) {
                //#68872: don't do anything if the given file has non-saved changes:
                return ;
            }
            path = PRIVATE_XML_PATH;
            privateXmlValid = false;
        } else {
            LOG.log(Level.WARNING, "#184132: unexpected file change in {0}; possibly deleted project?", f);
            return;
        }
    }
    fireExternalChange(path);
}
 
Example 36
Project: incubator-netbeans   File: PatchContextChooser.java   Source Code and License 5 votes vote down vote up
private void locationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_locationButtonActionPerformed
    FileChooserBuilder builder = new FileChooserBuilder(PatchContextChooser.class);
    File file = builder.setApproveText(NbBundle.getMessage(PatchContextChooser.class, "LBL_Select")).showOpenDialog();
    if (file != null) {
        FileObject fob = FileUtil.toFileObject(file);
        locationField.setText(FileUtil.getFileDisplayName(fob));
    }
}
 
Example 37
Project: incubator-netbeans   File: FilesystemInterceptor.java   Source Code and License 5 votes vote down vote up
private void enableEvents (File repository, boolean enabled) {
    File gitFolder = FileUtil.normalizeFile(GitUtils.getGitFolderForRoot(repository));
    synchronized (disabledEvents) {
        if (enabled) {
            disabledEvents.remove(gitFolder);
        } else {
            disabledEvents.add(gitFolder);
        }
    }
}
 
Example 38
Project: incubator-netbeans   File: ExportSnapshotAction.java   Source Code and License 5 votes vote down vote up
private static void export(final FileObject sourceFO, final File targetFile) {
    final ProgressHandle progress = ProgressHandle.createHandle(
            Bundle.ExportSnapshotAction_ProgressMsg());
    progress.setInitialDelay(500);
    RequestProcessor.getDefault().post(new Runnable() {
        public void run() {
            progress.start();
            try {
                if (targetFile.exists() && !targetFile.delete()) {
                    ProfilerDialogs.displayError(
                            Bundle.ExportSnapshotAction_CannotReplaceMsg(targetFile.getName()));
                } else {
                    targetFile.toPath();
                    File targetParent = FileUtil.normalizeFile(targetFile.getParentFile());
                    FileObject targetFO = FileUtil.toFileObject(targetParent);
                    String targetName = targetFile.getName();
                    FileUtil.copyFile(sourceFO, targetFO, targetName, null);
                }
            } catch (Throwable t) {
                ProfilerLogger.log("Failed to export NPSS snapshot: " + t.getMessage()); // NOI18N
                String msg = t.getLocalizedMessage().replace("<", "&lt;").replace(">", "&gt;"); // NOI18N
                ProfilerDialogs.displayError("<html><b>" + Bundle.ExportSnapshotAction_ExportFailedMsg() + // NOI18N
                                                           "</b><br><br>" + msg + "</html>"); // NOI18N
            } finally {
                progress.finish();
            }
        }
    });
}
 
Example 39
Project: incubator-netbeans   File: ActionProviderSupport.java   Source Code and License 5 votes vote down vote up
void start() {
    try {
        final FileSystem fs = project.getProjectDirectory().getFileSystem();
        // XXX would be more efficient to only listen while TRACK_FILE_CHANGES is set,
        // but it needs adding and removing of listeners depending on PropertyEvaluator events,
        // the file event handling is cheap when TRACK_FILE_CHANGES is disabled.
        fs.addFileChangeListener(FileUtil.weakFileChangeListener(modificationListener, fs));
    } catch (FileStateInvalidException x) {
        Exceptions.printStackTrace(x);
    }
}
 
Example 40
Project: incubator-netbeans   File: JavaSource.java   Source Code and License 5 votes vote down vote up
/**
     * Creates a new instance of JavaSource
     * @param files to create JavaSource for
     * @param cpInfo classpath info
     */
    private JavaSource (final ClasspathInfo cpInfo,
                        final @NonNull Collection<? extends FileObject> files) throws IOException {
// TODO: Split
//        boolean multipleSources = files.size() > 1;
        final List<Source> sources = new ArrayList<Source>(files.size());
        final List<FileObject> fl = new ArrayList<FileObject>(files.size());
        for (Iterator<? extends FileObject> it = files.iterator(); it.hasNext();) {
            FileObject file = it.next();
            Logger.getLogger("TIMER").log(Level.FINE, "JavaSource",
                new Object[] {file, this});
            if (!file.isValid()) {
// TODO: Split
//                if (multipleSources) {
                    LOGGER.warning("Ignoring non existent file: " + FileUtil.getFileDisplayName(file));     //NOI18N
// TODO: Split
//                }
//                else {
//                    DataObject.find(file);  //throws IOE
//                }
            }
            else {
                fl.add (file);
                sources.add(Source.create(file));
            }
        }
        this.files = Collections.unmodifiableList(fl);
        this.sources = Collections.unmodifiableList(sources);
        this.classpathInfo = cpInfo;
    }