Example usage for org.eclipse.jdt.core IJavaElement getHandleIdentifier

List of usage examples for org.eclipse.jdt.core IJavaElement getHandleIdentifier

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaElement getHandleIdentifier.

Prototype

String getHandleIdentifier();

Source Link

Document

Returns a string representation of this element handle.

Usage

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLinks.java

License:Open Source License

/**
 * Creates an {@link URI} with the given scheme based on the given element.
 * The additional arguments specify a member referenced from the given element.
 *
 * @param scheme a scheme//from   ww w . j  a  va  2s. c  o m
 * @param element the declaring element
 * @param refTypeName a (possibly qualified) type or package name, can be <code>null</code>
 * @param refMemberName a member name, can be <code>null</code>
 * @param refParameterTypes a (possibly empty) array of (possibly qualified) parameter type
 *            names, can be <code>null</code>
 * @return an {@link URI}, encoded as {@link URI#toASCIIString() ASCII} string, ready to be used
 *         as <code>href</code> attribute in an <code>&lt;a&gt;</code> tag
 * @throws URISyntaxException if the arguments were invalid
 */
public static String createURI(String scheme, IJavaElement element, String refTypeName, String refMemberName,
        String[] refParameterTypes) throws URISyntaxException {
    /*
     * We use an opaque URI, not ssp and fragments (to work around Safari bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=212527 (wrongly encodes #)).
     */

    StringBuffer ssp = new StringBuffer(60);
    ssp.append(LINK_SEPARATOR); // make sure first character is not a / (would be hierarchical URI)

    // replace '[' manually, since URI confuses it for an IPv6 address as per RFC 2732:
    ssp.append(element.getHandleIdentifier().replace('[', LINK_BRACKET_REPLACEMENT)); // segments[1]

    if (refTypeName != null) {
        ssp.append(LINK_SEPARATOR);
        ssp.append(refTypeName); // segments[2]

        if (refMemberName != null) {
            ssp.append(LINK_SEPARATOR);
            ssp.append(refMemberName); // segments[3]

            if (refParameterTypes != null) {
                ssp.append(LINK_SEPARATOR);
                for (int i = 0; i < refParameterTypes.length; i++) {
                    ssp.append(refParameterTypes[i]); // segments[4|5|..]
                    if (i != refParameterTypes.length - 1) {
                        ssp.append(LINK_SEPARATOR);
                    }
                }
            }
        }
    }
    return new URI(scheme, ssp.toString(), null).toASCIIString();
}

From source file:com.android.ide.eclipse.adt.internal.launch.junit.AndroidJUnitLaunchConfigurationTab.java

License:Open Source License

private void initializeTestContainer(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) {
    config.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_CONTAINER,
            javaElement.getHandleIdentifier());
    initializeName(config, javaElement.getElementName());
}

From source file:com.android.ide.eclipse.cheatsheets.actions.SetBreakpoint.java

License:Open Source License

public void run(final String[] params, ICheatSheetManager manager) {
    // param1 - project
    // param2 - path
    // param3 - type name
    // param4 - line number
    if (params == null || params[0] == null || params[1] == null || params[2] == null || params[3] == null) {
        return;/*from w  w w  .  j a v a  2s. c om*/
    }
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();

    IProject project = workspaceRoot.getProject(params[0]);
    if (project == null || !project.isOpen()) {
        Activator.log("Invalid the project " + params[0] + ".");
        return;
    }
    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject == null || !javaProject.isOpen()) {
        Activator.log("Invalid the project: " + params[0] + ".");
        return;
    }
    IJavaElement element;
    try {
        element = javaProject.findElement(new Path(params[1]));

        if (element == null) {
            Activator.log("Invalid the path: " + params[1] + ".");
            return;
        }
        resource = element.getCorrespondingResource();
        if (resource == null || resource.getType() != IResource.FILE) {
            Activator.log("Invalid the path: " + params[1] + ".");
            return;
        }
    } catch (JavaModelException e1) {
        Activator.log("Invalid the " + params[1] + " path.");
        return;
    }
    String tname = params[2];
    Display.getDefault().syncExec(new Runnable() {

        public void run() {
            editor = openEditor(params, (IFile) resource);
        }
    });
    if (editor == null) {
        Activator.log("Cannot open the " + " " + params[0] + "file.");
        return;
    }
    try {
        //String markerType = "org.eclipse.jdt.debug.javaLineBreakpointMarker";
        int lnumber;
        try {
            lnumber = new Integer(params[3]).intValue();
        } catch (NumberFormatException e) {
            Activator.log("Invalid line number " + params[1]);
            return;
        }
        Map attributes = new HashMap(10);
        IDocumentProvider documentProvider = editor.getDocumentProvider();
        if (documentProvider == null) {
            return;
        }
        IDocument document = documentProvider.getDocument(editor.getEditorInput());
        int charstart = -1, charend = -1;
        try {
            IRegion line = document.getLineInformation(lnumber - 1);
            charstart = line.getOffset();
            charend = charstart + line.getLength();
        } catch (BadLocationException e) {
            Activator.log(e);
        }
        //BreakpointUtils.addJavaBreakpointAttributes(attributes, type);

        String handleId = element.getHandleIdentifier();
        attributes.put(HANDLE_ID, handleId);
        JavaCore.addJavaElementMarkerAttributes(attributes, element);
        IJavaLineBreakpoint breakpoint = JDIDebugModel.createLineBreakpoint(resource, tname, lnumber, charstart,
                charend, 0, true, attributes);

        IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager();
        breakpointManager.addBreakpoint(breakpoint);
    } catch (CoreException e) {
        Activator.log(e);
    }
}

