Wednesday, August 9, 2017

Grep for dummies

I always have problems with grep as I don't use it enough to remember all the options. I found a useful answer on stack overflow

grep -rnw -e 'pattern' '/path/to/somewhere/' 
  • -r or -R is recursive,
  • -n is line number, and
  • -w stands for match the whole word.
  • -l (lower-case L) can be added to just give the file name of matching files.
  • /path/to/somewhere/ can be just  .  for current directory

  • Along with these, --exclude--include--exclude-dir or --include-dir flags could be used for efficient searching:
  • This will only search through those files which have .c or .h extensions:
    grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
    
  • This will exclude searching all the files ending with .o extension:
grep --exclude=*.o -rnw '/path/to/somewhere/' -e "pattern"
  • Just like exclude files, it's possible to exclude/include directories through --exclude-dir and --include-dir parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"

Friday, July 21, 2017

Getting started with Ansible

If you try to get started with Ansible you will probably be disappointed!
You will see tutorial explaining that you need a host file located at /etc/ansible/hosts, that you need to connect with ssh.

But what do you really want to start with?
Experiment locally, on your local machine. And that is not described in these tutorials :(

Luckily, I found a blog @mechanicalfish which explains exactly how to start.

The Shortest Path To Using Ansible
A One-Line Configuration

$ ansible all -i 'localhost,' -c local -m ping

Let’s take our one-liner apart. Could we make it shorter or simpler?
  • ansible is the command which runs one task at a time all tells Ansible to run this task on all the hosts in the inventory.
  • -i localhost, …is a trick, to avoid the need to make an inventory file. -i means “here is the pathname of the inventory file”. But ansible has a poorly-documented bonus feature: Instead of a path, we can choose to provide a list of host names, each of which names a computer on the network. And our list can have just one entry, localhost. (The weird extra comma after localhost is vital; do not leave it out. It tells Ansible that this is a list of hosts and not a pathname.)
  • -c local is shorthand for --connection=local. It tells Ansible not to try to use SSH to contact the hosts, but to run tasks on our local computer instead. Ansible uses SSH by default, because usually it’s running tasks on faraway machines in the cloud. However, it’s common to encounter problems when connecting to your own computer via SSH, and fixing these problems without impairing your security is tricky and not worth the effort.
  • Finally, -m means “use this Ansible module”, and ping is the name of the module. The ping module contacts the host and proves that it’s listening.

I would recommend the reading of the post, as there are more details in it :).
Thank you Mechanical Fish for this post.



Once this is read I would check the following tutorial by black sail division
Part 1
Part 2
Part 3


Wednesday, June 14, 2017

Not so well known IntelliJ keyboard sortcuts

IntelliJ is well known for its heavy use of keyboard shortcuts.
Many times you don't even know that a shortcut exists.

This blog shows how to refactor maven's pom.xml
https://blog.jetbrains.com/idea/2010/04/maven-refactorings-introduce-property/

Select the dependency version then:
Ctrl-Alt-V (Extract property) 
will introduce a version property.

Thursday, March 16, 2017

IntelliJ on Ubuntu the false promises

I guess every one who develops with IntelliJ on Ubuntu is disappointed that the keyboard shortcuts do not work as they should.
The problem is that Ubuntu (Linux in general) maps a lot of keyboard shortcuts.

Here is the list of keyboard shortcut doing problems but that I do need in IntelliJ:
  • Ctrl+Alt+Left/Right : back in IntelliJ
  • Ctrl+Alt+L : reformat code
  • Alt+F7 : find usage
  • Alt+F8 : evaluate expression
  • Ctrl+Alt+S : settings dialog
  • Alt+Mouse Button 1 : Block selection
  • Ctrl+Shift+U : to uppercase
  • Alt+F1 : select in

First if you are working in a virtual machine like VmWare

Ctrl+Alt+Left is most probably used to switch between vm. So is you are using VmWare navigate to and change the combination
  • VmWare: Edit->preferences->hot keys

Some of these can be changed in Ubuntu keyboard settings

