Commit c8a881d5 authored by Matija Obreza's avatar Matija Obreza
Browse files

TransifexService provided by a factory bean

parent 6674581d
...@@ -50,7 +50,7 @@ public class ArticleController extends BaseController { ...@@ -50,7 +50,7 @@ public class ArticleController extends BaseController {
@Autowired @Autowired
private ContentService contentService; private ContentService contentService;
@Autowired @Autowired(required = false)
private TransifexService transifexService; private TransifexService transifexService;
@Autowired @Autowired
...@@ -61,6 +61,9 @@ public class ArticleController extends BaseController { ...@@ -61,6 +61,9 @@ public class ArticleController extends BaseController {
@RequestMapping(value = "/transifex", params = { "post" }, method = RequestMethod.POST) @RequestMapping(value = "/transifex", params = { "post" }, method = RequestMethod.POST)
@PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')") @PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')")
public String postTotransifex(@RequestParam("slug") String slug, Model model) { public String postTotransifex(@RequestParam("slug") String slug, Model model) {
if (transifexService == null) {
throw new ResourceNotFoundException("translationService not enabled");
}
Article article = contentService.getGlobalArticle(slug, getLocale()); Article article = contentService.getGlobalArticle(slug, getLocale());
String resourceName = "article-" + slug; String resourceName = "article-" + slug;
try { try {
...@@ -82,6 +85,10 @@ public class ArticleController extends BaseController { ...@@ -82,6 +85,10 @@ public class ArticleController extends BaseController {
@RequestMapping(value = "/transifex", params = { "remove" }, method = RequestMethod.POST) @RequestMapping(value = "/transifex", params = { "remove" }, method = RequestMethod.POST)
@PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')") @PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')")
public String deleteFromtransifex(@RequestParam("slug") String slug, Model model) { public String deleteFromtransifex(@RequestParam("slug") String slug, Model model) {
if (transifexService == null) {
throw new ResourceNotFoundException("translationService not enabled");
}
Article article = contentService.getGlobalArticle(slug, getLocale()); Article article = contentService.getGlobalArticle(slug, getLocale());
model.addAttribute("article", article); model.addAttribute("article", article);
...@@ -102,6 +109,9 @@ public class ArticleController extends BaseController { ...@@ -102,6 +109,9 @@ public class ArticleController extends BaseController {
@RequestMapping(value = "/translate/{slug}/{language}", method = RequestMethod.GET) @RequestMapping(value = "/translate/{slug}/{language}", method = RequestMethod.GET)
@PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')") @PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')")
public String fetchFromtransifex(@PathVariable("slug") String slug, @PathVariable("language") String language, Model model) throws Exception { public String fetchFromtransifex(@PathVariable("slug") String slug, @PathVariable("language") String language, Model model) throws Exception {
if (transifexService == null) {
throw new ResourceNotFoundException("translationService not enabled");
}
Locale locale = new Locale(language); Locale locale = new Locale(language);
...@@ -188,7 +198,7 @@ public class ArticleController extends BaseController { ...@@ -188,7 +198,7 @@ public class ArticleController extends BaseController {
* @return * @return
*/ */
@PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')") @PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')")
@RequestMapping("{url}/edit") @RequestMapping("{url:.+}/edit")
public String edit(ModelMap model, @PathVariable(value = "url") String slug) { public String edit(ModelMap model, @PathVariable(value = "url") String slug) {
_logger.debug("Editing article " + slug); _logger.debug("Editing article " + slug);
return "redirect:/content/" + slug + "/edit/" + LocaleContextHolder.getLocale().getLanguage(); return "redirect:/content/" + slug + "/edit/" + LocaleContextHolder.getLocale().getLanguage();
...@@ -203,7 +213,7 @@ public class ArticleController extends BaseController { ...@@ -203,7 +213,7 @@ public class ArticleController extends BaseController {
* @return * @return
*/ */
@PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')") @PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')")
@RequestMapping("{url}/edit/{language}") @RequestMapping("{url:.+}/edit/{language}")
public String edit(ModelMap model, @PathVariable(value = "url") String slug, @PathVariable("language") String language) { public String edit(ModelMap model, @PathVariable(value = "url") String slug, @PathVariable("language") String language) {
_logger.debug("Editing article " + slug); _logger.debug("Editing article " + slug);
......
...@@ -35,7 +35,7 @@ import org.springframework.web.bind.annotation.RequestParam; ...@@ -35,7 +35,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
/** /**
* Transifex web hook listener. * Transifex web hook listener.
* *
* @author matijaobreza * @author matijaobreza
* *
...@@ -44,77 +44,81 @@ import org.springframework.web.bind.annotation.ResponseBody; ...@@ -44,77 +44,81 @@ import org.springframework.web.bind.annotation.ResponseBody;
@RequestMapping(value = "/transifex") @RequestMapping(value = "/transifex")
public class TransifexAPIController extends BaseController { public class TransifexAPIController extends BaseController {
@Autowired @Autowired
private ContentService contentService; private ContentService contentService;
@Autowired @Autowired(required = false)
private TransifexService transifexService; private TransifexService transifexService;
@Value("${transifex.content.template}") @Value("${transifex.content.template}")
private String contentTemplate; private String contentTemplate;
@Value("${transifex.min.translated}") @Value("${transifex.min.translated}")
private int transifexMinTranslated; private int transifexMinTranslated;
@Value("${transifex.hook.key}") @Value("${transifex.hook.key}")
private Object transifexHookKey; private Object transifexHookKey;
/** /**
* Note: the hook key value should be set in preferences * Note: the hook key value should be set in preferences
*/ */
@AsAdmin @AsAdmin
@RequestMapping(value = "/hook/{hookKey:.+}", method = RequestMethod.POST) @RequestMapping(value = "/hook/{hookKey:.+}", method = RequestMethod.POST)
public @ResponseBody public @ResponseBody String webHookHandle(@PathVariable("hookKey") String hookKey, @RequestParam(value = "project") String projectSlug,
String webHookHandle(@PathVariable("hookKey") String hookKey, @RequestParam(value = "project") String projectSlug, @RequestParam(value = "resource") String resource, @RequestParam(value = "language") String language,
@RequestParam(value = "resource") String resource, @RequestParam(value = "language") String language, @RequestParam(value = "translated") Integer translatedPercentage, Model model) {
@RequestParam(value = "translated") Integer translatedPercentage, Model model) {
if (!transifexHookKey.equals(hookKey)) { if (!transifexHookKey.equals(hookKey)) {
_logger.error("Invalid key provided for Transifex callback hook: " + hookKey); _logger.error("Invalid key provided for Transifex callback hook: " + hookKey);
throw new RuntimeException("I don't know you!"); throw new RuntimeException("I don't know you!");
} }
if (!resource.startsWith("article-")) { if (!resource.startsWith("article-")) {
_logger.warn("Ignoring Transifex'd hook for " + resource); _logger.warn("Ignoring Transifex'd hook for " + resource);
return "Ignored"; return "Ignored";
} }
String slug = resource.split("-")[1]; String slug = resource.split("-")[1];
_logger.warn("Transifex'd article slug=" + slug); _logger.warn("Transifex'd article slug=" + slug);
if (translatedPercentage != null && translatedPercentage >= transifexMinTranslated) { if (translatedPercentage != null && translatedPercentage >= transifexMinTranslated) {
// fetch updated resource from Transifex // fetch updated resource from Transifex
try { try {
updateArticle(slug, language); updateArticle(slug, language);
} catch (TransifexException e) { } catch (TransifexException e) {
_logger.error(e.getMessage(), e); _logger.error(e.getMessage(), e);
throw new RuntimeException("Server error"); throw new RuntimeException("Server error");
} }
return "Thanks!"; return "Thanks!";
} else { } else {
return "Not sufficiently translated"; return "Not sufficiently translated";
} }
} }
private Article updateArticle(String slug, String lang) throws TransifexException { private Article updateArticle(String slug, String lang) throws TransifexException {
_logger.info("Fetching updated translation for article " + slug + " lang=" + lang); if (transifexService == null) {
_logger.error("translationService not available.");
Locale locale = new Locale(lang); throw new TransifexException("transifex.com service not available", null);
_logger.warn("Locale: " + locale); }
String resourceBody = transifexService.getTranslatedResource("article-".concat(slug), locale); _logger.info("Fetching updated translation for article " + slug + " lang=" + lang);
String title = resourceBody.split("<title>")[1].split("</title>")[0]; Locale locale = new Locale(lang);
_logger.warn("Title: " + title); _logger.warn("Locale: " + locale);
String body = resourceBody.split("<body>")[1].split("</body>")[0]; String resourceBody = transifexService.getTranslatedResource("article-".concat(slug), locale);
_logger.warn("Body: " + body);
String title = resourceBody.split("<title>")[1].split("</title>")[0];
// Extract article from database we need (correct locale + do not use _logger.warn("Title: " + title);
// default (EN) language)
Article article = contentService.getGlobalArticle(slug, locale, false); String body = resourceBody.split("<body>")[1].split("</body>")[0];
_logger.warn("Body: " + body);
// TODO Enable when tested
// Extract article from database we need (correct locale + do not use
// default (EN) language)
Article article = contentService.getGlobalArticle(slug, locale, false);
// TODO Enable when tested
// if (article == null) { // if (article == null) {
// // No article for selected locale // // No article for selected locale
// article = contentService.createGlobalArticle(slug, locale, title, // article = contentService.createGlobalArticle(slug, locale, title,
...@@ -125,7 +129,7 @@ public class TransifexAPIController extends BaseController { ...@@ -125,7 +129,7 @@ public class TransifexAPIController extends BaseController {
// body); // body);
// } // }
_logger.info("Updated translation for article " + slug + " lang=" + lang); _logger.info("Updated translation for article " + slug + " lang=" + lang);
return article; return article;
} }
} }
...@@ -16,22 +16,50 @@ ...@@ -16,22 +16,50 @@
package org.genesys2.spring.config; package org.genesys2.spring.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.genesys2.transifex.client.TransifexService; import org.genesys2.transifex.client.TransifexService;
import org.genesys2.transifex.client.TransifexServiceImpl; import org.genesys2.transifex.client.TransifexServiceImpl;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.ImportResource;
@Configuration @Configuration
@Import({ SpringProperties.class, SpringCommonConfig.class, SpringAclConfig.class, SpringSchedulerConfig.class, SpringDataBaseConfig.class, SpringMailConfig.class, @Import({ SpringProperties.class, SpringCommonConfig.class, SpringAclConfig.class, SpringSchedulerConfig.class, SpringDataBaseConfig.class,
SpringSecurityOauthConfig.class, SpringCacheConfig.class, ElasticsearchConfig.class }) SpringMailConfig.class, SpringSecurityOauthConfig.class, SpringCacheConfig.class, ElasticsearchConfig.class })
@ImportResource({ "classpath:/spring/spring-security.xml" }) @ImportResource({ "classpath:/spring/spring-security.xml" })
public class ApplicationConfig { public class ApplicationConfig {
public static final Log LOG = LogFactory.getLog(ApplicationConfig.class);
@Bean @Bean
public TransifexService transifexService() { public FactoryBean<TransifexService> transifexService() {
return new TransifexServiceImpl(); TransifexService i = null;
try {
i = new TransifexServiceImpl();
} catch (Throwable e) {
LOG.warn("Transifex integration not enabled: " + e.getMessage(), e);
}
final TransifexService instance = i;
return new FactoryBean<TransifexService>() {
@Override
public TransifexService getObject() throws Exception {
return instance;
}
@Override
public Class<?> getObjectType() {
return TransifexService.class;
}
@Override
public boolean isSingleton() {
return true;
}
};
} }
} }
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment