Retrieve key in JSF from the proper i18n properties file - jsf-2

does somebody know whats wrong with the next method?
public static String getMessageBundleString(String key, String localeAcronym) throws MissingResourceException {
FacesContext facesContext = FacesContext.getCurrentInstance();
String messageBundleName = facesContext.getApplication().getMessageBundle();
ResourceBundle bundle = ResourceBundle.getBundle(messageBundleName, new Locale(localeAcronym));
//THE LOCALE OF THIS BUNDLE IS ALWAYS 'es_ES' !!!
return bundle.getString(key);
}
In a Primefaces/JSF environment, I want to retrieve a key from the proper i18n properties file.
But it always take it from the messages_es_ES.properties file.
Following invocations return same value (='Inicio'):
getMessageBundleString("home", "es_ES")
getMessageBundleString("home", "uk_UK")
messages_es_ES.properties:
home=Inicio
messages_uk_UK.properties:
home=Home
Thanks
Here some of my faces-config.xml content:
<application>
<locale-config>
<supported-locale>es_ES</supported-locale>
<supported-locale>uk_UK</supported-locale>
</locale-config>
<message-bundle>cfg.i18n.messages</message-bundle>
<resource-bundle>
<base-name>cfg.i18n.messages</base-name>
<var>msgs</var>
</resource-bundle>
</application>

This variant works (separating country and language):
public static String getMessageBundleString(String key, String language, String country) throws MissingResourceException {
FacesContext facesContext = FacesContext.getCurrentInstance();
String messageBundleName = facesContext.getApplication().getMessageBundle();
ResourceBundle bundle = ResourceBundle.getBundle(messageBundleName, new Locale(language, country));
//Valid ones: "es","ES"; "en","GB"!!!
return bundle.getString(key);
}

Did you try this variation?
getMessageBundleString("home", "es")
getMessageBundleString("home", "en")
messages_es.properties:
home=Inicio
messages_en.properties:
home=Home

Related

Google Tink: How to get raw key string from a KeysetHandle?

I am new to Tink and would like to extract the raw key data(in String form) from KeysetHandle which I generated like this:
keysetHandle = KeysetHandle.generateNew(
AeadKeyTemplates.AES128_GCM);
Or maybe some other API to get it.
How can I achieve this?
You can write the Keyset to disk with either KeysetHandle.write(), which requires encryption, other CleartextKeysetHandle.write(). Both require a BinaryKeysetWriter or JsonKeysetWriter.
Example will help. Here is how you would use CleartextKeysetHandle.write() to observe the key profile:
Try this for display:
// display key [Caveat: ONLY for observation]
public void display_key_profile_for_test_observation_only(KeysetHandle keysetHandle) throws IOException, GeneralSecurityException
{
System.out.println("\nDisplay key:");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CleartextKeysetHandle.write(keysetHandle, JsonKeysetWriter.withOutputStream(outputStream));
System.out.println("\n"+ new String(outputStream.toByteArray()));
}
As this belongs to a class, you may have to do some slight code modification. You see the keyword this denoting that the code snippets come from a class. Here is the test usage:
public void trial_usage_key_generation() throws IOException, GeneralSecurityException {
for (CIPHER_SYMMETRIC_ALGOS algo_type : CIPHER_SYMMETRIC_ALGOS.values()) {
System.out.println("Generating key for : " + algo_type);
KeysetHandle keysetHandle = this.generate_key_for_test_observation_only(algo_type);
this.display_key_profile_for_test_observation_only(keysetHandle);
}
}
You can use reflection to get the keyset as code below, or JsonKeysetWriter to get base64ed key bytestring (still needs to be unserialized to corresponding key object to get the raw key bytes).
KeysetHandle keysetHandle = KeysetHandle.generateNew(
AeadKeyTemplates.CHACHA20_POLY1305);
Method method = keysetHandle.getClass().getDeclaredMethod("getKeyset");
method.setAccessible(true);
Keyset keyset = (Keyset) method.invoke(keysetHandle);
ChaCha20Poly1305Key key = ChaCha20Poly1305Key.parseFrom(keyset.getKey(0).getKeyData().getValue());
byte[] keyBytes = key.getKeyValue().toByteArray();

Entity Framework with oracle can´t change connection string

