Example usage for org.eclipse.jdt.core ISourceReference getSourceRange

List of usage examples for org.eclipse.jdt.core ISourceReference getSourceRange

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ISourceReference getSourceRange.

Prototype

ISourceRange getSourceRange() throws JavaModelException;

Source Link

Document

Returns the source range associated with this element.

Usage

From source file:ca.uvic.cs.tagsea.extraction.TagExtractor.java

License:Open Source License

/**
 * Gets the tag regions associated with this document, restricted to the given source referece, if no tag regions 
 * are found an empty array is returned//w w w. j  a v a2  s  . c om
 * @param document
 * @param source reference
 * @return Array of tag regions
 */
public static IRegion[] getTagRegions(IDocument document, ISourceReference reference) {
    ISourceRange range;

    try {
        range = reference.getSourceRange();
    } catch (JavaModelException e) {
        TagSEAPlugin.log("", e);
        return new IRegion[0];
    }

    if (range.getOffset() < 0 || range.getOffset() + range.getLength() > document.getLength())
        return new IRegion[0];

    return getTagRegions(document, range.getOffset(), range.getLength());
}

From source file:com.cb.eclipse.folding.java.calculation.AbstractCalculationStrategy.java

License:Open Source License

/**
 * This method finds the ISourceRange object for an IJavaElement
 * //  w w w .  j  a v  a2s  .  c  om
 * @param elem
 * @return @throws
 *         JavaModelException
 */
protected ISourceRange getNaturalRange(IJavaElement elem) throws JavaModelException {
    ISourceReference ref = (ISourceReference) elem;
    return ref.getSourceRange();
}

From source file:com.cb.eclipse.folding.java.calculation.JavaProjectionCalculator.java

License:Open Source License

/**
 * The core logic of this class.//from w w w.j  a  v a  2  s  . c om
 * 
 * Computes using the strategy objects what regions are available as
 * projections for this particular element.
 * 
 * @param elem
 * @return @throws
 *         JavaModelException
 * @throws InvalidInputException
 */
private Set computeProjections(IJavaElement elem) throws JavaModelException, InvalidInputException {
    if (!(elem instanceof ISourceReference))
        return null;

    RegionCalculationStrategy strategy = StrategyFactory.instance(this, elem);
    strategy.initialize();
    Set regionSet;
    if (!strategy.shouldScan(elem)) {
        regionSet = strategy.result(); // call immediately...
    } else {
        ISourceReference reference = (ISourceReference) elem;
        ISourceRange range = reference.getSourceRange();

        // All other element types require some parsing...
        String contents = reference.getSource();

        if (contents == null)
            return null;

        IScanner scanner = ToolFactory.createScanner(true, false, false, false);
        scanner.setSource(contents.toCharArray());

        int shift = range.getOffset();
        int start = shift;

        while (true) {
            int token = scanner.getNextToken();

            start = shift + scanner.getCurrentTokenStartPosition();
            int end = shift + scanner.getCurrentTokenEndPosition() + 1;

            if (!strategy.keepProcessing(token) || token == ITerminalSymbols.TokenNameEOF) {
                break; // end case.
            }

            strategy.handle(token, start, end, elem);

        }

        strategy.postScan(start, elem);

        regionSet = strategy.result();

    }

    if (regionSet == null) {
        regionSet = Collections.EMPTY_SET;
    }

    strategy.dispose();

    return regionSet;

}

From source file:com.cb.eclipse.folding.java.JavaProjectionAnnotation.java

License:Open Source License

private String computeSource() {
    StringBuffer result = new StringBuffer();
    try {//  w  w w  .j a va  2  s  . co  m
        ISourceReference ref = (ISourceReference) owner;
        ISourceRange range = ref.getSourceRange();
        int sourceOffset = range.getOffset();
        int sourceLen = range.getLength();
        int offset = position.getOffset();
        int len = position.getLength();

        offset -= sourceOffset;
        if (offset < 0) {
            offset = 0;
            result.append("Position precedes element!\n");
        }
        if (len > sourceLen) {
            len = sourceLen;
            result.append("Position extends past element!\n");
        }
        if (len < 0) {
            len = 0;
            result.append("Length was less than 0!\n");
        }
        result.append(ref.getSource().substring(offset, offset + len));

    } catch (Exception e) {
        e.printStackTrace();
    }
    return result.toString();

}

