List of usage examples for org.eclipse.jdt.core IJavaElement getResource
IResource getResource();
From source file:de.ovgu.featureide.core.mpl.job.CreateFujiSignaturesJob.java
License:Open Source License
private static String getClassPaths(IFeatureProject featureProject) { String classpath = ""; String sep = System.getProperty("path.separator"); try {/* w w w . j a va 2s. c o m*/ JavaProject proj = new JavaProject(featureProject.getProject(), null); IJavaElement[] elements = proj.getChildren(); for (IJavaElement e : elements) { String path = e.getPath().toOSString(); if (path.contains(":")) { classpath += sep + path; continue; } IResource resource = e.getResource(); if (resource != null && "jar".equals(resource.getFileExtension())) { classpath += sep + resource.getRawLocation().toOSString(); } } } catch (JavaModelException e) { } return classpath.length() > 0 ? classpath.substring(1) : classpath; }
From source file:de.ovgu.featureide.ui.actions.generator.ConfigurationBuilder.java
License:Open Source License
/** * Sets the java classPath for compiling. */// ww w . j a va 2s . co m private void setClassPath() { String sep = System.getProperty("path.separator"); try { JavaProject proj = new JavaProject(featureProject.getProject(), null); IJavaElement[] elements = proj.getChildren(); for (IJavaElement e : elements) { String path = e.getPath().toOSString(); if (path.contains(":")) { classpath += sep + path; continue; } IResource resource = e.getResource(); if (resource != null && "jar".equals(resource.getFileExtension())) { classpath += sep + resource.getRawLocation().toOSString(); } } } catch (JavaModelException e) { } classpath = classpath.length() > 0 ? classpath.substring(1) : classpath; }
From source file:de.ovgu.featureide.ui.actions.generator.TestRunner.java
License:Open Source License
private URL[] getURLs() { ArrayList<URL> urls = new ArrayList<>(); try {/* w w w.j a v a 2 s.c o m*/ URL url = tmp.getLocationURI().toURL(); url = new URL(url.toString() + "/"); urls.add(url); JavaProject proj = new JavaProject(tmp.getProject(), null); IJavaElement[] elements = proj.getChildren(); for (IJavaElement e : elements) { String path = e.getPath().toOSString(); if (path.contains(":")) { continue; } IResource resource = e.getResource(); if (resource != null && "jar".equals(resource.getFileExtension())) { urls.add(resource.getRawLocationURI().toURL()); } } } catch (MalformedURLException | JavaModelException e) { UIPlugin.getDefault().logError(e); } return urls.toArray(new URL[urls.size()]); }
From source file:edu.buffalo.cse.green.editor.action.refactor.RefactorRenameParticipant.java
License:Open Source License
@Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { if (!(getProcessor() instanceof RenameProcessor)) { return null; }/* ww w . ja va2s . com*/ CompositeChange change = null; //Allows the return of a null change if no applicable changes are found. IJavaElement element = ((IJavaElement) (getProcessor()).getElements()[0]); String oldName = element.getElementName(); oldName = oldName.replace(".java", ""); String handle = element.getHandleIdentifier(); String newName = ((JavaRenameProcessor) getProcessor()).getNewElementName(); newName = newName.replace(".java", ""); ArrayList<HandleNode> handleList = new ArrayList<HandleNode>(); String handleCopy = handle; char prefix = handleCopy.charAt(0); handleCopy = handleCopy.substring(1); for (int j = 0; j < handleCopy.length(); j++) { if (HANDLE_PREFIXES.contains(handleCopy.charAt(j) + "")) { handleList.add(new HandleNode(prefix + handleCopy.substring(0, j))); prefix = handleCopy.charAt(j); handleCopy = handleCopy.substring(j + 1); j = 0; } } handleList.add(new HandleNode(prefix + handleCopy)); handleCopy = ""; Iterator<HandleNode> itr = handleList.iterator(); while (itr.hasNext()) { HandleNode node = itr.next(); // if(node.getName().contains(".")) { // if((node.getName()).substring(0, node.getName().indexOf('.')) == oldName) { // node.setName(newName + ".java"); // } // } if (node.getName().equals(oldName)) { node.setName(newName); } } Iterator<HandleNode> itr2 = handleList.iterator(); String newHandle = ""; while (itr2.hasNext()) { HandleNode node = itr2.next(); newHandle += node.toString(); } // if(newName.indexOf('.') != -1) { //To handle type names that include .java // if(oldName.contains(".java")) { // oldName = oldName.substring(0, oldName.indexOf(".java")); // } // newName = newName.substring(0, newName.indexOf('.')); // } //Assumes project is open and exists (which should be the case if the element //was able to be selected) IProject project = element.getResource().getProject(); ArrayList<IFile> greenFiles = ResourceUtil.getGreenFiles(project); for (IFile file : greenFiles) { BufferedReader br = new BufferedReader(new InputStreamReader(file.getContents())); String fileText = ""; String line = null; try { while ((line = br.readLine()) != null) { fileText += line + '\n'; } } catch (IOException e) { e.printStackTrace(); } //Starting index of element handle int[] handleIndices = ResourceUtil.findAllOccurrences(fileText, handle); // ArrayList<Integer> offsets = new ArrayList<Integer>(); if (change == null) { //Creates a new Change object if necessary change = new CompositeChange("Change reference '" + oldName + "' to '" + newName + "'."); } TextFileChange result = new TextFileChange(file.getName(), file); MultiTextEdit fileChangeRootEdit = new MultiTextEdit(); result.setEdit(fileChangeRootEdit); for (int i = 0; i < handleIndices.length; i++) { ReplaceEdit edit = new ReplaceEdit(handleIndices[i], handle.length(), newHandle); fileChangeRootEdit.addChild(edit); change.add(result); } // for(int i = 0; i < handleIndices.length; i++) { // int[] tempOffsets = ResourceUtil.findAllOccurrences(handle, oldName); // for(int j = 0; j < tempOffsets.length; j++) { // offsets.add(new Integer(handleIndices[i] + tempOffsets[j])); // } // } // if(!offsets.isEmpty()) { //Changes exist // if(change == null) { //Creates a new Change object if necessary // change = new CompositeChange("Change reference '" + oldName + "' to '" + newName + "'."); // } // // TextFileChange result = new TextFileChange(file.getName(), file); // MultiTextEdit fileChangeRootEdit = new MultiTextEdit(); // result.setEdit(fileChangeRootEdit); // // for(Integer offset : offsets) { // ReplaceEdit edit = new ReplaceEdit(offset.intValue(), oldName.length(), newName); // fileChangeRootEdit.addChild(edit); // } // change.add(result); // } } return change; }
From source file:edu.buffalo.cse.green.editor.DiagramEditor.java
License:Open Source License
/** * Finds all relationships that have the given element as their source. * /*from w ww .j a va 2s . c o m*/ * @param element - The element to find relationships for. */ private void findRelationships(IJavaElement element) { long modified; // if the element contains errors, quit try { if (!element.exists() || !element.isStructureKnown()) return; } catch (JavaModelException e) { e.printStackTrace(); return; } CompilationUnit cu; String id = element.getHandleIdentifier(); // generate AST if necessary - check modification stamp Long modifiedStore = _cuMap.getModificationStamp(id); IResource resource = element.getResource(); if (resource == null) { if (_cuMap.getCompilationUnit(id) != null) { modifiedStore = new Long(0); } modified = 0; } else { modified = resource.getModificationStamp(); } // if there isn't an up-to-date AST, create one if ((modifiedStore == null) || (modified != modifiedStore)) { ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setResolveBindings(true); if (element instanceof ICompilationUnit) { parser.setSource((ICompilationUnit) element); } else if (element instanceof IClassFile) { // only search through the class if it has source code attached IClassFile classFile = (IClassFile) element; try { if (classFile.getSource() == null) { return; } } catch (JavaModelException e) { e.printStackTrace(); } parser.setSource(classFile); } else { GreenException.illegalOperation("Illegal element type: " + element.getClass()); } cu = (CompilationUnit) parser.createAST(null); _cuMap.put(element, cu); } else { cu = _cuMap.getCompilationUnit(id); } // run the recognizers for (Class klass : PlugIn.getRelationships()) { RelationshipRecognizer recognizer = PlugIn.getRelationshipGroup(klass).getRecognizer(); // run the recognizer recognizer.run(cu, getRootModel().getRelationshipCache()); } }
From source file:edu.buffalo.cse.green.editor.DiagramEditor.java
License:Open Source License
/** * Maps an element to its corresponding <code>CompilationUnit</code>. * //from w w w . j a va 2 s .co m * @param element - The element. * @param cu - Its corresponding <code>CompilationUnit</code>. */ public void put(IJavaElement element, CompilationUnit cu) { String id = element.getHandleIdentifier(); _map.put(id, cu); if (!(element.isReadOnly())) { _cuModMap.put(id, element.getResource().getModificationStamp()); } }
From source file:edu.cmu.cs.crystal.internal.StandardAnalysisReporter.java
License:Open Source License
public void reportUserProblem(String problemDescription, ASTNode node, String analysisName, SEVERITY severity) { if (node == null) throw new NullPointerException("null ASTNode argument in reportUserProblem"); if (analysisName == null) throw new NullPointerException("null analysis argument in reportUserProblem"); if (logger.isLoggable(Level.FINE)) logger.fine("Reporting problem to user: " + problemDescription + "; node: " + node); if (regressionLogger.isLoggable(Level.INFO)) { regressionLogger.info(problemDescription); regressionLogger.info(node.toString()); }/*from ww w . j av a2 s. com*/ IResource resource; ASTNode root = node.getRoot(); // Identify the closest resource to the ASTNode, // otherwise fall back to using the high-level workspace root. if (root.getNodeType() == ASTNode.COMPILATION_UNIT) { CompilationUnit cu = (CompilationUnit) root; IJavaElement je = cu.getJavaElement(); resource = je.getResource(); } else { // Use the high-level Workspace resource = ResourcesPlugin.getWorkspace().getRoot(); } int sevMarker; if (severity == SEVERITY.ERROR) sevMarker = IMarker.SEVERITY_ERROR; else if (severity == SEVERITY.WARNING) sevMarker = IMarker.SEVERITY_WARNING; else sevMarker = IMarker.SEVERITY_INFO; // Create the marker // TODO: create markers according to the type of the analysis try { IMarker marker = resource.createMarker(Crystal.MARKER_DEFAULT); marker.setAttribute(IMarker.CHAR_START, node.getStartPosition()); marker.setAttribute(IMarker.CHAR_END, node.getStartPosition() + node.getLength()); marker.setAttribute(IMarker.MESSAGE, "[" + analysisName + "]: " + problemDescription); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_NORMAL); marker.setAttribute(IMarker.SEVERITY, sevMarker); marker.setAttribute(Crystal.MARKER_ATTR_ANALYSIS, analysisName); CompilationUnit cu = (CompilationUnit) node.getRoot(); int line = cu.getLineNumber(node.getStartPosition()); if (line >= 0) // -1 and -2 indicate error conditions marker.setAttribute(IMarker.LINE_NUMBER, line); } catch (CoreException ce) { logger.log(Level.SEVERE, "CoreException when creating marker", ce); } }
From source file:edu.washington.cs.cupid.scripting.java.CupidScriptingPlugin.java
License:Open Source License
/** * Load a class defined by <code>element</code>. If <code>notify</code> and the element is a capability, alert * listeners that the capability has been loaded. * @param element the element to load/*w w w .j av a2 s. c o m*/ * @param notify <code>true</code> iff listeners should be alerted * @throws Exception if loading the capability fails * @throws Error if there are compilation or type resolution errors */ public void loadDynamicCapability(final IJavaElement element, final boolean notify) throws Exception, Error { CupidCapabilityLoader loader = new CupidCapabilityLoader(CupidScriptingPlugin.class.getClassLoader()); if (!element.getResource().exists()) return; Class<?> definition = loader.loadClass(simpleName(element)); if (!ICapability.class.isAssignableFrom(definition)) return; logInformation("Loaded dynamic capability " + definition.getSimpleName() + " from " + simpleName(element)); ICapability capability = (ICapability) definition.newInstance(); removeCapability(capability.getName()); dynamic.add(capability); if (notify) { notifier.onCapabilityAdded(capability); } }
From source file:edu.wpi.cs.jburge.SEURAT.actions.AssociateArtifactAction.java
License:Open Source License
/** Executes the association. We get our selected rationale item and * associated it with the java element selected. * /*w w w . j a v a 2 s . c o m*/ */ public void run() { //Get our selected items. Send a message to the user to confirm that //this is the correct association. if (navigatorSelection != null) { ISelection selection = viewer.getSelection(); obj = ((IStructuredSelection) selection).getFirstElement(); if (obj instanceof TreeParent) { String assQ = "Associate '" + ((TreeParent) obj).getName() + "' with " + navigatorSelection.getElementName() + "?"; boolean selOk = showQuestion(assQ); // showMessage(navigatorSelection.getHandleIdentifier()); // System.out.println(navigatorSelection.getHandleIdentifier()); if (selOk) { cstart = 0; ourRes = null; try { if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) { ourRes = navigatorSelection.getCorrespondingResource(); } else { ourRes = navigatorSelection.getUnderlyingResource(); if (ourRes != null) { // *** System.out.println("this one wasn't null?"); } //find the enclosing class file IJavaElement nextE = navigatorSelection.getParent(); while ((nextE != null) && (nextE.getElementType() != IJavaElement.COMPILATION_UNIT)) { // *** System.out.println("Name = " + nextE.getElementName()); // *** System.out.println("Type = " + nextE.getElementType()); nextE = nextE.getParent(); } try { // *** System.out.println("getting our resource"); // ourRes = nextE.getUnderlyingResource(); ourRes = nextE.getCorrespondingResource(); ourRes = nextE.getResource(); } catch (JavaModelException ex) { System.out.println("exception getting resource?"); } // *** System.out.println("Final name = " + nextE.getElementName()); // *** System.out.println("Final type = " + nextE.getElementType()); if (ourRes == null) { //see if we can get the element from the working copy IJavaElement original = nextE.getPrimaryElement(); // Get working copy has been deprecated // IJavaElement original = ((ICompilationUnit) ((ICompilationUnit) nextE).getWorkingCopy()).getOriginalElement(); ourRes = original.getCorrespondingResource(); } } // ourRes = navigatorSelection.getUnderlyingResource(); if (ourRes == null) { // *** System.out.println("why would our resource be null?"); } // *** System.out.println("FullPath = " + ourRes.getFullPath().toString()); // *** System.out.println("now checking file extension?"); if (ourRes.getFullPath().getFileExtension().compareTo("java") == 0) { // *** System.out.println("creating our file?"); IJavaElement myJavaElement = JavaCore.create((IFile) ourRes); // *** System.out.println("created an element?"); if (myJavaElement.getElementType() == IJavaElement.COMPILATION_UNIT) { // *** System.out.println("Compilation Unit"); ICompilationUnit myCompilationUnit = (ICompilationUnit) myJavaElement; IType[] myTypes = myCompilationUnit.getTypes(); boolean found = false; int i = 0; while ((!found) && i < myTypes.length) { //selected item was the class itself if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) { // *** System.out.println("found the class"); if (myTypes[i].isClass()) { found = true; cstart = myTypes[i].getNameRange().getOffset(); } } else if (navigatorSelection.getElementType() == IJavaElement.FIELD) { // *** System.out.println("looking for types"); IField[] myFields = myTypes[i].getFields(); for (int j = 0; j < myFields.length; j++) { if (myFields[j].getElementName() .compareTo(navigatorSelection.getElementName()) == 0) { // *** System.out.println("found a type"); found = true; cstart = myFields[j].getNameRange().getOffset(); } } } else if (navigatorSelection.getElementType() == IJavaElement.METHOD) { // *** System.out.println("looking for a method"); IMethod[] myMethods = myTypes[i].getMethods(); for (int j = 0; j < myMethods.length; j++) { if (myMethods[j].getElementName() .compareTo(navigatorSelection.getElementName()) == 0) { // *** System.out.println("found a method"); found = true; cstart = myMethods[j].getNameRange().getOffset(); } } } //don't forget to increment! i++; } //end while } else { // *** System.out.println("not a compilation unit?"); System.out.println(myJavaElement.getElementType()); } //ok... now what type is our selected item? System.out.println("got the resource?"); if (ourRes == null) { System.out.println("null resource???"); } } else { System.out.println("not a java file?"); } // from the newsgroup - in a runnable? ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) { try { // *** System.out.println("line number = " + new Integer(lineNumber).toString()); IMarker ratM = ourRes.createMarker("SEURAT.ratmarker"); String dbname = RationaleDB.getDbName(); String markD = "Alt: '" + ((TreeParent) obj).getName() + "' Rationale DB: '" + dbname + "'"; ratM.setAttribute(IMarker.MESSAGE, markD); ratM.setAttribute(IMarker.CHAR_START, cstart); ratM.setAttribute(IMarker.CHAR_END, cstart + 1); ratM.setAttribute(IMarker.SEVERITY, 0); String artName = navigatorSelection.getElementName(); ratM.setAttribute("alternative", ((TreeParent) obj).getName()); SEURATResourcePropertiesManager.addPersistentProperty(ourRes, "Rat", "true"); RationaleDB d = RationaleDB.getHandle(); d.associateAlternative(((TreeParent) obj).getName(), navigatorSelection.getHandleIdentifier(), ourRes.getName(), artName, markD); } catch (CoreException e) { e.printStackTrace(); } } }, null); // *** System.out.println("adding persistent property"); SEURATDecoratorManager.addSuccessResources(ourRes); // *** System.out.println("added our property"); // Refresh the label decorations... Change it to DemoDecoratorWithImageCaching if image caching should be used // ((TreeParent) obj).setStatus(RationaleErrorLevel.ERROR); viewer.update((TreeParent) obj, null); SEURATLightWeightDecorator.getRatDecorator().refresh(); // *** System.out.println("refresh"); } catch (Exception ex) { ex.printStackTrace(); System.out.println("an exception occured in AssociateArtifactAction"); } } else System.out.println("selection rejected"); } } else { System.out.println("No java element selected..."); } }
From source file:edu.wpi.cs.jburge.SEURAT.actions.RemoveRationaleAssociation.java
License:Open Source License
/** * This is when the action really runs/*from ww w. j a v a2 s.com*/ * @param action - not used */ public void run(IAction action) { IJavaElement navigatorSelection; // *** System.out.println("removing association"); if (selection.getFirstElement() instanceof IJavaElement) { // *** System.out.println("we are a java element"); navigatorSelection = (IJavaElement) selection.getFirstElement(); ourRes = null; boolean proceed = showQuestion("Do you want to delete all associations to this file?"); if (!proceed) { return; } //find the associated resource that goes with the element try { if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) { ourRes = navigatorSelection.getCorrespondingResource(); } else { ourRes = navigatorSelection.getUnderlyingResource(); if (ourRes != null) { // *** System.out.println("this one wasn't null?"); } //find the enclosing class file IJavaElement nextE = navigatorSelection.getParent(); while ((nextE != null) && (nextE.getElementType() != IJavaElement.COMPILATION_UNIT)) { // *** System.out.println("Name = " + nextE.getElementName()); // *** System.out.println("Type = " + nextE.getElementType()); nextE = nextE.getParent(); } try { // *** System.out.println("getting our resource"); // ourRes = nextE.getUnderlyingResource(); ourRes = nextE.getCorrespondingResource(); ourRes = nextE.getResource(); } catch (JavaModelException ex) { // *** System.out.println("exception getting resource?"); } System.out.println("Final name = " + nextE.getElementName()); System.out.println("Final type = " + nextE.getElementType()); if (ourRes == null) { // *** System.out.println("see if there's a working copy"); IJavaElement original = nextE.getPrimaryElement(); //see if we can get the element from the working copy // IJavaElement original = ((IWorkingCopy) ((ICompilationUnit) nextE).getWorkingCopy()).getOriginalElement(); ourRes = original.getCorrespondingResource(); } } // ourRes = navigatorSelection.getUnderlyingResource(); if (ourRes == null) { // *** System.out.println("why would our resource be null?"); } // *** System.out.println("FullPath = " + ourRes.getFullPath().toString()); // *** System.out.println("now checking file extension?"); if (ourRes.getFullPath().getFileExtension().compareTo("java") == 0) { // *** System.out.println("creating our file?"); IJavaElement myJavaElement = JavaCore.create((IFile) ourRes); // *** System.out.println("created an element?"); if (myJavaElement.getElementType() == IJavaElement.COMPILATION_UNIT) { // *** System.out.println("Compilation Unit"); ICompilationUnit myCompilationUnit = (ICompilationUnit) myJavaElement; IType[] myTypes = myCompilationUnit.getTypes(); boolean found = false; int i = 0; while ((!found) && i < myTypes.length) { //selected item was the class itself if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) { // *** System.out.println("found the class"); if (myTypes[i].isClass()) { found = true; } } else if (navigatorSelection.getElementType() == IJavaElement.FIELD) { // *** System.out.println("looking for types"); IField[] myFields = myTypes[i].getFields(); for (int j = 0; j < myFields.length; j++) { if (myFields[j].getElementName() .compareTo(navigatorSelection.getElementName()) == 0) { // *** System.out.println("found a type"); found = true; } } } else if (navigatorSelection.getElementType() == IJavaElement.METHOD) { // *** System.out.println("looking for a method"); IMethod[] myMethods = myTypes[i].getMethods(); for (int j = 0; j < myMethods.length; j++) { if (myMethods[j].getElementName() .compareTo(navigatorSelection.getElementName()) == 0) { // *** System.out.println("found a method"); found = true; } } } //don't forget to increment! i++; } //end while } else { // *** System.out.println("not a compilation unit?"); // *** System.out.println(myJavaElement.getElementType()); } //ok... now what type is our selected item? // *** System.out.println("got the resource?"); if (ourRes == null) { // *** System.out.println("null resource???"); } } else { // *** System.out.println("not a java file?"); } // from the newsgroup - in a runnable? ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) { try { // *** System.out.println("removing our markers, etc."); // ourResource.setPersistentProperty() SEURATResourcePropertiesManager.addPersistentProperty(ourRes, "Rat", "false"); SEURATDecoratorManager.addSuccessResources(ourRes); ourRes.deleteMarkers("SEURAT.ratmarker", true, IResource.DEPTH_INFINITE); RationaleDB d = RationaleDB.getHandle(); d.removeAssociation(ourRes.getName()); } catch (CoreException e) { e.printStackTrace(); } } }, null); } catch (Exception ex) { ex.printStackTrace(); System.out.println("an exception occured in AssociateArtifactAction"); } } }