List of usage examples for org.eclipse.jdt.core IJavaProject getPackageFragmentRoot
IPackageFragmentRoot getPackageFragmentRoot(IResource resource);
From source file:fr.imag.adele.cadse.cadseg.operation.MigrateCodePagesAction.java
License:Apache License
@Override public void doFinish(UIPlatform uiPlatform, Object monitor) throws Exception { super.doFinish(uiPlatform, monitor); IProgressMonitor pmo = (IProgressMonitor) monitor; its_old = new HashMap<String, CItemType>(); its_new = new HashMap<String, CItemType>(); for (CItemType cit : oldCadse.getItemType()) { its_old.put(cit.getId(), cit);//from ww w . j ava2 s . c o m } for (CItemType cit : newCadse.getItemType()) { its_new.put(cit.getId(), cit); } IFolder oldsources = oldProject.getFolder("sources"); IJavaProject oldjp = JavaCore.create(oldProject); IPackageFragmentRoot joldsources = oldjp.getPackageFragmentRoot(oldsources); String oldCstClass = oldCadse.getCstClass(); IPackageFragment pn = joldsources.getPackageFragment(getPackage(oldCstClass)); String oldCstCn = getClassName(oldCstClass); ICompilationUnit cu = pn.getCompilationUnit(oldCstCn + ".java"); IType cstType = cu.getType(oldCstCn); for (CItemType cit : oldCadse.getItemType()) { CItemType newcit = its_new.get(cit.getId()); if (newcit == null) { continue; } String oldcst = cit.getCstName(); String newcst = cit.getCstName(); if (!oldcst.equals(newcst)) { IField cstField = cstType.getField(oldcst); if (cstField.exists()) { RenameSupport.create(cstField, newcst, RenameSupport.UPDATE_REFERENCES); cit.setCstName(newcst); } } HashMap<String, CLinkType> ltits_new = new HashMap<String, CLinkType>(); for (CLink clt : newcit.getOutgoingLink()) { if (!(clt instanceof CLinkType)) continue; ltits_new.put(((CLinkType) clt).getName(), (CLinkType) clt); } for (CLink clt : cit.getOutgoingLink()) { if (!(clt instanceof CLinkType)) continue; CLinkType newclt = ltits_new.get(((CLinkType) clt).getName()); if (newclt == null) continue; oldcst = ((CLinkType) clt).getCstName(); newcst = newclt.getCstName(); if (!oldcst.equals(newcst)) { IField cstField = cstType.getField(oldcst); if (cstField.exists()) { RenameSupport.create(cstField, newcst, RenameSupport.UPDATE_REFERENCES); ((CLinkType) clt).setCstName(newcst); } } } pmo.worked(1); } writeCadse(oldProject); // finish1(pmo); }
From source file:fr.imag.adele.cadse.cadseg.operation.MigrateCodePagesAction.java
License:Apache License
/** * Finish1./* w w w . j a v a2 s . c o m*/ * * @param pmo * the pmo * * @throws IOException * Signals that an I/O exception has occurred. * @throws JAXBException * the JAXB exception * @throws CoreException * the core exception */ private void finish1(IProgressMonitor pmo) throws IOException, JAXBException, CoreException { CadseCore.getCadseDomain().beginOperation("Import binary cadse"); List<IJavaElement> destinations = new ArrayList<IJavaElement>(); List<IJavaElement> elements = new ArrayList<IJavaElement>(); List<String> names = new ArrayList<String>(); try { pmo.beginTask("migrate code from " + oldCadse.getName() + " to " + newCadse.getName(), oldCadse.getItemType().size() * 2 + 1); its_old = new HashMap<String, CItemType>(); its_new = new HashMap<String, CItemType>(); IFolder oldsources = oldProject.getFolder("sources"); IFolder newsources = newProject.getFolder("sources"); IJavaProject oldjp = JavaCore.create(oldProject); IJavaProject newjp = JavaCore.create(newProject); IPackageFragmentRoot joldsources = oldjp.getPackageFragmentRoot(oldsources); IPackageFragmentRoot jnewsources = newjp.getPackageFragmentRoot(newsources); for (CItemType cit : oldCadse.getItemType()) { its_old.put(cit.getId(), cit); } for (CItemType cit : newCadse.getItemType()) { its_new.put(cit.getId(), cit); } pmo.worked(1); for (CItemType cit : oldCadse.getItemType()) { pmo.worked(1); String qclazz = cit.getManagerClass(); if (qclazz == null) continue; String oldpn = getPackage(qclazz); String oldcn = getClassName(qclazz); CItemType newcit = its_new.get(cit.getId()); if (newcit == null) { System.out.println("Cannot migrate " + qclazz); continue; } String newqclazz = newcit.getManagerClass(); if (newqclazz == null) { System.out.println("Cannot migrate " + qclazz); continue; } String newpn = getPackage(newqclazz); String newcn = getClassName(newqclazz); IFile fo = oldsources.getFile(new Path(oldpn.replace('.', '/')).append(oldcn + ".java")); IFile fn = newsources.getFile(new Path(newpn.replace('.', '/')).append(newcn + ".java")); if (!fo.exists() || !fn.exists()) { System.out.println("Cannot migrate " + qclazz); continue; } ICompilationUnit oldcu = JavaCore.createCompilationUnitFrom(fo); ICompilationUnit newcu = JavaCore.createCompilationUnitFrom(fn); if (oldcu == null || newcu == null || !oldcu.exists() || !newcu.exists()) { System.out.println("Cannot migrate " + qclazz); continue; } IJavaElement findelement = oldcu; IJavaElement newdestination = joldsources.createPackageFragment(oldpn, true, pmo); ; String newname = oldcn + ".java"; if (!oldpn.equals(newpn)) { // move System.out.println("move " + oldpn + " to " + newpn); newdestination = joldsources.createPackageFragment(newpn, true, pmo); } if (!oldcn.equals(newcn)) { System.out.println("rename " + oldcn + " to " + newcn); newname = newcn + ".java"; } elements.add(findelement); destinations.add(newdestination); names.add(newname); cit.setManagerClass(oldCadse.getName() + "/" + newpn + "." + newcn); System.out.println("change manager to " + cit.getManagerClass()); } IJavaModel jm = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); jm.rename((IJavaElement[]) elements.toArray(new IJavaElement[elements.size()]), (IJavaElement[]) destinations.toArray(new IJavaElement[destinations.size()]), (String[]) names.toArray(new String[names.size()]), false, pmo); writeCadse(oldProject); // // for (CItemType cit : cadse.getItemType()) { // Item sourceItemType = its.get(cit.getId()); // if (sourceItemType == null) continue; // for( CLinkType clt : cit.getOutgoingLink()) { // // } // pmo.worked(1); // } } catch (JavaModelException e) { System.out.println(e.getStatus()); e.printStackTrace(); } finally { CadseCore.getCadseDomain().endOperation(); } }
From source file:hydrograph.ui.project.structure.wizard.ProjectStructureCreator.java
License:Apache License
/** * Sets the <b>src</b> folder as the source folder in project * @param project//from w w w. j ava2 s . c o m * @param javaProject * @return IClasspathEntry[] * @throws JavaModelException */ private IClasspathEntry[] setSourceFolderInClassPath(IProject project, IJavaProject javaProject) throws JavaModelException { IFolder sourceFolder = project.getFolder(Constants.ProjectSupport_SRC); //$NON-NLS-1$ 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()); return newEntries; }
From source file:hydrograph.ui.propertywindow.widgets.utility.FilterOperationClassUtility.java
License:Apache License
/** * Open file editor to view java file./* w ww . j av a 2 s.com*/ * * @param fileName * the file name * @return true, if successful */ @SuppressWarnings("restriction") public boolean openFileEditor(Text filePath, String pathFile) { String fullQualifiedClassName = filePath.getText(); try { logger.debug("Searching " + fullQualifiedClassName + " in project's source folder"); PackageFragment packageFragment = null; String[] packages = StringUtils.split(fullQualifiedClassName, "."); String className = fullQualifiedClassName; String packageStructure = ""; IFile javaFile = null; if (packages.length > 1) { className = packages[packages.length - 1]; packageStructure = StringUtils.replace(fullQualifiedClassName, "." + className, ""); } IFileEditorInput editorInput = (IFileEditorInput) PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage().getActiveEditor().getEditorInput(); IProject project = editorInput.getFile().getProject(); IJavaProject iJavaProject = JavaCore.create(project); IPackageFragmentRoot packageFragmentRoot = iJavaProject .getPackageFragmentRoot(project.getFolder(Constants.ProjectSupport_SRC)); if (packageFragmentRoot != null) { for (IJavaElement iJavaElement : packageFragmentRoot.getChildren()) { if (iJavaElement instanceof PackageFragment && StringUtils.equals(iJavaElement.getElementName(), packageStructure)) { packageFragment = (PackageFragment) iJavaElement; break; } } } if (packageFragment != null) { for (IJavaElement element : packageFragment.getChildren()) { if (element instanceof CompilationUnit && StringUtils.equalsIgnoreCase(element.getElementName(), className + Constants.JAVA_EXTENSION)) { javaFile = (IFile) element.getCorrespondingResource(); break; } } } if (javaFile != null && javaFile.exists()) { IFileStore fileStore = EFS.getLocalFileSystem().getStore(javaFile.getLocationURI()); IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IDE.openEditorOnFileStore(page, fileStore); return true; } } catch (Exception e) { logger.error("Fail to open file"); return false; } return false; }
From source file:icy.icy4eclipse.core.NewIcyProjectWizard.java
License:Open Source License
@Override public boolean performFinish() { String pluginName = myPage.getPluginName(); String devName = Icy4EclipsePlugin.getIcyDeveloper(); String subpackageName = myPage.getSubpackageName(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(pluginName); String templateName = myPage.getTemplateName(); IcyTemplateLocator locator = Icy4EclipsePlugin.getDefault().getTemplateLocator(); locator.init();/*from w ww .j a v a 2 s.c o m*/ IcyProjectTemplate template = locator.getTemplate(templateName); if (template == null) { Icy4EclipsePlugin.logError("Unable to find a template (" + templateName + ")"); return false; } try { // Project creation project.create(null); if (!project.isOpen()) { project.open(null); } } catch (CoreException e) { Icy4EclipsePlugin.logException(e); return false; } try { // Natures Icy4EclipsePlugin.addNature(project, JavaCore.NATURE_ID); IJavaProject javaProject = JavaCore.create(project); Icy4EclipsePlugin.addIcyNature(javaProject); // Folder IFolder src = project.getFolder("src"); if (!src.exists()) { src.create(true, true, null); } // Classpath List<IClasspathEntry> classpath = new ArrayList<IClasspathEntry>(); classpath.add(JavaCore.newSourceEntry(src.getFullPath())); for (String e : ICY_JARS) { classpath.add(JavaCore.newVariableEntry(new Path(ICY4ECLIPSE_HOME_VARIABLE + "/" + e), null, null)); } List<IClasspathEntry> templateEntries = template.getSpecificClasspathEntries(); if (templateEntries != null) { classpath.addAll(templateEntries); } IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary(); for (IClasspathEntry cpe : jreEntries) { classpath.add(cpe); } javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), null); // Default plugin java file String packageName = Icy4EclipsePlugin.getFullPackageName(devName, subpackageName); IPackageFragmentRoot srcRoot = javaProject.getPackageFragmentRoot(src); IPackageFragment pack = srcRoot.createPackageFragment(packageName, false, null); String className = Icy4EclipsePlugin.fromPluginnameToClassname(pluginName); pack.createCompilationUnit(className + ".java", template.getPluginMainClassImplementation(pluginName, packageName, className), false, null); // Compile project.build(IncrementalProjectBuilder.FULL_BUILD, null); } catch (CoreException e) { Icy4EclipsePlugin.logException(e); try { project.delete(true, true, null); } catch (CoreException e1) { Icy4EclipsePlugin.logException(e1); } return false; } return true; }
From source file:it.unibz.instasearch.indexing.WorkspaceIndexerJDT.java
License:Open Source License
/** * @param doc// w ww . j a va2 s . c om * @return * @throws JavaModelException */ private IClassFile getClassFile(SearchResultDoc doc) throws Exception { IWorkspaceRoot workspaceRoot = InstaSearchPlugin.getWorkspaceRoot(); IJavaModel javaModel = JavaCore.create(workspaceRoot); String javaProjectName = doc.getProject().segment(0); IJavaProject proj = javaModel.getJavaProject(javaProjectName); if (proj == null) throw new Exception("Project " + javaProjectName + " not found"); if (!proj.isOpen()) proj.open(new NullProgressMonitor()); javaModel.refreshExternalArchives(new IJavaElement[] { proj }, new NullProgressMonitor()); IPath filePath = new Path(doc.getFilePath()); String fileName = filePath.lastSegment(); IPath jarPath = filePath.removeLastSegments(2); // remove pkg and filename IPackageFragmentRoot jar = null; IResource jarFile = workspaceRoot.findMember(jarPath); if (jarFile != null) jar = proj.getPackageFragmentRoot(jarFile); else jar = proj.getPackageFragmentRoot(jarPath.toString()); // external archive if (jar == null) throw new Exception("Jar " + jarPath + " not found in project " + doc.getProjectName()); IPath pkgPath = filePath.removeLastSegments(1); // remove filename String pkgName = pkgPath.lastSegment(); IPackageFragment pkg = jar.getPackageFragment(pkgName); if (pkg == null) throw new Exception("Package " + pkgName + " not found in " + doc.getProjectName()); IClassFile classFile = pkg.getClassFile(fileName); return classFile; }
From source file:kieker.develop.rl.ui.wizards.RecordLangNewWizardPage.java
License:Apache License
private IPackageFragmentRoot chooseSourceFolder() { final ISelectionStatusValidator validator = new ISelectionStatusValidator() { @Override// ww w .j a v a 2s. c o m public IStatus validate(final Object[] selection) { // NOCS if (selection.length == 1) { if (this.isSelectedValid(selection[0])) { return Status.OK_STATUS; } else { return Status.CANCEL_STATUS; } } else { return Status.CANCEL_STATUS; } } private boolean isSelectedValid(final Object element) { try { if (element instanceof IJavaProject) { final IJavaProject jproject = (IJavaProject) element; final IPath path = jproject.getProject().getFullPath(); return jproject.findPackageFragmentRoot(path) != null; } else if (element instanceof IPackageFragmentRoot) { return ((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE; } return true; } catch (final JavaModelException e) { return false; } } }; final ViewerFilter filter = new ViewerFilter() { private final Class<?>[] acceptedClasses = new Class<?>[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class }; @Override public boolean select(final Viewer viewer, final Object parent, final Object element) { if (element instanceof IPackageFragmentRoot) { try { return ((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE; } catch (final JavaModelException e) { return false; } } for (final Class<?> acceptedClasse : this.acceptedClasses) { if (acceptedClasse.isInstance(element)) { return true; } } return false; } }; final StandardJavaElementContentProvider provider = new StandardJavaElementContentProvider(); final ILabelProvider labelProvider = new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); final ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(this.getShell(), labelProvider, provider); dialog.setValidator(validator); dialog.setComparator(new JavaElementComparator()); dialog.setTitle("Select source folder"); dialog.setMessage("Select a source folder"); dialog.addFilter(filter); dialog.setInput(JavaCore.create(ResourcesPlugin.getWorkspace().getRoot())); dialog.setInitialSelection(this.sourceFolder); dialog.setHelpAvailable(false); if (dialog.open() == Window.OK) { final Object element = dialog.getFirstResult(); if (element instanceof IJavaProject) { final IJavaProject jproject = (IJavaProject) element; return jproject.getPackageFragmentRoot(jproject.getProject()); } else if (element instanceof IPackageFragmentRoot) { return (IPackageFragmentRoot) element; } return null; } return null; }
From source file:metabup.annotations.wizards.NewAnnotationWizard.java
License:Open Source License
/** * The worker method. It will find the container, create the * file if missing or just replace its contents, and open * the editor on the newly created file. *//* w w w . ja v a2s .c o m*/ private void doFinish(String projectName, String fileName, String annotationName, String description, IProgressMonitor monitor) throws CoreException { // create a sample file monitor.beginTask("Creating " + fileName, 2); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(projectName)); if (!resource.exists() || !(resource instanceof IProject)) throwCoreException("Project \"" + projectName + "\" does not exist."); monitor.worked(1); IProject project = (IProject) resource; /* * Turn project into a Java project, if not yet */ IProjectDescription projectDescription = project.getDescription(); String javaNature[] = { JavaCore.NATURE_ID }; String projectNatures[] = projectDescription.getNatureIds(); boolean isJavaEnabled = false; for (int i = 0; i < projectNatures.length; i++) { if (projectNatures[i].equals(javaNature[0])) { isJavaEnabled = true; i = projectNatures.length; } } IJavaProject javaProject = JavaCore.create(project); if (!isJavaEnabled) { IProjectDescription pDescription = project.getDescription(); pDescription.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(pDescription, monitor); IFolder binFolder = project.getFolder("bin"); if (!binFolder.exists()) binFolder.create(false, true, monitor); javaProject.setOutputLocation(binFolder.getFullPath(), monitor); } monitor.worked(1); //Import Activator library Bundle plugin = Activator.getDefault().getBundle(); IPath relativePagePath = new Path(AnnotationsPluginPreferenceConstants.P_ANNOTATIONS_LIB_FILES); URL fileInPlugin = FileLocator.find(plugin, relativePagePath, null); if (fileInPlugin != null) { // the file exists URL fileUrl; try { fileUrl = FileLocator.toFileURL(fileInPlugin); File file = new File(fileUrl.getPath()); IClasspathEntry libEntry[] = { JavaCore.newLibraryEntry(new Path(file.getAbsolutePath()), null, // no source null, // no source false) }; // not exported monitor.worked(1); //set the build path IClasspathEntry[] buildPath = { JavaCore.newSourceEntry(project.getFullPath().append("src")), JavaRuntime.getDefaultJREContainerEntry(), libEntry[0] }; javaProject.setRawClasspath(buildPath, project.getFullPath().append("bin"), null); IFolder srcFolder = project.getFolder("src"); if (!srcFolder.exists()) srcFolder.create(true, true, monitor); project.refreshLocal(IResource.DEPTH_INFINITE, monitor); monitor.worked(1); //Add folder to Java element IPackageFragmentRoot folder = javaProject.getPackageFragmentRoot(srcFolder); //create package fragment IPackageFragment fragment = folder.createPackageFragment( AnnotationsPluginPreferenceConstants.P_ANNOTATIONS_PACKAGE, true, monitor); StringBuffer buffer = new StringBuffer(); ICompilationUnit cu = fragment.createCompilationUnit(fileName, AnnotationHandler.generateInstanceCode(buffer, annotationName, description).toString(), false, monitor); project.refreshLocal(IResource.DEPTH_INFINITE, monitor); monitor.worked(1); project.refreshLocal(IResource.DEPTH_INFINITE, monitor); } catch (IOException e) { // TODO Auto-generated catch block Activator.log(IStatus.ERROR, "Activator library couldn't be added to the java build path."); } } else { Activator.log(IStatus.ERROR, "Activator library couldn't be added to the java build path."); } /*final IFile file = container.getFile(new Path(fileName)); try { InputStream stream = openContentStream(); if (file.exists()) { file.setContents(stream, true, true, monitor); } else { file.create(stream, true, monitor); } stream.close(); } catch (IOException e) { }*/ /*monitor.setTaskName("Opening file for editing..."); getShell().getDisplay().asyncExec(new Runnable() { public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { IDE.openEditor(page, file, true); } catch (PartInitException e) { } } });*/ monitor.worked(1); }
From source file:net.roamstudio.roamflow.wizard.NewProjectWizard.java
License:Open Source License
private void addSourceFolder(IJavaProject javaProject, List<IClasspathEntry> entries, String path) throws CoreException { IFolder folder = javaProject.getProject().getFolder(path); createFolder(folder);/*from w ww .j av a 2 s. co m*/ IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder); entries.add(JavaCore.newSourceEntry(root.getPath())); }
From source file:net.sf.refactorit.eclipse.vfs.EclipseSourcePath.java
License:Open Source License
public List getNonJavaSources(WildcardPattern[] patterns) { // FIXME: overlook and user Source instead maybe? IJavaProject javaProject = getJavaProject(); List result = new ArrayList(); try {/*from w ww . j av a2 s .co m*/ Source[] rootSources = getRootSources(); for (int i = 0; i < rootSources.length; i++) { IResource resource = ((EclipseSource) rootSources[i]).getResource(); IPackageFragmentRoot packageRoot = javaProject.getPackageFragmentRoot(resource); if (!packageRoot.exists()) { continue; } collectNonJavaResources(result, packageRoot.getNonJavaResources(), patterns); // must collect recursively collectNonJavaResources(result, packageRoot.getChildren(), patterns); } return result; } catch (JavaModelException e) { AppRegistry.getExceptionLogger().error(e, this); throw new SystemException(ErrorCodes.ECLIPSE_INTERNAL_ERROR, e); } }