Example usage for org.aspectj.bridge ISourceLocation getLine

List of usage examples for org.aspectj.bridge ISourceLocation getLine

Introduction

In this page you can find the example usage for org.aspectj.bridge ISourceLocation getLine.

Prototype

int getLine();

Source Link

Usage

From source file:de.zalando.mojo.aspectj.MavenMessageHandler.java

License:Open Source License

/**
 * Copies output from the supplied message onto the active Maven Log.
 * If the message type (i.e. {@code message.getKind()}) is listed in the showDetailsForMessageKindList List,
 * the message is prefixed with location details (Class, row/line number etc.) as well.
 * <p/>//from   www  .  j av a2s .  co m
 * {@inheritDoc}
 */
public boolean handleMessage(final IMessage message) {

    // Compose the message text
    final StringBuilder builder = new StringBuilder(message.getMessage());
    if (isMessageDetailDesired(message)) {

        //
        // The AJC details are typically delivered on the format [fileName]:[lineNumber]
        // (i.e. /src/main/java/Clazz.java:16).
        //
        // Mimic this, and include the context of the message as well,
        // including guarding against NPEs.
        //
        final ISourceLocation sourceLocation = message.getSourceLocation();
        final String sourceFile = sourceLocation == null || sourceLocation.getSourceFile() == null
                ? "<unknown source file>"
                : sourceLocation.getSourceFile().getAbsolutePath();
        final String context = sourceLocation == null || sourceLocation.getContext() == null ? ""
                : sourceLocation.getContext() + "\n";
        final String line = sourceLocation == null ? "<no line information>" : "" + sourceLocation.getLine();

        builder.append("\n\t").append(sourceFile).append(":").append(line).append("\n").append(context);
    }

    final String messageText = builder.toString();

    if (isNotIgnored(message, IMessage.DEBUG) || isNotIgnored(message, IMessage.INFO)
            || isNotIgnored(message, IMessage.TASKTAG)) {

        // The DEBUG, INFO, and TASKTAG ajc message kinds are considered Maven Debug messages.
        log.debug(messageText);

    } else if (isNotIgnored(message, IMessage.WEAVEINFO)) {

        // The WEAVEINFO ajc message kind is considered Maven Info messages.
        log.info(messageText);

    } else if (isNotIgnored(message, IMessage.WARNING)) {

        // The WARNING ajc message kind is considered Maven Warn messages.
        log.warn(messageText);

    } else if (isNotIgnored(message, IMessage.ERROR) || isNotIgnored(message, IMessage.ABORT)
            || isNotIgnored(message, IMessage.FAIL)) {

        // We map ERROR, ABORT, and FAIL ajc message kinds to Maven Error messages.
        log.error(messageText);
    }

    // Delegate to normal handling.
    return super.handleMessage(message);
}

From source file:org.caesarj.compiler.asm.StructureModelDump.java

License:Open Source License

protected void printNodeHeader(PrintStream outArg, IProgramElement node) {

    outArg.print("[" + node.getKind() + "] " + node.getName());

    ISourceLocation srcLoc = node.getSourceLocation();
    if (srcLoc != null) {
        outArg.print("(L " + srcLoc.getLine() + ") ");
    }// w  w w .  j  a  v  a 2 s  .  co m
}

From source file:org.caesarj.compiler.asm.StructureModelDump.java

License:Open Source License

protected void printNodeHeader(PrintStream outArg, LinkNode node) {

    if (node.type == LinkNode.LINK_NODE_RELATIONSHIP) {
        outArg.print("[relationship] " + node.getRelationship().getName());
    } else {//from  w  w w  .j  a  v a 2 s .c  o  m
        outArg.print("[link] " + node.getTargetElement().getName());

        ISourceLocation srcLoc = node.getTargetElement().getSourceLocation();
        if (srcLoc != null) {
            outArg.print("(L " + srcLoc.getLine() + ") ");
        }
    }
}

From source file:org.caesarj.compiler.aspectj.CaesarMessageHandler.java

License:Open Source License

/**
 * Handles the (AspectJ) message, by creating a KOPI-error and report it to
 * the compiler./*from   ww  w. ja v a2 s .  c  o  m*/
 */
