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:org.eclipse.capra.handler.jdt.JavaElementHandler.java

License:Open Source License

@Override
public String getURI(Object selection) {
    if (selection instanceof IJavaElement) {
        IJavaElement cu = (IJavaElement) selection;
        return cu.getHandleIdentifier();
    } else if (selection instanceof WorkingSet) {
        WorkingSet ws = (WorkingSet) selection;
        return ws.getId();
    }//from w w  w.  j a  v  a2s .  c  o  m

    return "";
}

From source file:org.eclipse.che.jdt.javadoc.JavaElementLinks.java

License:Open Source License

/**
 * Creates an {@link java.net.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// ww w  .  j a  va2  s.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 java.net.URI}, encoded as {@link java.net.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 #)).
     */

    StringBuilder ssp = new StringBuilder(60);
    //        ssp.append(scheme);
    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);
                    }
                }
            }
        }
    }
    try {
        String encode = URLEncoder.encode(ssp.toString(), "UTF-8");
        return new URI(scheme + encode).toASCIIString();
    } catch (UnsupportedEncodingException e) {
        throw new URISyntaxException(ssp.toString(), e.getMessage());
    }
}

From source file:org.eclipse.che.jdt.search.SearchManager.java

License:Open Source License

private FindUsagesResponse performFindUsageSearch(IJavaElement element)
        throws JavaModelException, BadLocationException {
    JavaSearchScopeFactory factory = JavaSearchScopeFactory.getInstance();
    boolean isInsideJRE = factory.isInsideJRE(element);
    JavaSearchQuery query = new JavaSearchQuery(new ElementQuerySpecification(element,
            IJavaSearchConstants.REFERENCES, factory.createWorkspaceScope(isInsideJRE), "workspace scope"));
    NewSearchUI.runQueryInForeground(null, query);
    ISearchResult result = query.getSearchResult();
    JavaSearchResult javaResult = ((JavaSearchResult) result);
    FindUsagesResponse response = DtoFactory.newDto(FindUsagesResponse.class);
    Map<String, List<org.eclipse.che.ide.ext.java.shared.dto.search.Match>> mapMaches = new HashMap<>();
    JavaElementToDtoConverter converter = new JavaElementToDtoConverter(javaResult);
    for (Object o : javaResult.getElements()) {
        IJavaElement javaElement = (IJavaElement) o;
        IDocument document = null;// ww  w.  ja v a  2  s. co  m
        if (javaElement instanceof IMember) {
            IMember member = ((IMember) javaElement);
            if (member.isBinary()) {
                if (member.getClassFile().getSource() != null) {
                    document = new Document(member.getClassFile().getSource());
                }
            } else {
                document = getDocument(member.getCompilationUnit());
            }
        } else if (javaElement instanceof IPackageDeclaration) {
            ICompilationUnit ancestor = (ICompilationUnit) (javaElement)
                    .getAncestor(IJavaElement.COMPILATION_UNIT);
            document = getDocument(ancestor);

        }
        converter.addElementToProjectHierarchy(javaElement);

        Match[] matches = javaResult.getMatches(o);

        List<org.eclipse.che.ide.ext.java.shared.dto.search.Match> matchList = new ArrayList<>();
        for (Match match : matches) {
            org.eclipse.che.ide.ext.java.shared.dto.search.Match dtoMatch = DtoFactory
                    .newDto(org.eclipse.che.ide.ext.java.shared.dto.search.Match.class);
            if (document != null) {
                IRegion lineInformation = document.getLineInformationOfOffset(match.getOffset());

                int offsetInLine = match.getOffset() - lineInformation.getOffset();
                Region matchInLine = DtoFactory.newDto(Region.class).withOffset(offsetInLine)
                        .withLength(match.getLength());
                dtoMatch.setMatchInLine(matchInLine);
                dtoMatch.setMatchLineNumber(document.getLineOfOffset(match.getOffset()));
                dtoMatch.setMatchedLine(document.get(lineInformation.getOffset(), lineInformation.getLength()));
            }
            dtoMatch.setFileMatchRegion(DtoFactory.newDto(Region.class).withOffset(match.getOffset())
                    .withLength(match.getLength()));
            matchList.add(dtoMatch);

        }
        mapMaches.put(javaElement.getHandleIdentifier(), matchList);
    }
    List<JavaProject> projects = converter.getProjects();
    response.setProjects(projects);
    response.setMatches(mapMaches);
    response.setSearchElementLabel(JavaElementLabels.getElementLabel(element, JavaElementLabels.ALL_DEFAULT));
    return response;
}