For these I used to remove the settings in Ubuntu.
  • Ctrl+Alt+L : settings->keyboard->shortcuts->system->lock screen
  • Alt+F7 : settings->keyboard->shortcuts->windows->move window
  • Alt+F8 : settings->keyboard->Windows->resize window 
  • Ctrl+Alt+S : settings->keyboad->windows-> toggle shade state

Some can be set at other places in the gui.

In the dconf editor: 
  • Alt+Mouse Button 1 /org/gnome/desktop/wm/preferences/mouse-button-modifier
    You can't just disable the key, you must assign it to something fancy like Ctrl+Alt+Shift+Super+Escape
This one is still at another location

The interesting part is that some of these can be changed on the console:

Changing keyboard shortcut from the command line

In order to have the complete list of shortcut available, try this command
gsettings list-recursively

Which gives us the following commands
  • Ctrl+F8 : gsettings set org.gnome.desktop.wm.keybindings begin-resize "['disabled']"
  • Ctrl+Alt+S : gsettings set org.gnome.desktop.wm.keybindings toggle-shaded "['disabled']"
  • Ctrl+Alt+L: dconf write /org/gnome/desktop/screensaver/lock-enabled false
  • Alt+Mouse Button 1: gsettings set org.gnome.desktop.wm.preferences mouse-button-modifier "['Escape']"
  • Ctrl+Alt+Right : gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-right "['disabled']"
  • Ctrl+Alt+Left : gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-left "['disabled']"

Ansible

We can take this a step further and use ansible.
By putting this script in a file: e..g, main.yml in ubuntu/tasks folder, with a hosts file containing 

hosts file
[localhost]

localhost ansible_user=dev ansible_connection=local

playbook.yml file
- hosts: localhost
  roles:
  - intellij

  - ubuntu

note that the initellij task do some additional configuration. like a quick list config etc.

Finally the following command should do the trick:

ansible-playbook -i hosts playbook.yml

- name: disable screen lock see http://xmodulo.com/control-screen-lock-settings-linux-desktop.html
  command: dconf write /org/gnome/desktop/screensaver/lock-enabled false
  tags: [ubuntu]

- name: disable mouse-button-modifier do not disable dconf Editor key /org/gnome/desktop/wm/preferences/mouse-button-modifier
  command: gsettings set org.gnome.desktop.wm.preferences mouse-button-modifier "['Escape']"
  tags: [ubuntu]

- name: disable keyboard->Navigation->switch workspace org.gnome.desktop.wm.keybindings switch-to-workspace-right ['Right']
  command: gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-right "['disabled']"
  tags: [ubuntu]

- name: disable keyboard->Navigation->switch workspace org.gnome.desktop.wm.keybindings switch-to-workspace-left ['left']
  command: gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-left "['disabled']"
  tags: [ubuntu]

- name: disable keyboard->Windows->resize window | evaluate expression org.gnome.desktop.wm.keybindings begin-resize ['F8']
  command: gsettings set org.gnome.desktop.wm.keybindings begin-resize "['disabled']"
  tags: [ubuntu]

- name: disable S shortcut. keyboad->windows-> toggle shade state
  command: gsettings set org.gnome.desktop.wm.keybindings toggle-shaded "['disabled']"

  tags: [ubuntu]

Short cut to change in IntelliJ

 - The Navigate -> Select in shortcut is normally mapped to Alt-F1 which I do not want to unmap in Ubuntu. So I add another shortcut in IntelliJ

File->Settings->Keymap->Main menu->Navigate->Select In 
And I give the short cut: Ctrl-§

References

Alt+Left Button  see http://askubuntu.com/questions/118151/how-do-i-disable-window-move-with-alt-left-mouse-button-in-gnome-shell
I don't know how to deactivate Alt+F1 so I have to change the mapping in IntelliJ
check this post : http://askubuntu.com/questions/412046/unable-to-use-intellij-idea-keyboard-shortcuts-on-ubuntu



Thursday, June 2, 2016

Display the value of a property with Maven

Sometime you need to know the value of a property in you maven scripts.
This happend to me when there were to many profiles.

So can just write the value of a property.
Add this plugin definintion in you build section
et voilà


