Use property in OSGI component declaration - liferay

In my module, in OSGI component declarationIi need to use a property which will be in my portal-ext.properties, like that :
#Component(
immediate = true,
property = {
"dispatcher=FORWARD",
"dispatcher=REQUEST",
"servlet-context-name=",
"servlet-filter-name=Detail UC Filter",
"url-pattern=/web/guest/" + PropsUtil.get("myPath") + "/*"
}
But i get the compilation error : " The value for annotation attribute Component.property must be a constant expression". How can i do to use a property here?

But i get the compilation error : " The value for annotation attribute Component.property must be a constant expression". How can i do to use a property here?
The entry:
"url-pattern=/web/guest/" + PropsUtil.get("myPath") + "/*"
is the problem. This is because annotations can only have values that are compile-time constants. Obviously this property is not a compile time constant as its value depends on calling a method.
If you want to supply property values at runtime then you can do this in OSGi using Configuration Admin. All Declarative Services components are configurable by default, using a pid which is either:
User configured by setting #Component(configurationPid="foo")
User configured by setting #Component(name="bar")
Defaulted using the fully qualified class name of the component implementation
When you supply a configuration dictionary to Configuration Admin which matches the pid for your DS component then it will be bound to the component.
Your component properties will be merged with the configuration dictionary (with the configuration overriding the static properties). This can be received by your component using an #Activate method
If your component is registered as a service then your service properties will also be updated.
If your component has a #Modified method then these changes will be dynamic, otherwise your component instance will be deactivated and discarded, and a new instance created and activated.
You can force your component not to activate until a configuration has been provided by setting your component's configuration policy. This is useful when you have a property that needs to exist, but can't be known until runtime.
#Component(configurationPolicy=ConfigurationPolicy.REQUIRE)

You can set any of these properties using a config admin configuration.
So one approach is to have a separate component that writes a configuration for this component.
You can use configurationPolicy = ConfigurationPolicy.REQUIRE to prevent the component to become activated before this configuration is present.
Another approach is to use a component factory. See this blog from Scott.

Related

Properties files to control form inputs based on roles

