Cannot find data format in registry - Camel - java

I have a maven project, and I'm trying to marshal a file using jaxb and camel with the command:
from("file://...").marshal("myDataFormat").to("file://...");
When I run the project, I get the following error:
Cannot find data format in registry with ref: myDataFormat
First, does anyone know what the "registry" is? I've searched Google, but can't find anything. I'm guessing it might be another name for the camel-context file. Second, how can I register a data format using camel? Is there a default data format that I can use?
Sorry if the answer is simple, but I'm relatively new to camel and the online docs that I can find haven't been too helpful.

You should use something like this
DataFormat jaxb = new JaxbDataFormat("com.acme.model");
from("activemq:My.Queue").
unmarshal(jaxb).
to("mqseries:Another.Queue");
In other words, first create dataformat object then try to unmarshal it.

About Camel registry http://camel.apache.org/registry.html
For simple, test task Simple registry will be fine.
Spring or Blueprint is good for more complex tasks. http://camel.apache.org/using-osgi-blueprint-with-camel.html , http://camel.apache.org/spring.html , http://camel.apache.org/data-format.html (see Spring example below page)
Blueprint context example, with some data formats.
<?xml version="1.0" encoding="UTF-8"?>
<blueprint
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0"
xsi:schemaLocation=
"http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">
<camelContext id="camelTest"
xmlns="http://camel.apache.org/schema/blueprint" >
<propertyPlaceholder id="properties" location="blueprint:server.placeholder"/>
<package>camel.test</package>
<dataFormats>
<beanio id="cashWarrantFormat" mapping="beanio/mapping.xml" streamName="CashWarrant" encoding="UTF-8"/>
<beanio id="metaDocFormat" mapping="beanio/mapping.xml" streamName="MetaDoc" encoding="UTF-8"/>
<beanio id="accStatementFormat" mapping="beanio/mapping.xml" streamName="AccStatement" encoding="UTF-8"/>
<beanio id="advanceReport" mapping="beanio/mapping.xml" streamName="AdvanceReport" encoding="UTF-8"/>
</dataFormats>
</camelContext>
<bean id="javaUuidGenerator" class="org.apache.camel.impl.JavaUuidGenerator"/>
</blueprint>
Simple registry example.
public static SimpleRegistry createRegistry() {
SimpleRegistry simpleRegistry = new SimpleRegistry();
simpleRegistry.put("transformerFactory", com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.class);
simpleRegistry.put("javaUuidGenerator", org.apache.camel.impl.JavaUuidGenerator.class);
return simpleRegistry;
}
public void createCamelContext() {
logger.info("Create Camel context");
simpleRegistry = createRegistry();
defaultCamelContext = new DefaultCamelContext(simpleRegistry);
}

Related

Apache Camel route with MongoDB gives an error No bean could be found in the registry

I am trying into implement a route to insert content into MongoDB. Below is the route I tried and it gives me an error:
Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: localhost:27017 of type: com.mongodb.client.MongoClient
from("rabbitmq:localhost:5672/tasks?autoDelete=false&routingKey=camel&queue=task_queue")
.bean(itemDetails, "consumeItemDetails(${exchange})")
.to("mongodb://localhost:27017?database=ItemDB&collection=ItemDetails&operation=save");
I was not sure where and how to define a bean of type MongoClient and how I can pass the host and port numbers as parameters. Could anyone please guide me on this?
You need to declare a MongoClient bean. If you're running your application through Spring Boot (starter), it will provide your app with a bean named mongo. Otherwise, you need to follow Chanfir's advice.
In your route definition , you need to add the beanId as following :
from("rabbitmq:localhost:5672/tasks?autoDelete=false&routingKey=camel&queue=task_queue")
.bean(itemDetails, "consumeItemDetails(${exchange})")
.to("mongodb:mongoBean?database=ItemDB&collection=ItemDetails&operation=save");
And define a bean of type MongoClient with beanId mentionned in your xml/annotation configuration then define database connection params inside the bean :
Example using Spring xml configuration :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mongo:mongo-client id="mongoBean" host="${mongo.url}" port="${mongo.port}" credentials="${mongo.user}:${mongo.pass}#${mongo.dbname}">
<mongo:client-options write-concern="NORMAL" />
</mongo:mongo-client>
</beans>
Example using Annotations :
#Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
#Override
protected String getDatabaseName() {
return "test";
}
#Override
public MongoClient mongoClient() {
ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test");
MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();
return MongoClients.create(mongoClientSettings);
}
#Override
public Collection getMappingBasePackages() {
return Collections.singleton("com.baeldung");
}
}
To be able to execute the code using Spring Boot 2.7.3 and Camel 3.18.2, I have to explicitely register the Mongo client when loading the route:
#Autowired
MongoConfig mongoConfig;
then :
context.getRegistry().bind("connectionBean", mongoConfig.mongoClient());
Is there a way to automatically register the Mongo Client?
you can easily add a bean inside your Application class if you are developing using Java DSL, like this:
#Bean("myconnection")
public MongoClient mongo() {
return new MongoClient("localhost", 27107);
}

