How can I configure the indexes for using db4o with Spring? - spring

I'm currently evaluating the Spring-db4o integration. I was impressed by the declarative transaction support as well as the ease to provide declarative configuration.
Unfortunately, I'm struggling to figure how to create an index on specific fields. Spring is preparing the db during the tomcat server startup. Here's my spring entry :
<bean id="objectContainer" class="org.springmodules.db4o.ObjectContainerFactoryBean">
<property name="configuration" ref="db4oConfiguration" />
<property name="databaseFile" value="/WEB-INF/repo/taxonomy.db4o" />
</bean>
<bean id="db4oConfiguration" class="org.springmodules.db4o.ConfigurationFactoryBean">
<property name="updateDepth" value="5" />
<property name="configurationCreationMode" value="NEW" />
</bean>
<bean id="db4otemplate" class="org.springmodules.db4o.Db4oTemplate">
<constructor-arg ref="objectContainer" />
</bean>
db4oConfiguration doesn't provide any means to specify the index. I wrote a simple ServiceServletListener to set the index. Here's the relevant code:
Db4o.configure().objectClass(com.test.Metadata.class).objectField("id").indexed(true);
Db4o.configure().objectClass(com.test.Metadata.class).objectField("value").indexed(true);
I inserted around 6000 rows in this table and then used a SODA query to retrieve a row based on the key. But the performance was pretty poor. To verify that indexes have been applied properly, I ran the following program:
private static void indexTest(ObjectContainer db){
for (StoredClass storedClass : db.ext().storedClasses()) {
for (StoredField field : storedClass.getStoredFields()) {
if(field.hasIndex()){
System.out.println("Field "+field.getName()+" is indexed! ");
}else{
System.out.println("Field "+field.getName()+" isn't indexed! ");
}
}
}
}
Unfortunately, the results show that no field is indexed.
On a similar context, in OME browser, I saw there's an option to create index on fields of each class. If I turn the index to true and save, it appears to be applying the change to db4o. But again, if run this sample test on the db4o file, it doesn't reveal any index.
Any pointers on this will be highly appreciated.

Unfortunately I don't know the spring extension for db4o that well.
However the Db4o.configure() stuff is deprecated and works differently than in earlier versions. In earlier versions there was a global db4o configuration. Not this configuration doesn't exist anymore. The Db4o.configure() call doesn't change the configuration for running object containers.
Now you could try to do this work around and a running container:
container.ext().configure().objectClass(com.test.Metadata.class).objectField("id").indexed(true);
This way you change the configuration of the running object container. Note that changing the configuration of a running object container can lead to dangerous side effect and should be only used as last resort.

Related

How to copy value of custom field/property to another custom field/property of database-bean?

i need following things but unfortunately i am unable to do it,
can any one help then appreciate....!!!
NOTE : classANumber, classABNumber both field is not available into Database - it's custom field for our bean.
ABC.hbm.xml
<property name="classANumber" lazy="false" type="java.lang.String" formula="(select ac.classNumber from accessClass ac)"/>
<property name="classABNumber" lazy="false" type="java.lang.String" formula="(select abc.classNumber from accessBothClass abc where ac.classCombileNumber = classANumber)"/>
Above is my .hbm.xml file configuration.
Actually, I want to use value of 'classANumber' property into another custom-field's value searching query.

Spring Integration - Move File After Xpath-splitter

i'm working with spring integration and i have the next case: i'm reading a XML file with an int-file:inbound-channel-adapter and i split the file with a int-xml:xpath-splitter, the thing is that i need to move the file after been splitted.
I want all features of int-xml:xpath-splitter plus moving the file, should i implement a custom splitter extending XPathMessageSplitter? or is there any other way to do that with an out-of-box components?
Thanks.
<int-xml:xpath-splitter id="salesTransSplitter"
input-channel="salesInputChannel"
output-channel="splitterOutChannel" order="1">
<int-xml:xpath-expression expression="/sales_transactions/trans"/>
</int-xml:xpath-splitter>
Something like this should work...
<int-file:inbound ... channel="foo" />
<int:publish-subscribe-channel id="foo" />
<int-xml:xpath-splitter input-channel="foo" ... order="1" />
<int-service-activator input-channel="foo" order="2"
expression="payload.renameTo(new java.io.File('/newDir/' + payload.name)" output-channel="nullChannel" />
If you want to test the rename was successful, send to some other channel other than nullChannel - boolean true means success.
EDIT
Sorry about that; order should be supported on every consuming endpoint, I will open a JIRA issue.
The order is not strictly necessary; if no order is present, the order they appear in the configuration will be used; I just prefer to make it explicit.
There are (at least) two work arounds:
Remvoe the order attribute from BOTH consumers and they will be invoked in the order they appear in the XML.
Configure the XPath splitter as a normal splitter, which does support order...
<int:splitter id="salesTransSplitter" order="1"
input-channel="salesInputChannel"
output-channel="splitterOutChannel" order="1">
<bean class="org.springframework.integration.xml.splitter.XPathMessageSplitter">
<constructor-arg value="/sales_transactions/trans" />
</bean>
</int-xml:xpath-splitter>