From source file:com.github.ajaxsys.jdtx.utils.JDTUtils.java

License:Open Source License

/**
 * Return a unique string representing the specified Java element across
 * projects in the workspace. The returned string can be used as a handle to
 * create JavaElement by 'JavaCore.create(String)'
 *
 * For example, suppose we have the method
 * 'fooPackage.barPackage.FooClass.fooMethod(int)' which is in the
 * 'FooProject' and source folder 'src' the handle would be
 * '=FooProject/src<fooPackage.barPackage{FooClass.java[FooClass~fooMethod~I
 * '/*ww  w. j a va  2 s.c o  m*/
 *
 * @param javaElt
 * @throws IllegalArgumentException
 *             if javaElt is null
 */
public static String getJdtHandleString(IJavaElement javaElt) {
    if (javaElt == null) {
        throw new IllegalArgumentException("javaElt is null");
    }
    return javaElt.getHandleIdentifier();
}

From source file:com.microsoft.javapkgsrv.JavaParser.java

License:MIT License

public String ProcessOpenTypeRequest(String fileName) throws Exception {
    File file = new File(fileName);
    IFile[] files = WorkspaceRoot.findFilesForLocationURI(file.toURI(), IResource.FILE);

    if (files.length > 1)
        throw new Exception("Ambigous parse request for file " + fileName);
    else if (files.length == 0)
        throw new Exception("File not found: " + fileName);

    IJavaElement javaFile = JavaCore.create(files[0]);
    if (javaFile instanceof ITypeRoot) {
        //int hashCode = javaFile.hashCode();
        String handle = javaFile.getHandleIdentifier();
        ActiveTypeRoots.put(handle, (ITypeRoot) javaFile);
        return handle;
    }//  w  w w  . jav a2s.c om
    return null;
}

From source file:com.microsoft.javapkgsrv.JavaParser.java

License:MIT License

public String ProcessAddTypeRequest(String handle) {
    IJavaElement javaFile = JavaCore.create(handle);
    if (javaFile instanceof ITypeRoot) {
        String newHandle = javaFile.getHandleIdentifier();
        ActiveTypeRoots.put(newHandle, (ITypeRoot) javaFile);
        return newHandle;
    }/* w  w  w  .  j  a va  2 s.  c om*/
    return null;
}

From source file:de.tobject.findbugs.reporter.MarkerReporter.java

License:Open Source License

/**
 * @param mp// www  .  ja  v a  2 s  . com
 * @return attributes map which should be assigned to the given marker. If the map is empty,
 * the marker shouldn't be generated
 */