<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-antrun-plugin</artifactId>
  <version>1.1</version>
  <executions>
    <execution>
      <phase>validate</phase>
      <goals>
        <goal>run</goal>
      </goals>
      <configuration>
       <tasks>
         <echo>Displaying value of 'myProperty' property</echo>
         <echo>[myProperty] ${myProperty}</echo>
       </tasks>
      </configuration>
    </execution>
  </executions>
</plugin>

Thank you http://www.avajava.com/tutorials/lessons/how-do-i-display-the-value-of-a-property.html

Tuesday, April 5, 2016

Accessing an in-memory H2 Database

Some times while trying to understand what is going on in your unit tests, you might want to see what is written in an in-memory H2 database.
You can do this :)

You have to start a server in your test.

Server.createWebServer("-web", "-webAllowOthers", "-webPort", "8082").start();

and you can then access the db via a web browser at following address: http://localhost:8082/ In order to access the db you will have to stop your unit test thread. Do something like

boolean sleep = true;
while(sleep)
    Thread.sleep(10000);

This will allow you to connect to the db.

Friday, January 29, 2016

Decorator Pattern with Spring

The decorator pattern is well known and described.
See for example https://en.wikipedia.org/wiki/Decorator_pattern

 The question is how can we implement easily the pattern with Spring.

 Lets just do an example.
 We have a SearchService which can be configuratively be switch on or off.

We have a simple interface
public interface SearchService{
    List find(Param p);
}
and a simple implementation
@Component
public class DefaultSearchService implements SearchService{
    public List find(Param p){
        repository.find(p);
    }
}
Our decorator logically implements the SearchService interface as well
@Component
public class SearchServiceDecorator implements SearchService{

    private final SearchService searchService;
    private final Config config;

    @Autowired
    public SearchServiceDecorator(SearchService searchService, Config config){
        this.searchService = searchService;
    }

    public List find(Param p){
        if(config.allowed())
            searchSerice.find(p);
    }
}
This will obviously not work. Spring cannot decide which version of SearchService to use. The solution is quite elegant:
@Component
@Primary
public class SearchServiceDecorator implements SearchService{

    private final SearchService searchService;
    private final Config config;

    @Autowired
    public SearchServiceDecorator(@Named("defaultSearchService")SearchService searchService, Config config){
        this.searchService = searchService;
    }

    public List find(Param p){
        if(config.allowed())
            searchSerice.find(p);
    }
}
The @Primary annotation, according to its Javadoc "Indicates that a bean should be given preference when multiple candidates * are qualified to autowire a single-valued dependency." The @Named allows to inject the decorator chain. Thats it :)

Wednesday, October 7, 2015

JavaFx with Spring Boot

I guess I'm not the only one trying to make JavaFx application with Spring Boot. I ended up with the best summary I could find to date (http://stackoverflow.com/questions/28804012/javafx-fxml-how-to-use-spring-di-with-nested-custom-controls) I will only put it here so I can find it again quickly :)
@SpringBootApplication
public class FxBootApplication extends Application {
    private static String[] args;

    public static void main(String[] args) {
        FxBootApplication.args = args;
        launch(args);
    }

    @Override
    public void start(final Stage primaryStage) {

        // Bootstrap Spring context here.
        ApplicationContext context = SpringApplication.run(FxBootApplication.class, args);

        // Create a Scene
        MainPaneController mainPaneController = context.getBean(MainPaneController.class);
        Scene scene = new Scene((Parent) mainPaneController.getRoot());

        // Set the scene on the primary stage
        primaryStage.setScene(scene);
        // Any other shenanigans on the primary stage...
        primaryStage.show();
    }
}
@Configuration
public class ApplicationConfiguration {

    @Bean
    public MainPaneController mainPaneController() throws IOException {
        return loadController(MainPaneController.VIEW);
    }

    private  T loadController(String url) throws IOException {
        try (InputStream fxmlStream = getClass().getResourceAsStream(url)) {
            FXMLLoader loader = new FXMLLoader();
            loader.load(fxmlStream);
            return loader.getController();
        }
    }
}
public class MainPaneController {
    public static final String VIEW = "/MainPanel.fxml";