From source file:com.github.elucash.lambda4jdt.FoldingStructureProvider.java

License:Open Source License

/**
 * Computes the projection ranges for a given <code>ISourceReference</code>. More than one range
 * or none at all may be returned. If there are no foldable regions, an empty array is returned.
 * <p>/*from   w w w  .j  a va2s .  co m*/
 * The last region in the returned array (if not empty) describes the region for the java element
 * that implements the source reference. Any preceding regions describe javadoc comments of that
 * java element.
 * </p>
 * @param reference a java element that is a source reference
 * @param ctx the folding context
 * @return the regions to be folded
 */
protected final IRegion[] computeProjectionRanges(ISourceReference reference,
        FoldingStructureComputationContext ctx) {
    try {
        ISourceRange range = reference.getSourceRange();
        if (!SourceRange.isAvailable(range))
            return new IRegion[0];

        String contents = reference.getSource();
        if (contents == null)
            return new IRegion[0];

        List<IRegion> regions = new ArrayList<IRegion>();
        if (!ctx.hasFirstType() && reference instanceof IType) {
            ctx.setFirstType((IType) reference);
            IRegion headerComment = computeHeaderComment(ctx);
            if (headerComment != null) {
                regions.add(headerComment);
                ctx.setHasHeaderComment();
            }
        }

        final int shift = range.getOffset();
        IScanner scanner = ctx.getScanner();
        scanner.resetTo(shift, shift + range.getLength());

        int start = shift;
        while (true) {

            int token = scanner.getNextToken();
            start = scanner.getCurrentTokenStartPosition();

            switch (token) {
            case ITerminalSymbols.TokenNameCOMMENT_JAVADOC:
            case ITerminalSymbols.TokenNameCOMMENT_BLOCK: {
                int end = scanner.getCurrentTokenEndPosition() + 1;
                regions.add(new Region(start, end - start));
                continue;
            }
            case ITerminalSymbols.TokenNameCOMMENT_LINE:
                continue;
            }

            break;
        }

        regions.add(new Region(start, shift + range.getLength() - start));

        return regions.toArray(new IRegion[regions.size()]);
    } catch (JavaModelException e) {
    } catch (InvalidInputException e) {
    }

    return new IRegion[0];
}

From source file:com.ibm.research.tagging.java.extractor.WaypointDefinitionExtractor.java

License:Open Source License

/**
 * Gets the tag regions associated with this document, restricted to the given source referece, if no tag regions 
 * are found an empty array is returned/*from  w  w w .  j  a v a2 s  .  co  m*/
 * @param document
 * @param source reference
 * @return Array of tag regions
 */
public static IRegion[] getWaypointRegions(IDocument document, ISourceReference reference) {
    ISourceRange range;

    try {
        range = reference.getSourceRange();
    } catch (JavaModelException e) {
        e.printStackTrace();
        return new IRegion[0];
    }

    if (range.getOffset() < 0 || range.getOffset() + range.getLength() > document.getLength())
        return new IRegion[0];

    return getWaypointRegions(document, range.getOffset(), range.getLength());
}

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

License:MIT License

public List<FindDefinitionResponse.JavaElement> ProcessFindDefinintionRequest(String fileParseContents,
        String typeRootId, int cursorPosition) throws Exception {
    if (ActiveTypeRoots.containsKey(typeRootId)) {
        ITypeRoot cu = ActiveTypeRoots.get(typeRootId);
        cu.getBuffer().setContents(fileParseContents.toCharArray());
        IJavaElement[] elements = cu.codeSelect(cursorPosition, 0);

        List<FindDefinitionResponse.JavaElement> ret = new ArrayList<FindDefinitionResponse.JavaElement>();
        for (IJavaElement element : elements) {
            String definition = element.toString();
            String path = element.getResource() != null ? element.getResource().getLocation().toOSString()
                    : element.getPath().toOSString();
            //String path = element.getPath().makeAbsolute().toOSString(); // element.getPath().toString();

            boolean isAvailable = false;
            int posStart = -1;
            int posLength = 0;
            String contents = null;
            String classFileName = null;
            IClassFile classFileObj = null;

            ISourceReference srcRef = (ISourceReference) element;
            if (srcRef != null) {
                ISourceRange range = srcRef.getSourceRange();
                if (SourceRange.isAvailable(range)) {
                    isAvailable = true;/*from  w ww .j  ava2  s . c o  m*/
                    posStart = range.getOffset();
                    posLength = range.getLength();

                    //if (path.endsWith(".jar"))
                    //{
                    IOpenable op = element.getOpenable();
                    if (op != null && op instanceof IClassFile) {
                        IBuffer buff = op.getBuffer();
                        classFileObj = (IClassFile) op;
                        classFileName = classFileObj.getElementName();
                        contents = buff.getContents();
                    }
                    //}
                }
            }

            FindDefinitionResponse.JavaElement.Builder retItem = FindDefinitionResponse.JavaElement.newBuilder()
                    .setDefinition(definition).setFilePath(path).setHasSource(isAvailable)
                    .setPositionStart(posStart).setPositionLength(posLength);

            if (contents != null) {
                //int hashCode = classFileObj.hashCode();
                String handle = classFileObj.getHandleIdentifier();
                ActiveTypeRoots.put(handle, classFileObj);

                retItem.setFileName(classFileName);
                retItem.setTypeRootIdentifier(TypeRootIdentifier.newBuilder().setHandle(handle).build());
            }
            System.out.println(retItem.toString());
            if (contents != null) {
                retItem.setFileContents(contents);
            }
            ret.add(retItem.build());
        }
        return ret;
    }
    return null;
}

