How to define a null element in simpleframework - simple-framework

i am very new to simpleframework
This is my xml file:
<Resource>
<attribute>
<vegetable>
<fruit xsi:nil="true"/>
<flowers>
</attribute>
</Resource>
and my annotated java class using simple framework is as follows:
Resource.java
#Root (name="Resource")
public static class Attribute {
#Element(required=false)
public String vegetable;
#Element( required=false)
public String fruit;
#Attribute (name="xsi:nil", required=false)
---
#Element(required=false)
public String flowers;
}
i am not sure what to write in the Attribute to as to make fruit value as null. Can anyone help me with it?

Related

Make Id column to work with sequence or GenerationType.IDENTITY according to the database

When we have to use the same code base to work with Oracle or other MSSql databases, is there a way to tell how to choose the type of mapping inside entity classes? For oracle it uses sequences like
#Id
#GeneratedValue(generator="InvSeq")
#SequenceGenerator(name="InvSeq",sequenceName="INV_SEQ", allocationSize=5)
private long id;
and for MySQL it uses
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
Is there a way to configure this without duplicating entity classes?
Ok I figured this out. In Spring Boot there is a way we can override default persistence mappings that is there inside a persistence.xml file. We first need to create a bean in app config like this(entityManagerFactory name should be there since spring will look for it):
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory =
new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(springJpaDataSource());
factory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
if(!db_url.contains("oracle"))// something that tells you it's not oracle
{
factory.setPersistenceXmlLocation("classpath:jpa/custom-persistance.xml");
}
else{
// this file will not contain any mapping files to override ID generation
factory.setPersistenceXmlLocation("classpath:jpa/custom-persistance-oracle.xml");
}
return factory;
}
Now add the file (custom-persistance.xml):
<persistence
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="persistenceUnit">
<provider>
org.hibernate.jpa.HibernatePersistenceProvider
</provider>
<mapping-file>
jpa/entity-mappings.xml
</mapping-file>
</persistence-unit>
For custom-persistance-oracle.xml file will be same without mapping-file xml tag. Then add the actual file having mappings:
<entity-mappings
xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm"
version="2.1">
<package>com.example.pcakageto.classes</package>
<entity class="ClassA" access="FIELD">
<attributes>
<id name="id">
<generated-value strategy="IDENTITY"/>
</id>
</attributes>
</entity>
<entity class="ClassB" access="FIELD">
<attributes>
<id name="id">
<generated-value strategy="IDENTITY"/>
</id>
</attributes>
</entity>
Finally ID mappings in Java files should be using sequences as it normally would:
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_generator")
#SequenceGenerator(name="id_generator", sequenceName = "sequence_name", allocationSize=1)
private Integer id;

How to resolve a NoSuchMethodError for org.springframework.data.solr.repository.config.SolrRepositoryConfigExtension?

I am trying to extend the sample SpingMongoDB example shared here to include Solr Search and Indexing capability. In a nutshell building a SpringData + MongoDB + Spring-Solr application so that any document getting stored in MongoDB would also be stored as an index into Solr.
The following changes were made to the existing project:
Added a model class Book.java
#SolrDocument(solrCoreName = "book")
public class Book implements Serializable
{
private static final long serialVersionUID = -8243145429438016231L;
#Id
#Field
private String id;
#Field
private String title;
#Field
private String description;
Updated the SpringConfig.xml file as:
<?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"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:solr="http://www.springframework.org/schema/data/solr"
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-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/solr
http://www.springframework.org/schema/data/solr/spring-solr.xsd">
<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="yourdb" />
<bean id="mongoTemplate"
class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory"
ref="mongoDbFactory" />
</bean>
<solr:repositories base-package="com.mkyong.repo" />
<!-- Define HTTP Solr server -->
<solr:solr-server id="solrServer"
url="http://localhost:8983/solr/" />
<!-- Define Solr template -->
<bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
<constructor-arg index="0" ref="solrServer"/>
</bean>
</beans>
And added the below code in the App.java class:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new ClassPathResource("SpringConfig.xml").getPath());
com.mkyong.repo.BookRepo bookRepo = context.getBean(com.mkyong.repo.BookRepo.class);
com.mkyong.model.Book hobbit = new com.mkyong.model.Book();
hobbit.setId("3");
hobbit.setTitle("Hobbit");
hobbit.setDescription("Prelude to LOTR");
//bookRepo.save(hobbit);
mongoOperation.save(hobbit);
//solrOperation.saveBean("book", hobbit);
System.out.println("##$# bookRepo.findOne(3l) ="+bookRepo.findOne(3l));
System.out.println("#!$# bookRepo.findByBookTitle(\"Hobbit\") ="+bookRepo.findByBookTitle("Hobbit"));
context.close();
When I run my code main method it gives me the below error:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [SpringConfig.xml]; nested exception is java.lang.NoSuchMethodError: org.springframework.data.solr.repository.config.SolrRepositoryConfigExtension.registerIfNotAlreadyRegistered(Lorg/springframework/beans/factory/support/AbstractBeanDefinition;Lorg/springframework/beans/factory/support/BeanDefinitionRegistry;Ljava/lang/String;Ljava/lang/Object;)V
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.mkyong.core.App.main(App.java:64)
Caused by: java.lang.NoSuchMethodError: org.springframework.data.solr.repository.config.SolrRepositoryConfigExtension.registerIfNotAlreadyRegistered(Lorg/springframework/beans/factory/support/AbstractBeanDefinition;Lorg/springframework/beans/factory/support/BeanDefinitionRegistry;Ljava/lang/String;Ljava/lang/Object;)V
at org.springframework.data.solr.repository.config.SolrRepositoryConfigExtension.registerSolrMappingContextIfNotPresent(SolrRepositoryConfigExtension.java:156)
at org.springframework.data.solr.repository.config.SolrRepositoryConfigExtension.registerBeansForRoot(SolrRepositoryConfigExtension.java:105)
at org.springframework.data.repository.config.RepositoryBeanDefinitionParser.parse(RepositoryBeanDefinitionParser.java:72)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1438)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1428)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:185)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:139)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:108)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
... 14 more
Any help would be great. My modified code is available at my github link https://github.com/DipakRai/_springdatasolrWorkspace

