How to use internationalization in JSF that retrieve the data from DB - database

I want to use the standard internationalization from JSF (in property files )and the possibility to switch to database. Is it possible to replace JSF internationalization with own implementation that retrieve the data from DB, so I can configure it ? Or is in this case another aproach better ?
I've found the following example: http://jdevelopment.nl/internationalization-jsf-utf8-encoded-properties-files/ . In this example the own resource bundle class is defined. To use it only the reference in xml to implementation class is replaced.

As BalusC pointed, you need to create a ResourceBundle and register it to the app or individually per page.
Simple example:
index.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui">
<h:body>
<h:outputText value="[helloworld]: #{msgs.helloworld}" />
</h:body>
</html>
faces-config.xml
<?xml version="1.0"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<resource-bundle>
<base-name>com.myproject.CustomResourceBundle</base-name>
<var>msgs</var>
</resource-bundle>
</application>
</faces-config>
CustomResourceBundle.java
package com.myproject;
import java.util.ListResourceBundle;
public class CustomResourceBundle extends ListResourceBundle {
#Override
protected Object[][] getContents() {
return getMapOfWordsFromDatabase();
}
private Object[][] getMapOfWordsFromDatabase() {
// TODO get key and words relation from database!
return map;
}
}
Theory:
http://docs.oracle.com/javaee/5/tutorial/doc/bnaxv.html
http://docs.oracle.com/javase/7/docs/api/java/util/ResourceBundle.html

Related

How to generate header using SoapJaxbDataFormat

First I have generated pojo class using jsonschema2pojo plugin using WSDL file.
My WSDL file contains Header and Body.
Body Root Pojo looks like this:
public class SubmitCustomerOrderRequest {
#XmlElement(required = true)
protected List<Order> order;
}
Header looks like this:
public class MessageHeader {
.....
}
Now in a process class of camel i am putting SubmitCustomerOrderRequest (Here this pojo only consider body not header) into body like this:
submitCustomerOrderRequest.setOrder(orderList);
exchange.getIn().setBody(submitCustomerOrderRequest);
Now in the route i am marshalling using this concept
SoapJaxbDataFormat soapDF = new SoapJaxbDataFormat("org.com.model",
new ServiceInterfaceStrategy(order.class, true));
And marshalling into xml like this:
.marshal(soapDF)
Now here the problem here is, its generating xml but without header, how to include header also in the process class so that while converting into xml, its generates header also with body
Its generating like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:Envelope xmlns:ns2="org.com" xmlns:ns3="org.com.something">
<ns2:Body>
<ns3:submitCustomerOrderV3Request>
</ns3:submitCustomerOrderV3Request>
</ns2:Body>
</ns2:Envelope>
whereas i need like this with header:
<SOAP-ENV:Envelope xmlns:SOAP-ENV=org.com>
<SOAP-ENV:Header>
<messageHeader xmlns=org.om>
</messageHeader>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns2:submitCustomerOrderV3Request xmlns:ns2=org.com>
</ns2:submitCustomerOrderV3Request>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Any help would be appreciable.

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

how to escape quote in a variable sent by the server in angularjs? [duplicate]

Sometimes, I need to render a JavaScript variable using EL in a JSF page.
E.g.
<script>var foo = '#{bean.foo}';</script>
or
<h:xxx ... onclick="foo('#{bean.foo}')" />
This fails with a JS syntax error when the EL expression evaluates to a string containing JS special characters such as apostrophe and newline. How do I escape it?
You can use Apache Commons Lang 3.x StringEscapeUtils#escapeEcmaScript() method for this in EL.
First create a /WEB-INF/functions.taglib.xml which look like this:
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
version="2.0">
<namespace>http://example.com/functions</namespace>
<function>
<name>escapeJS</name>
<function-class>org.apache.commons.lang3.StringEscapeUtils</function-class>
<function-signature>java.lang.String escapeEcmaScript(java.lang.String)</function-signature>
</function>
</taglib>
Then register it in /WEB-INF/web.xml as follows:
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/WEB-INF/functions.taglib.xml</param-value>
</context-param>
Then you can use it as follows:
<html ... xmlns:func="http://example.com/functions">
...
<script>var foo = '#{func:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{func:escapeJS(bean.foo)}')" />
Alternatively, if you happen to already use the JSF utility library OmniFaces, then you can also just use its builtin of:escapeJS() function:
<html ... xmlns:of="http://omnifaces.org/functions">
...
<script>var foo = '#{of:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{of:escapeJS(bean.foo)}')" />
Have you tried \'#{_selectedItem.item.webName}\',?

How to view the inserted rows when JPA testing with arquillian / hibernate?

I have an arquillian unit test that is writing a Note and passing the unit tests.
Now I would like to actually view what is being persisted into my SQLServer database.
When I open up SQLServer, I see my "Note" table, with all of the requisite columns...but there's no data.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="noteUnit"
transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/jdbc/datasources/notes</jta-data-source>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2005Dialect" />
<property name="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.JBossTransactionManagerLookup" />
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
</persistence>
I've tried various values for hbm22ddl.auto--'create-drop', 'update','validate', but since my test passes, I assume that the new rows are being inserted and then immediately removed by arquillian after the unit test?
Unit test below passes--meaning arquillian's xml file and all the other assorted plumbing appears to be set up correctly. Is there a setting somewhere to save all the data that's being inserted?
private NoteEntity createNote(){
NoteEntity note = new NoteEntity();
note.setGuid("123456789");
note.setAuthorId("12345");
return note;
}
#Test
public void createNoteTest(){
NoteEntity note1 = createNote();
mEntityManager.persist(note1);
Assert.assertNotNull(note1.getId());
}
Generally, jUnit are configured so that their transaction is in defaultrollback=true mode. This is done to avoid inserting test data in your database. You will probably find the configuration over your class definition or in an extended class.
Example for jUnit with Spring IOC configuration :
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath*:myPath/spring*Context.xml")
#TransactionConfiguration(defaultRollback = true)
#Transactional
public abstract class AbstactSpringTestCase {
...
}

Resources