From source file:org.eclim.plugin.jdt.command.junit.JUnitFindTestCommand.java

License:Open Source License

@Override
public Object execute(CommandLine commandLine) throws Exception {
    String projectName = commandLine.getValue(Options.PROJECT_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    int offset = getOffset(commandLine);

    IProject project = ProjectUtils.getProject(projectName);
    IJavaProject javaProject = JavaUtils.getJavaProject(project);
    JUnit4TestFinder finder = new JUnit4TestFinder();

    ICompilationUnit src = JavaUtils.getCompilationUnit(javaProject, file);
    ICompilationUnit result = null;/*from ww w.ja v a2s  . com*/
    if (finder.isTest(src.getTypes()[0])) {
        result = JUnitUtils.findClass(javaProject, src.getTypes()[0]);
        if (result == null) {
            return Services.getMessage("junit.testing.class.not.found");
        }
    } else {
        result = JUnitUtils.findTest(javaProject, src.getTypes()[0]);
        if (result == null) {
            return Services.getMessage("junit.testing.test.not.found");
        }
    }

    IType resultType = result.getTypes()[0];
    String name = resultType.getElementName();
    ISourceReference ref = resultType;
    ISourceRange docRange = resultType.getJavadocRange();

    IJavaElement element = src.getElementAt(offset);
    if (element != null && element.getElementType() == IJavaElement.METHOD) {
        IMethod method = null;
        if (finder.isTest(src.getTypes()[0])) {
            method = JUnitUtils.findClassMethod(result, (IMethod) element);
        } else {
            method = JUnitUtils.findTestMethod(result, (IMethod) element);
        }
        if (method != null) {
            name = method.getElementName();
            ref = method;
            docRange = method.getJavadocRange();
        }
    }

    String lineDelim = result.findRecommendedLineSeparator();
    int docLength = docRange != null ? docRange.getLength() + lineDelim.length() : 0;
    return Position.fromOffset(result.getResource().getLocation().toOSString(), name,
            ref.getSourceRange().getOffset() + docLength, 0);
}

From source file:org.eclim.plugin.jdt.util.TypeUtils.java

License:Open Source License

/**
 * Gets the Position of the suplied ISourceReference.
 *
 * @param type The type./*from   w  w  w . j a  v  a2s .c om*/
 * @param reference The reference.
 * @return The position.
 */
public static Position getPosition(IType type, ISourceReference reference) throws Exception {
    ISourceRange range = reference.getSourceRange();
    return Position.fromOffset(type.getResource().getLocation().toOSString(), null, range.getOffset(),
            range.getLength());
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.SelectionUtil.java

License:Open Source License

public static boolean isEnclosed(IJavaElement _el, int offset, int length) {
    if (!(_el instanceof ISourceReference))
        return false;
    try {/*from  w  w w . j  a  v a2s  . c o m*/
        ISourceReference el = (ISourceReference) _el;
        int end = offset + length;
        int elOffset = ((ISourceReference) el).getSourceRange().getOffset();
        int elEnd = elOffset + el.getSourceRange().getLength();
        return offset <= elOffset && elEnd <= end;
    } catch (JavaModelException e) {
        return false;
    }
}