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.