List of usage examples for org.eclipse.jdt.core IJavaProject getPackageFragmentRoot
IPackageFragmentRoot getPackageFragmentRoot(IResource resource);
From source file:org.eclipse.pde.internal.ui.search.dependencies.AddNewDependenciesOperation.java
License:Open Source License
private void addPackagesFromResource(IJavaProject jProject, IResource res, Set<String> ignorePkgs) { if (res == null) return;/* ww w . j a va 2s . c o m*/ try { IPackageFragmentRoot root = jProject.getPackageFragmentRoot(res); IJavaElement[] children = root.getChildren(); for (int i = 0; i < children.length; i++) { String pkgName = children[i].getElementName(); if (children[i] instanceof IParent) if (pkgName.length() > 0 && ((IParent) children[i]).hasChildren()) ignorePkgs.add(children[i].getElementName()); } } catch (JavaModelException e) { } }
From source file:org.eclipse.pde.internal.ui.wizards.plugin.NewLibraryPluginCreationOperation.java
License:Open Source License
private Set<String> findPackages(IProject proj, Map<?, List<?>> libs, IBuild build) { TreeSet<String> result = new TreeSet<String>(); IJavaProject jp = JavaCore.create(proj); Iterator<?> it = libs.entrySet().iterator(); while (it.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) it.next(); String libName = entry.getKey().toString(); List<?> filter = (List<?>) entry.getValue(); IBuildEntry libEntry = build.getEntry(SOURCE_PREFIX + libName); if (libEntry != null) { String[] tokens = libEntry.getTokens(); for (int i = 0; i < tokens.length; i++) { IResource folder = null; if (tokens[i].equals(".")) //$NON-NLS-1$ folder = proj;/*from w w w. j ava 2s.com*/ else folder = proj.getFolder(tokens[i]); if (folder != null) addPackagesFromFragRoot(jp.getPackageFragmentRoot(folder), result, filter); } } else { IResource res = proj.findMember(libName); if (res != null) addPackagesFromFragRoot(jp.getPackageFragmentRoot(res), result, filter); } } return result; }
From source file:org.eclipse.pde.internal.ui.wizards.plugin.NewProjectCreationOperation.java
License:Open Source License
private void addAllSourcePackages(IProject project, Set<String> list) { try {//from w ww . ja v a 2 s . c o m IJavaProject javaProject = JavaCore.create(project); IClasspathEntry[] classpath = javaProject.getRawClasspath(); for (int i = 0; i < classpath.length; i++) { IClasspathEntry entry = classpath[i]; if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { IPath path = entry.getPath().removeFirstSegments(1); if (path.segmentCount() > 0) { IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(project.getFolder(path)); IJavaElement[] children = root.getChildren(); for (int j = 0; j < children.length; j++) { IPackageFragment frag = (IPackageFragment) children[j]; if (frag.getChildren().length > 0 || frag.getNonJavaResources().length > 0) list.add(children[j].getElementName()); } } } } } catch (JavaModelException e) { } }
From source file:org.eclipse.recommenders.tests.models.EclipseDependencyListenerTest.java
License:Open Source License
private IJavaProject createProject(final String projectName) throws Exception { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IProject project = workspaceRoot.getProject(projectName); project.create(null);//from w ww . j av a2s.c o m project.open(null); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, null); IJavaProject javaProject = JavaCore.create(project); List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>(); entries.add(JavaRuntime.getDefaultJREContainerEntry()); javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null); IFolder sourceFolder = project.getFolder("src"); sourceFolder.create(false, true, null); IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder); IClasspathEntry[] oldEntries = javaProject.getRawClasspath(); IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1]; System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length); newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath()); javaProject.setRawClasspath(newEntries, null); javaProject.open(null); return javaProject; }
From source file:org.eclipse.stardust.modeling.validation.util.TypeRequestor.java
License:Open Source License
private IType getJarIType(IJavaModel model, char[] packageName, String qualifiedName, String path, int index) throws JavaModelException { String jar = path.substring(0, index); String rest = path.substring(index + 1); index = rest.lastIndexOf(SEPARATOR); if (index != -1) { rest = rest.substring(index + 1); }/*from w w w . ja va2 s.co m*/ index = rest.lastIndexOf(EXTENSION_SEPARATOR); if (index != -1) { String file = rest.substring(0, index); String extension = rest.substring(index + 1); IPath[] enclosedPaths = scope.enclosingProjectsAndJars(); for (int i = 0; i < enclosedPaths.length; i++) { IPath curr = enclosedPaths[i]; if (curr.segmentCount() == 1) { IJavaProject project = model.getJavaProject(curr.segment(0)); IPackageFragmentRoot root = project.getPackageFragmentRoot(jar); if (root.exists()) { IPackageFragment fragment = root.getPackageFragment(String.valueOf(packageName)); if (fragment.exists()) { if ("class".equals(extension)) //$NON-NLS-1$ { IClassFile classFile = fragment.getClassFile(file + ".class"); //$NON-NLS-1$ if (classFile.exists()) { return classFile.getType(); } } else if ("java".equals(extension)) //$NON-NLS-1$ { ICompilationUnit unit = fragment.getCompilationUnit(file + ".java"); //$NON-NLS-1$ IType[] types = unit.getAllTypes(); for (int j = 0; j < types.length; j++) { if (qualifiedName.equals(types[j].getTypeQualifiedName('.'))) { return types[j]; } } } } break; } } } } return null; }
From source file:org.eclipse.titan.codegenerator.AstWalkerJava.java
License:Open Source License
public void run(IAction action) { /**//*from www .j a v a 2s . c o m*/ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (IProject p : projects) { if (p.getName().equals("org.eclipse.titan.codegenerator.output")) try { p.delete(true, true, null); } catch (Exception e) { e.printStackTrace(); } } IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject("org.eclipse.titan.codegenerator.output"); try { project.create(null); project.open(null); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, null); IJavaProject javaProject = JavaCore.create(project); IFolder binFolder = project.getFolder("bin"); binFolder.create(false, true, null); javaProject.setOutputLocation(binFolder.getFullPath(), null); List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>(); IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall(); LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall); for (LibraryLocation element : locations) { entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null)); } javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null); IFolder sourceFolder = project.getFolder("src"); sourceFolder.create(false, true, null); IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder); IClasspathEntry[] oldEntries = javaProject.getRawClasspath(); IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1]; System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length); newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath()); javaProject.setRawClasspath(newEntries, null); javaProject.getPackageFragmentRoot(sourceFolder) .createPackageFragment("org.eclipse.titan.codegenerator.javagen", false, null); javaProject.getPackageFragmentRoot(sourceFolder) .createPackageFragment("org.eclipse.titan.codegenerator.TTCN3JavaAPI", false, null); } catch (Exception e) { e.printStackTrace(); } String destpath = new String(""); String wspath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString().replaceAll("/", "\\\\"); destpath += wspath; destpath += "\\org.eclipse.titan.codegenerator.output\\src\\org\\eclipse\\titan\\codegenerator\\javagen\\"; props.setProperty("javafile.path", destpath); /**/ AstWalkerJava.files.clear(); AstWalkerJava.fileNames.clear(); AstWalkerJava.componentList.clear(); AstWalkerJava.testCaseList.clear(); AstWalkerJava.testCaseRunsOnList.clear(); AstWalkerJava.functionList.clear(); AstWalkerJava.functionRunsOnList.clear(); AstWalkerJava.initOutputFolder(); AstWalkerJava.getActiveProject(); /* * // init console logger IConsole myConsole = findConsole("myLogger"); * IWorkbenchPage page = window.getActivePage(); String id = * IConsoleConstants.ID_CONSOLE_VIEW; IConsoleView view; try { view = * (IConsoleView) page.showView(id); view.display(myConsole); } catch * (PartInitException e) { // TODO Auto-generated catch block * e.printStackTrace(); } */ // initialize common files myASTVisitor.currentFileName = "TTCN_functions"; myASTVisitor.visualizeNodeToJava(myASTVisitor.importListStrings); myASTVisitor.visualizeNodeToJava("class TTCN_functions{\r\n}\r\n"); Def_Template_Visit_Handler.isTemplate = false; final ProjectSourceParser sourceParser = GlobalParser.getProjectSourceParser(selectedProject); sourceParser.analyzeAll(); logToConsole("Version built on 2016.10.24"); logToConsole("Starting to generate files into: " + props.getProperty("javafile.path")); myASTVisitor visitor = new myASTVisitor(); for (Module module : sourceParser.getModules()) { // start AST processing walkChildren(visitor, module.getOutlineChildren()); } visitor.finish(); logToConsole("Files generated into: " + props.getProperty("javafile.path")); // write additional classes Additional_Class_Writer additional_class = new Additional_Class_Writer(); myASTVisitor.currentFileName = "HC"; myASTVisitor.visualizeNodeToJava(myASTVisitor.importListStrings); myASTVisitor.visualizeNodeToJava(additional_class.writeHCClass()); myASTVisitor.currentFileName = "HCType"; myASTVisitor.visualizeNodeToJava(myASTVisitor.importListStrings); myASTVisitor.visualizeNodeToJava(additional_class.writeHCTypeClass()); // clear lists logger.severe("analysis complete"); /**/ File fromdir = new File(wspath + "\\org.eclipse.titan.codegenerator\\src\\org\\eclipse\\titan\\codegenerator\\TTCN3JavaAPI\\"); String toapidir = wspath + "\\org.eclipse.titan.codegenerator.output\\src\\org\\eclipse\\titan\\codegenerator\\TTCN3JavaAPI\\"; File[] fromfiles = fromdir.listFiles(); for (File f : fromfiles) { try { Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(toapidir + f.getName()), StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { e.printStackTrace(); } } String tppath = wspath + "\\" + selectedProject.getFullPath().toString().split("/")[1] + "\\src\\"; File tp_cfg_dir = new File(tppath); String togendir = wspath + "\\org.eclipse.titan.codegenerator.output\\src\\org\\eclipse\\titan\\codegenerator\\javagen\\"; File[] from_testports_cfg = tp_cfg_dir.listFiles(); for (File f : from_testports_cfg) { if (f.getName().endsWith(".java")) { try { Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(togendir + f.getName()), StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { e.printStackTrace(); } } if (f.getName().endsWith(".cfg")) { try { Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(toapidir + "cfg.cfg"), StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { e.printStackTrace(); } } } try { ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (Exception e) { e.printStackTrace(); } /**/ }
From source file:org.eclipse.umlgen.gen.java.services.WorkspaceServices.java
License:Open Source License
/** * Creates a project from scratch in the workspace. * * @param eObject/*from www .j a v a 2 s . co m*/ * The model element */ public void createDefaultProject(EObject eObject) { if (!EMFPlugin.IS_ECLIPSE_RUNNING) { return; } IProgressMonitor monitor = new NullProgressMonitor(); IWorkspace workspace = ResourcesPlugin.getWorkspace(); try { IWorkspaceRoot workspaceRoot = workspace.getRoot(); String projectName = UML2JavaConfigurationHolder.getDefaultProjectName(eObject); IProject project = workspaceRoot.getProject(projectName); if (project.exists() && project.isAccessible()) { if (!project.isOpen()) { project.open(monitor); } } else { project.create(new NullProgressMonitor()); project.open(new NullProgressMonitor()); IContainer intputContainer = project; String sourceFolderName = UML2JavaConfigurationHolder.getSourceFolderPath(eObject); StringTokenizer stringTokenizer = new StringTokenizer(sourceFolderName, "/"); while (stringTokenizer.hasMoreTokens()) { String token = stringTokenizer.nextToken(); IFolder src = intputContainer.getFolder(new Path(token)); if (!src.exists()) { src.create(true, true, monitor); } intputContainer = src; } IContainer outputContainer = project; String outputFolderName = UML2JavaConfigurationHolder.getOutputFolderPath(eObject); stringTokenizer = new StringTokenizer(outputFolderName, "/"); while (stringTokenizer.hasMoreTokens()) { String token = stringTokenizer.nextToken(); IFolder out = outputContainer.getFolder(new Path(token)); if (!out.exists()) { out.create(true, true, monitor); } outputContainer = out; } IProjectDescription description = project.getDescription(); String[] natures = new String[] {}; if (IUML2JavaConstants.Default.DEFAULT_COMPONENT_ARTIFACTS_TYPE_OSGI .equals(UML2JavaConfigurationHolder.getComponentBasedArchitecture(eObject)) || IUML2JavaConstants.Default.DEFAULT_COMPONENT_ARTIFACTS_TYPE_ECLIPSE .equals(UML2JavaConfigurationHolder.getComponentBasedArchitecture(eObject))) { natures = new String[] { JavaCore.NATURE_ID, IUML2JavaConstants.PDE_PLUGIN_NATURE_ID }; } else { natures = new String[] { JavaCore.NATURE_ID, }; } description.setNatureIds(natures); project.setDescription(description, monitor); IJavaProject javaProject = JavaCore.create(project); List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>(); IExecutionEnvironmentsManager executionEnvironmentsManager = JavaRuntime .getExecutionEnvironmentsManager(); IExecutionEnvironment[] executionEnvironments = executionEnvironmentsManager .getExecutionEnvironments(); String defaultJREExecutionEnvironment = UML2JavaConfigurationHolder .getJREExecutionEnvironment(eObject); for (IExecutionEnvironment iExecutionEnvironment : executionEnvironments) { if (defaultJREExecutionEnvironment.equals(iExecutionEnvironment.getId())) { entries.add( JavaCore.newContainerEntry(JavaRuntime.newJREContainerPath(iExecutionEnvironment))); break; } } javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null); IClasspathEntry[] oldEntries = javaProject.getRawClasspath(); IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1]; System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length); javaProject.setOutputLocation(outputContainer.getFullPath(), monitor); IPackageFragmentRoot packageRoot = javaProject .getPackageFragmentRoot(intputContainer.getFullPath().toString()); newEntries[oldEntries.length] = JavaCore.newSourceEntry(packageRoot.getPath(), new Path[] {}, new Path[] {}, outputContainer.getFullPath()); javaProject.setRawClasspath(newEntries, null); IFile buildPropertiesFile = project.getFile("build.properties"); if (!buildPropertiesFile.exists()) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( "#################################################################################" + System.getProperty(LINE_SEPARATOR)); stringBuilder.append("## " + UML2JavaConfigurationHolder.getCopyrightAndLicense(eObject) + System.getProperty(LINE_SEPARATOR)); stringBuilder.append( "#################################################################################" + System.getProperty(LINE_SEPARATOR)); stringBuilder.append("source.. = " + UML2JavaConfigurationHolder.getSourceFolderPath(eObject) + System.getProperty(LINE_SEPARATOR)); stringBuilder.append("output.. = " + UML2JavaConfigurationHolder.getOutputFolderPath(eObject) + System.getProperty(LINE_SEPARATOR)); stringBuilder.append("" + System.getProperty(LINE_SEPARATOR)); buildPropertiesFile.create(new ByteArrayInputStream(stringBuilder.toString().getBytes()), true, monitor); } } } catch (CoreException coreException) { AcceleoEnginePlugin.log(coreException, true); } }
From source file:org.eclipse.wb.internal.core.utils.jdt.core.ProjectUtils.java
License:Open Source License
private static void createCompilationUnitWithType(IJavaProject javaProject, String typeName, String contents) throws Exception { ICompilationUnit unit;//from ww w .j a v a 2s. c om { String packageName = CodeUtils.getPackage(typeName); String unitName = CodeUtils.getShortClass(typeName) + ".java"; IContainer sourceContainer = CodeUtils.getSourceContainers(javaProject, false).get(0); IPackageFragmentRoot packageFragmentRoot = javaProject.getPackageFragmentRoot(sourceContainer); IPackageFragment packageFragment = packageFragmentRoot.createPackageFragment(packageName, true, null); unit = packageFragment.createCompilationUnit(unitName, contents, true, null); } saveCompilationUnitWithType(unit); }
From source file:org.eclipse.wb.internal.core.utils.jdt.ui.PackageRootSelectionDialogField.java
License:Open Source License
/** * Tries to build a package fragment root out of a string and sets the string into this package * fragment root./*from w ww.j a v a2s.c o m*/ */ private static IPackageFragmentRoot getRootFromString(String rootString) { if (rootString.length() == 0) { return null; } // prepare resource for given string IPath path = new Path(rootString); IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = workspaceRoot.findMember(path); if (resource == null) { return null; } // resource should be project or source folder int resourceType = resource.getType(); if (resourceType == IResource.PROJECT || resourceType == IResource.FOLDER) { // check project IProject project = resource.getProject(); if (!project.isOpen()) { return null; } // try to convert resource into package fragment root IJavaProject javaProject = JavaCore.create(project); IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(resource); if (root.exists()) { return root; } } return null; }
From source file:org.eclipse.wb.tests.designer.core.model.util.FactoryCreateActionTest.java
License:Open Source License
public void test_validate() throws Exception { ContainerInfo panel = parseContainer("public class Test extends JPanel {", " public Test() {", " add(new JButton());", " }", "}"); ComponentInfo button = panel.getChildrenComponents().get(0); // prepare Java elements IJavaProject javaProject = m_testProject.getJavaProject(); IProject project = m_testProject.getProject(); IPackageFragmentRoot validRoot = javaProject.getPackageFragmentRoot(project.getFolder("src")); IPackageFragment validPackage = validRoot.getPackageFragment("test"); String validClass = "MyFactory"; String validMethod = "createComponent"; // source folder {// www .j av a 2 s.c om // "null" as source folder { String message = callValidate(button, null, null, validClass, validMethod); assertTrue(message.contains("source folder")); assertTrue(message.contains("invalid")); } // not existing source folder { IPackageFragmentRoot invalidRoot = javaProject.getPackageFragmentRoot(project.getFolder("src2")); String message = callValidate(button, invalidRoot, null, validClass, validMethod); assertTrue(message.contains("source folder")); assertTrue(message.contains("invalid")); } } // package { // "null" as package { String message = callValidate(button, validRoot, null, validClass, validMethod); assertTrue(message.contains("package")); assertTrue(message.contains("invalid")); } // not existing package { IPackageFragment invalidPackage = validRoot.getPackageFragment("test2"); String message = callValidate(button, validRoot, invalidPackage, validClass, validMethod); assertTrue(message.contains("package")); assertTrue(message.contains("invalid")); } // default package { IPackageFragment defaultPackage = validRoot.getPackageFragment(""); String message = callValidate(button, validRoot, defaultPackage, validClass, validMethod); assertTrue(message.contains("package")); assertTrue(message.contains("default")); } } // class { // empty class name { String message = callValidate(button, validRoot, validPackage, "", validMethod); assertTrue(message.contains("class name")); assertTrue(message.contains("empty")); } // "." in class name { String message = callValidate(button, validRoot, validPackage, "bad.name", validMethod); assertTrue(message.contains("class name")); assertTrue(message.contains("dot")); } // bad in class name { String message = callValidate(button, validRoot, validPackage, "bad name", validMethod); assertTrue(message.contains("identifier")); } } // method { // empty method name { String message = callValidate(button, validRoot, validPackage, validClass, ""); assertTrue(message.contains("method name")); assertTrue(message.contains("empty")); } // bad method name { String message = callValidate(button, validRoot, validPackage, validClass, "bad method name"); assertTrue(message.contains("identifier")); } } // OK { String message = callValidate(button, validRoot, validPackage, validClass, validMethod); assertNull(message); } }