Wednesday, December 11, 2013

Cyclop - CQL3 web based editor for Cassandra

I've developed web based CQL3 editor:


The idea is, to deploy it once and have simple and comfortable CQL3 interface over web - without need to install anything.
The editor itself supports code completion, not only for CQL syntax, but also based on database content. So for example the select statement will suggest tables from active keyspace, or within where-closure only columns from table provided after "select from"

The results are displayed in reversed table - rows horizontally and columns vertically. It seems to be more natural for column oriented database.

You can also export query results to CSV, or add query as browser bookmark, send it to another developer to share results, tweeter might not be the  best idea ;)

The whole application is based on wicket + bootstrap + spring and can be deployed in any web 3.0 container.

 Here is the project (open source): https://github.com/maciejmiklas/cyclop

Thursday, November 28, 2013

Spring 3 - SpEl solution for non existing optional @Resource injection

@Resource is used to inject resources into Spring beans - like in example below: MyService uses #serverMapping to map server aliases into full names.

  1 public class MyService {
  2
  3     @Resource(name = "serverMappingConf")
  4     private Map<String, String> serverMapping;
  5
  6     public String getFullName(String alias){
  7         return serverMapping.get(alias);
  8     }
  9 }

  1 <beans xmlns=....">
  2
  3      <util:map id="serverMappingConf">
  4          <entry key="serverEU" value="my-domain.eu" />
  5          <entry key="serverUS" value="my-domain.us" />
  6      </util:map>
  7 </beans>

This is not really spectacular, but in some cases it is required to inject null if #serverMappingConf is not defined (optional functionality). This is simple in case of spring bean, because you can use @Autowired(required="false"). But you cannot inject collections of resources using @Autowired - this was discussed in this JIRA case  - autowired would collect all beans of given type and try to inject it (case describes collections, but the same rules apply to maps).

This is the solution:
  1 public class MyService {
  2
  3     @Value("#{getObject('serverMappingConf')}")
  4     private Map<String, String> dcMappingInitial;
  5 }

@Value supports SpEl expressions. SpEl's root object has method getObject(String) which returns spring bean or resource, or null if was not found. We are calling this method with name of our resource - it returns Map<String, String> or null.

Tuesday, October 15, 2013

Wicket 6 - Paging Navigator for Bootstrap 3

Bootstrap has many fine looking themes and web pages based on it's CSS look just great - this is common knowledge.  It's quiet simple to integrate Bootstrap into Wicket application, with maybe few exceptions, like for example Paging Navigator.
The usual solution to this problem would be the adoption of CSS to mach Wickets's HTML structure. I've decided to modify Wicket Paging Navigator to use unmodified Bootstrap CSS.

We will use Bootstrap 3 with Cyborg Theme, the final pager will have following look:


Before we begin, let's point out some key differences between both HTML markups.
Wicket:
<html xmlns:wicket="http://wicket.apache.org">
    <body>
        <wicket:panel>
<a wicket:id="first" class="first">&lt;&lt;</a>
<a wicket:id="prev" class="prev">&lt;</a>
<span wicket:id="navigation" class="goto">
<a wicket:id="pageLink" href="#"><span wicket:id="pageNumber">5</span></a>
</span>
<a wicket:id="next" class="next">&gt;</a>
<a wicket:id="last" class="last">&gt;&gt;</a>
        </wicket:panel>
    </body>
</html>
and corresponding Bootstrap part:
    <ul class="pagination pagination-sm">
        <li class="disabled"><a href="#">«</a></li>
        <li class="active"><a href="#">1</a></li>
        <li><a href="#">2</a></li>
        <li><a href="#">3</a></li>
        <li><a href="#">4</a></li>
        <li><a href="#">5</a></li>
        <li><a href="#">»</a></li>
    </ul>
  • HTML tree structure is completely different. Wicket layouts hyperlinks one after another. Bootstrap wraps them with bulleted list.
  • Some links in pager are not clickable - so for example it's not possible to jump to the last page, if we are already there. Both frameworks solve it differently: wicket changes rendered HTML and replaces a-tag with div-tag. Bootstrap on the other hand side does not modify HTML tree at all, it applies different CSS. But it does not change class-argument directly on a-tag, but on it's parent (li-tag), which even dose not exits in Wicket markup.
  • Current page (nr-1 on picture above, blue rectangle) has also two different indicators: Wicket solves it by replacing hyperlink with div-tag, Bootstrap sets class=active on li-tag.
  • Bootstrap additionally provides focus for onmouseover (gray box) for active links, it comes from class=pagination on ul-tag.
Let's dive into implementation details - we will modify Wicket's AjaxPagingNavigator by replacing it's HTML and corresponding java part. The new component name is: BootstrapPagingNavigator.

