I understand that there is the ServletContextPropertyPlaceholderConfigurer which:
resolves placeholders as ServletContext init parameters (that is, web.xml context-param entries).
Does anyone know of a PropertyPlaceholderConfigurer that would similarly resolve placeholders as portlet-preferences (that is, portlet.xml portlet-preference entries)?
Here's how I solved the problem, I ended up writing a class similar to ServletContextPropertyPlaceholderConfigurer.. :-)
public class PortletConfigPropertyPlaceholderConfigurer extends
PropertyPlaceholderConfigurer implements PortletConfigAware {
private PortletConfig portletConfig;
private boolean configOverride = false;
public void setPortletConfig(PortletConfig portletConfig) {
this.portletConfig = portletConfig;
}
public void setConfigOverride(boolean configOverride) {
this.configOverride = configOverride;
}
#Override
protected String resolvePlaceholder(String placeholder, Properties props) {
String value = null;
if (this.configOverride && this.portletConfig != null) {
value = resolvePlaceholder(placeholder, this.portletConfig);
}
if (value == null) {
value = super.resolvePlaceholder(placeholder, props);
}
return value;
}
protected String resolvePlaceholder(String placeholder,
PortletConfig portletConfig) {
return portletConfig.getInitParameter(placeholder);
}
}
Cheers,
Gerson
Related
I want to provide values from properties file in tags section of the swagger for ex: tags = "${metric.tags}" but not able to pickup from properties file. for values it is working fine value = "${metric.value}".
I have made plugin configuration in swagger configuration file and it started working as per my requirement.
#Bean
public TranslationOperationBuilderPlugin translationPlugin() {
return new TranslationOperationBuilderPlugin();
}
#Order(Ordered.LOWEST_PRECEDENCE)
public static class TranslationOperationBuilderPlugin implements OperationBuilderPlugin {
#Autowired
Environment environment;
#Override
public boolean supports(DocumentationType delimiter) {
return true;
}
#Override
public void apply(OperationContext context) {
String summary = context.operationBuilder().build().getSummary();
String notes = context.operationBuilder().build().getNotes();
Set<String>tags = context.operationBuilder().build().getTags();
Set<String>translatedTags= new HashSet<>();
for(String tag:tags) {
if(environment.getProperty(tag)!=null) {
translatedTags.add(environment.getProperty(tag));
}else {
translatedTags.add(tag);
}
}
ModelReference modelReference= context.operationBuilder().build().getResponseModel();
AllowableListValues allowableValues=(AllowableListValues) modelReference.getAllowableValues();
if(allowableValues!=null && allowableValues.getValues()!=null) {
List<String> translatedAllowables=new ArrayList<>();
for(String value:allowableValues.getValues()) {
if(environment.getProperty(value)!=null) {
translatedAllowables.add(environment.getProperty(value));
}else {
translatedAllowables.add(value);
}
}
allowableValues.getValues().removeAll(allowableValues.getValues());
allowableValues.getValues().addAll(translatedAllowables);
}
//String summaryTranslated = apiDescriptionPropertiesReader.getProperty(summary);
//String notesTranslated = apiDescriptionPropertiesReader.getProperty(notes);
//context.operationBuilder().summary(summaryTranslated);
//context.operationBuilder().notes(notesTranslated);
context.operationBuilder().tags(translatedTags);
}
Updated my code as per #Ryan Emerson suggestion but still i don't see any auto-generation of Impl file and proto file
#AutoProtoSchemaBuilder(
includeClasses = { Book.class, Author.class },
schemaFileName = "library.proto",
schemaFilePath = "proto/")
interface DummyInitializer extends SerializationContextInitializer {
}
Author.class
public class Author {
private final String name;
private final String surname;
#ProtoFactory
public Author(String name, String surname) {
this.name = (String)Objects.requireNonNull(name);
this.surname = (String)Objects.requireNonNull(surname);
}
#ProtoField(
number = 1
)
public String getName() {
return this.name;
}
#ProtoField(
number = 2
)
public String getSurname() {
return this.surname;
}
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o != null && this.getClass() == o.getClass()) {
Author author = (Author)o;
return this.name.equals(author.name) && this.surname.equals(author.surname);
} else {
return false;
}
}
public int hashCode() {
return Objects.hash(new Object[]{this.name, this.surname});
}
}
Book.class
public class Book {
private final String title;
private final String description;
private final int publicationYear;
private final Set<Author> authors;
#ProtoFactory
public Book(String title, String description, int publicationYear, Set<Author> authors) {
this.title = (String)Objects.requireNonNull(title);
this.description = (String)Objects.requireNonNull(description);
this.publicationYear = publicationYear;
this.authors = (Set)Objects.requireNonNull(authors);
}
#ProtoField(
number = 1
)
public String getTitle() {
return this.title;
}
#ProtoField(
number = 2
)
public String getDescription() {
return this.description;
}
#ProtoField(
number = 3,
defaultValue = "-1"
)
public int getPublicationYear() {
return this.publicationYear;
}
#ProtoField(
number = 4
)
public Set<Author> getAuthors() {
return this.authors;
}
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o != null && this.getClass() == o.getClass()) {
Book book = (Book)o;
return this.publicationYear == book.publicationYear && this.title.equals(book.title) && this.description.equals(book.description) && this.authors.equals(book.authors);
} else {
return false;
}
}
public int hashCode() {
return Objects.hash(new Object[]{this.title, this.description, this.publicationYear, this.authors});
}
}
context-initialzer class with over-ride methods
import org.infinispan.protostream.SerializationContext;
import java.io.UncheckedIOException;
public class contextInitializer implements DummyInitializer {
#Override
public String getProtoFileName() {
return null;
}
#Override
public String getProtoFile() throws UncheckedIOException {
return null;
}
#Override
public void registerSchema(SerializationContext serCtx) {
}
#Override
public void registerMarshallers(SerializationContext serCtx) {
}
}
Then ClassA that instantiates context-initializer
public class classA {
DummyInitializer myInterface= new contextInitializer();
//Create a new cache instance
public void startCache() {
{
try {
manager = new DefaultCacheManager("src/main/resources/infinispan.xml");
GlobalConfigurationBuilder builder= new GlobalConfigurationBuilder();
builder.serialization().addContextInitializers(myInterface);
System.out.println("------------------>"+ builder.serialization().addContextInitializers(myInterface));
cache = manager.getCache();
System.out.println(cache.getName()+" is initialized ");
} catch (IOException e) {
throw new IllegalArgumentException("Failed to initialize cache due to IO error",e);
}
}
}
Maven
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-bom</artifactId>
<version>${infinispan.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.infinispan.protostream</groupId>
<artifactId>protostream-processor</artifactId>
<scope>provided</scope>
</dependency>
I am still not seeing any auto-generated proto file. Can someone tell me what am i doing wrong ?
You also need to add the org.infinispan.protostream:protostream-processor artifact as a dependency in order for code to be generated:
<dependency>
<groupId>org.infinispan.protostream</groupId>
<artifactId>protostream-processor</artifactId>
<version>4.3.2.Final</version>
</dependency>
Once that's present, a DummyInitializerImpl.java class will be generated that automatically registers the proto file and marshallers for the Book and Author classes. Remember that these classes must also have protostream annotations in order for the schema and marshallers to be generated. Please see the documentation for code examples.
There are two issues with your current code:
You have provided a DummyInitializerImpl class, but that is what should be generated by #AutoProtoSchemaBuilder.
In your DummyInitializerImpl you're trying to register the Infinispan UUIDMarshaller for the Book and Author types. This won't work as that marshaller is designed for the java UUID class.
I suspect that the two issues are due to a missunderstanding of how the code generation works. If you just required a SerializationContextInitializer for the Author and Book classes, it's not necessary to create the DummyInitializerImpl manually and you definitely don't need to utilise the UUIDMarshaller.
You are not saying which build system is used. maven maybe ? Did you add the protostream annotation processor as a dependency? Having a definite answer to these questions would help unriddle the issue of code generation. And after, we still need to find out who is supposed to initialize that dummyInitializer field.
I'm providing a value via a conditional Bean. If the Condition is met everything is fine but if the condition is not met (hence the bean is not present) my code fails. is there some way to check if the bean is defined before hand. in SpEL ?
I tried something like
#{someBean? someBean.myValue:null} but it does not work.
See this answer for why this works...
#SpringBootApplication
public class So56189689Application {
public static void main(String[] args) {
SpringApplication.run(So56189689Application.class, args);
}
#Value("#{containsObject('foo') ? getObject('foo').foo : null}")
String foo;
#Bean
public ApplicationRunner runner() {
return args -> System.out.println(foo);
}
// #Bean
// public Foo foo() {
// return new Foo();
// }
public static class Foo {
private String foo = "bar";
public String getFoo() {
return this.foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
}
EDIT
The #root object of the SpEL Expression is a BeanExpressionContext, you can invoke containsObject() and getObject() methods on that context.
Here's the code from the BeanExpressionContext:
public boolean containsObject(String key) {
return (this.beanFactory.containsBean(key) ||
(this.scope != null && this.scope.resolveContextualObject(key) != null));
}
public Object getObject(String key) {
if (this.beanFactory.containsBean(key)) {
return this.beanFactory.getBean(key);
}
else if (this.scope != null){
return this.scope.resolveContextualObject(key);
}
else {
return null;
}
}
Hello I have a problem with osgi on servicemix.
It cannot bind or unbind service to delegate cache, when using TaskListener interface. JavaDelegate works fine in osgi with delegate expression.
Could this solution solve the problem or is there something else needed with BlueprintContextELResolver? Because the blueprint with the
service ref="something" interface="org.activiti.engine.delegate.TaskListener"/>
package org.activiti.osgi.blueprint;
/**
* #see org.activiti.spring.ApplicationContextElResolver
*/
public class BlueprintELResolver extends ELResolver {
private Map<String, JavaDelegate> delegateMap = new HashMap<String, JavaDelegate>();
private Map<String, TaskListener> taskListenerMap = new HashMap<String, TaskListener>();
private Map<String, ActivityBehavior> activityBehaviourMap = new HashMap<String, ActivityBehavior>();
public Object getValue(ELContext context, Object base, Object property) {
if (base == null) {
// according to javadoc, can only be a String
String key = (String) property;
LOGGER.info("Show string key: {}", key);
LOGGER.info("Show property: {}", property);
for (String name : delegateMap.keySet()) {
if (name.equalsIgnoreCase(key)) {
LOGGER.info("Show property JavaDelegate: {}", name);
context.setPropertyResolved(true);
return delegateMap.get(name);
}
}
for (String name : taskListenerMap.keySet()) {
if (name.equalsIgnoreCase(key)) {
LOGGER.info("Show property TaskListener: {}", name);
context.setPropertyResolved(true);
return taskListenerMap.get(name);
}
}
for (String name : activityBehaviourMap.keySet()) {
if (name.equalsIgnoreCase(key)) {
context.setPropertyResolved(true);
return activityBehaviourMap.get(name);
}
}
}
return null;
}
#SuppressWarnings("rawtypes")
public void bindService(JavaDelegate delegate, Map props) {
String name = (String) props.get("osgi.service.blueprint.compname");
delegateMap.put(name, delegate);
LOGGER.info("added Activiti service to delegate cache {}", name);
}
#SuppressWarnings("rawtypes")
public void unbindService(JavaDelegate delegate, Map props) {
String name = (String) props.get("osgi.service.blueprint.compname");
if(delegateMap.containsKey(name)) {
delegateMap.remove(name);
}
LOGGER.info("removed Activiti service from delegate cache {}", name);
}
#SuppressWarnings("rawtypes")
public void bindTaskListenerService(TaskListener delegate, Map props) {
String name = (String) props.get("osgi.service.blueprint.compname");
taskListenerMap.put(name, delegate);
LOGGER.info("added Activiti service to delegate cache {}", name);
}
#SuppressWarnings("rawtypes")
public void unbindTaskListenerService(TaskListener delegate, Map props) {
String name = (String) props.get("osgi.service.blueprint.compname");
if(taskListenerMap.containsKey(name)) {
taskListenerMap.remove(name);
}
LOGGER.info("removed Activiti service from delegate cache {}", name);
}
#SuppressWarnings("rawtypes")
public void bindActivityBehaviourService(ActivityBehavior delegate, Map props) {
String name = (String) props.get("osgi.service.blueprint.compname");
activityBehaviourMap.put(name, delegate);
LOGGER.info("added Activiti service to activity behaviour cache {}", name);
}
#SuppressWarnings("rawtypes")
public void unbindActivityBehaviourService(ActivityBehavior delegate, Map props) {
String name = (String) props.get("osgi.service.blueprint.compname");
if(activityBehaviourMap.containsKey(name)) {
activityBehaviourMap.remove(name);
}
LOGGER.info("removed Activiti service from activity behaviour cache {}", name);
}
public boolean isReadOnly(ELContext context, Object base, Object property) {
return true;
}
public void setValue(ELContext context, Object base, Object property,
Object value) {
}
public Class<?> getCommonPropertyType(ELContext context, Object arg) {
return Object.class;
}
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context,
Object arg) {
return null;
}
public Class<?> getType(ELContext context, Object arg1, Object arg2) {
return Object.class;
}
}
After this I still get:
Exception while invoking TaskListener: Unknown property used in
expression: ${expression}
I have experienced a similar problem where the El resolver was not being fully initiated.
I resolved the problem by overloading the BlueprintExpressionManager when loading the configuration:
public class BlueprintExpressionManagerReordered extends ExpressionManager
{
#Override
protected ELResolver createElResolver(VariableScope variableScope){
CompositeELResolver elResolver = new CompositeELResolver();
elResolver.add(new VariableScopeElResolver(variableScope));
elResolver.add(new ArrayELResolver());
elResolver.add(new ListELResolver());
elResolver.add(new MapELResolver());
if (_blueprintContextELResolver != null) {
elResolver.add(_blueprintContextELResolver);
}
elResolver.add(_blueprintELResolver);
elResolver.add(new BeanELResolver());
return elResolver;
}
}
It is called during init of the process engine configuration:
public class ProcessEngineFactoryWithELResolverReordered extends ProcessEngineFactoryWithELResolver
{
private BlueprintELResolver _blueprintELResolver;
private BlueprintContextELResolver _blueprintContextELResolver;
public void init() throws Exception
{
super.init();
ProcessEngineConfigurationImpl configImpl = (ProcessEngineConfigurationImpl)getProcessEngineConfiguration();
final BlueprintExpressionManagerReordered mgr = new BlueprintExpressionManagerReordered();
configImpl.setExpressionManager(mgr);
if (configImpl.getActivityBehaviorFactory() instanceof DefaultActivityBehaviorFactory) {
((DefaultActivityBehaviorFactory)configImpl.getActivityBehaviorFactory()).setExpressionManager(mgr);
}
if (configImpl.getListenerFactory() instanceof DefaultListenerFactory) {
((DefaultListenerFactory)configImpl.getListenerFactory()).setExpressionManager(mgr);
}
}
And referenced in my context.xml
<bean id="processEngineFactory"
class="com.bp3.oss.custom.ProcessEngineFactoryWithELResolverReordered"
init-method="init"
destroy-method="destroy">
<property name="processEngineConfiguration"
ref="configuration"/>
<property name="bundle" ref="blueprintBundle"/>
<property name="blueprintELResolver"
ref="blueprintELResolver"/>
<property name="blueprintContextELResolver" ref="blueprintContextELResolver"/>
</bean>
Not sure if this will help, but may give you something to go after.
Hi My thread class is showing null pointer exception please help me to resolve
#Component
public class AlertsToProfile extends Thread {
public final Map<Integer, List<String>> userMessages = Collections.synchronizedMap(new HashMap<Integer, List<String>>());
#Autowired
ProfileDAO profileDAO;
private String categoryType;
private String dataMessage;
public String getCategoryType() {
return categoryType;
}
public void setCategoryType(String categoryType) {
this.categoryType = categoryType;
}
public String getDataMessage() {
return dataMessage;
}
public void setDataMessage(String dataMessage) {
this.dataMessage = dataMessage;
}
public void run() {
String category=getCategoryType();
String data= getDataMessage();
List<Profile> all = profileDAO.findAll();
if (all != null) {
if (category == "All" || category.equalsIgnoreCase("All")) {
for (Profile profile : all) {
List<String> list = userMessages.get(profile.getId());
if (list == null ) {
ArrayList<String> strings = new ArrayList<String>();
strings.add(data);
userMessages.put(profile.getId(), strings);
} else {
list.add(data);
}
}
}
}
}
and my service method is as follows
#Service
public class NoteManager
{
#Autowired AlertsToProfile alertsToProfile;
public void addNote(String type, String message, String category) {
alertsToProfile.setCategoryType(category);
String data = type + "," + message;
alertsToProfile.setDataMessage(data);
alertsToProfile.start();
System.out.println("addNotes is done");
}
But when i call start() method am getting null pointer exception please help me. I am new to spring with thread concept
It pretty obvious: you instantiate your thread directly, as opposed to letting spring create AlertsToProfile and auto wire your instance.
To fix this, create a Runnable around your run() method and embed that into a method, something like this:
public void startThread() {
new Thread(new Runnable() {
#Override
public void run() {
// your code in here
}}).start();
}
you will want to bind the Thread instance to a field in AlertsToProfile in order to avoid leaks and stop the thread when you're done.