Commit c8a881d5 authored by Matija Obreza's avatar Matija Obreza

TransifexService provided by a factory bean

parent 6674581d
......@@ -50,7 +50,7 @@ public class ArticleController extends BaseController {
@Autowired
private ContentService contentService;
@Autowired
@Autowired(required = false)
private TransifexService transifexService;
@Autowired
......@@ -61,6 +61,9 @@ public class ArticleController extends BaseController {
@RequestMapping(value = "/transifex", params = { "post" }, method = RequestMethod.POST)
@PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')")
public String postTotransifex(@RequestParam("slug") String slug, Model model) {
if (transifexService == null) {
throw new ResourceNotFoundException("translationService not enabled");
}
Article article = contentService.getGlobalArticle(slug, getLocale());
String resourceName = "article-" + slug;
try {
......@@ -82,6 +85,10 @@ public class ArticleController extends BaseController {
@RequestMapping(value = "/transifex", params = { "remove" }, method = RequestMethod.POST)
@PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')")
public String deleteFromtransifex(@RequestParam("slug") String slug, Model model) {
if (transifexService == null) {
throw new ResourceNotFoundException("translationService not enabled");
}
Article article = contentService.getGlobalArticle(slug, getLocale());
model.addAttribute("article", article);
......@@ -102,6 +109,9 @@ public class ArticleController extends BaseController {
@RequestMapping(value = "/translate/{slug}/{language}", method = RequestMethod.GET)
@PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')")
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);
......@@ -188,7 +198,7 @@ public class ArticleController extends BaseController {
* @return
*/
@PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('CONTENTMANAGER')")
@RequestMapping("{url}/edit")
@RequestMapping("{url:.+}/edit")
public String edit(ModelMap model, @PathVariable(value = "url") String slug) {
_logger.debug("Editing article " + slug);
return "redirect:/content/" + slug + "/edit/" + LocaleContextHolder.getLocale().getLanguage();
......@@ -203,7 +213,7 @@ public class ArticleController extends BaseController {
* @return
*/
@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) {
_logger.debug("Editing article " + slug);
......
......@@ -35,7 +35,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Transifex web hook listener.
* Transifex web hook listener.
*
* @author matijaobreza
*
......@@ -44,77 +44,81 @@ import org.springframework.web.bind.annotation.ResponseBody;
@RequestMapping(value = "/transifex")
public class TransifexAPIController extends BaseController {
@Autowired
private ContentService contentService;
@Autowired
private ContentService contentService;
@Autowired
private TransifexService transifexService;
@Autowired(required = false)
private TransifexService transifexService;
@Value("${transifex.content.template}")
private String contentTemplate;
@Value("${transifex.content.template}")
private String contentTemplate;
@Value("${transifex.min.translated}")
private int transifexMinTranslated;
@Value("${transifex.min.translated}")
private int transifexMinTranslated;
@Value("${transifex.hook.key}")
private Object transifexHookKey;
@Value("${transifex.hook.key}")
private Object transifexHookKey;
/**
* Note: the hook key value should be set in preferences
*/
@AsAdmin
@RequestMapping(value = "/hook/{hookKey:.+}", method = RequestMethod.POST)
public @ResponseBody
String webHookHandle(@PathVariable("hookKey") String hookKey, @RequestParam(value = "project") String projectSlug,
@RequestParam(value = "resource") String resource, @RequestParam(value = "language") String language,
@RequestParam(value = "translated") Integer translatedPercentage, Model model) {
/**
* Note: the hook key value should be set in preferences
*/
@AsAdmin
@RequestMapping(value = "/hook/{hookKey:.+}", method = RequestMethod.POST)
public @ResponseBody String webHookHandle(@PathVariable("hookKey") String hookKey, @RequestParam(value = "project") String projectSlug,
@RequestParam(value = "resource") String resource, @RequestParam(value = "language") String language,
@RequestParam(value = "translated") Integer translatedPercentage, Model model) {
if (!transifexHookKey.equals(hookKey)) {
_logger.error("Invalid key provided for Transifex callback hook: " + hookKey);
throw new RuntimeException("I don't know you!");
}
if (!transifexHookKey.equals(hookKey)) {
_logger.error("Invalid key provided for Transifex callback hook: " + hookKey);
throw new RuntimeException("I don't know you!");
}
if (!resource.startsWith("article-")) {
_logger.warn("Ignoring Transifex'd hook for " + resource);
return "Ignored";
}
if (!resource.startsWith("article-")) {
_logger.warn("Ignoring Transifex'd hook for " + resource);
return "Ignored";
}
String slug = resource.split("-")[1];
_logger.warn("Transifex'd article slug=" + slug);
String slug = resource.split("-")[1];
_logger.warn("Transifex'd article slug=" + slug);
if (translatedPercentage != null && translatedPercentage >= transifexMinTranslated) {
// fetch updated resource from Transifex
try {
if (translatedPercentage != null && translatedPercentage >= transifexMinTranslated) {
// fetch updated resource from Transifex
try {
updateArticle(slug, language);
} catch (TransifexException e) {
_logger.error(e.getMessage(), e);
throw new RuntimeException("Server error");
}
return "Thanks!";
} else {
return "Not sufficiently translated";
}
}
private Article updateArticle(String slug, String lang) throws TransifexException {
_logger.info("Fetching updated translation for article " + slug + " lang=" + lang);
Locale locale = new Locale(lang);
_logger.warn("Locale: " + locale);
String resourceBody = transifexService.getTranslatedResource("article-".concat(slug), locale);
String title = resourceBody.split("<title>")[1].split("</title>")[0];
_logger.warn("Title: " + title);
String body = resourceBody.split("<body>")[1].split("</body>")[0];
_logger.warn("Body: " + body);
// 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
return "Thanks!";
} else {
return "Not sufficiently translated";
}
}
private Article updateArticle(String slug, String lang) throws TransifexException {
if (transifexService == null) {
_logger.error("translationService not available.");
throw new TransifexException("transifex.com service not available", null);
}
_logger.info("Fetching updated translation for article " + slug + " lang=" + lang);
Locale locale = new Locale(lang);
_logger.warn("Locale: " + locale);
String resourceBody = transifexService.getTranslatedResource("article-".concat(slug), locale);
String title = resourceBody.split("<title>")[1].split("</title>")[0];
_logger.warn("Title: " + title);
String body = resourceBody.split("<body>")[1].split("</body>")[0];
_logger.warn("Body: " + body);
// 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) {
// // No article for selected locale
// article = contentService.createGlobalArticle(slug, locale, title,
......@@ -125,7 +129,7 @@ public class TransifexAPIController extends BaseController {
// body);
// }
_logger.info("Updated translation for article " + slug + " lang=" + lang);
return article;
}
_logger.info("Updated translation for article " + slug + " lang=" + lang);
return article;
}
}
......@@ -16,22 +16,50 @@
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.TransifexServiceImpl;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
@Configuration
@Import({ SpringProperties.class, SpringCommonConfig.class, SpringAclConfig.class, SpringSchedulerConfig.class, SpringDataBaseConfig.class, SpringMailConfig.class,
SpringSecurityOauthConfig.class, SpringCacheConfig.class, ElasticsearchConfig.class })
@Import({ SpringProperties.class, SpringCommonConfig.class, SpringAclConfig.class, SpringSchedulerConfig.class, SpringDataBaseConfig.class,
SpringMailConfig.class, SpringSecurityOauthConfig.class, SpringCacheConfig.class, ElasticsearchConfig.class })
@ImportResource({ "classpath:/spring/spring-security.xml" })
public class ApplicationConfig {
public static final Log LOG = LogFactory.getLog(ApplicationConfig.class);
@Bean
public TransifexService transifexService() {
return new TransifexServiceImpl();
public FactoryBean<TransifexService> transifexService() {
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