Property Injection from a blueprint file into java DSL Camel Routebuilder is not working

I am defining a list in the following way in my blueprint-bean.xml
<cm:default-properties>
<cm:property name="test-list">
<list>
<value type="java.lang.String"> "test 1" </value>
<value type ="java.lang.String"> "test 2." </value>
<value type ="java.lang.String"> "test 3." </value>
</list>
</cm:property>
...
And i have not found a way to successfully retrieve it as a list in my routebuilder class.
Which looks like the following:
public class TestRoute extends RouteBuilder {
#PropertyInject("testInt") int rate;
#PropertyInject("test-list") List<String> testlist;
...
I always get the exception:
No type converter available to convert from type: java.lang.String to the required type: java.util.List with value [ "test 1." , "test 2." , "test 3." ]
So the list seems to be converted to a String at some point and then cannot be converted back to a list at the point of injection.
Am i using the Annotation in a wrong way or is there another way to inject a list property into my JDSL route?
The annotation is working for all my other properties except for the List.

ignore method params from apache CXF javatowsdl generation

#POST
#Path("/version")
#Consumes("application/xml")
public final void testPost(#Suspended final AsyncResponse response, #Context final UriInfo uriInfo, #HeaderParam("xyz") final String user, final InputStream input){ }
generated WADL:
<request>
<representation mediaType="application/xml"/>
<param name="xyz" style="header" type="xs:string"/>
<representation mediaType="application/xml"/>
</request>
I see the "representation" is getting generated in WADL for both "input" and "response".
I don't want "representation" for "#Suspended AsyncResponse response".
Also i dont want "param" tag for "HeaderParam("xyz") final String user".
Is there a way to ignore method params from WADL?
First of all, in order to customise WADL generation, you need this dependency.
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-service-description</artifactId>
<version>${cxf.version}</version>
</dependency>
Than you can use annotations to customise your generation. But still you cannot ignore parameters. Here is an example from cxf documentation
#POST
#Path("books/{bookid}")
#Descriptions({
#Description(value = "Adds a new book", target = DocTarget.METHOD),
#Description(value = "Requested Book", target = DocTarget.RETURN),
#Description(value = "Request", target = DocTarget.REQUEST),
#Description(value = "Response", target = DocTarget.RESPONSE),
#Description(value = "Resource", target = DocTarget.RESOURCE)
})
public Book addBook(#Description("book id") #PathParam("id") Long id, #Description("New Book") Book book) {...}
There is an other way but it not documented well. You can use ElementClass annotation to modify request and response representation. Although there is no example usage, I hope it will work for you.

Element does not have a match in class

I am working with Simple XML framework, and just renamed some XML layouts, which now don't seem to work any more.
This is my XML:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<orderListReply id="R000000000006">
<order orderid="12" type="outbound" state="available">
<todo>2</todo>
<done>0</done>
<lines>1</lines>
<erporderid>0</erporderid>
</order>
</orderListReply>
And this is my code class definition:
#Root(name="orderListReply")
public class OrderListReplyTelegram extends Telegram {
#ElementList(name="order", inline=true, required=false)
private List<OrderListItem> orders;
...
This is the error I get:
org.simpleframework.xml.core.ElementException: Element 'order' does not have a match in class nl.minerall.sapphire.pocket.telegrams.OrderListReplyTelegram at line 1
Unfortunately, debugging Simple XML Framework isn't easy, but some trial and error helped me.
My OrderListItem class had this header:
#Element(name="order")
public class OrderListItem {
when changed to this:
#Root(name="order")
public class OrderListItem {
it worked. Strange thing is, in other code, the #Element annotation seemed to work (this code comes from another, working, tree).

Resources