Pivotal GemFire: PDX serializer config in Spring Data GemFire

I have created a GemFire cluster with 2 Locators, 2 cache servers and a "Customer" REPLICATE Region. (Domain object class is placed in classpath during server startup).
I am able to run a Java program (Peer) to load the "Customer" Region in the cluster. Now we want to move to Spring Data GemFire where I am not sure how to configure PDX serialization and getting...
com.gemstone.gemfire.InternalGemFireException: java.io.NotSerializableException: com.gemfire.poc.DomainObjects.Customer
cache.xml in simple Java program...
<?xml version="1.0" encoding="UTF-8"?><cache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schema.pivotal.io/gemfire/cache" xsi:schemaLocation="http://schema.pivotal.io/gemfire/cache http://schema.pivotal.io/gemfire/cache/cache-8.1.xsd" version="8.1" lock-lease="120" lock-timeout="60" search-timeout="300" is-server="false" copy-on-read="false">
<pdx>
<pdx-serializer>
<class-name>
com.gemstone.gemfire.pdx.ReflectionBasedAutoSerializer
</class-name>
<parameter name="classes">
<string>com.gemfire.poc.DomainObjects.*</string>
</parameter>
</pdx-serializer>
</pdx>
<region name="Customer" refid="REPLICATE">
<region-attributes refid="REPLICATE" scope="distributed-no-ack">
<cache-loader>
<class-name>com.citigroup.pulse.pt.gemfire.poc.clientserver.SimpleCacheLoader</class-name>
</cache-loader>
</region-attributes>
</region>
</cache>
spring-context.xml in Spring Boot app...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:gfe="http://www.springframework.org/schema/gemfire"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/data/gemfire
http://www.springframework.org/schema/data/gemfire/spring-data-gemfire.xsd">
<util:properties id="gemfireProperties">
<prop key="log-level">config</prop>
<prop key="locators">hostA[10334],hostB[10334]</prop>
</util:properties>
<bean id="mappingPdxSerializer" class="com.gemstone.gemfire.pdx.ReflectionBasedAutoSerializer"/>
<gfe:cache use-bean-factory-locator="false" properties-ref="gemfireProperties" use-cluster-configuration="true" pdx-serializer-ref="mappingPdxSerializer" />
<gfe:replicated-region id="Customer" ignore-if-exists="true">
</gfe:replicated-region>
</beans>
Can someone help me fix the serialization issue?
Caused by: com.gemstone.gemfire.InternalGemFireException: java.io.NotSerializableException: com.gemfire.poc.DomainObjects.Customer
at com.gemstone.gemfire.distributed.internal.DistributionManager.putOutgoing(DistributionManager.java:1954)
at com.gemstone.gemfire.internal.cache.DistributedCacheOperation.distribute(DistributedCacheOperation.java:476)
at com.gemstone.gemfire.internal.cache.AbstractUpdateOperation.distribute(AbstractUpdateOperation.java:65)
at com.gemstone.gemfire.internal.cache.DistributedRegion.distributeUpdate(DistributedRegion.java:519)
at com.gemstone.gemfire.internal.cache.DistributedRegion.basicPutPart3(DistributedRegion.java:500)
at com.gemstone.gemfire.internal.cache.AbstractRegionMap.basicPut(AbstractRegionMap.java:3052)
at com.gemstone.gemfire.internal.cache.LocalRegion.virtualPut(LocalRegion.java:5838)
Precisely, how to add "classes" parameter of ReflectionBasedAutoSerializer in spring-data-gemfire tags?
PDX deserialization exception while retrieving value from Region:
com.gemstone.gemfire.ToDataException: PdxSerializer failed when calling toData on class javax.management.Notification
at com.gemstone.gemfire.internal.InternalDataSerializer.writePdx(InternalDataSerializer.java:3130)
at com.gemstone.gemfire.internal.InternalDataSerializer.writeUserObject(InternalDataSerializer.java:1520)
at com.gemstone.gemfire.internal.InternalDataSerializer.writeWellKnownObject(InternalDataSerializer.java:1416)
at com.gemstone.gemfire.internal.InternalDataSerializer.basicWriteObject(InternalDataSerializer.java:2208)
at com.gemstone.gemfire.DataSerializer.writeObject(DataSerializer.java:3181)
at com.gemstone.gemfire.internal.util.BlobHelper.serializeToBlob(BlobHelper.java:50)
at com.gemstone.gemfire.internal.util.BlobHelper.serializeToBlob(BlobHelper.java:38)
at com.gemstone.gemfire.internal.cache.UpdateOperation$UpdateMessage.toData(UpdateOperation.java:492)
at com.gemstone.gemfire.internal.InternalDataSerializer.invokeToData(InternalDataSerializer.java:2407)
at com.gemstone.gemfire.internal.InternalDataSerializer.writeDSFID(InternalDataSerializer.java:1378)
at com.gemstone.gemfire.internal.tcp.MsgStreamer.writeMessage(MsgStreamer.java:239)
at com.gemstone.gemfire.distributed.internal.direct.DirectChannel.sendToMany(DirectChannel.java:458)
at com.gemstone.gemfire.distributed.internal.direct.DirectChannel.sendToOne(DirectChannel.java:310)
at com.gemstone.gemfire.distributed.internal.direct.DirectChannel.send(DirectChannel.java:696)
at com.gemstone.gemfire.distributed.internal.membership.jgroup.JGroupMembershipManager.directChannelSend(JGroupMembershipManager.java:2929)
at com.gemstone.gemfire.distributed.internal.membership.jgroup.JGroupMembershipManager.send(JGroupMembershipManager.java:3163)
at com.gemstone.gemfire.distributed.internal.DistributionChannel.send(DistributionChannel.java:79)
at com.gemstone.gemfire.distributed.internal.DistributionManager.sendOutgoing(DistributionManager.java:3907)
at com.gemstone.gemfire.distributed.internal.DistributionManager.sendMessage(DistributionManager.java:3948)
at com.gemstone.gemfire.distributed.internal.DistributionManager.putOutgoing(DistributionManager.java:1951)
at com.gemstone.gemfire.internal.cache.DistributedCacheOperation.distribute(DistributedCacheOperation.java:476)
at com.gemstone.gemfire.internal.cache.AbstractUpdateOperation.distribute(AbstractUpdateOperation.java:65)
at com.gemstone.gemfire.internal.cache.DistributedRegion.distributeUpdate(DistributedRegion.java:519)
at com.gemstone.gemfire.internal.cache.DistributedRegion.basicPutPart3(DistributedRegion.java:500)
at com.gemstone.gemfire.internal.cache.ProxyRegionMap.basicPut(ProxyRegionMap.java:242)
at com.gemstone.gemfire.internal.cache.LocalRegion.virtualPut(LocalRegion.java:5838)
at com.gemstone.gemfire.internal.cache.DistributedRegion.virtualPut(DistributedRegion.java:387)
at com.gemstone.gemfire.internal.cache.LocalRegionDataView.putEntry(LocalRegionDataView.java:118)
at com.gemstone.gemfire.internal.cache.LocalRegion.basicPut(LocalRegion.java:5228)
at com.gemstone.gemfire.internal.cache.LocalRegion.validatedPut(LocalRegion.java:1599)
at com.gemstone.gemfire.internal.cache.LocalRegion.put(LocalRegion.java:1582)
at com.gemstone.gemfire.internal.cache.AbstractRegion.put(AbstractRegion.java:327)
at com.gemstone.gemfire.management.internal.ManagementResourceRepo.putEntryInLocalNotificationRegion(ManagementResourceRepo.java:169)
at com.gemstone.gemfire.management.internal.NotificationHub$NotificationHubListener.handleNotification(NotificationHub.java:193)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor$ListenerWrapper.handleNotification(DefaultMBeanServerInterceptor.java:1754)
at javax.management.NotificationBroadcasterSupport.handleNotification(NotificationBroadcasterSupport.java:275)
at javax.management.NotificationBroadcasterSupport$SendNotifJob.run(NotificationBroadcasterSupport.java:352)
at javax.management.NotificationBroadcasterSupport$1.execute(NotificationBroadcasterSupport.java:337)
at javax.management.NotificationBroadcasterSupport.sendNotification(NotificationBroadcasterSupport.java:248)
at com.gemstone.gemfire.management.internal.beans.ManagementAdapter.handleRegionRemoval(ManagementAdapter.java:879)
at com.gemstone.gemfire.management.internal.beans.ManagementListener.handleEvent(ManagementListener.java:123)
at com.gemstone.gemfire.distributed.internal.InternalDistributedSystem.notifyResourceEventListeners(InternalDistributedSystem.java:2252)
at com.gemstone.gemfire.distributed.internal.InternalDistributedSystem.handleResourceEvent(InternalDistributedSystem.java:506)
at com.gemstone.gemfire.internal.cache.LocalRegion.basicDestroyRegion(LocalRegion.java:6642)
at com.gemstone.gemfire.internal.cache.DistributedRegion.basicDestroyRegion(DistributedRegion.java:1957)
at com.gemstone.gemfire.internal.cache.LocalRegion.close(LocalRegion.java:2219)
at org.springframework.data.gemfire.RegionFactoryBean.destroy(RegionFactoryBean.java:529)
at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:272)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:961)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.destroySingletons(FactoryBeanRegistrySupport.java:230)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:968)
at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1032)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1008)
at org.springframework.context.support.AbstractApplicationContext$2.run(AbstractApplicationContext.java:929)
Caused by: org.springframework.data.mapping.model.MappingException: Could not write value for property protected transient java.lang.Object java.util.EventObject.source
at org.springframework.data.gemfire.mapping.MappingPdxSerializer$2.doWithPersistentProperty(MappingPdxSerializer.java:188)
at org.springframework.data.gemfire.mapping.MappingPdxSerializer$2.doWithPersistentProperty(MappingPdxSerializer.java:173)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:309)
at org.springframework.data.gemfire.mapping.MappingPdxSerializer.toData(MappingPdxSerializer.java:173)
at com.gemstone.gemfire.internal.InternalDataSerializer.writePdx(InternalDataSerializer.java:3075)
... 56 more
Caused by: com.gemstone.gemfire.pdx.PdxFieldAlreadyExistsException: The field "source" already exists.
at com.gemstone.gemfire.pdx.internal.PdxType.addField(PdxType.java:262)
at com.gemstone.gemfire.pdx.internal.PdxWriterImpl.updateMetaData(PdxWriterImpl.java:858)
at com.gemstone.gemfire.pdx.internal.PdxWriterImpl.updateMetaData(PdxWriterImpl.java:851)
at com.gemstone.gemfire.pdx.internal.PdxWriterImpl.writeObject(PdxWriterImpl.java:303)
at com.gemstone.gemfire.pdx.internal.PdxWriterImpl.writeField(PdxWriterImpl.java:705)
at com.gemstone.gemfire.pdx.internal.PdxWriterImpl.writeField(PdxWriterImpl.java:625)
at org.springframework.data.gemfire.mapping.MappingPdxSerializer$2.doWithPersistentProperty(MappingPdxSerializer.java:184)
... 60 more
You have a couple of options here, along with a few suggested recommendations.
1) First, I would not use Pivotal GemFire's o.a.g.pdx.ReflectionBasedAutoSerializer. Rather SDG has a much more robust PdxSerializer implementation based on Spring Data's Mapping Infrastructure (i.e. the o.s.d.g.mapping.MappingPdxSerializer).
In addition, SDG's MappingPdxSerializer allows you to register custom PdxSerializer's on an entity field/property case-by-case basis. Imagine if your Customer class has a reference to a complex Address class and that class has special serialization needs.
Furthermore, SDG's MappingPdxSerializer can handle transient and read-only properties.
Finally, you don't have to mess with any fussy/complex Regex to properly identify the application domain model types that need to be serialized.
2) Second, you can leverage Spring's JavaConfig along with SDG's new Annotation-based configuration model to configure Pivotal GemFire PDX Serialization as simply as this...
#SpringBootApplication
#PeerCacheApplication
#EnablePdx(..)
class MySpringBootApacheGeodeApplication {
...
}
That is, using the SDG #EnablePdx annotation.
More details on #1 and #2 above are available here and here.
Of course, the later is more applicable when using Pivotal GemFire 9.x+ with Spring Data GemFire Kay (2.0+). Judging by the package in your configuration of the com.gemstone.gemfire.pdx.ReflectionBasedAutoSerializer from your XML config (i.e. the com.gemstone.gemfire package) it would appear you are using Pivotal GemFire 8.2.x with Spring Data GemFire Ingalls (or 1.9.x.RELEASE), perhaps?
However, if you insist on, or are required to use XML for your configuration, then you can do the following...
<beans ...>
<bean id="mappingPdxSerializer" class="org.springframework.data.gemfire.mapping.MappingPdxSerializer"/>
<gfe:cache pdx-serializer-ref="mappingPdxSerializer" .../>
</beans>
And, if you really want to use Pivotal GemFire's ReflectionBasedAutoSerializer, then you can find examples of it's use in the SDG test suite. For instance.
I also have a few more examples in my spring-gemfire-test project/repo (which is quite a mess and I don't maintain this repo much anymore, as a warning). Examples here, using Java configuration with GemFire's API here, here, here which also shows the use of SDG's MappingPdxSerializer as well (by comparison), and so on and so forth. Many examples riddle throughout my repos.
Hope this helps!
Cheers,
-John

NoSuchBeanDefinitionException: No bean named 'FirstPage' is defined

I am very new to Spring Framework. I am using NetBeans for IDE. I followed couple of tutorials to learn it by myself. However, I am stuck in the middle and cannot proceed further. Let me breakdown my project here:
My project folder structure looks like this:
There are two classes; the major one MainApp.java contains following code:
package com.myprojects.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context;
context = new ClassPathXmlApplicationContext("classpath*:beans.xml");
FirstPage obj;
obj = (FirstPage) context.getBean("firstPage");
obj.getMessage();
}
}
Second class file FirstPage.java looks like this:
package com.myprojects.spring;
public class FirstPage {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
The beans.xml file looks like below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.0.RELEASE.xsd
">
<bean id = "firstPage" class = "com.myprojects.spring.FirstPage">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
Now, the error I am getting is like below:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'firstPage' is defined
I know I have been doing some silly mistake here.
Thank you in Advance !
Almost similar problem have been discussed before. I think your program is unable to locate beans.xml.
Try doing this:
context = new ClassPathXmlApplicationContext("META-INF/beans.xml");
EDIT:
This new error XmlBeanDefinitionStoreException means that your schema is not valid. Try changing your schema as described in one of these answers:
https://stackoverflow.com/a/21525719/2815219
https://stackoverflow.com/a/25782515/2815219
Spring configuration XML schema: with or without version?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id = "firstPage" class = "com.myprojects.spring.FirstPage">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
According to the directory structure you posted it is very likely that src/main/resources is on your classpath. If you like to reference your spring context file beans.xml you have to specify it relative to the folders on your classpath. Hence you should try:
context = new ClassPathXmlApplicationContext("classpath:/META-INF/beans.xml");
Besides: the notation classpath*:beans.xml means you want to read in all context files having a name of beans.xml.
Put beans.xml to outside Meta-inf ,
or use new ClassPathXmlApplicationContext("META-INF/beans.xml");
And http://www.springframework.org/schema/beans/spring-beans-4.0.0.RELEASE.xsd
should change to
http://www.springframework.org/schema/beans/spring-beans-4.0.0.xsd , as spring's xsd filenames don't contain "RELEASE".
The xsd files are in org.springframework.beans.factory.xml package in spring-beans.jar, see if the xsd file is in that package.
Doing following two things solved my issue.
1) There was an incorrect beans.xml path. I changed that to context = new ClassPathXmlApplicationContext("META-INF/beans.xml");.
2) Also, there was an invalid xsi:schemaLocation attribute value. I changed that attribute's value to http://www.springframework.org/schema/beans/spring-beans-3.0.xsd.
Thank you all for your help.

