List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment
IPackageFragment getPackageFragment(String packageName);
From source file:org.springframework.ide.eclipse.internal.bestpractices.quickfix.CreateNewClassMarkerResolution.java
License:Open Source License
public void run(IMarker marker) { NewClassCreationWizard wizard = new NewClassCreationWizard(); wizard.init(JavaPlugin.getDefault().getWorkbench(), null); Shell shell = JavaPlugin.getActiveWorkbenchShell(); WizardDialog dialog = new WizardDialog(shell, wizard); dialog.create();/*from w w w . jav a2 s . com*/ dialog.getShell().setText("New"); IWizardPage[] pages = wizard.getPages(); NewTypeWizardPage page = (NewTypeWizardPage) pages[0]; String markerMessage = marker.getAttribute(MESSAGE_ATTRIBUTE_KEY, ""); IJavaProject javaProject = JdtUtils.getJavaProject(marker.getResource()); IPackageFragmentRoot sourcePackageFragmentRoot = null; String packageName = extractPackageNameFromMessage(markerMessage); try { sourcePackageFragmentRoot = inferPackageFragmentRoot(javaProject, packageName); if (sourcePackageFragmentRoot != null) { page.setPackageFragmentRoot(sourcePackageFragmentRoot, true); IPackageFragment packageFragment = sourcePackageFragmentRoot.getPackageFragment(packageName); if (packageFragment != null) { page.setPackageFragment(packageFragment, true); } } } catch (CoreException e) { StatusHandler.log(e.getStatus()); } page.setTypeName(extractClassNameFromMessage(markerMessage), true); if (dialog.open() == Window.OK) { IType createdType = (IType) wizard.getCreatedElement(); String fullyQualifiedClassName = createdType.getFullyQualifiedName(); updateXmlBeanClass(marker, fullyQualifiedClassName); } }
From source file:org.springframework.ide.eclipse.internal.uaa.monitor.LibraryUsageMonitor.java
License:Open Source License
@SuppressWarnings("deprecation") private ProductMatch readPackageFragmentRoot(IJavaProject source, IPackageFragmentRoot entry) throws JavaModelException { // Quick assertion that we only check JARs that exist if (!entry.exists() || !entry.isArchive()) { return null; }/*from w w w . ja v a 2s . c o m*/ // Check for previous matches or misses if (matches.containsKey(entry.getElementName())) { ProductMatch match = matches.get(entry.getElementName()); return match; } else if (noMatches.contains(entry.getElementName())) { return null; } String groupId = null; String artifactId = null; String version = null; ProductInfo productInfo = null; JarEntryDirectory metaInfDirectory = getJarEntryDirectory(entry); // Step 1: Check META-INF/maven if (metaInfDirectory != null) { for (IJarEntryResource jarEntryResource : metaInfDirectory.getChildren()) { if ("maven".equals(jarEntryResource.getName())) { Product product = readMaven(jarEntryResource, entry); if (product != null) { groupId = product.getGroupId(); artifactId = product.getArtifactId(); version = product.getVersion(); break; } } } } // Step 2: Check path if it follows the Maven convention of groupId/artifactId/version if (artifactId == null || groupId == null) { IPath jarPath = entry.getPath(); IPath m2RepoPath = JavaCore.getClasspathVariable(M2_REPO); if (m2RepoPath == null) { m2RepoPath = ResourcesPlugin.getWorkspace().getPathVariableManager().getValue(M2_REPO); } if (m2RepoPath != null && m2RepoPath.isPrefixOf(jarPath)) { jarPath = jarPath.removeFirstSegments(m2RepoPath.segmentCount()); int segments = jarPath.segmentCount(); for (int i = 0; i < segments - 1; i++) { if (i == 0) { groupId = jarPath.segment(i); } else if (i > 0 && i < segments - 3) { groupId += "." + jarPath.segment(i); } else if (i == segments - 3) { artifactId = jarPath.segment(i); } else if (i == segments - 2) { version = jarPath.segment(i); } } } } // Step 3: Check for typeName match if (artifactId == null || groupId == null) { for (ProductInfo info : getProducts()) { String typeName = info.getTypeName(); String packageName = ""; if (typeName != null) { int i = typeName.lastIndexOf('.'); if (i > 0) { packageName = typeName.substring(0, i); typeName = typeName.substring(i + 1); } IPackageFragment packageFragment = entry.getPackageFragment(packageName); if (packageFragment.exists()) { if (packageFragment.getClassFile(typeName + ClassUtils.CLASS_FILE_SUFFIX).exists()) { artifactId = info.getArtifactId(); groupId = info.getGroupId(); productInfo = info; break; } } } } } // Step 4: Obtain version from MANIFEST.MF if (groupId != null && artifactId != null && metaInfDirectory != null && version == null) { for (IJarEntryResource jarEntryResource : metaInfDirectory.getChildren()) { if (MANIFEST_FILE_NAME.equals(jarEntryResource.getName())) { version = readManifest(jarEntryResource, entry); } } } // Step 5: Obtain version from file name if (groupId != null && artifactId != null && version == null && entry.getPath() != null) { String fileName = entry.getPath().lastSegment(); // Use regular expression to match any version number Matcher matcher = VERSION_PATTERN.matcher(fileName); if (matcher.matches()) { StringBuilder builder = new StringBuilder(); for (int i = 1; i <= matcher.groupCount(); i++) { builder.append(matcher.group(i)); } version = builder.toString(); } } // Step 6: Construct the ProductMatch ProductMatch productMatch = null; if (productInfo == null) { for (ProductInfo info : getProducts()) { if (info.getArtifactId().equals(artifactId) && info.getGroupId().equals(groupId)) { productInfo = info; productMatch = new ProductMatch(info, version); break; } } } else { productMatch = new ProductMatch(productInfo, version); } // Step 7: Store ProductMatch for faster access in subsequent runs if (productMatch != null) { matches.put(entry.getElementName(), productMatch); return productMatch; } else { noMatches.add(entry.getElementName()); return null; } }
From source file:org.springframework.ide.eclipse.quickfix.proposals.CreateNewClassQuickFixProposal.java
License:Open Source License
public CreateNewClassQuickFixProposal(int offset, int length, String text, boolean missingEndQuote, IJavaProject javaProject, Set<String> properties, int numConstructorArgs, boolean allowUserChanges) { super(offset, length, missingEndQuote); this.properties = properties; this.numConstructorArgs = numConstructorArgs; this.javaProject = javaProject; this.allowUserChanges = allowUserChanges; int classNameOffset = text.lastIndexOf("$"); int packageEnd; if (classNameOffset >= 0) { String enclosingClassName = text.substring(0, classNameOffset); enclosingType = JdtUtils.getJavaType(javaProject.getProject(), enclosingClassName); packageEnd = enclosingClassName.lastIndexOf("."); } else {//from w w w .j a v a2 s . c o m classNameOffset = text.lastIndexOf("."); packageEnd = classNameOffset; } if (classNameOffset < 0) { className = text; } else { className = text.substring(classNameOffset + 1); } if (packageEnd >= 0) { packageName = text.substring(0, packageEnd); } else { packageName = ""; } String packageFragmentName = null; if (enclosingType != null) { packageFragmentName = enclosingType.getPackageFragment().getElementName(); } IPackageFragmentRoot[] allPackageFragmentRoots; try { allPackageFragmentRoots = javaProject.getAllPackageFragmentRoots(); if (allPackageFragmentRoots != null && allPackageFragmentRoots.length > 0) { for (IPackageFragmentRoot packageFragmentRoot : allPackageFragmentRoots) { if (!(packageFragmentRoot instanceof JarPackageFragmentRoot)) { if (packageFragmentName != null) { if (packageFragmentRoot.getPackageFragment(packageFragmentName) == null) { continue; } } sourceRoot = packageFragmentRoot; break; } } } } catch (JavaModelException e) { } }
From source file:org.talend.designer.core.ui.viewer.java.TalendJavaSourceViewer.java
License:Open Source License
/** * DOC nrousseau TalendJavaSourceViewer2 constructor comment. * /*from w w w . jav a 2s .co m*/ * @param parent * @param verticalRuler * @param overviewRuler * @param showAnnotationsOverview * @param styles * @param annotationAccess * @param sharedColors * @param checkCode */ public TalendJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles, IAnnotationAccess annotationAccess, ISharedTextColors sharedColors, boolean checkCode, IDocument document) { super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles, annotationAccess, sharedColors, checkCode, document, null); int id = currentId++; className = TalendJavaSourceViewer.VIEWER_CLASS_NAME + id; filename = TalendJavaSourceViewer.VIEWER_CLASS_NAME + id++ + JavaUtils.JAVA_EXTENSION; IPackageFragment packageFragment; try { IRunProcessService runProcessService = getRunProcessService(); if (runProcessService != null) { ITalendProcessJavaProject talendProcessJavaProject = runProcessService .getTalendProcessJavaProject(); if (talendProcessJavaProject == null) { return; } IPackageFragmentRoot root = talendProcessJavaProject.getJavaProject() .getPackageFragmentRoot(talendProcessJavaProject.getSrcFolder()); packageFragment = root.getPackageFragment(JavaUtils.JAVA_INTERNAL_DIRECTORY); if (packageFragment != null) { compilationUnit = packageFragment.createCompilationUnit(filename, document.get(), false, new NullProgressMonitor()); } } } catch (JavaModelException e) { ExceptionHandler.process(e); } updateContents(); }
From source file:org.talend.designer.rowgenerator.data.AbstractTalendFunctionParser.java
License:Open Source License
protected void addEveryProjectElements(IPackageFragmentRoot root, List<IJavaElement> elements) throws JavaModelException { if (root == null || elements == null) { return;//from w ww . ja v a2 s . com } // system IPackageFragment Pkg = root.getPackageFragment(getPackageFragment()); if (Pkg != null && Pkg.exists()) { elements.addAll(Arrays.asList(Pkg.getChildren())); } ProjectManager projectManager = ProjectManager.getInstance(); Project currentProject = projectManager.getCurrentProject(); // current project IPackageFragment userPkg = root.getPackageFragment(getPackageFragment() + "." //$NON-NLS-1$ + currentProject.getLabel().toLowerCase()); if (userPkg != null && userPkg.exists()) { elements.addAll(Arrays.asList(userPkg.getChildren())); } // referenced project. projectManager.retrieveReferencedProjects(); for (Project p : projectManager.getReferencedProjects()) { userPkg = root.getPackageFragment(getPackageFragment() + "." + p.getLabel().toLowerCase()); //$NON-NLS-1$ if (userPkg != null && userPkg.exists()) { elements.addAll(Arrays.asList(userPkg.getChildren())); } } }
From source file:org.talend.repository.ui.actions.EditPropertiesAction.java
License:Open Source License
protected IPackageFragment getPackageFragment(IPackageFragmentRoot root, IRepositoryNode node) { String folder = node.getContentType().getFolder(); String packageName = Path.fromOSString(folder).lastSegment(); return root.getPackageFragment(packageName); }
From source file:org.universaal.tools.newwizard.plugin.wizards.NewItemWizard.java
License:Apache License
/** * This method is called when 'Finish' button is pressed in the wizard. We * will create an operation and run it using wizard as execution context. *//*w ww . j a v a 2s . c om*/ public boolean performFinish() { // get info from the wizard final IMWVersion mwVersion = page.getMWVersion(); final String clsname = page.getTextClass().getText(); final int clstype = page.getDropClass().getSelectionIndex(); // this job performs the creation of the item Job job = new WorkspaceJob(Messages.getString("Item.1")) { //$NON-NLS-1$ public IStatus runInWorkspace(IProgressMonitor monitor) { try { // Get the place to put the new file (or create it) IPackageFragmentRoot root = page.getPackageFragmentRoot(); IPackageFragment pack = page.getPackageFragment(); if (pack == null) { root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName = pack.getElementName(); pack = root.createPackageFragment(packName, true, monitor); } else { monitor.worked(1); } IResource resource = pack.getCorrespondingResource(); IContainer container = (IContainer) resource; if (!mwVersion.createNewFile(container, pack.getElementName(), clstype, clsname, monitor)) { MessageDialog.openError(getShell(), Messages.getString("Item.2"), //$NON-NLS-1$ Messages.getString("Item.3")); //$NON-NLS-1$ } // Now update dependencies in pom IFile pom = pack.getJavaProject().getProject().getFile("pom.xml"); //$NON-NLS-1$ if (pom.exists()) { // Modify the pom to add dependencies mwVersion.modifyPOMFile(pom, clstype, monitor); } else { MessageDialog.openError(getShell(), Messages.getString("Item.4"), //$NON-NLS-1$ Messages.getString("Item.5")); //$NON-NLS-1$ } } catch (Exception e) { throw new OperationCanceledException(e.getMessage()); } return Status.OK_STATUS; } }; // Listener in case job fails job.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { final IStatus result = event.getResult(); if (!result.isOK()) { Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openError(getShell(), Messages.getString("Item.6"), result //$NON-NLS-1$ .getMessage()); } }); } } }); // Because we dont need to monitor changes in workspace, // we directly perform the job job.setRule(ResourcesPlugin.getWorkspace().getRoot()); job.schedule(); return true; }
From source file:org.wso2.developerstudio.eclipse.artifact.jaxrs.ui.wizard.JaxrsClassWizard.java
License:Open Source License
public boolean performFinish() { String id = ""; String address = ""; String serviceClass = ""; try {//from w ww . j a v a 2s . co m IProject project = getSelectedProject(); IFolder sourceFolder = ProjectUtils.getWorkspaceFolder(project, "src", "main", "java"); IFolder webINF = ProjectUtils.getWorkspaceFolder(project, "src", "main", "webapp", "WEB-INF"); IFile cxfServletXML = webINF.getFile("cxf-servlet.xml"); IJavaProject javaProject = JavaCore.create(project); IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder); if (classWizardPage.getIsCreateIfClass()) { String ifPkg = classWizardPage.getIfPkg(); String ifClass = classWizardPage.getIfClass(); IPackageFragment ifSourcePackage = root.getPackageFragment(ifPkg); if (!ifSourcePackage.exists()) { ifSourcePackage = root.createPackageFragment(ifPkg, false, null); } ICompilationUnit compilationUnit = ifSourcePackage.createCompilationUnit(ifClass + ".java", JaxUtil.getServiceClassSource(ifPkg, ifClass, classWizardPage.isCreateStubs()), false, null); project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); List superInterfaces = classWizardPage.getSuperInterfaces(); superInterfaces.add(compilationUnit.getTypes()[0].getFullyQualifiedName()); classWizardPage.setSuperInterfaces(superInterfaces, false); id = compilationUnit.getTypes()[0].getElementName(); id = Character.toLowerCase(id.charAt(0)) + id.substring(1); serviceClass = ""; address = "/" + compilationUnit.getTypes()[0].getElementName(); } classWizardPage.createType(new NullProgressMonitor()); IType classSource = classWizardPage.getCreatedType(); ICompilationUnit unit = classSource.getCompilationUnit(); unit.getJavaProject().getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); unit.becomeWorkingCopy(new NullProgressMonitor()); unit.createImport("javax.ws.rs.Path", null, new NullProgressMonitor()); String source = unit.getSource(); String searchFor = "public class " + classSource.getTypeQualifiedName(); int pos = source.indexOf(searchFor); source = (source.substring(0, pos) + "@Path(\"/" + "\")" + System.getProperty("line.separator") + source.substring(pos)); IBuffer workingCopyBuffer = unit.getBuffer(); workingCopyBuffer.setContents(source); unit.commitWorkingCopy(false, new NullProgressMonitor()); try { if (!classWizardPage.getIsCreateIfClass()) { id = unit.getTypes()[0].getElementName(); id = Character.toLowerCase(id.charAt(0)) + id.substring(1); serviceClass = unit.getTypes()[0].getFullyQualifiedName(); address = "/" + unit.getTypes()[0].getElementName(); } JaxUtil.CxfServlet cxfServlet = new JaxUtil.CxfServlet(); cxfServlet.deserialize(cxfServletXML); address = address.replaceAll("([A-Z])", "_$1"); // split CamelCase address = address.replaceAll("^/_", "/"); address = address.toLowerCase(); String beanClass = unit.getTypes()[0].getFullyQualifiedName(); cxfServlet.addServer(id, serviceClass, address, beanClass); String content = cxfServlet.toString().replaceAll("\\ xmlns=\"\"", ""); cxfServletXML.setContents(new ByteArrayInputStream(content.getBytes()), IResource.FORCE, null); project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); try { IEditorPart javaEditor = JavaUI.openInEditor(unit); JavaUI.revealInEditor(javaEditor, (IJavaElement) unit); } catch (Exception e) {/* ignore */ log.error("Exception has occurred", e); } } catch (Exception e) { log.error("cannot update cxf-servlet.xml", e); } } catch (CoreException e) { log.error("CoreException has occurred", e); } catch (InterruptedException e) { log.error("An InterruptedException has occurred", e); } return true; }
From source file:org.wso2.developerstudio.eclipse.artifact.jaxws.ui.wizard.JaxwsClassWizard.java
License:Open Source License
public boolean performFinish() { try {/*from ww w . j a va2s . co m*/ String ifPkg = jaxwsClassWizardPage.getIfPkg(); String ifClass = jaxwsClassWizardPage.getIfClass(); IProject project = getSelectedProject(); IFolder sourceFolder = ProjectUtils.getWorkspaceFolder(project, "src", "main", "java"); IFolder webINF = ProjectUtils.getWorkspaceFolder(project, "src", "main", "webapp", "WEB-INF"); IFile cxfServletXML = webINF.getFile("cxf-servlet.xml"); IJavaProject javaProject = JavaCore.create(project); IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder); String id = ""; String serviceClass = null; String address = ""; List superInterfaces = jaxwsClassWizardPage.getSuperInterfaces(); if (jaxwsClassWizardPage.isCreateServiceInterface()) { IPackageFragment ifSourcePackage = root.getPackageFragment(ifPkg); if (!ifSourcePackage.exists()) { ifSourcePackage = root.createPackageFragment(ifPkg, false, null); } ICompilationUnit cu = ifSourcePackage.createCompilationUnit(ifClass + ".java", JaxUtil.getServiceClassSource(ifPkg, ifClass, jaxwsClassWizardPage.isCreateStubs()), false, null); project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); superInterfaces.add(cu.getTypes()[0].getFullyQualifiedName()); id = cu.getTypes()[0].getElementName(); id = Character.toLowerCase(id.charAt(0)) + id.substring(1); serviceClass = cu.getTypes()[0].getFullyQualifiedName(); address = "/" + cu.getTypes()[0].getElementName(); } jaxwsClassWizardPage.setSuperInterfaces(superInterfaces, false); jaxwsClassWizardPage.createType(new NullProgressMonitor()); IType classSource = jaxwsClassWizardPage.getCreatedType(); ICompilationUnit unit = classSource.getCompilationUnit(); unit.becomeWorkingCopy(new NullProgressMonitor()); unit.createImport("javax.jws.WebService", null, new NullProgressMonitor()); String source = unit.getSource(); String searchFor = "public class " + classSource.getTypeQualifiedName(); int pos = source.indexOf(searchFor); source = (source.substring(0, pos) + "@WebService(serviceName = \"" + classSource.getTypeQualifiedName() + "\")" + System.getProperty("line.separator") + source.substring(pos)); IBuffer workingCopyBuffer = unit.getBuffer(); workingCopyBuffer.setContents(source); unit.commitWorkingCopy(false, new NullProgressMonitor()); unit.getJavaProject().getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); if (!jaxwsClassWizardPage.isCreateServiceInterface()) { id = classSource.getElementName(); id = Character.toLowerCase(id.charAt(0)) + id.substring(1); //serviceClass = classSource.getFullyQualifiedName(); address = "/" + classSource.getElementName(); } JaxUtil.CxfServlet cxfServlet = new JaxUtil.CxfServlet(); try { cxfServlet = new JaxUtil.CxfServlet(); cxfServlet.deserialize(cxfServletXML); address = address.replaceAll("([A-Z])", "_$1"); // split CamelCase address = address.replaceAll("^/_", "/"); address = address.toLowerCase(); String beanClass = unit.getTypes()[0].getFullyQualifiedName(); cxfServlet.addServer(id, serviceClass, address, beanClass); /*to drop empty NS, due to https://issues.apache.org/jira/browse/AXIOM-97 (was fixed in AXIOM 1.2.10)*/ String content = cxfServlet.toString().replaceAll("xmlns=\"\"", ""); cxfServletXML.setContents(new ByteArrayInputStream(content.getBytes()), IResource.FORCE, null); project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); IEditorPart javaEditor = JavaUI.openInEditor(unit); JavaUI.revealInEditor(javaEditor, (IJavaElement) unit); } catch (Exception e) { log.error("cannot update cxf-servlet.xml", e); } } catch (CoreException e) { log.error("CoreException has occurred", e); } catch (InterruptedException e) { log.error("An InterruptedException has occurred", e); } return true; }
From source file:qwickie.hyperlink.WicketHyperlink.java
License:Apache License
private void createJavaFile(final IResource resource) { Assert.isNotNull(resource);/* w w w . j av a 2s . c o m*/ final OpenNewClassWizardAction action = new OpenNewClassWizardAction(); final NewClassWizardPage ncwp = new NewClassWizardPage(); ncwp.setTypeName(resource.getName().replaceAll("\\.html", ""), true); final IJavaProject javaProject = JavaCore.create(resource.getProject()); IPackageFragmentRoot root = null; try { final IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots(); for (int i = 0; i < roots.length; i++) { if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { root = roots[i]; break; } } ncwp.setPackageFragmentRoot(root, true); } catch (final JavaModelException e) { } final String os = root.getParent().getPath().toPortableString(); final String fp = root.getResource().getFullPath().toPortableString().replaceFirst(os, "").substring(1); final String ps = resource.getProjectRelativePath().toPortableString().replaceFirst(fp, ""); String pn = ps.replaceFirst(resource.getName(), "").substring(1).replaceAll("/", "."); pn = pn.substring(0, pn.length() - 1); ncwp.setPackageFragment(root.getPackageFragment(pn), true); ncwp.setSuperClass("org.apache.wicket.markup.html.WebPage", openJavaFile()); action.setConfiguredWizardPage(ncwp); action.setOpenEditorOnFinish(true); action.run(); }