CommonModelControllerAdvice.java

package info.textgrid.rep;

import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import info.textgrid.rep.i18n.I18N;
import info.textgrid.rep.i18n.I18NProvider;
import info.textgrid.rep.service.TgrepConfigurationService;

/**
 * Add ModelAttributes to all Controllers which are needed for
 * all Models like i18n (the translation map) or the config
 *
 * @author Ubbo Veentjer
 */
@ControllerAdvice
public class CommonModelControllerAdvice {

  private TgrepConfigurationService tgrepConfig;
  private I18NProvider i18nProvider;

  @Autowired
  public CommonModelControllerAdvice(I18NProvider i18nProvider, TgrepConfigurationService tgrepConfig) {
    this.i18nProvider = i18nProvider;
    this.tgrepConfig = tgrepConfig;
  }

  @ModelAttribute
  public void handleRequest(Model model, Locale locale) {

    I18N i18n = i18nProvider.getI18N(locale);

    // translation array
    model.addAttribute("i18n", i18n.getTranslationMap());
    model.addAttribute("language", i18n.getLanguage());

    // config
    model.addAttribute("config", this.tgrepConfig);

  }

}