    @FXML
    private Node root;
   
    @PostConstruct
    public void init() {}

    public Node getRoot() {
        return root;
    }
}

Wednesday, February 11, 2015

Tomcat context.xml

You may want to have a context.xml file uner your vcs.
You might have some config in there e.g.

Context
   Environment name="jsf/ProjectStage" override="true" type="java.lang.String" value="Development"
   
   Manager className='org.apache.catalina.session.PersistentManager'/
      Store className='org.apache.catalina.session.FileStore'/
   /Manager
/Context

You can then publish this file with IntelliJ
 Edit Configuration... -> Deployment -> Edit Artifact -> Add file
 The context.xml file must reside in META-INF/context.xml

Tomcats Infamous “SEVERE: Error listenerStart”

I refere to this http://java.dzone.com/articles/tomcat-6-infamous-%E2%80%9Csevere article to solve the logging problem. So if you need more logging from your tomcat server "just" create a “logging.properties” file under your”/WEB-INF/classes” folder of your WAR and you’re all set.
org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler
If your are working with IntelliJ, you can add the file Edit Configuration... -> Deployment -> Edit Artifact -> Add file

Monday, December 9, 2013

adding jsf2 facet to eclipse

Ever tried to intall jsf 2 facet in Eclipse and go the following error?

Failed while installing JavaServer Faces 2.0.
org.osgi.service.prefs.BackingStoreException: Resource '/projectName/.settings' does not exist.

Don't give up hope. As you do not have the option to use a better IDE you can still edit the files by hand.

 open the file :  "org.eclipse.wst.common.project.facet.core.xml" located in the .settings directory and add:
 <installed facet="jst.jsf" version="2.0"> </installed>
That should do the trick

Thursday, February 16, 2012

Disable session saving in tomcat

When starting Tomcat you may have such an error:



Feb 16, 2012 10:24:15 AM org.apache.catalina.session.StandardManager doLoad
SEVERE: IOException while loading persisted sessions:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException:


If you are developing and changing your code regularly, it is most annoying. The easiest is to convince tomcat not to persist sessions across Tomcat restarts.

1. Got to file: context.xml (in eclipse, you find it under Serves->tomcat v7.0 at localhost. or something equivalent)
2. Uncomment

That's it.

Friday, February 3, 2012

Execution plan with Derby

I don't know for you, but I do have sometimes the problem to find out how a database works.
I usually have SQuirreL SQL for connecting the db, but I don't know how to retrieve the execution plan.

I went through the documentation for Derby and finally got the answer. I still will have to find out how to interpret the stuff !


CALL SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(1);
select * from EDW_BPM_OBJECT;
call SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(0);
VALUES SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS();

Friday, December 2, 2011

Adding user data to a timer thread

I had the quite usual requirement to add user info to a timer.
Some code was retrieving user date from the request scope in order to log the data with each change in the database.
Unfortunately, the timer has no request scope associated with it. And of course no user object attached to the request scope.

With Spring you can user the RunAs mechanism to add rights to a user. This is exactly what I did.

1. First I use the thread scope found www.springbyexample.org/examples/custom-thread-scope-module.html which I configure as
  
      
          
              
                  
              
          
      
  


Now the authentication itself gets configured:
    
    
        
        
    


The third element of configuration is the proxy configuration after the timer.
    
        
        
        
            
                threadScopeAfterAdvice
                threadAuthenticationInterceptor
            
        
    


the threadScopeAfterAdvice only cleans the scope after the thread execution is done.

the threadAuthenticationInterceptor is a org.aopalliance.intercept.MethodInterceptor

public Object invoke(MethodInvocation invocation) throws Throwable {
        UserDetails userDetail = userDetailService.loadUserByUsername(userId);
        RunAsUserToken runAsUserToken = new RunAsUserToken("mykey", userDetail, USER_CREDENTIALS,
                userDetail.getAuthorities(), null);

        Authentication authentication = authenticationManager.authenticate(runAsUserToken);
        if (authentication.isAuthenticated()) {
            SecurityContext sc = new SecurityContextImpl();
            sc.setAuthentication(authentication);
            SecurityContextHolder.setContext(sc);
        }

        try {
            return invocation.proceed();
        } finally {
            SecurityContextHolder.clearContext();

        }
    }

