NetBeans settings for smooth debugging Spring Boot Applications

Here’s a short tip for a smoother debugging experience using NetBeans for developing Spring Boot Applications while using the Spring Boot Devtools:

Make sure you include the Devtools inside your dependency management:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

or

dependencies {
    compile("org.springframework.boot:spring-boot-devtools")
}

Devtools will automatically recognize that you’re running in an IDE respectively debugger and apart from a LiveReload server it’ll monitor your files and restart the context if necessary. To make this work you’ll to enable “Compile on save” in your NetBeans project (that is a project property) like this:


projectproperties

NetBeans however tries to apply all code changes in “Compile on save”-Mode. That works pretty well (not as good as JRebel, but then, NetBeans is free), but for example not for method deletions etc and you’ll end up with that error:


error-dialog

As you’re already opted to use Spring Boot Devtools, you won’t need that feature. The checkbox to turn it of is not a project specific setting but a global which you’ll find under the Java Debugger Tab inside Java options:


remove-apply-code

Turn “Apply code changes after save” of to enjoy a really smooth debugging and working on Spring Boot applications with NetBeans and Devtools.

| Comments (0) »

22-Apr-16


8 new features you’ll get with Spring Boot 1.4

Phil as a nice post about the improvements on testing in Spring Boot 1.4, check it out here: Testing improvements in Spring Boot 1.4.

I’d like to add a concrete example for those and some more, please have a look at the comments inside one of the most important controllers I’ve ever written 😉

Those are the dependencies you’ll need for the demo:

<dependencies>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>		
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-test</artifactid>
        <scope>test</scope>
    </dependency>
    <dependency> 
        <groupid>org.springframework.restdocs</groupid>
        <artifactid>spring-restdocs-mockmvc</artifactid>	    	    
        <scope>test</scope>
    </dependency>
</dependencies>

Here’s the complete demo application:

import java.io.IOException;
import java.io.PrintStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
 
@SpringBootApplication
public class Demo14Application {
 
    @Controller
    @RequestMapping("/api/banner")
    static class BannerController {
 
	// 1) If you didn't chose to disable banner in your application (and why
	//    should you? ;) ), the banner will be availabe as a bean in your 
	//    application
	// 2) banner.jpg :) You can replace banner.txt with a banner.jpg or banner.png
	//    to generate some nice ascii art during startup
	private final Banner banner;
 
	private final Environment environment;
 
	// 3) no more @Autowired on constructors necessary 
	//    when there's on a unique non-default constructor
	//    This also works on @Configuration classes, which didn't support 
	//    constructor injection at all so far.
	//    This comes actually from Spring Framework 4.3.RC1   
	public BannerController(final Banner banner, final Environment environment) {
	    this.banner = banner;
	    this.environment = environment;
	}
 
	// 4) More annotations ;) 
	//    Precomposed @GetMapping, @PostMapping, @RequestScope, @SessionScope etc
	@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
	public void get(final HttpServletResponse response) throws IOException {
	    try (PrintStream printStream = new PrintStream(response.getOutputStream())) {
		banner.printBanner(environment, BannerController.class, printStream);
	    }
	}
    }
 
    public static void main(String[] args) {
	SpringApplication.run(Demo14Application.class, args);
    }
}

And here’s the test. I really like the simplifications there:

import BannerController;
import java.io.PrintStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
 
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.doAnswer;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
// 5) Easier named JUnit Runner ;)
@RunWith(SpringRunner.class)
// 6) Test slices of your application, in this case the Spring MVC slice
//    similiar options are available for @DataJpaTest and @JsonTest (incuding
//    JacksonTester).
@WebMvcTest(controllers = BannerController.class)	
// 7) Together with the above auto configuration comes autoconfiguration of
//    Spring REST docs, which removes the need for the JUnit rule and additional
//    configuration of the mock mvc instance
//    BTW: It seams that you can use addtitional formats like markdown for the
//    snippets
@AutoConfigureRestDocs(
	outputDir = "target/generated-snippets",
	uriHost = "banner-as-a-service.io",
	uriPort = 80
)
public class Demo14ApplicationTests {
 
    // 8) Spring Boot includes a @MockBean annotation that can be used to define
    //    a Mockito mock for a bean inside your ApplicationContext. You can use 
    //    the annotation to add new beans, or replace a single existing bean 
    //    definition. 
    @MockBean
    private Banner banner;
 
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    public void testSomeMethod() throws Exception {
	doAnswer(invocation -> {
	    final PrintStream out = invocation.getArgumentAt(2, PrintStream.class);
	    out.write(bannerText.getBytes());
	    return null;
	}).when(banner).printBanner(anyObject(), anyObject(), anyObject());
 
	mockMvc
		.perform(
			get("/api/banner").accept(APPLICATION_JSON)
		)
		.andExpect(status().isOk())
		.andExpect(content().string(bannerText))
		.andDo(document("api/banner",
			preprocessRequest(prettyPrint()),
			preprocessResponse(prettyPrint())
		));
    }
 
