List of usage examples for org.eclipse.jdt.core IJavaProject getCorrespondingResource
IResource getCorrespondingResource() throws JavaModelException;
null
if there is no resource that corresponds to this element. From source file:com.drgarbage.controlflowgraphfactory.actions.GenerateGraphAction.java
License:Apache License
/** * Process all parents from the selected node by calling getParent() method. * Tree | Interfaces * ---------------------------------+----------- * Project | IJavaElement, IJavaProject * + Package | IJavaElement, IPackageFragment * + Source: *.java or *.class | IJavaElement * + Class | IJavaElement, IType * + Method | IJavaElement, IMethod * /*from ww w. ja va 2 s. co m*/ * Classpath for the selected class files can be resolved from the * project tree node by calling getPath() method. * Classpath for the source files should be resolved via Java runtime, * because it can be different with the source path. * */ private void createControlFlowGraph(TreeSelection treeSel) { String mMethodName = null; String mMethodSignature = null; String mClassName = null; String mPackage = null; List<String> mPath = new ArrayList<String>(); /* java model elements */ IMethod iMethod = null; IJavaProject jp = null; try { /* Method Name */ iMethod = (IMethod) treeSel.getFirstElement(); if (!hasCode(iMethod)) { Messages.info(MessageFormat.format(CoreMessages.CannotGenerateGraph_MethodIsAnAbstractMethod, new Object[] { iMethod.getElementName() })); return; } if (iMethod.isConstructor()) { mMethodName = "<init>"; } else { mMethodName = iMethod.getElementName(); } /** * Method Signature: * NOTE: if class file is selected then the method signature is resolved. */ if (iMethod.isBinary()) { mMethodSignature = iMethod.getSignature(); } else { try { /* resolve parameter signature */ StringBuffer buf = new StringBuffer("("); String[] parameterTypes = iMethod.getParameterTypes(); String res = null; for (int i = 0; i < parameterTypes.length; i++) { res = ActionUtils.getResolvedTypeName(parameterTypes[i], iMethod.getDeclaringType()); buf.append(res); } buf.append(")"); res = ActionUtils.getResolvedTypeName(iMethod.getReturnType(), iMethod.getDeclaringType()); buf.append(res); mMethodSignature = buf.toString(); } catch (IllegalArgumentException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } } IType type = iMethod.getDeclaringType(); mClassName = type.getFullyQualifiedName(); mPackage = type.getPackageFragment().getElementName(); mClassName = mClassName.replace(mPackage + ".", ""); if (iMethod.isBinary()) { /* Classpath for selected class files */ mPath.add(type.getPackageFragment().getPath().toString()); } /* Classpath for selected source code files */ jp = iMethod.getJavaProject(); try { String[] str = JavaRuntime.computeDefaultRuntimeClassPath(jp); for (int i = 0; i < str.length; i++) { mPath.add(str[i]); } } catch (CoreException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } } catch (ClassCastException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } catch (JavaModelException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } /* convert classpath to String array */ String[] classPath = new String[mPath.size()]; for (int i = 0; i < mPath.size(); i++) { classPath[i] = mPath.get(i); } /* create control flow graph diagram */ final ControlFlowGraphDiagram controlFlowGraphDiagram = createDiagram(classPath, mPackage, mClassName, mMethodName, mMethodSignature); if (controlFlowGraphDiagram == null) { Messages.warning(ControlFlowFactoryMessages.DiagramIsNullMessage); return; } /* create empty shell */ Shell shell = page.getActivePart().getSite().getShell(); /* Show a SaveAs dialog */ ExportGraphSaveAsDialog dialog = new ExportGraphSaveAsDialog(shell); try { IPath path = jp.getCorrespondingResource().getFullPath(); if (iMethod.isConstructor()) { /* use class name for constructor */ path = path.append(IPath.SEPARATOR + mClassName + "." + mClassName + "." + GraphConstants.graphTypeSuffixes[getGraphType()]); } else { path = path.append(IPath.SEPARATOR + mClassName + "." + mMethodName + "." + GraphConstants.graphTypeSuffixes[getGraphType()]); } path = path.addFileExtension(FileExtensions.GRAPH); /* get file and set in the dialog */ IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); dialog.setOriginalFile(file); } catch (JavaModelException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } /* open SaveAS dialog */ dialog.open(); IPath path = dialog.getResult(); if (path == null) {/* action canceled */ return; } graphSpecification = dialog.getGraphSpecification(); /* convert if necessary and start an editor */ switch (graphSpecification.getExportFormat()) { case GraphConstants.EXPORT_FORMAT_DRGARBAGE_GRAPH: ActionUtils.saveDiagramInFileAndOpenEditor(path, shell, page, controlFlowGraphDiagram, graphSpecification.isOpenInEditor()); break; default: AbstractExport2 exporter = null; switch (graphSpecification.getExportFormat()) { case GraphConstants.EXPORT_FORMAT_DOT: exporter = new GraphDOTExport(); break; case GraphConstants.EXPORT_FORMAT_GRAPHXML: exporter = new GraphXMLExport(); break; case GraphConstants.EXPORT_FORMAT_GRAPHML: exporter = new GraphMlExport(); break; default: throw new IllegalStateException( "Unexpected export format '" + graphSpecification.getExportFormat() + "'."); } exporter.setGraphSpecification(graphSpecification); StringWriter sb = new StringWriter(); try { exporter.write(controlFlowGraphDiagram, sb); } catch (ExportException e) { /* This will never happen as * StringBuilder.append(*) does not throw IOException*/ throw new RuntimeException(e); } ActionUtils.saveContentInFileAndOpenEditor(path, shell, page, sb.toString(), graphSpecification.isOpenInEditor()); break; } dialog = null; }
From source file:com.flamefire.importsmalinames.handlers.RenameVariablesHandler.java
License:Open Source License
private void doRename(Shell shell, ICompilationUnit cu) { IJavaProject proj = getProject(cu); String cClassName = null;//from w w w . jav a 2s . c o m String pName = null; try { cClassName = cu.getCorrespondingResource().getName(); if (proj != null) pName = proj.getElementName(); } catch (JavaModelException e) { e.printStackTrace(); } if (cClassName == null || pName == null || cClassName.length() == 0 || pName.length() == 0) { MessageDialog.openError(shell, "Error", "Could not access project and class names"); return; } boolean classOnly = MessageDialog.openQuestion(shell, "Apply smali names only to current class?", "Do you want to apply the names only to current java file (" + cClassName + ") ->YES\n" + "Or to the whole project (" + pName + ") -> NO"); String lastFolder = null; IResource res = null; try { res = proj.getCorrespondingResource(); lastFolder = com.flamefire.importsmalinames.utils.Util.getPersistentProperty(res, LASTFOLDER); } catch (JavaModelException e) { } JFileChooser j = new JFileChooser(); j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); j.setDialogTitle("Select smali directory"); if (lastFolder != null) j.setSelectedFile(new File(lastFolder)); if (j.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) return; com.flamefire.importsmalinames.utils.Util.setPersistentProperty(res, LASTFOLDER, j.getSelectedFile().getAbsolutePath()); File smaliFolder = j.getSelectedFile(); RefactoringController controller = new RefactoringController(); if (!controller.init(smaliFolder)) { MessageDialog.openError(shell, "Error", "Could not parse smali classes"); return; } if (classOnly) { if (!controller.renameVariablesInFile(cu)) { MessageDialog.openError(shell, "Error", "Initializing the changes failed. Please check output."); return; } } else { try { IPackageFragment[] packages = proj.getPackageFragments(); for (IPackageFragment mypackage : packages) { if (mypackage.getKind() != IPackageFragmentRoot.K_SOURCE) continue; for (ICompilationUnit unit : mypackage.getCompilationUnits()) { if (!controller.renameVariablesInFile(unit)) { if (!MessageDialog.openConfirm(shell, "Error in " + unit.getCorrespondingResource().getName(), "Initializing the changes to " + unit.getCorrespondingResource().getName() + " failed. Please check output.\n\nContinue?")) return; } } } } catch (JavaModelException e) { e.printStackTrace(); } } String msg = "This will apply the smali names to the "; if (classOnly) msg += "java file " + cClassName; else msg += "whole project " + pName; msg += "\n\nPlease note that you HAVE to check the changes without a preview and it is better to apply this to the decompiled source before you do any changes yourself."; msg += "\nThis might fail under certain circumstances e.g. with nested classes and certain name combinations."; msg += "\n\nProceed?"; if (!MessageDialog.openConfirm(shell, "Apply smali names", msg)) return; if (controller.applyRenamings(shell)) MessageDialog.openInformation(shell, "Success", "Names were changed. Please have a look at the output in the console for warnings and errors"); else MessageDialog.openInformation(shell, "Error", "There were erros changing the names. Some may have been changed. Please have a look at the output in the console for warnings and errors"); }
From source file:net.sf.fjep.fatjar.wizards.export.JProjectConfiguration.java
License:Open Source License
/** * @return associated IResource/*from w w w . j a v a 2 s. c om*/ */ public IResource[] getResource() { IResource[] results = new IResource[this.jProjectCollection.size()]; for (int i = 0; i < this.jProjectCollection.size(); i++) { IJavaProject project = (IJavaProject) this.jProjectCollection.get(i); try { results[i] = project.getCorrespondingResource(); } catch (JavaModelException e) { e.printStackTrace(); } } return results; }
From source file:org.assertj.eclipse.assertions.generator.internal.generation.EclipseAssertionGenerator.java
License:Apache License
private static File getAssertionClassDestinationDirectory(IType type) throws JavaModelException { IJavaProject javaProject = type.getCompilationUnit().getJavaProject(); // get test base directory as defined in preferences, ex : src/test/java String testSourceDirectory = Preferences.instance().getTestSourceDirectory(javaProject); IPath javaProjectPath = javaProject.getCorrespondingResource().getLocation(); IPath destinationFolderPath = javaProjectPath.append(testSourceDirectory); // get type's package elements, if type is org.demo.Player, then package elements -> ["org", "demo"] String[] typePackageElementNames = type.getPackageFragment().getElementName().split("\\."); for (String packageElementName : typePackageElementNames) { destinationFolderPath = destinationFolderPath.append(packageElementName); }//from ww w . j a va 2 s.com // following the given example, it would be : src/test/java/org/demo return destinationFolderPath.toFile(); }
From source file:org.digitalsoul.loom.core.EditorFileOpener.java
License:GNU General Public License
/** * @param searchFilename// w w w.j av a 2 s . co m * @param project * @return */ private IFile switchToFile(String searchFilename, IJavaProject project) { IFile foundFile = null; foundFile = findCachedFile(searchFilename); if (foundFile == null) { try { IPath projectPath = project.getCorrespondingResource().getLocation(); File searchFolder = new File(projectPath.toPortableString()); String pathURL = findFile(searchFilename, searchFolder, project); Path path = new Path(pathURL); foundFile = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(path)[0]; } catch (JavaModelException e) { e.printStackTrace(); } } return foundFile; }
From source file:org.infinitest.eclipse.workspace.JavaProjectSet.java
License:Open Source License
File workingDirectory(IJavaProject project) throws JavaModelException { return project.getCorrespondingResource().getLocation().toFile(); }
From source file:org.infinitest.eclipse.workspace.JavaProjectTestSupport.java
License:Open Source License
public static void expectProjectLocationFor(IJavaProject project, String projectName) throws JavaModelException { IResource projectResource = mock(IResource.class); when(projectResource.getLocation()).thenReturn(new Path(PATH_TO_WORKSPACE + projectName)); when(project.getCorrespondingResource()).thenReturn(projectResource); }
From source file:org.universaal.tools.transformationcommand.handlers.TransformOntJava2OWL.java
License:Apache License
private IProject getSelectedProject(ExecutionEvent event, IWorkbenchWindow window) { try {//from w w w .jav a 2 s . c om ISelection selection = HandlerUtil.getCurrentSelection(event); if (selection == null) selection = window.getSelectionService().getSelection("org.eclipse.jdt.ui.PackageExplorer"); if (selection == null) selection = window.getSelectionService().getSelection("org.eclipse.ui.navigator.ProjectExplorer"); if ((selection != null) && (selection instanceof StructuredSelection)) { Object selectedProject = ((StructuredSelection) selection).getFirstElement(); if ((selectedProject instanceof IJavaProject)) { IJavaProject javaProject = (IJavaProject) selectedProject; IProject project = (IProject) javaProject.getCorrespondingResource(); return project; } } return null; } catch (Exception e) { e.printStackTrace(); return null; } }