下面列出了org.eclipse.lsp4j.services.LanguageClient#org.openide.filesystems.FileUtil 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
/**
* 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();
}
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;
}
/** 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;
}
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]);
}
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;
}
@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
}
/**
* 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();
}
/**
* 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();
}
}
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;
}
}
/**
* @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);
}
@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;
}
@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);
}
}
});
}
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);
}
}
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;
}
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));
}
}
}
}
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
}
/**
* 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;
}
/**
* 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;
}
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;
}
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());
}
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;
}
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();
}
@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();
}
@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;
}
@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/"))
})
);
}
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);
}
}
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;
}
}
@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()]))
);
}
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);
}