Thursday, October 20, 2011

Step filtering in eclipse

With the Mockito framework it may be annoying to step through the internal Mockito code instead of your code.

With eclipse there is a way to prevent this. Step filtering.

Tuesday, July 19, 2011

Setting language in gimp

I regularly have the problem that my Windows machine is set for German! Some times I'm not even allowed to set it to English, but when I can, it doesn't work as it should. It is only half in English.

Changing the language of The Gimp. Well the problem is that gtk+ has the wrong language.
So control panel -> system -> advanced system setting.
Add a new environment varialbe named "lang" with a value of "c"
Restart The Gimp
et voila


thanks to Syko

Friday, July 1, 2011

JSF2 state saving and event phase shifting

An annoying aspect of valueChangeListener in JSF2 is that it is not handled in the phase I expected.







The method selectAllChangeListener is in the validation phase and not in the invoke application phase as you may need it.
The good news is you can re-throw the event.

public void selectAllChangeListener(ValueChangeEvent e) {
if (!e.getPhaseId().equals(PhaseId.INVOKE_APPLICATION)) {
e.setPhaseId(PhaseId.INVOKE_APPLICATION);
e.queue();
} else {
boolean selectAll = (Boolean) e.getNewValue();
boolean lastSelectAllStateSet = (Boolean) getStateHelper().get(LAST_SELECTED_ALL_SET);
if (lastSelectAllStateSet != selectAll) {
getTableModel().setSelectAll(selectAll);
getStateHelper().put(LAST_SELECTED_ALL_SET, selectAll);
}
}
}

It is important to queue the event on the same component. Which is what e.queue() does. It is equivalent to

e.getComponent().queueEvent(e);


Another important point is the call to getStateHelper.
You cannot keep states in a JSF component. You will loose the reference to the component after a refresh of your page (F5 on Firefox). You must keep them with the getStateHelper method.

Friday, June 24, 2011

Setting attributes in JSF2's commandLinks

One of the recurrent problem with JSF is how can I pass argument from my xhtml facelet page to my backing bean. I've seen various possibilities, but the simplest is probably this one.

<h:commandlink value="click me">
<f:setpropertyactionlistener target="#{myBean.mySetterMethod}" value="myNewValue" />
</h:commandlink>

The example is of course minimalist.

Monday, June 20, 2011

Spring with external configuration

org.springframework.beans.factory.config.PropertyPlaceholderConfigurer is well known for configuring external properties.
What may be less known is how to define default values.

1. Setting the values on the PropertyPlaceholderConfigurer
 


file://${system.properties.pointing.to.config.dir}/config.xml





42





2. Setting the value on the bean
 


file://${system.properties.pointing.to.config.dir}/config.xml







Monday, May 30, 2011

Spring PersistenceUnitPostProcessor

I needed 2 persistence.xml files, one for testing and one for production.
The only difference was the transaction-type which I had to set to JTA, as we were using Atomikos as a transaction manager for production. But for unit testing, resource-local was a better choice (less configuration).

The solution I found was to use a "PersistenceUnitPostProcessor" which changes the value after loading.




















The interesting part is the persistenceUnitPostProcessors property which registers a post processor.
Notice also the persistenceXmlLocation property. As we deploy on Websphere and make use of JPA 2.0, we can't name our file persistence.xml. It would conflict with Webphere !

The "TransactionTypeSelectorPersistenceUnitPostProcessor" java class is trivial, it just sets the transaction type.


public class TransactionTypeSelectorPersistenceUnitPostProcessor implements PersistenceUnitPostProcessor {

private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;

@Override
public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
pui.setTransactionType(transactionType);
}

public void setTransactionType(PersistenceUnitTransactionType transactionType) {
this.transactionType = transactionType;
}

public PersistenceUnitTransactionType getTransactionType() {
return transactionType;
}

}