Property file in spring mvc

I have a property file with key value pairs:
key1=value1
key2=value2
Now, in my controller, I want to directly print the value of a property file (of course after loading the property file using web.xml / app-servlet.xml), like:
System.out.printl(${key1});
Is it possible to do that?
If not, I want to create an interface with all constant variable to read values from property file. How do I do it??
public interface MyConstants
{
#Value("${key1}")
public static final KEY_1="";
}
But as expected only empty string is assigned.
How do I solve this issue? Or, what is the best way to using property files to retrieve values? Thanks in advance...
There are two reasons why having an interface for 'MyConstants' instead of a class is incorrect :
1) Spring cannot inject values to an interface which has no implementation. Simply because you wont be able instantiate the interface. Remember, Spring is just a factory and it can play only with 'things' which can be instantiated.
2) Another reason is that having an interface for storing your constants is an anti-pattern in itself. That is not what interfaces are designed for. You might want to refer to the Constant interface anti-pattern.
http://en.wikipedia.org/wiki/Constant_interface
It's possible! You need to use the util namespace in your app-servlet.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<util:properties id="props" location="classpath:yourfile.properties" />
<!-- other -->
</beans>
And your controller is something like
#org.springframework.beans.factory.annotation.Value("#{props.key1}")
public void setFoo(String foo) {
System.out.println("props.key1: " + foo);
}
update for another way:
You also can use namespace context
<context:property-placeholder location="classpath:yourfile.properties" />
In controller, declare a property as below
#Value("${pros.key1}")
private String foo;
Creating a ''Constants'' class / interface is a widely used approach, but I think its a flawed approach. It creates a weird coupling where classes from different layers in your system suddenly start depending on one Constants class. It also becomes difficult to understand by looking at the constants class, as to which constant is being used by who? Not to mention the fact that it completely mocks abstraction. You suddenly have a constants class which contains information about the error message to show on the jsp, username and password of a third party api, thread pool size etc.. all in one "I know everything" class
So avoid a constant class / interface as far as possible. Look at your controllers / services, if a particular service class needs a particular configuration value that you want exposed in a property file, inject it into the class and store it as an instance level constant. This design is much cleaner from an abstraction point of view, it also helps to unit test this class easily.
In Spring, you can create a handle to a property file as follows:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:my-application.properties" />
</bean>
As the code suggests, you can mention multiple property files here. After you do this, you can reference a key from the mentioned property file, elsewhere in the context like so:
<bean id="xx" class="com.xx.SomeClass" p:imageUrl="${categories.images}"/>
The SomeClass instance here has a property called imageUrl which is now injected with the value mentioned against the categories.images key from the property file called my-application.properties
Hope this helps.

Suppress prolog from XML during marshalling

I am using Mule XML module jaxb-object-to-xml-transformer to convert my object to XML. Then this XML is embedded into another XML using templates.
But the issue here is the object to XML transformer is giving an XML output with prolog:
<?xml version="1.0" encoding="UTF-8"?>
I need an XML without this. So that it can be embedded into another template without issues.
<flow name="main.flow">
....
....
<mule-xml:jaxb-object-to-xml-transformer name="obj2xml" jaxbContext-ref="myJaxbContext" returnClass="java.lang.String" />
<custom-transformer ..... >
....
....
</flow>
In plain JAXB there is a way to do this. But in Mule XML module I couldn't find any property to do this. Please advise if there is any property to achieve this behaviour.
The documentation indicates that you can intercept JAXB transforms (see: http://www.mulesoft.org/documentation/display/current/JAXB+Bindings). The following example is taken from that documentation.
#Transformer(sourceTypes = {String.class, InputStream.class})
public Person toPerson(Document doc, JAXBContext context) throws JAXBException
{
return (Person) context.createUnmarshaller().unmarshal(doc);
}
Assuming there is a corresponding thing you can do for marshalling you would be able to set the necessary JAXB property.
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

Categories