Categories
discuss

Discover the class of a methodinvocation in the Annotation Processor for java

I am writing some tools for our build system to enforce some strict calling conventions on methods belonging to classes containing certain annotations.

I’m using the Compiler Tree API…

What i’m wondering is when traversing the ‘tree’, how can you tell the type of class/interface for a MethodInvocation.

I’m subclassing TreePathScanner with :

@Override
public Object visitMethodInvocation(MethodInvocationTree node, Trees trees) {

}

I’m hoping theres a way to tell the type of the class(or interface) that you’re trying to invoke the method on. Am I going about this the wrong way? Thanks for any ideas…

Answer

There are a couple of issues here. You can either be interested in knowing the Java type of the method invocation receiver or just knowing the class on the method is invoked. Java information is more informative as it gives you generic types as well, e.g. List<String> while Elements would only provide you with the class, e.g. List<E>.

Getting the Element

To get the Element of the class the method is invoked on, you can do the following:

  MethodInvocationTree node = ...;
  Element method =
        TreeInfo.symbol((JCTree)node.getMethodSelect());
  TypeElement invokedClass = (TypeElement)method.getEnclosingElement();

Corner cases:

1. invokedClass might be a superclass of the receiver type. So running the snippet on new ArrayList<String>.equals(null) would return AbstractList rather than ArrayList, since equals() is implemented in AbstractList not ArrayList.

2. When handling array invocations, e.g. new int[].clone(), you would get TypeElement of class Array.

Getting the actual type

To get the type, there is no direct way for determining it what the receiver type is. There is some complexity in handling method invocations within inner classes where the receiver is not given explicitly (e.g. unlike OuterClass.this.toString()). Here is a sample implementation:

  MethodInvocationTree node = ...;
  TypeMirror receiver;
  if (methodSel.getKind() == Tree.Kind.MEMBER_SELECT) {
    ExpressionTree receiver = ((MemberSelectTree)methodSel).getExpression();
    receiverType = ((JCTree)receiver).type;
  } else if (methodSel.getKind() == Tree.Kind.IDENTIFIER) {
    // need to resolve implicit this, which is described in
    //  JLS3 15.12.1 and 15.9.2

    // A bit too much work that I don't want to work on now
    // Look at source code of
    //   Attr.visitApply(JCMethodInvocation)
    //   resolveImplicitThis(DiagnosticPosition, Env, Type)
  } else
    throw new AssertionError("Unexpected type: " + methodSel.getKind());

Note:

The receiver type needs to be TypeMirror not DeclaredType unfortunately. When calling new int[5].clone(), receiver would be an ArrayType of int[], which is more informative than the previous method.

Getting it to run

Both of the previous methods require the compiler to resolve the type information for the classes. In usual circumstances, the compiler only resolve the types for method declarations but not the bodies. Hence, the methods described earlier would return null instead.

To have the compiler resolve the type information, you can do one of the following ways:

1. Use AbstractTypeProcessor class that just got added to the compiler repository for JDK 7. Check out the work on JSR 308 and their compiler. While the work is mainly on annotated types, it might be useful for. The compiler allows you to use the provided class in a backward compatible manner with Java 5.

This approach allows you to write processors that get invoked just like your current processors.

2. Use JavacTask instead and call JavacTask.analyze(). Look at the main method of this javac test to see how to invoke your visitor on the classes.

This approach makes your processor look more like an analysis tool rather than a plug-in to the compiler, as you would need to invoke it directly rather than have it be a regular process.

Categories
discuss

Is there a hot key to run the contents of the Firebug Console?

If you’re using Firebug (Firefox) and you type in javascript in the Console command line and press enter it executes. However, for good reason, when you expand the command line into a multi-line text area to the right then pressing enter does not execute the code. Instead you have to click Run at the lower left of this window.

Is there a hot-key/shortcut to run the contents of the command window? (i.e. without mouse clicking.)

Answer

Command + Enter does it for me. (on OS X)

For windows it’s likely Ctrl + Enter.

Categories
discuss

How to mark some code that must be removed before production?

Sometimes for testing/developing purposes we make some changes in the code that must be removed in a production build. I wonder if there is an easy way of marking such blocks so that production build would fail as long as they are present or at least it will warn you during the build somehow.