spring mongodb write-concern values

I have the following core mongo options configuration in spring:
<mongo:mongo host="${db.hostname}" >
<mongo:options
connections-per-host="40"
threads-allowed-to-block-for-connection-multiplier="1500"
connect-timeout="15000"
auto-connect-retry="true"
socket-timeout="60000"
write-number="1"
write-fsync="false"/>
</mongo:mongo>
What I want to know is about different write-number options which is relevant to write concern like none, normal, safe etc.
Can I assume the mapping of write-number to writeconcern as below?
NONE: -1
NORMAL: 0
SAFE: 1 (default)
FSYNC_SAFE: 2
REPLICAS_SAFE: 3
JOURNAL_SAFE: 4
MAJORITY: 5
Following link has provided a good help to set mongo options in spring, but not specific enough for write-number values:
How to configure MongoDB Java driver MongoOptions for production use?
The write-concern number is the value of "w" which maps to the number of replicas that the write must propagate to before being considered successful when w > 1.
FSYNC_SAFE maps to setting write-fsync (true or false) and since JOURNAL_SAFE is also a boolean value, I suspect there is a similar boolean setting in Spring but I couldn't find it in any of their docs.
If you have everything installed to test this out empirically, just try several configurations and check the actual setting of the resultant write concern with something like:
WriteConcern wc = new WriteConcern(); // should get your default write concern
System.out.println(wc.getJ());
System.out.println(wc.getFsync());
System.out.println(wc.getW());
That should show you Journal setting, Fsync setting (both boolean), W (as an int).
You can confiture write-concern="ACKNOWLEDGED".
<mongo:mongo id="replicaSetMongo" replica-set="${mongo.replicaSetSevers}" />
<mongo:db-factory dbname="${mongo.dbname}" mongo-ref="replicaSetMongo" write-concern="ACKNOWLEDGED" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
Hope this can help.

Spring security + i18n = how to make it work together?