public boolean handleMessage(IMessage message) throws AbortException {
    if (isIgnoring(message.getKind())) {
        return true;
    }

    ISourceLocation location = message.getSourceLocation();

    if (message.getKind() == IMessage.WARNING) {

        if (location != null) {

            compiler.get()
                    .reportTrouble(new CWarning(
                            new TokenReference(location.getSourceFile().getPath(), location.getSourceFile(),
                                    location.getLine()),
                            new Message(CaesarMessages.ASPECTJ_WARNING, message.getMessage())));
        } else {

            compiler.get().reportTrouble(new CWarning(TokenReference.NO_REF,
                    new Message(CaesarMessages.ASPECTJ_WARNING, message.getMessage())));

        }

        return true;
    }

    if (location != null) {

        compiler.get()
                .reportTrouble(new PositionedError(
                        new TokenReference(location.getSourceFile().getPath(), location.getSourceFile(),
                                location.getLine()),
                        new Message(CaesarMessages.ASPECTJ_ERROR, message.getMessage())));

    } else {

        compiler.get().reportTrouble(new PositionedError(TokenReference.NO_REF,
                new Message(CaesarMessages.ASPECTJ_ERROR, message.getMessage())));

    }

    return true;
}

From source file:org.caesarj.ui.editor.CaesarJContentOutlinePage.java

License:Open Source License

/**
 * This method is called when the user select a node in the content tree.
 * It searches the location of this node and opens it in the editor.
 * /*  w  ww .java 2  s . c  o m*/
 * @see org.eclipse.jface.viewers.ISelectionChangedListener 
 */