Simple "//TODO:" doesn’t really work because it is ofter forgotten and mixed with tons of other todos. Is there anything stronger?

Or maybe even if I can create some external txt file and put there instructions on what to do before production, and that ant would check if that file is present then cancel build.

We are using Eclipse/Ant (and java + Spring).

Update: I don’t mean that there are big chunks of code that are different in local and production. In fact all code is the same and should be the same. Just lets say I comment out some line of code to save lot of time during development and forget to uncomment it or something along those lines. I just want to be able to flag the project somehow that something needs an attention and that production build would fail or show a warning.

Answer

You could also just define stronger task comment markers: FIXME (high priority) and XXX (normal priority) are standard in Eclipse, and you could define more task tags (Eclipse Properties -> Java -> Compiler -> Task Tags)

If you want to fail your build, you could use the Ant (1.7) contains file selector to look for files containing specified text:

<target name="fixmeCheck">
  <fail message="Fixmes found">
    <condition>
      <not>
        <resourcecount count="0">
          <fileset dir="${pom.build.sourceDirectory}"
                   includes="**/*.java">
             <contains text="FIXME" casesensitive="yes"/>
          </fileset>
        </resourcecount>
      </not>
    </condition>
  </fail>
</target>

<target name="compile" depends="fixmeCheck">

Obviously, change ${pom.build.sourceDirectory} to your source directory, and FIXME to the comment that you want to search for.

Does anyone know a nice way to print out the files found in this fileset in the build file (other than just looking in Eclipse again)?

Categories
discuss

Inserting a text where cursor is using Javascript/jquery

I have a page with a lot of textboxes. When someone clicks a link, i want a word or two to be inserted where the cursor is, or appended to the textbox which has the focus.

For example, if the cursor/focus is on a textbox saying ‘apple’ and he clicks a link saying ‘[email]’, then i want the textbox to say, ‘apple bob@example.com’.

How can I do this? Is this even possible, since what if the focus is on a radio/dropdown/non textbox element? Can the last focused on textbox be remembered?

Answer

Use this, from here:

function insertAtCaret(areaId, text) {
  var txtarea = document.getElementById(areaId);
  if (!txtarea) {
    return;
  }

  var scrollPos = txtarea.scrollTop;
  var strPos = 0;
  var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
    "ff" : (document.selection ? "ie" : false));
  if (br == "ie") {
    txtarea.focus();
    var range = document.selection.createRange();
    range.moveStart('character', -txtarea.value.length);
    strPos = range.text.length;
  } else if (br == "ff") {
    strPos = txtarea.selectionStart;
  }

  var front = (txtarea.value).substring(0, strPos);
  var back = (txtarea.value).substring(strPos, txtarea.value.length);
  txtarea.value = front + text + back;
  strPos = strPos + text.length;
  if (br == "ie") {
    txtarea.focus();
    var ieRange = document.selection.createRange();
    ieRange.moveStart('character', -txtarea.value.length);
    ieRange.moveStart('character', strPos);
    ieRange.moveEnd('character', 0);
    ieRange.select();
  } else if (br == "ff") {
    txtarea.selectionStart = strPos;
    txtarea.selectionEnd = strPos;
    txtarea.focus();
  }

  txtarea.scrollTop = scrollPos;
}
<textarea id="textareaid"></textarea>
<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>
Categories
discuss

Where do I find a good, short, architecture-oriented introduction to Java Swing GUI for web developerrs?

I’m just starting my first Java Swing project(doing mainly web-based apps before) and try to understand how to build a proper architecture with separation of concerns between the MVC components.

Just about any documentation I find goes very deep into the details of how each and every Swing UI widget works and can be used, but all examples just directly call program logic from a Class that extends, for example, JPanel – which seems odd and no good architecure.

It would be best if that would be IDE-independent, but if such things come into play, it should be said that in the overall project, we have already Eclipse, JFormdesigner and JGoodies in use.

I also see that JSR296 defines a framework that seems to address my concerns. Should I just use something that implements it?

Answer

This is an area of Java programming that is highly under-documented. As you mention, extending from JFrame or JDialog to develop a GUI is not a good design practice, yet you see it all over the place in sample code.

JSR 296 is a useful starting place, but it’s architecture has some serious problems. I do use JSR 296, but I have my own flavor of it, and consistently have to work around issues introduced by the framework design.

