I am trying to do internationalization for my templates but i'm not sure if it's most efficient way to do it like this.
I extracted messages to resource bundle and i use MessageSource method getMessage(String var1, #Nullable Object[] var2, Locale var3) to get translation based on Locale, then i put it into model and process the template.
private String processTemplate(String templateName, String locale) {
try {
String greeting = messageSource.getMessage("messages.greeting", null, new Locale(locale));
Map<String, String> model = new HashMap<>();
model.put("greeting", greeting);
Template template = freemarkerConfiguration.getConfiguration().getTemplate(templateName);
return FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
} catch (IOException | TemplateException e) {
log.error("Error when processing template {}", templateName);
throw new EmailNotSentException();
}
}
My question is if there is more efficient way to process template in this manner ? Or it would be better to have internatiolization for templates ?
It depends. If you use those templates as your main ui renderers, internationalize the message is the better option. But if those templates are for "emailing" I'll opt for their internationalization.
In my application I have a similar use case, and I defined my templates like:
order-template-fr.ftl, order-template-es.ftl, order-template-en.ftl, ...
I resolve the template at runtime basing on the user's locale, using LOCALE_CONTRY.toLowerCase(). Example:
String template = "order-template-"+LOCALE_CONTRY.toLowerCase()+".ftl";
Related
I have MyComponent:
public class MyComponent
{
#Parameter(required = false)
#Property
private String testParameter;
}
And I render it offline with the following code:
PageRenderRequestParameters pageRenderRequestParameters = new PageRenderRequestParameters(
"mycomponent", new ArrayEventContext(this.typeCoercer, ""), false);
StringWriter stringWriter = new StringWriter();
try
{
this.offlineComponentRenderer.renderPage(stringWriter,
new DefaultOfflineRequestContext(), pageRenderRequestParameters);
} catch (IOException e)
{
e.printStackTrace();
}
String htmlOutput = stringWriter.toString();
I don't know how to set the testParameter of MyComponent to imitate the following call:
<t:mycomponent testParameter="something" />
I think you failed to mention that you're using tapestry-offline, a 3rd party tapestry library.
You will need to create a page which includes the component before it can be rendered. If you want to make the parameter configurable, you will probably bind the property to the page activation context
Note: If you don't want the page to be visible on your website, you could probably annotate it with WhitelistAccessOnly and tweak the offline request so that it is whitelisted.
I have a sample CRUD application, The application used is a Wine Cellar app. You can search for wines, add a wine to your cellar, update and delete wines. I got it from RESTful services with jQuery and Java using JAX-RS and Jersey.
I modified the Wine class to include validation constraints.
#NotNull(message='Name must have a value')
private String name;
#NotNull(message='Grapes must have a value')
private String grapes;
If the user creates/updates, a wine the errors will be thrown if the name and grape fields are empty. All my validation messages are returned to the browser in json format.
public Wine create(Wine wine) {...}
public Wine update(Wine wine) {...}
If only one error is thrown, I want to display the correct message to the user and also highlight the field.
How do I get the empty field(name or id) that triggered the error as well as the correct validation message?
Sorry about inconsistencies or for lack of clarity.
I used an Web Application Exception Mapper to handle the exceptions. It checks if the error was generated from a web application exception or constraint violation exception.
if (exception instanceof ConstraintViolationException) {
Set<ErrorResponse> errorResponses = new HashSet<>();
for (ConstraintViolation violation : ((ConstraintViolationException) exception).getConstraintViolations()) {
errorResponses.add(new ErrorResponse(violation.getPropertyPath().toString(),violation.getMessage()));
}
builder.entity(new WebApplicationError(errorResponses));
}
Also, I checked if was a JsonMapping Exception
if (exception instanceof JsonMappingException) {
ResourceBundle bundle = ResourceBundle.getBundle("ValidationMessages");
Set<ErrorResponse> errorResponses = new HashSet<>();
for(Reference ref : ((JsonMappingException) exception).getPath()) {
String className = ref.getFrom().getClass().getName()
.substring(ref.getFrom().getClass().getName()
.lastIndexOf(".") + 1).toLowerCase();
String key = "the.key";
try {
message = bundle.getString(key);
} catch (MissingResourceException e) {
logger.error(e.getMessage());
}
errorResponses.add(new ErrorResponse(ref.getFieldName(), message));
}
builder.entity(new WebApplicationError(errorResponses));
}
JsonMapping Exception
Constraint Violation
I want to read properties from a .properties file using a controller and display its value in jsp file, which is a view using dependency injection, by storing the retrieved properties in a pojo.
Use the PropertyPlaceholderConfigurer for this. The properties will be loaded by spring so no need for your controller to do this. You can inject the properties directly into your view.
Try this
#Component
class MyComponent {
#Property(key = "proo.xmlurl")
public void setUrlString(String urlStr) {
try {
this.url = new URL(urlStr);
} catch(MalformedURLException e) {
throw new IllegalArgumentException(urlStr + " is not a valid http url", e);
}
}
}
in your properties files put this
proo.xmlurl=${proo.xmlurl}
AppContext can have this :
<context:property-placeholder location="classpath:my.properties" ignore-unresolvable="true"/>
Controller can have this
#Value("${language}")
private String language;
#Value("${allLanguages}")
private String allLanguages;
where properties file contains this, or similar
language = java
alllanguages = java and \
c++
somethingelse = whatever
We work on a Java (Java EE) application, and we generate XML files in order to send them to a remote .NET application with MSMQ reading on their side.
The XML file is generated by JDom, like so :
// add elements...
Document doc = new Document(root);
String XmlData = new XMLOutputter(Format.getPrettyFormat().setOmitEncoding(true)).outputString(doc);
try {
SendFile( XmlData, "title" , "path");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MessageQueueException e) {
e.printStackTrace();
}
Then we use this function, using the MsmqJava library to send the file :
private void SendFile(String data, String title, String outputPath) throws UnsupportedEncodingException, MessageQueueException{
String qname="name_of_the_queue";
String fullname= "server_path" + qname;
String body = data;
String label = title;
String correlationId= "L:none";
try {
Queue queue= new Queue(fullname);
Message msg= new Message(body, label, correlationId);
queue.send(msg);
} catch (MessageQueueException ex1) {
System.out.println("Put failure: " + ex1.toString());
}
}
They correctly receive the file, but they told us that the bodyType was set to "VT_EMPTY" while they wanted "VT_BSTR", and we haven't find a clue about how to fix this. If you know another lib who does the job, or a workaround to this one, we can change with no problem.
Thanks !
Looking at the documentation for the library you use, it is not possible using that library.
Jmsmqqueue also doesn't provide the functionality you need.
It seems sun also had an adapter: https://wikis.oracle.com/display/JavaCAPS/Sun+Adapter+for+MSMQ
I am new to freemarker. I have a spring application that I am planning to use with freemarker. Templates will be stored in database and based on the login, I want to retrieve the template from database. Can any one tell me how to configure the freemarker in spring and get the html tags as a string after constructing the template. I did googling but I could not understand much.
I tried till this level. In spring I have done till this level. Finally I want html tags in a string.
// Spring freemarker specific code
Configuration configuration = freemarkerConfig.getConfiguration();
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
// My application specific code
String temp = tempLoader.getTemplateForCurrentLogin();
Thanks.
To tie together the bits of code you posted, you can do something like this:
// you already have this bit
String templateText = tempLoader.getTemplateForCurrentLogin();
// now programmatically instantiate a template
Template t = new Template("t", new StringReader(templateText), new Configuration());
// now use the Spring utility class to process it into a string
// myData is your data model
String output = FreeMarkerTemplateUtils.processTemplateIntoString(template, myData);
This java method will process the freemarker template and will give html tags as String after constructing the template.
public static String processFreemarkerTemplate(String fileName) {
StringWriter stringWriter = new StringWriter();
Map<String, Object> objectMap = new HashMap<>();
Configuration cfg = new Configuration(Configuration.VERSION_2_3_24);
try {
cfg.setDirectoryForTemplateLoading(new File("path/of/freemarker/template"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
Template template = cfg.getTemplate(fileName);
template.process(objectMap, stringWriter);
} catch (IOException | TemplateException e) {
e.printStackTrace();
} finally {
if (stringWriter != null) {
try {
stringWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringWriter.toString();
}