From source file:org.eclipse.mylyn.examples.monitor.study.SelectionMonitor.java

License:Open Source License

@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    String structureKind = InteractionEvent.ID_UNKNOWN;
    // String obfuscatedElementHandle = InteractionEvent.ID_UNKNOWN;
    String elementHandle = InteractionEvent.ID_UNKNOWN;
    InteractionEvent.Kind interactionKind = InteractionEvent.Kind.SELECTION;
    if (selection instanceof StructuredSelection) {
        StructuredSelection structuredSelection = (StructuredSelection) selection;
        Object selectedObject = structuredSelection.getFirstElement();
        if (selectedObject == null) {
            return;
        }/*  w w w . j a v a 2  s . c  o m*/
        if (selectedObject instanceof IJavaElement) {
            IJavaElement javaElement = (IJavaElement) selectedObject;
            structureKind = STRUCTURE_KIND_JAVA;
            elementHandle = javaElement.getHandleIdentifier();
            // obfuscatedElementHandle =
            // obfuscateJavaElementHandle(javaElement);
            lastSelectedElement = javaElement;
        } else {
            structureKind = InteractionEvent.ID_UNKNOWN + ": " + selectedObject.getClass();
            if (selectedObject instanceof IAdaptable) {
                IResource resource = (IResource) ((IAdaptable) selectedObject).getAdapter(IResource.class);
                if (resource != null) {
                    elementHandle = getHandleIdentifier(resource.getFullPath());
                    // obfuscatedElementHandle =
                    // obfuscator.obfuscateResourcePath(resource.getProjectRelativePath());
                }
            }
        }
    } else {
        if (selection instanceof TextSelection && part instanceof JavaEditor) {
            TextSelection textSelection = (TextSelection) selection;
            IJavaElement javaElement;
            try {
                javaElement = SelectionConverter.resolveEnclosingElement((JavaEditor) part, textSelection);
                if (javaElement != null) {
                    structureKind = STRUCTURE_KIND_JAVA;
                    // obfuscatedElementHandle =
                    // obfuscateJavaElementHandle(javaElement);
                    elementHandle = javaElement.getHandleIdentifier();
                    if (javaElement.equals(lastSelectedElement)) {
                        interactionKind = InteractionEvent.Kind.EDIT;
                    }
                    lastSelectedElement = javaElement;
                }
            } catch (JavaModelException e) {
                // ignore unresolved elements
            }
        } else if (part instanceof EditorPart) {
            EditorPart editorPart = (EditorPart) part;
            IEditorInput input = editorPart.getEditorInput();
            if (input instanceof IPathEditorInput) {
                structureKind = "file";
                elementHandle = getHandleIdentifier(((IPathEditorInput) input).getPath());
                // obfuscatedElementHandle =
                // obfuscator.obfuscateResourcePath(((IPathEditorInput)
                // input).getPath());
            }
        }
    }
    IInteractionElement node = ContextCore.getContextManager().getElement(elementHandle);
    String delta = "";
    float selectionFactor = ContextCore.getCommonContextScaling().get(InteractionEvent.Kind.SELECTION);

    if (node != null) {
        if (node.getInterest().getEncodedValue() <= selectionFactor
                && node.getInterest().getValue() > selectionFactor) {
            delta = SELECTION_PREDICTED;
        } else if (node.getInterest().getEncodedValue() < selectionFactor
                && node.getInterest().getDecayValue() > selectionFactor) {
            delta = SELECTION_DECAYED;
        } else if (node.getInterest().getValue() == selectionFactor
                && node.getInterest().getDecayValue() < selectionFactor) {
            delta = SELECTION_NEW;
        } else {
            delta = SELECTION_DEFAULT;
        }
    }

    InteractionEvent event = new InteractionEvent(interactionKind, structureKind, elementHandle,
            part.getSite().getId(), "null", delta, 0);
    MonitorUiPlugin.getDefault().notifyInteractionObserved(event);
}