    private final String bannerText
	    = " _____            _              ______ _____ _____ _____       _                \n"
	    + "/  ___|          (_)             | ___ \\  ___/  ___|_   _|     | |               \n"
	    + "\\ `--. _ __  _ __ _ _ __   __ _  | |_/ / |__ \\ `--.  | |     __| | ___   ___ ___ \n"
	    + " `--. \\ '_ \\| '__| | '_ \\ / _` | |    /|  __| `--. \\ | |    / _` |/ _ \\ / __/ __|\n"
	    + "/\\__/ / |_) | |  | | | | | (_| | | |\\ \\| |___/\\__/ / | |   | (_| | (_) | (__\\__ \\\n"
	    + "\\____/| .__/|_|  |_|_| |_|\\__, | \\_| \\_\\____/\\____/  \\_/    \\__,_|\\___/ \\___|___/\n"
	    + "      | |                  __/ |                                                 \n"
	    + "      |_|                 |___/                                                  \n"
	    + "          _ _   _        ___   _____ _____ _____ _____              _            \n"
	    + "         (_) | | |      / _ \\ /  ___/  __ \\_   _|_   _|            | |           \n"
	    + "__      ___| |_| |__   / /_\\ \\\\ `--.| /  \\/ | |   | |     __ _ _ __| |_          \n"
	    + "\\ \\ /\\ / / | __| '_ \\  |  _  | `--. \\ |     | |   | |    / _` | '__| __|         \n"
	    + " \\ V  V /| | |_| | | | | | | |/\\__/ / \\__/\\_| |_ _| |_  | (_| | |  | |_          \n"
	    + "  \\_/\\_/ |_|\\__|_| |_| \\_| |_/\\____/ \\____/\\___/ \\___/   \\__,_|_|   \\__|         \n"
	    + "                                                                                 \n"
	    + "                                                                                 ";
}

Have a look at the release notes or the updated reference documentation for more.

Read the complete article »

| Comments (1) »

17-Apr-16


Get your InstrumentationLoadTimeWeaver recognized by LocalContainerEntityManagerFactoryBean

org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean is LoadTimeWeaverAware and as thus should be provided with such. Usually this would be done with a @Configuration, but then there is SPR-10856. In short: a LoadTimeWeaverAwareProcessor is provided before post processing the bean factory. This means that an @Bean inside a configuration class comes to load for load time weaving.

At least for Spring Boot there’s a solution. You can register the LoadTimeWeaver before startup:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
 
@SpringBootApplication
@EnableConfigurationProperties
public class Application {    
    public static void main(final String... args) {
        final SpringApplication springApplication = new SpringApplication(Application.class);
        springApplication.addListeners(new ApplicationListener<ApplicationPreparedEvent>() {
            @Override
            public void onApplicationEvent(final ApplicationPreparedEvent event) {
                event.getApplicationContext().getBeanFactory().registerSingleton(ConfigurableApplicationContext.LOAD_TIME_WEAVER_BEAN_NAME, new InstrumentationLoadTimeWeaver());
            }
        });
        springApplication.run(args);
    }
}

Be careful not to use a lambda, because there’s SPR-14109.

Anyway: This way byte code enhancement for JPA / Hibernate entities will work. Another solution would be build time byte code enhancement, as Vlad points out here: For Hibernate 5 and 4.

| Comments (0) »

10-Apr-16


Back to the roots: Playing with computer hardware…

Introduction

In January 2012 i bought a 27″ iMac 12,2 with a Intel Core i5 at 2,7Ghz which should have been a pretty decent and fast machine back then. The RAM can be easily upgraded in this thing which i did already back then to 16Gb for a fraction of the price Apple wants.

The machine came with OS X 10.6 “Snow Leopard” and shortly after migrating from my MacBook (i was using a MacBook back then for everything but the external display at home was annoying) i got a little disappointed. The iMac never was as fast as expected because the built-in, Apple branded Western Digital “WD1001FALS” was and is incredible slow (and I’m not the only one who thinks so). But the iMac was usable until OS X 10.8 “Mountain Lion” came out. From that point on i was afraid of every OS update coming out because booting took already ages.

I had all the RAM inside the machine for running VMs for testing purposes but i was afraid of restarting them. The Win 7 VM needed about 30 minutes to boot and the disk noise during that time was hardly bearable.

The problem with this iMac is not only that you have to open it through the front (removing the glas panel as well as the display) but also that it’s equipped with Apple branded disk having a custom firmware that reports the temperature through the power cable. If you replace it with a standard disk, the fans go haywire as the OS assumes something wrong. You can solve this with software but that seems too unstable for me.

German Apple reseller Gravis has it’s cBreeze module for fixing that but i wasn’t sure if i can buy it stand alone. Bringing my Mac to store would have forced me to delete my system upfront (totally out of question bringing a system into a store for days containing my personal life for the last 20 years).

Other World Computing also has a module available but i hesitated ordering until last week, when i read this tweet by Dominikus and i thought: What the heck… Let’s try this.

Read the complete article »

| Comments (1) »

22-Feb-16


Surface Pro 4 factory reset gets stuck at 7% (or 31%)

If you reset your Microsoft Surface Pro 4 to factory defaults for whatever reasons you might end up like me: In an endless boot loop or the reset process being stuck at 7% (or, if you choose to erase everything, at 31%), this solution worked for me:

  • Download the recovery image for your device and create an USB stick like described
  • Use it to boot your surface (press volume down, hold it, than power on)
  • Maybe the official way described here works for your. For me, it didn’t.
  • Instead i used “Troubleshoot > Advanced Options > Command Prompt.”. Start “diskpart”, enter “select disk system” and nuke your system drive with a “clean”
  • After that, you can reset and restore your device via the disk method which works for me at the point of writing

I needed to reset my Surface because i bound it to the wrong account. Happens. But i wonder how an average user would react to such a bad first experience. Even i was totally disappointed, which is sad, because the hardware really feels fabulous and the promise to run pretty much anything on this thing is great.

| Comments (27) »

09-Feb-16