I´m using Entity Framework (latest Version) with the Oracle Driver (latest Version) in an ASP.NET MVC 5 Application. I want to set the connection string for my model during runtime, but every time I do it receives the data from the table that I used to create the model. It´s the same when I change the connection string in the web.config. Does anybody know why it behaves this way?
this is how i create the connection string:
public static string CreateConnectionString(string userName, string service)
{
const string providerName = "Oracle.ManagedDataAccess.Client";
OracleConnectionStringBuilder oraBuilder = new OracleConnectionStringBuilder();
oraBuilder.DataSource = service + ":1521/" + service;
oraBuilder.UserID = userName;
oraBuilder.Password ="xxx";
oraBuilder.PersistSecurityInfo = true;
EntityConnectionStringBuilder efBuilder = new EntityConnectionStringBuilder();
efBuilder.Metadata = "res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl";
efBuilder.Provider = providerName;
efBuilder.ProviderConnectionString = oraBuilder.ConnectionString;
return efBuilder.ConnectionString;
}
this is the overload of the model´s constructor:
public Entities(string connectionString)
: base(connectionString)
{
}
this ist my connection string:
try this connection string:
<connectionStrings>
<add name="VoccDbContext" connectionString="metadata=res://*/Entities.Vocc.VoccModel.csdl|res://*/Entities.Vocc.VoccModel.ssdl|
res://*/Entities.Vocc.VoccModel.msl;provider=Oracle.DataAccess.Client;provider connection string="DATA SOURCE=sameDbName;PASSWORD=somePass;USER ID=someUser;""providerName="System.Data.EntityClient" />
</connectionStrings>
DIRECTORY_SERVERS=(tnsnames.somesite.org:389:636)
DEFAULT_ADMIN_CONTEXT="dc=site,dc=com"
DIRECTORY_SERVER_TYPE=OID
here( LDAP.ORA file) to be modified with correct LDAP Parameters
Do not edit XXXModels.cs. Try to edit XXXModels.Context.tt.
Add following code after public <#=code.Escape(container)#>()...}
public <#=code.Escape(container)#>(string connectionString)
: base(connectionString)
{
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
this.Configuration.LazyLoadingEnabled = false;
<#
}
foreach (var entitySet in container.BaseEntitySets.OfType<EntitySet>())
{
// Note: the DbSet members are defined below such that the getter and
// setter always have the same accessibility as the DbSet definition
if (Accessibility.ForReadOnlyProperty(entitySet) != "public")
{
#>
<#=codeStringGenerator.DbSetInitializer(entitySet)#>
<#
}
}
#>
}

How to create action for HtmlCommandLink#setActionExpression()

I am trying to add commandlink programatically, but I am not able to add action.
HtmlCommandLink link = new HtmlCommandLink();
link.setValue(data);
link.setActionExpression(no idea);
How do I create it?
Use ExpressionFactory#createMethodExpression().
Here's a convenience method:
private static MethodExpression createMethodExpression(String expression, Class<?> returnType) {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().getExpressionFactory().createMethodExpression(
context.getELContext(), expression, returnType, new Class[0]);
}
Here's how you could use it, provided that you've a public String doSomething() {} action in a managed bean identified by #{bean}:
link.setActionExpression(createMethodExpression("#{bean.doSomething}", String.class));

NServiceBus Messages and Encapsulation

I hope this is not an idiot question... my brain is so full of new stuff it hurts.
I'm attempting to get to know NServiceBus a little better.
My message classes look like this:
public class Address // value object
{
public readonly string AddressLine1;
public readonly string AddressLine2;
public readonly string AddressLine3;
public readonly string City;
public readonly string Country;
public readonly string PostCode;
public Address(string addressLine1,
string addressLine2,
string addressLine3,
string city,
string country,
string postCode)
{
AddressLine1 = addressLine1;
AddressLine2 = addressLine2;
AddressLine3 = addressLine3;
City = city;
Country = country;
PostCode = postCode;
}
}
Problem is NServiceBus serializer cannot deal with it (understandably so) and i end up having to revert to auto properties. I can live with it for this learning exercise... but is there a way to use the message class above?
I thought I would ask instead of delving into NServiceBus source code. Thanks!
I have not used NSB for some time, but i remember that there was a contrib module that contains a JsonSerializer based on Newtonsoft Json.NET library.
The json.net lib supports (de)serialization of objects like the one you describe. You can find more details about what is supported by serialization libraries here.
I'm pretty sure it'll work if you expose get/private set properties rather than fields.

f:convertDateTime not being strict in pattern match?

I have a f:convertDateTime with a pattern of mm/dd/yyyy. However, people are able to enter 2/19/78 and it would be 0078 rather then 1978 or 2078. I want to force people to enter in all 4 digits.
I tried using a regexPattern validator, but that is complaining because it wants a string and not a Date object. Seems that the converters fire first and validators validate the converted value?
I guess I could write a custom converter or validator, but this seems like such a simple thing I figure I'm doing something wrong.
The javadocs for the convertor say it is strict in matching the pattern, but I'm not seeing that?
Any ideas or suggestions?
thanks!
It's only strict for days/months, not for years. Here's an extract of relevance from SimpleDateFormat javadoc which <f:convertDateTime> is using under the covers:
For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.
It's by design indeed not possible to fire validators before converters. Essentially, this one should have thrown a ConverterException because the input is not in the proper format. I'd create a custom converter which validates the pattern beforehand. Something like this:
#FacesConverter("validatingPatternDateTimeConverter")
public class ValidatingPatternDateTimeConverter extends DateTimeConverter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
String regex = getMandatoryAttribute(component, "validateRegex");
String pattern = getMandatoryAttribute(component, "convertPattern");
if (value != null && !value.matches(regex)) {
throw new ConverterException(new FacesMessage(String.format("Invalid date, must be in pattern %s", pattern)));
}
setPattern(pattern);
return super.getAsObject(context, component, value);
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
setPattern(getMandatoryAttribute(component, "convertPattern"));
return super.getAsString(context, component, value);
}
private String getMandatoryAttribute(UIComponent component, String name) {
String value = (String) component.getAttributes().get(name);
if (value == null || value.isEmpty()) {
throw new IllegalArgumentException(String.format("<f:attribute name=\"%s\"> is missing.", name));
}
return value;
}
}
which is to be used as follows:
<h:inputText value="#{bean.date}">
<f:converter converterId="validatingPatternDateTimeConverter" />
<f:attribute name="validateRegex" value="\d{1,2}/\d{1,2}/\d{4}" />
<f:attribute name="convertPattern" value="MM/dd/yyyy" />
</h:inputText>

Resources