From source file:org.eclipse.mylyn.internal.java.ui.editor.FocusedJavaProposalProcessor.java

License:Open Source License

private boolean boostRelevanceWithInterest(AbstractJavaCompletionProposal proposal) {
    boolean hasInteresting = false;
    IJavaElement javaElement = proposal.getJavaElement();
    if (javaElement != null) {
        IInteractionElement interactionElement = ContextCore.getContextManager()
                .getElement(javaElement.getHandleIdentifier());
        float interest = interactionElement.getInterest().getValue();
        if (interest > ContextCore.getCommonContextScaling().getInteresting()) {
            // TODO: losing precision here, only going to one decimal place
            proposal.setRelevance(THRESHOLD_INTEREST + (int) (interest * 10));
            hasInteresting = true;/*from  www.  ja  v  a2 s  .  co m*/
        } else if (proposal.getRelevance() > RELEVANCE_IMPLICIT_INTEREST_JAVA) {
            proposal.setRelevance(THRESHOLD_IMPLICIT_INTEREST + proposal.getRelevance());
        }
    } else if (isImplicitlyInteresting(proposal)) {
        proposal.setRelevance(THRESHOLD_IMPLICIT_INTEREST + proposal.getRelevance());
        hasInteresting = true;
    }
    return hasInteresting;
}

From source file:org.eclipse.mylyn.internal.java.ui.InterestUpdateDeltaListener.java

License:Open Source License

/**
 * Only handles first addition/removal/*  www. j  a  v  a 2s.c om*/
 */
private void handleDelta(IJavaElementDelta[] delta) {
    try {
        IJavaElement added = null;
        IJavaElement removed = null;
        for (IJavaElementDelta child : delta) {
            if (child.getElement() instanceof ICompilationUnit) {
                if (((ICompilationUnit) child.getElement()).getOwner() != null) {
                    // see bug 195361, do not reduce interest of temporary working copy
                    return;
                }
            }

            if (child.getKind() == IJavaElementDelta.ADDED) {
                if (added == null) {
                    added = child.getElement();
                }
            } else if (child.getKind() == IJavaElementDelta.REMOVED) {
                if (removed == null) {
                    removed = child.getElement();
                }
            }
            handleDelta(child.getAffectedChildren());
        }

        if (added != null && removed != null) {
            IInteractionElement element = ContextCore.getContextManager()
                    .getElement(removed.getHandleIdentifier());
            if (element != null) {
                resetHandle(element, added.getHandleIdentifier());
            }
        } else if (removed != null) {

            IInteractionElement element = ContextCore.getContextManager()
                    .getElement(removed.getHandleIdentifier());
            if (element != null) {
                delete(element);
            }
        }
    } catch (Throwable t) {
        StatusHandler.log(new Status(IStatus.ERROR, JavaUiBridgePlugin.ID_PLUGIN, "Delta update failed", t)); //$NON-NLS-1$
    }
}

From source file:org.eclipse.mylyn.internal.java.ui.JavaStructureBridge.java

License:Open Source License

