Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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;
    }
}

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();

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.

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, 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;
}

}

Wednesday, May 4, 2011

Setting tomcats'language

I unfortunately have to work with computers with default language set to German.
Until now I was always able to change the language, but Windows does really support this. Which means I have part of my computer in English and many application remain in German.
It is very annoying for stack trace for instance.

Thus you can set the language of apache tomcat via a system property.
In eclipse you can set

-Duser.language=en

as VM argument to the launch configuration of tomcat.

Thursday, December 16, 2010

Accessing spring beans from liferay templates

I had an interesting task, display the version of the portal.
The question which immediately arises is: how do I get from my velocity template to my spring beans?

1. The first stop is the VelocityVariable class from Liferay.
there your fine "serviceLocator" variable which sound just as the right variable to use.
2. In your tpl file add the following


  • $serviceLocator.findService("versionBean").getVersion()



3. You may think now that you only have to configure a Spring bean named "versionBean". Wrong!







The bean name must be augmented with ".velocity" and the bean you are talking to is not yours, but the "ProxyFactoryBean" in which you inject your bean!
4. The Java bean class is up to you then.

Thanks you Martin for your help with this one.

Wednesday, December 1, 2010

Choose default java version in Ubuntu

I got annoyed today, as I needed the sun jdk on my Ubuntu machine.
I had to goodle a while before finding how to change the default from open jdk to sun jdk

The how to is located here.

But I reproduce the text here:

Choosing the default Java to use

  • Open a Terminal window
  • Run sudo update-java-alternatives -l to see the current configuration and possibilities.
  • Run sudo update-java-alternatives -s XXXX to set the XXX java version as default. For Sun Java 6 this would be sudo update-java-alternatives -s java-6-sun
  • Run java -version to ensure that the correct version is being called.
You can also use the following command to interactively make the change;
  • Open a Terminal window
  • Run sudo update-alternatives --config java
  • Follow the onscreen prompt
I still would prefer some gui to perform this. But it is a start.

Monday, November 29, 2010

Caching in Firefox

I was checking if my static content was effectively cached by my browser, but was stuck. Nothing got cached !
Until I found a very informative forum contribution from Aso

Type about:config in FF and search for 'cache'.
Check
browser.cache.disk.enable
browser.cache.memory.enable and
network.http.use-cache
are set to true.

Also try cranking up the size of browser.cache.disk.capacity (50000).
Lastly, make sure browser.cache.check_doc_frequency is integer 3.

Another thing I should mention - when you say you 'reload' the page, are you hitting refresh? Because this effectively reloads the page (and all it's objects) from the server, so you will not experience the effect of cache. Only when browsing a site will cache make a difference.

Monday, August 16, 2010

Property files encoding

Java resource bundle are saved in ascii. This can lead to problems and the special character must therefore be converted. There is a utility which comes with Java which allows to to exactly this.
The file is then awful, but everything is displayed correctly afterwards.


jdk1.6.0_18\bin\native2ascii.exe translations.properties translations_converted.properties

Friday, July 9, 2010

Java Quiz

I found a dirty peace of code and made a small quiz out of it.

What is the result of the following code?

I encountered twice the construction of a inner class
Outter.Inner in = out.new Inner();

but only in books. I never had any use of such a construct.

If you don't find out just try it :)


class Outter {
private int value;
private Inner in = new Inner();

Outter() {
value = 41;
}

void print() {
in.print();
}

class Inner {

Inner() {
print();
}

void print() {
System.out.println(value++);
}
}
}

public class Main {
public static void main(String[] args) {
Outter out = new Outter();
out.print();

Outter.Inner in = out.new Inner();
in.print();
}
}

Friday, May 7, 2010

Facelets and eclipse

Per default, eclipse does not recognize xhtml files, the default file extension for facelets. I.e., you don't have code completion and the jsf managed beans are not recognized either.

There is a solution:

In window->preferences you do 2 things...

1. In General->Content Types you choose text/jsp in the content types and add *.xhtml as a file association

2. In General->Editors->File Associations select the *.xhtml file type and add th JSP Editor as the Default

I'm not sure if you really need to put the TLD in WEB-INF. (at least with eclipse 3.5) It workds without for me.
now just add the TLD to WEB-INF dir of your project and hey presto tag:completion now works for xhtml files.

I picked this from Andrew Lovell, thanks a lot.

Friday, April 16, 2010

Template Method Pattern

I'm not a big fan of the template method pattern, but it is useful.
Usually I apply it only when I have to made a change, and realize, I have to do it at too many places. I don't like it because it is a bit confusing, especially the stack traces.

Here is an example taken from a db connection.

public abstract class Template{
String sql ;
Template(String sql){
this.sql = sql;
}

public void exec() {
Statement statement = null;
ResultSet rs = null;
try {
statement = getConnection().createStatement();
rs = statement.executeQuery(sql);
execute(rs);
} catch (SQLException e) {
log.error("failed to execute query " + sql);
throw e;
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.error("failed to close result set");
}
}
if (statement != null) {
statement.close();
}
}
public abstract void execute(ResultSet resultSet);
}


The problem lies in retrieving something from the execute method


final List results = new ArrayList();
Template call = new Template(sql) {

@Override
public void execute(ResultSet rs) throws SQLException {
rs.next();
Boolean result = rs.getBoolean("BoolColumn");
results.add(result);
}
};
call.exec();
boolean result = results.get(0);


Maybe I missed something, but It is the best way I found for retrieving a value.

Tuesday, March 16, 2010

Hidden feature of ant's Taskdef

I recently had a problem with ant taskdef task.
I could launch findbugs with ant from within eclipse and from the console, but once it was launched by hudson, I got an error:

BUILD FAILED
/var/lib/hudson/jobs/jpf/workspace/build.xml:30: taskdef class edu.umd.cs.findbugs.anttask.FindBugsTask cannot be found

the ant file was correct but I found out (by googling of course) that the by adding a classpathref entry, I solved the problem.









The taskdef task documentation does not evoke the classpathref tag. It should probably be well known, but I don't use ant on an everyday basis.