I’ve long thought that there should be a discussion group/wiki/something focused on this topic. So far, I’ve found the listserv for various rich client libraries to be useful, but not comprehensive. Something to think about starting maybe, in my free time 🙂

So I can’t provide any definitive resources for best practices in building swing applications. But I can give you some pointers to the toolkits and concepts that I’ve found that I use over and over again. Maybe these will be useful to you as you get going. Also, if enough people are interested in having a discussion about best practices, sharing code, etc… I’d be interested in being part of it.

First, some absolutely critical libraries if you are going to do Swing development:

  1. Binding – there are a number of libraries that do this (JGoodies, JSR295 which has spun off into an open source project called Better Beans Binding (BBB), Eclipse binding framework). I started years ago using JGoodies, but I have moved over to using BBB because I find it’s approach to be more intuitive. I can’t stress the advantages of the declarative coding approach that binding allows for – it will truly revolutionize your code

  2. AppFramework (or some flavor thereof) – JSR 296 is the place to start here. As I mentioned above, it has some problems – if you do use JSR296, I strongly, strongly recommend that you try to avoid using the singleton that is at the core of the framework (other than as a source for injection of the framework components that you actually need).

EDIT – since I wrote this, I’ve started using GUTS in our projects (this is a Guice based app framework – it started life as JSR 296, but has very little in common with it now). GUTS is still a young project, but it’s worth taking a look at if you are considering frameworks.

  1. GlazedLists – if you are doing anything in the UI that involves lists, tables or trees, you should take a hard look at GlazedLists. It’s an incredible project (not just for Swing apps, but it really shines in that arena)

  2. Validation – JGoodies has a very good validation library. Learn it, use it, be one with it. Real time validation is an incredibly important part of a modern Swing app.

  3. MigLayout – The Mig layout manager is the best around. I strongly advise against the temptation of using an IDE GUI builder – learn MigLayout (it will take a couple of hours, tops), and code things up by hand.

So those are the key, absolutely must-have libraries in my book.

Now some concepts:

A. Presentation Model – Martin Fowler has a lot of info on this design pattern. Long and short, it separates behavior from presentation at the GUI level. IF you are used to MVC, Presentation Model adds another layer of separation that is quite important to ‘live’ UIs. All of my views are backed by a corresponding presentation model. The end result is that the view code is really, really simple – focusing on two things: 1. Layout, and 2. Binding view components to the presentation model. That’s it.

B. Views are NOT subclasses of JPanel. Instead, I follow the JGoodies inspired technique of treating the View as a builder that creates JPanels. The basic pattern is:

public class MyView{
  private MyPresentationModel model;

  private JButton okButton;
  private JButton cancelButton;
  ...

  public MyView(MyPresentationModel model){
    this.model = model;
  }

  public JPanel buildView(){
    initComponents(); // this method actually creates the okButton and cancelButton objects
    bindComponentsToModel(); // this method binds those objects to the PresentationModel
    JPanel p = new JPanel(new MigLayout());
    p.add(...);
    ...
    return p;
  }
}

This approach, followed religiously, allows incredibly rapid development of UIs that are easy to maintain. Note that we can use a given View to construct multiple JPanels that are all backed by the same PresentationModel – changes in one panel generated by the view will immediately be visible in another panel generated by the same view.

C. Use Actions not event handlers. JSR 296 actually does a good job of making Actions easy to create and work with.

D. Do long running operations (even something that takes 100ms) off of the EDT. JSR 296 makes this fairly easy with it’s Task support – but there are a number of gotchas in 296’s Task system when it comes to exception handling. If you have property changes that in turn result in long running events, be sure you think carefully about which thread those changes are going to occur on. Using Tasks is a big change to how you do development, but it’s a really important area for any real Swing application – take the time to learn about it.

E. Resource injection is important. Use it from the beginning (instead of telling yourself that you’ll add it later) – if you find yourself calling setText() on a JLabel, it’s time to sit back and call setName() instead, and add an entry to the resources file. JSR 296 makes this pretty easy to do if you are disciplined about it.

I think that’s enough for now – this is a highly complex subject with lot’s of nuance. I’ve spent the past 7 or 8 years banging my head into things that don’t work – and I’m continually finding better ways to do even the things that work well for me.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..