@Override
public String getHandleForOffsetInObject(Object object, int offset) {
    IMarker marker;//from   w  ww .j  a  va 2 s  .  c o  m
    if (object instanceof ConcreteMarker) {
        marker = ((ConcreteMarker) object).getMarker();
    } else if (object instanceof Marker) {
        marker = (Marker) object;
    } else {
        return null;
    }

    try {
        ICompilationUnit compilationUnit = null;
        IResource resource = marker.getResource();
        if (resource instanceof IFile) {
            IFile file = (IFile) resource;
            // TODO: get rid of file extension check
            if (file.getFileExtension().equals("java")) { //$NON-NLS-1$
                compilationUnit = JavaCore.createCompilationUnitFrom(file);
            } else {
                return null;
            }
        }
        if (compilationUnit != null) {
            // first try to resolve the character start, then the line number if not present
            int charStart = 0;
            Object attribute = marker.getAttribute(IMarker.CHAR_START, 0);
            if (attribute instanceof Integer) {
                charStart = ((Integer) attribute).intValue();
            }
            IJavaElement javaElement = null;
            if (charStart != -1) {
                javaElement = compilationUnit.getElementAt(charStart);
            } else {
                int lineNumber = 0;
                Object lineNumberAttribute = marker.getAttribute(IMarker.LINE_NUMBER, 0);
                if (lineNumberAttribute instanceof Integer) {
                    lineNumber = ((Integer) lineNumberAttribute).intValue();
                }
                if (lineNumber != -1) {
                    // could do finer granularity by uncommenting what's below, see bug 132092
                    //                  Document document = new Document(compilationUnit.getSource());
                    //                  IRegion region = document.getLineInformation(lineNumber);
                    //                  javaElement = compilationUnit.getElementAt(region.getOffset());
                    javaElement = compilationUnit;
                }
            }

            if (javaElement != null) {
                if (javaElement instanceof IImportDeclaration) {
                    javaElement = javaElement.getParent().getParent();
                }
                return javaElement.getHandleIdentifier();
            } else {
                return null;
            }
        } else {
            return null;
        }
    } catch (JavaModelException ex) {
        if (!ex.isDoesNotExist()) {
            ExceptionHandler.handle(ex, "error", "could not find java element"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        return null;
    } catch (Throwable t) {
        StatusHandler.log(new Status(IStatus.ERROR, JavaUiBridgePlugin.ID_PLUGIN, "Could not find element for: " //$NON-NLS-1$
                + marker, t));
        return null;
    }
}

From source file:org.eclipse.mylyn.internal.java.ui.JavaUiBridge.java

License:Open Source License

@Override
public void close(IInteractionElement node) {
    try {/* ww  w.j a  v a  2s  .c  om*/
        IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        if (page != null) {
            List<IEditorReference> toClose = new ArrayList<IEditorReference>(4);
            for (IEditorReference reference : page.getEditorReferences()) {
                try {
                    IJavaElement input = (IJavaElement) reference.getEditorInput()
                            .getAdapter(IJavaElement.class);
                    if (input != null && node.getHandleIdentifier().equals(input.getHandleIdentifier())) {
                        toClose.add(reference);
                    }
                } catch (PartInitException e) {
                    // ignore
                }
            }
            if (toClose.size() > 0) {
                page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
            }
        }
    } catch (Throwable t) {
        StatusHandler
                .log(new Status(IStatus.ERROR, JavaUiBridgePlugin.ID_PLUGIN, "Could not auto close editor", t)); //$NON-NLS-1$
    }
}

From source file:org.eclipse.mylyn.internal.monitor.monitors.SelectionMonitor.java

License:Open Source License

@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    String structureKind = InteractionEvent.ID_UNKNOWN;
    String obfuscatedElementHandle = InteractionEvent.ID_UNKNOWN;
    String elementHandle = InteractionEvent.ID_UNKNOWN;
    InteractionEvent.Kind interactionKind = InteractionEvent.Kind.SELECTION;
    if (selection instanceof StructuredSelection) {
        StructuredSelection structuredSelection = (StructuredSelection) selection;
        Object selectedObject = structuredSelection.getFirstElement();
        if (selectedObject == null)
            return;
        if (selectedObject instanceof IJavaElement) {
            IJavaElement javaElement = (IJavaElement) selectedObject;
            structureKind = "java:" + javaElement.getClass();
            elementHandle = javaElement.getHandleIdentifier();
            obfuscatedElementHandle = obfuscateJavaElementHandle(javaElement);
            lastSelectedElement = javaElement;
        } else {/*from  ww w  . j  a v a 2 s  . c o m*/
            structureKind = InteractionEvent.ID_UNKNOWN + ": " + selectedObject.getClass();
            if (selectedObject instanceof IAdaptable) {
                IResource resource = (IResource) ((IAdaptable) selectedObject).getAdapter(IResource.class);
                if (resource != null) {
                    obfuscatedElementHandle = obfuscator
                            .obfuscateResourcePath(resource.getProjectRelativePath());
                }
            }
        }
    } else {
        if (selection instanceof TextSelection && part instanceof JavaEditor) {
            TextSelection textSelection = (TextSelection) selection;
            IJavaElement javaElement;
            try {
                javaElement = SelectionConverter.resolveEnclosingElement((JavaEditor) part, textSelection);
                if (javaElement != null) {
                    structureKind = "java:" + javaElement.getClass();
                    obfuscatedElementHandle = obfuscateJavaElementHandle(javaElement);
                    elementHandle = javaElement.getHandleIdentifier();
                    if (javaElement != null && javaElement.equals(lastSelectedElement)) {
                        interactionKind = InteractionEvent.Kind.EDIT;
                    }
                    lastSelectedElement = javaElement;
                }
            } catch (JavaModelException e) {
                // ignore unresolved elements
            }
        } else if (part instanceof EditorPart) {
            EditorPart editorPart = (EditorPart) part;
            IEditorInput input = editorPart.getEditorInput();
            if (input instanceof IPathEditorInput) {
                structureKind = "file";
                obfuscatedElementHandle = obfuscator
                        .obfuscateResourcePath(((IPathEditorInput) input).getPath());
            }
        }
    }
    IMylarElement node = ContextCorePlugin.getContextManager().getElement(elementHandle);
    String delta = "";
    float selectionFactor = MylarContextManager.getScalingFactors().get(InteractionEvent.Kind.SELECTION)
            .getValue();

    // XXX: broken in 0.4?
    if (node != null) {
        if (node.getInterest().getEncodedValue() <= selectionFactor
                && node.getInterest().getValue() > selectionFactor) {
            delta = SELECTION_PREDICTED;
        } else if (node.getInterest().getEncodedValue() < selectionFactor
                && node.getInterest().getDecayValue() > selectionFactor) {
            delta = SELECTION_DECAYED;
        } else if (node.getInterest().getValue() == selectionFactor
                && node.getInterest().getDecayValue() < selectionFactor) {
            delta = SELECTION_NEW;
        } else {
            delta = SELECTION_DEFAULT;
        }
    }

    InteractionEvent event = new InteractionEvent(interactionKind, structureKind, obfuscatedElementHandle,
            part.getSite().getId(), "null", delta, 0);
    ContextCore.notifyInteractionObserved(event);
}

From source file:org.eclipse.mylyn.internal.monitor.monitors.SelectionMonitor.java

License:Open Source License

private String obfuscateJavaElementHandle(IJavaElement javaElement) {
    try {//from   w w w .j ava2s  . com
        StringBuffer obfuscatedPath = new StringBuffer();
        IResource resource;
        resource = (IResource) javaElement.getUnderlyingResource();
        if (resource != null && (resource instanceof IFile)) {
            IFile file = (IFile) resource;
            obfuscatedPath.append(obfuscator.obfuscateResourcePath(file.getProjectRelativePath()));
            obfuscatedPath.append(':');
            obfuscatedPath.append(obfuscator.obfuscateString(javaElement.getElementName()));
            return obfuscatedPath.toString();
        } else {
            return obfuscator.obfuscateString(javaElement.getHandleIdentifier());
        }
    } catch (JavaModelException e) {
        // ignore non-existing element
    }
    return ID_JAVA_UNKNOWN;
}