BootstrapPagingNavigator.html
<html xmlns:wicket="http://wicket.apache.org">
<body>
<wicket:panel>
    <ul class="pagination pagination-sm">
        <li wicket:id="firstCont" class="disabled"><a wicket:id="first" href="#">&lt;&lt;</a></li>
        <li wicket:id="prevCont" class="disabled"><a wicket:id="prev" href="#">&lt;</a></li>
        <li wicket:id="navigation"><a wicket:id="pageLink" href="#">
            <span wicket:id="pageNumber">1</span></a>
        </li>
        <li wicket:id="nextCont" class="disabled"><a wicket:id="next" href="#">&gt;</a></li>
        <li wicket:id="lastCont" class="disabled"><a wicket:id="last" href="#">&gt;&gt;</a></li>
    </ul>
</wicket:panel>
</body>
</html>
The HTML markup has structure required by Bootstrap's CSS - bulleted list with hyperlinks. All original Wicket tag names are there (red color), plus we have some extra tags in blue.

Lest move into java implementation, it will contain two key modifications: 
  • HTML hyperlinks will not get removed for inactive links - a-tag will be still generated. 
  • Inactivation and activation of links will be handled by dynamic CSS applied to li-tags (blue wicket ids)
The original AjaxPagingNavigator generates three types of links, each one created by different factory method:
  • AjaxPagingNavigator#newNavigation(...) handles: "1 | 2 | 3 | 4"
  • AjaxPagingNavigator#newPagingNavigationLink(...) handles: "first, last"
  • AjaxPagingNavigator#newPagingNavigationIncrementLink(...) handles: "prev, next"
The controller class for our pager (BootstrapPagingNavigator.java) will overwrite each of those methods in order to apply required modifications. Here are the details:

AjaxPagingNavigator#newNavigation ( "1 | 2 | 3 | 4")


  1 public class BootstrapPagingNavigator extends AjaxPagingNavigator {
  2
  3 // .......
  4
  5     @Override
  6     protected PagingNavigation newNavigation(String id, IPageable pageable, 
  7         IPagingLabelProvider labelProvider) {
  8         return new AjaxPagingNavigation(id, pageable, labelProvider) {
  9             @Override
 10             protected LoopItem newItem(int iteration) {
 11                 LoopItem item = super.newItem(iteration);
 12
 13                 // add css for enable/disable link
 14                 long pageIndex = getStartIndex() + iteration;
 15                 item.add(new AttributeModifier("class"new PageLinkCssModel(pageable, 
 16                     pageIndex, "active")));
 17
 18                 return item;
 19             }
 20         };
 21     }
 22
 23 // .......
 24 }

The newNavigation(....) method (line 6) generates links for page numbers: "1 | 2 | 3 | 4". The only thing that needs to be changed here is the indication of current page - it's a disabled link on a blue background.
This can be done by applying active class to li-tag (not the hyperlink itself):
<li wicket:id="navigation" class="active">
    <a wicket:id="pageLink" href="#"><span wicket:id="pageNumber">1</span></a>
</li>
The HTML above is the modified version for Bootstrap. When compared to original Wicket HTML, the li-tag was replaced by div (wicket:id="navigation"), and class="active" is used to indicate current page.

The replacement of li-tag with div does not require adoption of java code because wicket uses WebMarkupContainer, which is compatible with both tags.

The assignment of dynamic CSS to li-tag (wicket:id="navigation") takes place in method newItem(...)  (line 15 class above). Each link with page number is generated as LoopItem, and applied CSS will change class-argument to active for current page - this will deactivate link, remove onmouseover highlighting, and change background to blue.
Here comes  the model for our dynamic CSS:

  1 class PageLinkCssModel implements IModel<String>, Serializable {
  2
  3     private final long pageNumber;
  4
  5     protected final IPageable pageable;
  6
  7     private final String css;
  8
  9     public PageLinkCssModel(IPageable pageable, long pageNumber, String css) {
 10         this.pageNumber = pageNumber;
 11         this.pageable = pageable;
 12         this.css = css;
 13     }
 14
 15     @Override
 16     public String getObject() {
 17         return isSelected() ? css : "";
 18     }
 19
 20     @Override
 21     public void setObject(String object) {
 22     }
 23
 24     @Override
 25     public void detach() {
 26     }
 27
 28     public boolean isSelected() {
 29         return getPageNumber() == pageable.getCurrentPage();
 30     }
 31
 32     private long getPageNumber() {
 33         long idx = pageNumber;
 34         if (idx < 0) {
 35             idx = pageable.getPageCount() + idx;
 36         }
 37
 38         if (idx > (pageable.getPageCount() - 1)) {
 39             idx = pageable.getPageCount() - 1;
 40         }
 41
 42         if (idx < 0) {
 43             idx = 0;
 44         }
 45
 46         return idx;
 47     }
 48
 49 }