@Nonnull
private Map<String, Object> createMarkerAttributes(MarkerParameter mp) {
    Map<String, Object> attributes = new HashMap<String, Object>(23);
    attributes.put(IMarker.LINE_NUMBER, mp.startLine);
    attributes.put(PRIMARY_LINE, mp.primaryLine);
    attributes.put(BUG_TYPE, mp.bug.getType());
    attributes.put(PATTERN_TYPE, mp.bug.getAbbrev());
    attributes.put(RANK, Integer.valueOf(mp.bug.getBugRank()));
    attributes.put(PRIO_AKA_CONFIDENCE, MarkerConfidence.getConfidence(mp.bug.getPriority()).name());

    long seqNum = mp.bug.getFirstVersion();
    if (seqNum == 0) {
        attributes.put(FIRST_VERSION, "-1");
    } else {
        AppVersion theVersion = collection.getAppVersionFromSequenceNumber(seqNum);
        if (theVersion == null) {
            attributes.put(FIRST_VERSION, "Cannot find AppVersion: seqnum=" + seqNum + "; collection seqnum="
                    + collection.getSequenceNumber());
        } else {
            attributes.put(FIRST_VERSION, Long.toString(theVersion.getTimestamp()));
        }
    }
    try {
        attributes.put(IMarker.MESSAGE, getMessage(mp));
    } catch (RuntimeException e) {
        FindbugsPlugin.getDefault().logException(e,
                "Error generating msg for " + mp.bug.getType() + ", attributes: " + attributes);
        attributes.clear();
        return attributes;
    }
    attributes.put(IMarker.SEVERITY, mp.markerSeverity);

    // Set unique id of warning, so we can easily refer back
    // to it later: for example, when the user classifies the warning.
    String uniqueId = mp.bug.getInstanceHash();
    if (uniqueId != null) {
        attributes.put(UNIQUE_ID, uniqueId);
    }

    // Set unique id of the plugin, so we can easily refer back
    // to it later: for example, when the user group markers by plugin.
    DetectorFactory detectorFactory = mp.bug.getDetectorFactory();
    if (detectorFactory != null) {
        String pluginId = detectorFactory.getPlugin().getPluginId();
        if (pluginId != null) {
            attributes.put(DETECTOR_PLUGIN_ID, pluginId);
        }
    } else {
        // Fix for loading bugs from XML: they do not have detector factory set, so we guess one
        BugPattern pattern = mp.bug.getBugPattern();
        Iterator<DetectorFactory> fit = DetectorFactoryCollection.instance().factoryIterator();
        while (fit.hasNext()) {
            DetectorFactory df2 = fit.next();
            if (!df2.isReportingDetector()) {
                continue;
            }
            Set<BugPattern> patterns = df2.getReportedBugPatterns();
            if (patterns.contains(pattern)) {
                String pluginId = df2.getPlugin().getPluginId();
                if (pluginId != null) {
                    attributes.put(DETECTOR_PLUGIN_ID, pluginId);
                    break;
                }
            }
        }
    }
    if (attributes.get(DETECTOR_PLUGIN_ID) == null) {
        attributes.clear();
        return attributes;
    }

    IJavaElement javaElt = mp.resource.getCorespondingJavaElement();
    if (javaElt != null) {
        attributes.put(UNIQUE_JAVA_ID, javaElt.getHandleIdentifier());
        // Eclipse markers model doesn't allow to have markers
        // attached to the (non-resource) part of the resource (like jar
        // entry inside the jar)
        // TODO we should add annotations to opened class file editors to
        // show (missing)
        // markers for single class file inside the jar. Otherwise we will
        // show markers
        // in the bug explorer view but NOT inside the class file editor
    }
    return attributes;
}

From source file:de.tobject.findbugs.reporter.MarkerUtil.java

License:Open Source License