My first question here and i'll try to be specific. I am quite new to Spring and i'm trying to create quite simple reservation system (but this actually doesn't matter). What matters is that I am creating some basic template which i will then fill in by real webpages. Application works on hibernate,mysql, I also setup i18n and spring security. The poblem is that I cannot change my locale. The only thing which works is changing the default one.
First I browed Web A LOT and I found out that usage a i18n together with spring security is more complicated that usually. What i found out is that i need to have additional filter:
<filter>
<filter-name>localizationFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>localizationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
What I found out is that this filter is indeed processed before the security one however it does not parse the request in a form: http://someserver.com/bla/home?locale=en. I debugged it and it seems that it's not created for such purpose (and that's what I need).
This is taken from spring sample "contacts" however in this example I couldn't find any code that was actually targeting in changing the language. The effect is that it simply doesn't work. It always tries to change locale to my default one. The good news is that if in debug mode I manualy changed the locale-to-set to some other one it worked fine so i felt hope in my heart... ;-)
Then i've found some other way - by creating our own filter. What i did is to merge found example (don't remeber author) together with the way how RequestContextFilter is created. After all the RequestContextFilter works fine - just donest parse my requests. That's code of the new filter:
public class InternationalizationFilter extends OncePerRequestFilter {
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
protected void doFilterInternal(final HttpServletRequest request,
final HttpServletResponse response, final FilterChain filterChain)
throws ServletException, IOException {
final String newLocale = request.getParameter("locale");
if (newLocale != null) {
final Locale locale = StringUtils.parseLocaleString(newLocale
.toLowerCase());
LocaleContextHolder.setLocale(locale);
}
try {
filterChain.doFilter(request, response);
} finally {
LocaleContextHolder.resetLocaleContext();
}
}
}
As you can see the request paramter locale is parsed and the locale is set. There are 2 problems:
1. After sending request xxxxx?locale=en it creates Locale without "country" attribute (only language is set). To be honest I don't know if it's any problem - maybe not.
2. The more serious problem is that it doesn't work... i mean it's in the right place in the filter chain (before the security one), it produces right locale and sets it in exackly the same way like RequestContextFilter... but it simply doesnt work.
I would be very happy if someone could let me know how to make i18n work with spring-security basing on my example given or any other...
Thanks!
ADDITIONAL INFO:
I made some experiments and it seems that the Locale instance from request is somehow specific.
Look at this code (modified the RequestContextFilter class):
#Override
protected void doFilterInternal(final HttpServletRequest request,
final HttpServletResponse response, final FilterChain filterChain)
throws ServletException, IOException {
final ServletRequestAttributes attributes = new ServletRequestAttributes(
request);
final Locale l = Locale.GERMAN;
final Locale l2 = request.getLocale();
LocaleContextHolder.setLocale(l,
this.threadContextInheritable);
RequestContextHolder.setRequestAttributes(attributes,
this.threadContextInheritable);
if (logger.isDebugEnabled()) {
logger.debug("Bound request context to thread: " + request);
}
(...)
if to this method: LocaleContextHolder.setLocale(l, this.threadContextInheritable);
I pass locale 'l' it doesn't work at all. I mean the locale doesn't change even thou it's explicitly changed.
On the other hand if I pass there Locale 'l2' which is modified to german (in debug mode) it works fine!
This means that for some reason the Locale instance from request.getLocale() is somehow favored, maybe something is going on later on in the code which I don't know/understant...
Please let me know how should I use this i18n together with security cause I got to the point where I must admit that I have no idea what's going on...
-====-======-======--=======-====
FINAL SOLUTION/ANSWER (but still with little question)
Thanks to Ralph I managed to fix my issue. Previously I was going the wrong direction but the roo generated project pushed me forward.
It seems that I kept adding the interceptor in a wrong/not accurate way (previous code):
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="pl"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
This way the interceptor was never invoked for some reason.
After changing interceptor def to:
<mvc:interceptors>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
</bean>
</mvc:interceptors>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="pl"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
... it started to work fine without any other changes to security/web.xml.
Now the problem is gone however I am not sure what happened. From what i understand in the second example (the one that works) I made the interceptor "global". But why the interceptor definded in the first example didn't work? Any hint?
Thanks again for help!
N.
After sending request xxxxx?locale=en it creates Locale without "country" attribute (only language is set).
It is the expected behaviour. In java there is some kind of hierarchy.
The language is more general then the country.
The idea behind is that you can have for example the text in the more common languge but some units (like currency) in the country specific files.
#see: http://java.sun.com/developer/technicalArticles/Intl/IntlIntro/
The more serious problem is that it doesn't work...
It should work without any hand made implementation!
You need to register the Local Change Interceptor, and need to set permitAll for the login page.
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="lang"/>
</mvc:interceptors>
<http auto-config="true" use-expressions="true">
<form-login login-processing-url="/resources/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t"/>
<logout logout-url="/resources/j_spring_security_logout"/>
<!-- Configure these elements to secure URIs in your application -->
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/**" access="isAuthenticated()" />
</http>
To see this example running, create a roo project with that roo script:
// Spring Roo 1.1.5.RELEASE [rev d3a68c3] log opened at 2011-12-13 09:32:23
project --topLevelPackage de.humanfork.test --projectName localtest --java 6
persistence setup --database H2_IN_MEMORY --provider HIBERNATE
ent --class ~.domain.Stuff
field string --fieldName title
controller all --package ~.web
security setup
web mvc language --code de
web mvc language --code es
Then you must only change the security filters intersept-url patterns like I have shown above (applicationContext-security.xml)!
Now you have a application where the user can change its local via the local change interceptor in the application (when the user is logged in) as well as when he is not logged in (in the login page)
I had a similar issue with Localization when I was working with GWT app . The issue I noted was that when we map
<filter-mapping>
<filter-name>localizationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
to the filter, Even image requests are routed to the filter . These requests sometime leave out the locale parameter and hence when multiple requests hit the filter, the Locale parameter was not. Hence as soon as I received the locale parameter , I put it in a session . Log all the request headers and the values and you may find the root cause.

hibernate + Oracle 11.2 + BLOB

I googled a lot and haven't found working issue... In my web app I need to upload large files using ajax. I use ajaxfileupload plugin for it. In my FormBean class I mapped file to InputStream:
private InputStream fileData;
and
#FormParam("file")
#PartType("application/octet-stream")
#JsonIgnore
public void setFileData(InputStream fileData) {
this.fileData = fileData;
}
It works fine. I can save this stream into a file and haven't got any problems with java heap size. Now I'm trying to save it into database using Hibernate. Like this:
repFile.setFileData(session.getLobHelper().createBlob(file.getFileData(), 1024L));
and when I save repFile object I have ORA-01461 can bind a LONG value only for insert into a LONG column.
It works with Oracle 10. But it crashes with Oracle 11.2
I tried to add lobHandler to my configuration - didn't help
<property name="lobHandler">
<bean class="org.springframework.jdbc.support.lob.OracleLobHandler">
<property name="nativeJdbcExtractor">
<bean class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"/>
</property>
</bean>
</property>
And set batch size to 0 and allow steams
<prop key="hibernate.jdbc.use_streams_for_binary">true</prop>
<prop key="hibernate.jdbc.batch_size">0</prop>
That didn't help also... does anyone have a solution for this? Any help would be good.
You need to map the domain class like this:
#javax.persistence.Lob
private java.sql.Blob fileData;
Also, make sure that you create the column in the database as a 'BLOB'.
Finally, I recommend that you do not use 'InputStream' in your FormBean, but instead use something like 'MultiPartFile', since you can read an InputStream only once (unless you rewind/reset it). Also, MultiPartFile will give you the filename and length.

Resources