AjaxPagingNavigator#newPagingNavigationLink ("first, last")


  1 public class BootstrapPagingNavigator extends AjaxPagingNavigator {
  2
  3     @Override
  4     protected AbstractLink newPagingNavigationLink(String id,
  5       IPageable pageable, int pageNumber) {
  6         ExternalLink navCont = new ExternalLink(id + "Cont", (String) null);
  7
  8         // add css for enable/disable link
  9         long pageIndex = pageable.getCurrentPage() + pageNumber;
 10         navCont.add(new AttributeModifier("class", new PageLinkCssModel(pageable,
 11            pageIndex, "disabled")));
 12
 13         // change original wicket-link, so that it always generates href
 14         navCont.add(new AjaxPagingNavigationLink(id, pageable, pageNumber) {
 15             @Override
 16             protected void disableLink(ComponentTag tag) {
 17             }
 18         });
 19         return navCont;
 20     }

and corresponding markup:
<wicket:panel>
    <ul class="pagination pagination-sm">
        <li wicket:id="firstCont" class="disabled"><a wicket:id="first" href="#">&lt;&lt;</a></li>
       ........
        <li wicket:id="lastCont" class="disabled"><a wicket:id="last" href="#">&gt;&gt;</a></li>
    </ul>
</wicket:panel>
For the first- and last-links we need to change they way how they are being deactivated. The HTML above is already modified for Bootstrap - the original had only hyperlinks (red wicket ids), now they are wrapped by ul/li-tags.
From java code perspective, the AjaxPagingNavigator#newPagingNavigationLink(...) method would return AjaxPagingNavigationLink directly, and it would replace href elements with div for inactive links. We need however only to apply different CSS on li-tag (which does not exits in original wicket code), and not on hyperlink itself. This CSS will take care of deactivation and also disable highlighting for onmouseover.
The overwritten method newPagingNavigationLink(...) in line 4 returns AbstractLink, but we rather need li-tag. The solution is to return ExternalLink that points to nowhere - it will contain the original link as child. The names for our new tag:  firstCont and lastCont are dynamically generated from name of original link.  This gives us dynamic li-tag, which is required, because we want to change its style.
In line 10 we are registering dynamic CSS on it, which will set class="disabled" if pager is already on first, or respectively last page.
In line 14 we create the original link, that would be returned by unmodified newPagingNavigationLink(...) method. But of course we have to add this link to #navCont in order to mach changed HTML structure.
The method disableLink(...) remains empty, to prevent wicket from replacing a-tag with div-tag.


AjaxPagingNavigator#newPagingNavigationIncrementLink ("prev, next")


Links for next and previous page are crated analogous to first/last links described above. The only difference is the CSS model, which disables link when first  or last page is active.

  1 public class BootstrapPagingNavigator extends AjaxPagingNavigator {
  2
  3     @Override
  4     protected AbstractLink newPagingNavigationIncrementLink(String id,
  5           IPageable pageable, int increment) {
  6         ExternalLink navCont = new ExternalLink(id + "Cont", (String) null);
  7
  8         // add css for enable/disable link
  9         long pageIndex = pageable.getCurrentPage() + increment;
 10         navCont.add(new AttributeModifier("class",
 11              new PageLinkIncrementCssModel(pageable, pageIndex)));
 12
 13         // change original wicket-link, so that it always generates href
 14         navCont.add(new AjaxPagingNavigationIncrementLink(id, pageable, increment) {
 15             @Override
 16             protected void disableLink(ComponentTag tag) {
 17             }
 18         });
 19         return navCont;
 20     }
 21 }

  1 public class PageLinkIncrementCssModel implements IModel<String>, Serializable {
  2
  3     protected final IPageable pageable;
  4
  5     private final long pageNumber;
  6
  7     public PageLinkIncrementCssModel(IPageable pageable, long pageNumber) {
  8         this.pageable = pageable;
  9         this.pageNumber = pageNumber;
 10     }
 11
 12     @Override
 13     public String getObject() {
 14         return isEnabled() ? "" : "disabled";
 15     }
 16
 17     @Override
 18     public void setObject(String object) {
 19     }
 20
 21     @Override
 22     public void detach() {
 23     }
 24
 25     public boolean isEnabled() {
 26         if (pageNumber < 0) {
 27             return !isFirst();
 28         } else {
 29             return !isLast();
 30         }
 31     }
 32
 33     public boolean isFirst() {
 34         return pageable.getCurrentPage() <= 0;
 35     }
 36
 37     public boolean isLast() {
 38         return pageable.getCurrentPage() >= (pageable.getPageCount() - 1);
 39     }
 40 }



You can download source code here.

Wednesday, September 25, 2013

Wicket 6 - Disable Page Serialization

In some cases it makes sense to disable Page Serialization, this can be archived by registering empty Page Store:

public class WicketWebApplication extends WebApplication {

    @Override 
    public Class<? extends Page> getHomePage() {
        return CqlCommanderPage.class; 
    } 

    @Override 
    protected void init() {
        super.init(); 
        setPageManagerProvider(new NoSerializationPageManagerProvider(this));
    } 
}
public class NoSerializationPageManagerProvider extends DefaultPageManagerProvider {

    public NoSerializationPageManagerProvider(Application application) {
        super(application); 
    } 

    @Override 
    protected IPageStore newPageStore(IDataStore dataStore) { 
        return new IPageStore() {
            @Override 
            public void destroy() {
            } 

            @Override 
            public IManageablePage getPage(String sessionId, int pageId) {
                return null;
            } 

            @Override 
            public void removePage(String sessionId, int pageId) {
            } 

            @Override 
            public void storePage(String sessionId, IManageablePage page) {
            } 

            @Override 
            public void unbind(String sessionId) {
            } 

            @Override 
            public Serializable prepareForSerialization(String sessionId, Object page) {
                return null;
            } 

            @Override 
            public Object restoreAfterSerialization(Serializable serializable) {
                return null;
            } 

            @Override 
            public IManageablePage convertToPage(Object page) {
                return null;
            } 
        }; 

    } 
}

Wednesday, July 17, 2013

Spring 3.1 - Programmatic access to Properties managed by Property Placeholder

Spring follows Inversion Of Control approach, this means that we can simply inject particular property into POJO. But there are some cases, when you would like to access property given by name directly from your code - some might see it as anti-pattern - this is palpably true, but lets concentrate on how to do it.
The PropertiesAccessor below provides access to properties loaded by Property Placeholder and encapsulates container specific stuff. It also caches found properties because call on AbstractBeanFactory#resolveEmbeddedValue(String) is not cheap.
@Named
public class PropertiesAccessor {

    private final AbstractBeanFactory beanFactory;

    private final Map<String,String> cache = new ConcurrentHashMap<>();

    @Inject
    protected PropertiesAccessor(AbstractBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public  String getProperty(String key) {
        if(cache.containsKey(key)){
            return cache.get(key);
        }

        String foundProp = null;
        try {
            foundProp = beanFactory.resolveEmbeddedValue("${" + key.trim() + "}");
            cache.put(key,foundProp);
        } catch (IllegalArgumentException ex) {
           // ok - property was not found
        }

        return foundProp;
    }
}

Saturday, June 8, 2013

Linux - search for text occurrences in files specified by pattern

Script below searches for files given by pattern (*.java)  containing given key word (case insensitive). It starts from current directory and goes over all sub-directories.
Produced output is divided into sections - one per matching file.
Each section lists key word occurrences within particular file, inclusive line numbers and highlighting.

Create file "se" with following content:
#!/bin/sh
find ${PWD} -name $1  -exec grep --color='auto' -ni $2 '{}' \; -printf '\n\n\n%h-%f\n'

Now in order to find *.java files containing text "nullpointer" execute:
se *.java nullpointer

search result could look like this one:


Thursday, February 7, 2013

Efficient mapping of Java Enums

The idea is to create Enum out of some other type like string or int - this is the method valueOfRole in examples below. I've seen few code examples which are based on this approach:
public enum RoleWithLoop {
    SU(0), ADMIN(1), USER(1000);

    private final int state;

    RoleWithLoop(int state) {
        this.state = state;
    }

    public static RoleWithLoop valueOfRole(int state) {
        for (RoleWithLoop role : RoleWithLoop.values()) {
            if (role.state == state) {
                return role;
            }
        }
        return null;
    }
}
Each mapping call iterates over all Enum entries - this is fine if it contains only few elements. But more efficient solution is to use Map lookup instead of loop:
public enum RoleWithMap {
    SU(0), ADMIN(1), USER(1000);

    private final int state;

    private final static Map<Integer, RoleWithMap> MAPPING = 
          new HashMap<Integer, RoleWithMap>(RoleWithMap.values().length);
    RoleWithMap(int state) {
        this.state = state;
    }

    static {
        for (RoleWithMap role : RoleWithMap.values()) {
            MAPPING.put(role.state, role);
        }
    }

    public static RoleWithMap valueOfRole(int state) {
        return MAPPING.get(state);
    }
}