public void selectionChanged(SelectionChangedEvent event) {

    super.selectionChanged(event);

    /* ignore the first selection message that comes from initialization */
    /* necessary for navigation by crosscutting links */
    if (bFirstSelection) {
        bFirstSelection = false;
        return;
    }

    ISelection selection = event.getSelection();
    if (selection.isEmpty()) {
    } else {
        Object item = ((IStructuredSelection) selection).getFirstElement();

        if (item instanceof LinkNode) {
            if (((LinkNode) item).getType() == LinkNode.LINK_NODE_RELATIONSHIP) {
                return;
            }
            item = ((LinkNode) item).getTargetElement();
        }

        IProgramElement selectedNode = (IProgramElement) item;
        ISourceLocation sourceLocation = selectedNode.getSourceLocation();

        if (sourceLocation != null) {
            try {

                IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

                IPath path = new Path(sourceLocation.getSourceFile().getAbsolutePath());
                IResource resource = root.getFileForLocation(path);
                IMarker marker;

                if (resource != null) {
                    marker = resource.createMarker(IMarker.MARKER);
                    marker.setAttribute(IMarker.LINE_NUMBER, sourceLocation.getLine());
                    marker.setAttribute(IMarker.CHAR_START, sourceLocation.getColumn());
                    IDE.openEditor(
                            CaesarPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage(),
                            marker);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

From source file:org.eclipse.ajdt.core.javaelements.AJCodeElement.java

License:Open Source License

public void initializeLocations() {
    // try the easy way:
    IProgramElement ipe = AJProjectModelFactory.getInstance().getModelForJavaElement(this)
            .javaElementToProgramElement(this);
    ISourceLocation sloc = ipe.getSourceLocation();
    if (sloc != null) {
        startLine = sloc.getLine();

        nameStart = sloc.getOffset();/*from  w ww.  j  a v  a 2s.  c o  m*/
        if (sloc instanceof EclipseSourceLocation) {
            EclipseSourceLocation esloc = (EclipseSourceLocation) sloc;
            nameEnd = esloc.getEndPos();
        }
    }

    // sometimes the start and end values are not set...so do it the hard way
    // so calculate it from the line
    if (nameStart <= 0 || nameEnd <= 0) {
        try {
            IOpenable openable = this.parent.getOpenableParent();
            IBuffer buffer;
            if (openable instanceof AJCompilationUnit) {
                AJCompilationUnit ajCompUnit = (AJCompilationUnit) openable;
                ajCompUnit.requestOriginalContentMode();
                buffer = openable.getBuffer();
                ajCompUnit.discardOriginalContentMode();
            } else {
                buffer = openable.getBuffer();
            }
            String source = buffer.getContents();

            int lines = 0;
            for (int i = 0; i < source.length(); i++) {
                if (source.charAt(i) == '\n') {
                    lines++;
                    if (lines == startLine - 1) {
                        // starting remove white space
                        i++;
                        while (i < source.length()
                                && (Character.isWhitespace(source.charAt(i)) && source.charAt(i) != '\n')) {
                            i++;
                        }
                        nameStart = i;
                        break;
                    }
                }
            }

            for (int i = nameStart + 1; i < source.length(); i++) {
                if (source.charAt(i) == '\n' || source.charAt(i) == ';') {
                    nameEnd = i - 1;
                    break;
                }
            }

            nameStart = Math.min(nameStart, nameEnd);
        } catch (JavaModelException e) {
        }
    }
}

From source file:org.eclipse.ajdt.core.model.AJProjectModelFacade.java

License:Open Source License

/**
 * Open up the buffer to to convert from line number to offset
 * this is slow/*from  w  ww  . j  a v  a2  s  .  co  m*/
 * We are always working in an AJCU with an aspect element
 * 
 * cache the results since it is likely that we will be 
 * calling this often for the same sloc
 */
private int offsetFromLine(ITypeRoot unit, ISourceLocation sloc) throws JavaModelException {
    if (sloc.getOffset() > 0) {
        return sloc.getOffset();
    }

    if (slocCache != null && slocCache.containsKey(sloc)) {
        return slocCache.get(sloc).intValue();
    }

    if (unit instanceof AJCompilationUnit) {
        AJCompilationUnit ajUnit = (AJCompilationUnit) unit;
        ajUnit.requestOriginalContentMode();
    }
    IBuffer buf = unit.getBuffer();
    if (unit instanceof AJCompilationUnit) {
        AJCompilationUnit ajUnit = (AJCompilationUnit) unit;
        ajUnit.discardOriginalContentMode();
    }
    if (buf != null) {
        int requestedLine = sloc.getLine();
        int currentLine = 1;
        int offset = 0;
        while (offset < buf.getLength() && currentLine < requestedLine) {
            if (buf.getChar(offset++) == '\n') {
                currentLine++;
            }
        }
        while (offset < buf.getLength() && Character.isWhitespace(buf.getChar(offset))) {
            offset++;
        }

        // cache
        if (slocCache == null) {
            slocCache = new HashMap<ISourceLocation, Integer>();
        }
        slocCache.put(sloc, new Integer(offset));
        return offset;
    }
    // no source code
    return 0;
}

From source file:org.eclipse.ajdt.core.model.AJProjectModelFacade.java

License:Open Source License

/**
 * find out what java elements are on a particular line
 *//*from  ww  w.j  a  va2 s  .  co  m*/
public List/*IJavaElement*/<IJavaElement> getJavaElementsForLine(ICompilationUnit icu, final int line) {
    IProgramElement ipe = javaElementToProgramElement(icu);
    final List/*IProgramElement*/<IProgramElement> elementsOnLine = new LinkedList<IProgramElement>();

    // walk the program element to get all ipes on the source line
    ipe.walk(new CancellableHierarchyWalker() {
        protected void preProcess(IProgramElement node) {
            ISourceLocation sourceLocation = node.getSourceLocation();
            if (sourceLocation != null) {
                if (sourceLocation.getEndLine() < line) {
                    // we don't need to explore the rest of this branch
                    cancel();
                } else if (sourceLocation.getLine() == line) {
                    elementsOnLine.add(node);
                }
            }
        }
    });
    // now convert to IJavaElements
    List /*IJavaElement*/<IJavaElement> javaElements = new ArrayList<IJavaElement>(elementsOnLine.size());
    for (Iterator<IProgramElement> ipeIter = elementsOnLine.iterator(); ipeIter.hasNext();) {
        IProgramElement ipeOnLine = ipeIter.next();
        javaElements.add(programElementToJavaElement(ipeOnLine));
    }
    return javaElements;
}

From source file:org.eclipse.ajdt.core.tests.model.AJComparatorTest.java

License:Open Source License

public void testCompareTwoAJCodeElements() {

    // get the class file and create the map for the file (the underlying one)      
    IFile main = aspectjPackage.getFile("Main.java");

    AsmManager asm = AspectJPlugin.getDefault().getCompilerFactory().getCompilerForProject(project.getProject())
            .getModel();//from   ww w. ja v a2s .  co m
    Map annotationsMap = asm.getInlineAnnotations(main.getRawLocation().toOSString(), true, true);
    assertNotNull("annotation map should not be null for Main.java", annotationsMap);
    // for the two IProgramElements which correspond to the two calls
    // in main - create the IJavaElements (or AJCodeElements)
    AJCodeElement ajce1 = null;
    AJCodeElement ajce2 = null;
    Set keys = annotationsMap.keySet();
    for (Iterator it = keys.iterator(); it.hasNext();) {
        Object key = it.next();
        List annotations = (List) annotationsMap.get(key);
        for (Iterator it2 = annotations.iterator(); it2.hasNext();) {
            IProgramElement node = (IProgramElement) it2.next();
            ISourceLocation sl = node.getSourceLocation();
            if (node.toLinkLabelString(false)
                    .equals("Main: method-call(void java.io.PrintStream.println(java.lang.String))")
                    && (sl.getLine() == 23)) {

                IJavaElement ije = model.programElementToJavaElement(node);
                if (ije instanceof AJCodeElement) {
                    ajce1 = (AJCodeElement) ije;
                }
            } else if (node.toLinkLabelString(false)
                    .equals("Main: method-call(void java.io.PrintStream.println(java.lang.String))")
                    && (sl.getLine() == 24)) {

                IJavaElement ije = model.programElementToJavaElement(node);
                if (ije instanceof AJCodeElement) {
                    ajce2 = (AJCodeElement) ije;
                }
            }
        }
    }
    assertNotNull("AJCodeElement shouldn't be null", ajce1);
    assertNotNull("AJCodeElement shouldn't be null", ajce2);

    // check that when call compare on them, that the one with
    // the lowest line number is first in the list
    AJComparator comp = new AJComparator();
    assertTrue("ajce1 should be less than ajce2", comp.compare(ajce1, ajce2) < 0);
    assertTrue("ajce2 should be greater than ajce1", comp.compare(ajce2, ajce1) > 0);
    assertTrue("ajce1 should be equal to ajce1", comp.compare(ajce1, ajce1) == 0);
}

From source file:org.eclipse.ajdt.core.tests.model.AJComparatorTest.java

License:Open Source License

public void testCompareTwoIJavaElements() {

    // get the aspect and create the map for the file (the underlying one)
    IFile aspect = aspectjPackage.getFile("A.aj");

    // for the two IProgramElements which correspond to the two calls
    // in main - create the IJavaElements

    AsmManager asm = AspectJPlugin.getDefault().getCompilerFactory().getCompilerForProject(project.getProject())
            .getModel();/*from   w w w. j a  v  a2s.co m*/
    Map annotationsMap = asm.getInlineAnnotations(aspect.getRawLocation().toOSString(), true, true);
    assertNotNull("annotation map should not be null for Main.java", annotationsMap);
    // for the two IProgramElements which correspond to the two pieces
    // of advice (before and after) in A.aj - create the IJavaElements 
    IJavaElement ije1 = null;
    IJavaElement ije2 = null;
    Set keys = annotationsMap.keySet();
    for (Iterator it = keys.iterator(); it.hasNext();) {
        Object key = it.next();
        List annotations = (List) annotationsMap.get(key);
        for (Iterator it2 = annotations.iterator(); it2.hasNext();) {
            IProgramElement node = (IProgramElement) it2.next();
            ISourceLocation sl = node.getSourceLocation();
            if (node.toLinkLabelString(false).equals("A.after(String): tracedPrint..")
                    && (sl.getLine() == 30)) {

                IJavaElement ije = model.programElementToJavaElement(node);
                if (!(ije instanceof AJCodeElement)) {
                    ije1 = ije;
                }
            } else if (node.toLinkLabelString(false).equals("A.before(String): tracedPrint..")
                    && (sl.getLine() == 26)) {

                IJavaElement ije = model.programElementToJavaElement(node);
                if (!(ije instanceof AJCodeElement)) {
                    ije2 = ije;
                }
            }
        }
    }
    assertNotNull("IJavaElement shouldn't be null", ije1);
    assertNotNull("IJavaElement shouldn't be null", ije2);

    // check that when call compare on them, that the one that comes first
    // alphabetically is the first in the list
    AJComparator comp = new AJComparator();
    assertTrue("ije1 should be less than ije2", comp.compare(ije1, ije2) < 0);
    assertTrue("ije2 should be greater than ije1", comp.compare(ije2, ije1) > 0);
    assertTrue("ije1 should be equal to ije1", comp.compare(ije1, ije1) == 0);

}