public static Set<IMarker> findMarkerForJavaElement(IJavaElement elt, IMarker[] possibleCandidates,
        boolean recursive) {
    String id = elt.getHandleIdentifier();
    Set<IMarker> markers = new HashSet<IMarker>();
    for (IMarker marker : possibleCandidates) {
        try {//  w ww  .j a v a2s  . c  o  m
            Object elementId = marker.getAttribute(FindBugsMarker.UNIQUE_JAVA_ID);
            // UNIQUE_JAVA_ID exists first since 1.3.9 as FB attribute
            if (!(elementId instanceof String)) {
                continue;
            }
            String stringId = (String) elementId;
            if (!recursive) {
                if (stringId.equals(id)) {
                    // exact match
                    markers.add(marker);
                } else if (isDirectChild(id, stringId)) {
                    // direct child: class in the package, but not in the
                    // sub-package
                    markers.add(marker);
                }
            } else if (stringId.startsWith(id)) {
                markers.add(marker);
            }
        } catch (CoreException e) {
            FindbugsPlugin.getDefault().logException(e, "Marker does not contain valid java element id");
            continue;
        }
    }
    return markers;
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockEditor.java

License:Open Source License

/********************************************************************************/

void rename(String proj, String bid, String file, int start, int end, String name, String handle,
        String newname, boolean keeporig, boolean getters, boolean setters, boolean dohier, boolean qual,
        boolean refs, boolean dosimilar, boolean textocc, boolean doedit, String filespat, IvyXmlWriter xw)
        throws BedrockException {
    FileData fd = file_map.get(file);/*from   www.  ja  va  2  s . c  o m*/
    ICompilationUnit icu;

    if (doedit) {
        // icu = fd.getDefaultUnit();
        icu = fd.getEditableUnit(bid);
    } else
        icu = fd.getEditableUnit(bid);

    IJavaElement[] elts;
    try {
        elts = icu.codeSelect(start, end - start);
    } catch (JavaModelException e) {
        throw new BedrockException("Bad location: " + e, e);
    }

    IJavaElement relt = null;
    for (IJavaElement ije : elts) {
        if (handle != null && !handle.equals(ije.getHandleIdentifier()))
            continue;
        if (name != null && !name.equals(ije.getElementName()))
            continue;
        relt = ije;
        break;
    }
    if (relt == null)
        throw new BedrockException("Item to rename not found");

    String id = null;
    switch (relt.getElementType()) {
    case IJavaElement.COMPILATION_UNIT:
        id = IJavaRefactorings.RENAME_COMPILATION_UNIT;
        break;
    case IJavaElement.FIELD:
        IField ifld = (IField) relt;
        try {
            if (ifld.isEnumConstant())
                id = IJavaRefactorings.RENAME_ENUM_CONSTANT;
            else
                id = IJavaRefactorings.RENAME_FIELD;
        } catch (JavaModelException e) {
        }
        break;
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
    case IJavaElement.PACKAGE_FRAGMENT:
        id = IJavaRefactorings.RENAME_PACKAGE;
        break;
    case IJavaElement.LOCAL_VARIABLE:
        id = IJavaRefactorings.RENAME_LOCAL_VARIABLE;
        break;
    case IJavaElement.TYPE:
        id = IJavaRefactorings.RENAME_TYPE;
        break;
    case IJavaElement.TYPE_PARAMETER:
        id = IJavaRefactorings.RENAME_TYPE_PARAMETER;
        break;
    case IJavaElement.METHOD:
        id = IJavaRefactorings.RENAME_METHOD;
        break;
    case IJavaElement.ANNOTATION:
    case IJavaElement.CLASS_FILE:
    case IJavaElement.IMPORT_CONTAINER:
    case IJavaElement.IMPORT_DECLARATION:
    case IJavaElement.INITIALIZER:
    case IJavaElement.JAVA_MODEL:
    case IJavaElement.JAVA_PROJECT:
    case IJavaElement.PACKAGE_DECLARATION:
        break;
    }
    if (id == null)
        throw new BedrockException("Invalid element type to rename");

    RenameJavaElementDescriptor renamer;

    RefactoringContribution rfc = RefactoringCore.getRefactoringContribution(id);
    if (rfc == null) {
        xw.begin("FAILURE");
        xw.field("TYPE", "SETUP");
        xw.textElement("ID", id);
        xw.end("FAILURE");
        renamer = new RenameJavaElementDescriptor(id);
    } else {
        renamer = (RenameJavaElementDescriptor) rfc.createDescriptor();
    }

    renamer.setJavaElement(relt);
    renamer.setKeepOriginal(keeporig);
    renamer.setNewName(newname);
    if (proj != null)
        renamer.setProject(proj);
    renamer.setRenameGetters(getters);
    renamer.setRenameSetters(setters);
    renamer.setUpdateHierarchy(dohier);
    renamer.setUpdateQualifiedNames(qual);
    renamer.setUpdateReferences(refs);
    renamer.setUpdateSimilarDeclarations(dosimilar);
    renamer.setUpdateTextualOccurrences(textocc);
    if (filespat != null)
        renamer.setFileNamePatterns(filespat);

    RefactoringStatus sts = renamer.validateDescriptor();
    if (!sts.isOK()) {
        xw.begin("FAILURE");
        xw.field("TYPE", "VALIDATE");
        BedrockUtil.outputStatus(sts, xw);
        xw.end("FAILURE");
        return;
    }

    try {
        Refactoring refactor = renamer.createRefactoring(sts);
        if (refactor == null) {
            xw.begin("FAILURE");
            xw.field("TYPE", "CREATE");
            xw.textElement("RENAMER", renamer.toString());
            xw.textElement("REFACTOR", renamer.toString());
            xw.textElement("STATUS", sts.toString());
            xw.end("FAILURE");
            return;
        }

        refactor.setValidationContext(null);

        // this seems to reset files from disk (mutliple times)
        sts = refactor.checkAllConditions(new NullProgressMonitor());
        if (!sts.isOK()) {
            xw.begin("FAILURE");
            xw.field("TYPE", "CHECK");
            BedrockUtil.outputStatus(sts, xw);
            xw.end("FAILURE");
            if (sts.hasFatalError())
                return;
        }
        BedrockPlugin.logD("RENAME: Refactoring checked");

        Change chng = refactor.createChange(new NullProgressMonitor());
        BedrockPlugin.logD("RENAME: Refactoring change created");

        if (doedit && chng != null) {
            chng.perform(new NullProgressMonitor());
        } else if (chng != null) {
            xw.begin("EDITS");
            BedrockUtil.outputChange(chng, xw);
            xw.end("EDITS");
        }
    } catch (CoreException e) {
        throw new BedrockException("Problem creating refactoring: " + e, e);
    }

    BedrockPlugin.logD("RENAME RESULT = " + xw.toString());
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockEditor.java

License:Open Source License

/********************************************************************************/

void moveElement(String proj, String bid, String what, String file, int start, int end, String name,
        String handle, String target, boolean qual, boolean refs, boolean doedit, IvyXmlWriter xw)
        throws BedrockException {
    FileData fd = findFile(proj, file, null, null);
    IJavaElement relt = null;//from  w ww.j  a  v  a  2 s.com
    if (what.equals("COMPUNIT")) {
        if (fd == null)
            throw new BedrockException("Invalid file");
        relt = fd.getSearchUnit();
    } else {
        ICompilationUnit icu = fd.getEditableUnit(bid);
        IJavaElement[] elts;
        try {
            elts = icu.codeSelect(start, end - start);
        } catch (JavaModelException e) {
            throw new BedrockException("Bad location: " + e, e);
        }

        for (IJavaElement ije : elts) {
            if (handle != null && !handle.equals(ije.getHandleIdentifier()))
                continue;
            if (name != null && !name.equals(ije.getElementName()))
                continue;
            relt = ije;
            break;
        }
    }
    if (relt == null)
        throw new BedrockException("Item to rename not found");

    RefactoringContribution rfc = null;
    RefactoringDescriptor rfd = null;
    IJavaElement tgt = null;

    switch (relt.getElementType()) {
    case IJavaElement.COMPILATION_UNIT:
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
    case IJavaElement.PACKAGE_FRAGMENT:
    case IJavaElement.TYPE:
        rfc = RefactoringCore.getRefactoringContribution(IJavaRefactorings.MOVE);
        tgt = our_plugin.getProjectManager().findPackageFragment(proj, target);
        break;
    case IJavaElement.METHOD:
        rfc = RefactoringCore.getRefactoringContribution(IJavaRefactorings.MOVE_METHOD);
        break;
    default:
        throw new BedrockException("Invalid element type to rename");
    }

    if (rfc == null) {
        xw.begin("FAILURE");
        xw.field("TYPE", "SETUP");
        xw.end("FAILURE");
        return;
    } else {
        rfd = rfc.createDescriptor();
    }

    RefactoringStatus sts = null;
    if (rfd instanceof MoveDescriptor) {
        MoveDescriptor md = (MoveDescriptor) rfd;
        md.setDestination(tgt);
        IFile[] ifls = new IFile[0];
        IFolder[] iflds = new IFolder[0];
        ICompilationUnit[] icus = new ICompilationUnit[] { (ICompilationUnit) relt };
        md.setMoveResources(ifls, iflds, icus);
        sts = md.validateDescriptor();
        if (!sts.isOK()) {
            xw.begin("FAILURE");
            xw.field("TYPE", "VALIDATE");
            BedrockUtil.outputStatus(sts, xw);
            xw.end("FAILURE");
            return;
        }
    } else if (rfd instanceof MoveMethodDescriptor) {
        MoveMethodDescriptor mmd = (MoveMethodDescriptor) rfd;
        System.err.println("HANDLE MOVE METHOD" + mmd);
    }

    try {
        Refactoring refactor = rfd.createRefactoring(sts);
        if (refactor == null) {
            xw.begin("FAILURE");
            xw.field("TYPE", "CREATE");
            if (sts != null)
                xw.textElement("STATUS", sts.toString());
            xw.end("FAILURE");
            return;
        }

        refactor.setValidationContext(null);

        sts = refactor.checkAllConditions(new NullProgressMonitor());
        if (!sts.isOK()) {
            xw.begin("FAILURE");
            xw.field("TYPE", "CHECK");
            BedrockUtil.outputStatus(sts, xw);
            xw.end("FAILURE");
            if (sts.hasFatalError())
                return;
        }

        Change chng = refactor.createChange(new NullProgressMonitor());
        BedrockPlugin.logD("RENAME: Refactoring change created");

        if (doedit && chng != null) {
            chng.perform(new NullProgressMonitor());
        } else if (chng != null) {
            xw.begin("EDITS");
            BedrockUtil.outputChange(chng, xw);
            xw.end("EDITS");
        }
    } catch (CoreException e) {
        throw new BedrockException("Problem with move", e);
    }
}