The requirements of the application that I'm building demands that user roles are to be dynamic, they will be stored in the database, and they will also be mapped to functionalities (forms) of the application, also stored in the database.
Restricting a role from accessing a specific page won't be difficult, but the requirements also states that form inputs must be customized based on roles, which means, an input can be mandatory or not, visible or not, read-only or not based on the role.
My approach to control these restrictions is based on creating a property file for each role, which will store all the inputs of all the forms in the application, as keys, and a long string as value in which we define the state of the input, like the following:
user-inputs.properties
# form.input=mandatory:visibility
searchBooks.bookName=true:true
searchBooks.bookCategory=false:true
searchBooks.authorName=false:false
admin-inputs.properties
searchBooks.bookName=true:true
searchBooks.bookCategory=false:true
searchBooks.authorName=false:true
And then do some magic Java code, whenever a form is accessed, read its inputs properties from the file of the specific user role, and parse the values so I could provide the right value for the rendered="" and required="" attribute of an <h:inputText/>.
This could be a solution, but the inputs of the application are much more than a book name and category, means I will be putting lots of required and rendered attributes which will make JSF pages look ugly with huge amount of variables in the managed bean.
Is there a better approach/framework/solution to my issue?
I think that you are in the right way, and i will continue using your approach which consists of creating multiple property files, one for each user, except that we will not use a any "huge amount of variables
in the managed bean".
So, the first step consists on managing multiple resource properties using a single resource bundle prefix ( the <var></var> in <resource-bundle>), in the second step we will see how to switch between those files, and in the last step we will read from property file using JSTL.
Managing multiple property files:
We start by defining our ResourceBundle in the faces-config file:
<application>
<resource-bundle>
<base-name>UserMessages</base-name>
<var>msgs</var>
</resource-bundle>
</application>
UserMessages is a ResourceBundle where we will implement the logic that allow us to switch between our property files (assuming that yourpackage.user-inputs is the fully qualified name of your user-inputs.properties):
import java.util.Enumeration;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;
public class UserMessages extends ResourceBundle {
public UserMessages() {
// we are loading user-inputs.properties as the default properties file
setParent(getBundle("yourpackage.user-inputs", FacesContext.getCurrentInstance()
.getViewRoot().getLocale()));
}
#Override
protected Object handleGetObject(String key) {
// we could just return parent.getObject(key) but we want to respect JSF recommandations
try {
return parent.getObject(key);
} catch (MissingResourceException e) {
return "???" + key + "???";
}
}
#Override
public Enumeration<String> getKeys() {
return parent.getKeys();
}
// this is the method that will allow us to switch between our .properties
public void setResourceBundle(String basename) {
setParent(getBundle(basename, FacesContext.getCurrentInstance()
.getViewRoot().getLocale()));
}
}
Switching between property files:
In order to switch from a property file to another we will need to use the method setResourceBundle(String basename) that we just declared in our class above, So in the managed bean where you are declaring your business logic and where you are intending to switch files depending on the user's role, you need to inject the bundle, like:
//don't forget adding getters and setters or you end with NullPointerException
#ManagedProperty("#{msgs}")
private UserMessages userMesssages;
Then, to switch to another file (admin-inputs.properties), just use it like this:
//yourpackage.admin-inputs is the fully qualified name
userMesssages.setResourceBundle("yourpackage.admin-inputs");
NB: You can inject the bundle in that way (above) only in request scoped beans, to use it in broader scopes please see: Read i18n variables from properties file in a Bean
Now, as we can switch easily from the user-inputs to the admin-inputs, the last step is the easiest one.
Parsing the property file:
The bad news, is that when using this approach you will need to add rendered="" and required="" attribute to every input you are willing to manage (but don't forget that the good ones was that you will not need to manage variables in managed beans ;) ).
First, you need to add JSTL namespaces declaration on the top of your xhtml file:
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
you can find more about JSTL functions in the javadocs, regarding the function substringAfter:
Returns a subset of a string following a specific substring.
Example:
P.O. Box: ${fn:substringAfter(zip, "-")}
The function substringBefore:
Returns a subset of a string before a specific substring.
Example:
Zip (without P.O. Box): ${fn:substringBefore(zip, "-")}
Second, as the first part of your String represents the required attribute:
//Returns the substring of msgs['searchBooks.authorName'] before the first occurrence of the separator ':'
required="${fn:substringBefore(msgs['searchBooks.authorName'], ':')}"
and the second part:
//Returns the substring of msgs['searchBooks.authorName'] after the first occurrence of the separator ':'.
rendered="${fn:substringAfter(msgs['searchBooks.authorName'], ':')}"
See also:
JSF Internationalization f:loadbundle or through faces-config:
Performance point
Difference between by Application#getResourceBundle() and ResourceBundle#getBundle() in JSF 2.0
How to remove the surrounding ??? when message is not found in
bundle
Context Sensitive Resource Bundle entries in JavaServer Faces
applications – going beyond plain language, region & variant
locales

Hibernate validator programmatic constraints declaration and JSF

I Have a JSF-2.2 web app on a WildFly 8.1 app server shiping Hibernate-validator 5.1
I want to set some constrainst programmaticaly using the fluent API, because they depends on the case for example a min and max of a #Size constraint could vary or a field could be #NotNull or not...
so I try to programmaticaly configure constraints such as describe here : http://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html_single/#section-programmatic-api
I do somthing like that to try (in a EJB #Singleton #Startup):
HibernateValidatorConfiguration configuration = Validation
.byProvider( HibernateValidator.class )
.configure();
ConstraintMapping constraintMapping = configuration.createConstraintMapping();
constraintMapping
.type( Car.class )
.property( "manufacturer", FIELD )
.constraint( new NotNullDef() )
.property( "licensePlate", FIELD )
.ignoreAnnotations()
.constraint( new NotNullDef() )
.constraint( new SizeDef().min( 2 ).max( 14 ) );
Validator validator = configuration.addMapping( constraintMapping )
.buildValidatorFactory()
.getValidator();
But then JSF don't use this new constraints mapping.
I can submit forms without problem even if I break the constraints programmaticaly set
I don't know how to configure the Validator or ValidatorFactory JSF is using or how to provide to JSF an other Validator or ValidatorFactory...
Or may be It's more about configuring WildFly server, something to do in a config file or JNDI, I don't have a clue...
EDIT
I try to bind new Validator and validator factory in JNDI
But I can't because "Naming context is read-only"
Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context context = new InitialContext(jndiProperties);
context.bind("java:comp/Validator", factory.getValidator());
context.bind("java:comp/ValidatorFactory", factory);
Thank you Hardy
As you proposed I post Hibenate Validator improvement
https://hibernate.atlassian.net/browse/HV-955
There is no way atm to do what you are after. Hibernate Validator has indeed the programmatic mapping, but it is a Hibernate Validator specific feature. There is no way to bootstrap this functionality in a Bean Validation way. I am saying this, since the only way to customize your ValidatorFactory and hence Validator instance within the container is via validation.xml. And there is no mechanism for the fluent API in this configuration file.
Your JNDI idea is in principal good, but as you say, it is only read only.
validation.xml allows for vendor specific properties though. One could imagine a property like org.hibernate.validator.config_factory=acme.MyConfig. The value of the property would point to a fully specified class which would contain some sort of factory method which returns the programmatic mapping to be added to the configuration. Unfortunately, such a property does not yet exist. You could open an issue here though ;-)

CDI extension, altering processed type

Using Weld 1.1.13.Final in test with Arquillian....
Let's say I inject into a field something volatile. Something like a property subject to change that I want the bean owning the injection point to receive change events. Thought about creating a CDI extension.
Caught ProcessAnnotatedType event and looking for all fields that have an custom annotation on field injection points:
<T> void pat(#Observes ProcessAnnotatedType<T> event, BeanManager bm) {
final AnnotatedType<T> target = event.getAnnotatedType();
for (AnnotatedField<? super T> field : target.getFields())
if (field.isAnnotationPresent(Value.class)) { // ignore that I don't check #Inject here for the moment
CtClass wrapper = pool.get(target.getJavaClass().getName());
ConstPool cp = wrapper.getClassFile().getConstPool();
CtMethod m = CtNewMethod.make(....)
....
wrapper.addMethod(m);
event.setAnnotatedType(bm.createAnnotatedType(wrapper.toClass()));
}
}
Had even grabbed thereafter all the injection points for fields and replaced the underlying WeldField with a new Field corresponding the "wrapper" type. Otherwise bean validation fails.
But this only works for stuff setup during startup not when for example Arquillian uses the Bean Manager to initialize a class that injects one of my "wraps". Things fail since the Bean Resolver uses the Type as a hash key to find beans.
Basically I don't think I can "mask" a class that is annotated (made into a bean) by the CDI with an extra method to receive custom events. Would have been cool but a Type is a Type (i.e. no idea how to proxy or fake the equals/hashCode).
Got it. Turns out the compute value function (google extension) inside the TypeSafeBeanResolver resolver (at least the CDI Weld implementation) is smart. If I just extend the class:
CtClass wrapper = pool.makeClass(target.getJavaClass().getName()+"Proxy");
wrapper.setSuperclass(pool.get(target.getJavaClass().getName()));
.....
final AnnotatedType<T> other = bm.createAnnotatedType(wrapper
.toClass());
then everything works fine. Tested capturing an event in a bean. Will post the code on a Gist with a comment.

JsConfig<MyClass>.ExcludePropertyNames example, not working for me

Trying to exclude properties from a model from being included during serialization.
I am using the following syntax:
JsConfig<MyTestClass>.ExcludePropertyNames = new[] { "ShortDescription" };
Just after that I have the following:
return (from o in __someProvider.GetAll() select (new
{
o.Name,
o.ShortDescription
o.InsertDate
}).TranslateTo<MyTestClass>()).ToList()
However once result is returned from the method, it still contains "ShortDescription" field in the Json. Am I doing something wrong?
JsConfig<T>.ExcludePropertyNames appears to be checked only once for each type, in a static constructor for TypeConfig<T>. Thus, if you are configuring ExcludePropertyNames in your service class, just before returning your response, it might be too late -- the TypeConfig properties may already be set up and cached for MyTestClass. I was able to reproduce this.
A more reliable alternative is to move all of your JsConfig<T> configuration to your AppHost setup code.
If you really do need to do this in your service class, e.g. if you are only conditionally excluding property names, then an alternative approach would be to ensure that JsConfig.IncludeNullValues is false (I believe it is by default) and in your service code set ShortDescription to null when appropriate.

Axis SecureSocketFactory - Setting the constructor attributes

I have a customer SecureSocketFactory set to be used by Axis when making an https connection using the following property:
AxisProperties.setProperty("axis.socketSecureFactory",
"com.metavante.csp.model.manager.mobilepayments.MonitiseSSLSocketFactory");
When this class is instantiated by Axis, the constructor with a Hashtable (attributes) is called. I see the timeout attribute is set in this table. Is there anyway to set more values in this?
I would like to be able to configure the Socket Factory on a per-instance scenario instead of globally by using static or system properties.
Edit: I found out these attributes are actually the HttpSender (BasicHandler) options. I still am unable to set these dynamically though.
I figured out a way around the problem. In my code where I wanted to set the property I use:
serviceLocator.getEngine().setOption(USE_CERT_PROPERTY, new Boolean(true));
where getEngine returns the AxisEngine in use. Then in the socket factory I can:
Boolean useSMS = (Boolean) MessageContext.getCurrentContext().getProperty(OtherClass.USE_CERT_PROPERTY);
I could set the object to whatever, maybe I'll go with the certificate name I needed. Hope this helps someone.
You can retrieve the SocketFactory instance and then change or add attributes, if you are interested in modify SocketFactory behavior. But if you do this, you also should inject the HashTable attribute (with the timeout). I think there is not a final and pretty solution.
AxisProperties.setProperty("org.apache.axis.components.net.SecureSocketFactory", MyAxisSocketFactory.class.getName());
MyAxisSocketFactory factory = (MyAxisSocketFactory) SocketFactoryFactory.getFactory("https", myHashTableParams);
factory.setMyStuff();
After this code, the instance of SocketFactory will be created and configured, and ready to use in web services, or whatever ^_^

Resources