Sunday, November 29, 2015

Accessing std::set container by index position

You like it or not? Accessing an element of a set container by index position is different from the vector container as it doesn't support operator[]. There is a weird way of doing this. Before I got to aware this shortcut, I was doing it in this manner:
   set<int> s;
   set<int>::iterator is;
   for (is = s.begin(); is != s.end(); is++)
      ...
This will loop until my desire string is found. Unlike vector, I can not do something like this: s[0]. The compiler will never allow this shit to proceed further. Sigh! If it is not supported, then I have to find the other way. As of my finding, this seems to be workable:
   ...

   str = (*std::next(s.begin(),4)).c_str();
   ...
With this, I'll be able to access the 4th elements of s. I'm sure the 4th element is not null, otherwise that code will cause my shit to blow up during runtime.

Thursday, November 26, 2015

Trick to iterate queue in C++

Oh shit! Iterator was not part of the queue interface, then how could I iterate the content of the queue?

While I was unit testing my code, I want to check whether the queue does contain any search string found in the queue. Thus, I have a QueuePath which storing some text and then iterate the queue with following way, it failed.
typedef queue<wstring> QueuePath;
QueuePath::iterator it;
for( it=list.begin(); it != list.end(); it++ ) {
   …
}
This will hit compilation error because an iterator isn’t a member of the queue, thus a better resolution would be to use deque. Since my earlier design was started with queue, I didn’t really want to change it for now. While searching for a solution, I had discovered the new trick in ideone.com which is to iterate the queue. This trick is a work around for the queue to support the iterator interface.
#include <deque>
#include <queue>

using namespace std;

template< typename T, typename Container=std::deque<T> >
class MyQueue : public queue<T,Container>
{
public:
	typedef typename Container::iterator iterator;

	iterator begin() { return this->c.begin(); }
	iterator end() { return this->c.end(); }
};
int _tmain(int argc, _TCHAR* argv[])
{
	MyQueue<int> q;
	for (int i = 0; i < 10; i++)
		q.push(i);

	for (auto it = q.begin(); it != q.end(); it++)
		cout << *it << endl;

	return 0;
}
Although this workaround is damn real cool, but I was so reluctant to change my code. Anyway, think about it, do I really need this just for the unit testing? Basically, I could have something like below to get my job accomplished since I’m working on the unit test.
while( !list.empty() ) {
        …
        list.pop();
}
Remember my objective? The objective of this unit test is to make sure that the content in the queue was correct.

Tuesday, November 24, 2015

JSF session in JMeter

Just a quick note, when running performance tests on JSF using JMeter, in order to successfully execute a single thread (single user), not even mention execute multiple thread (more than one user) at a time, a new JSF View State value need to be captured every time a thread start executes. Otherwise the test will fail, even though it was recorded through Recording Controller. To capture the new JSF view state value, I create a new Regular Expression Extractor post processor under the GET request and put in following details:

Parameter Name Value
Reference Name jsfViewState
Regular Expression id=\"javax.faces.ViewState\" value=\"(.+?)\"
Template $1$
Match No. (0 for Random)   1

And then in the POST request which fail in the test, replace the javax.faces.ViewState‘s parameter value with ${jsfViewState}. After this, I also need an HTTP Cookie Manager to be placed in thread group to make it work.

Sunday, November 22, 2015

My new reinforcement on C++ unit test

A few weeks ago, while I was working out on CppUnit in unit testing and I found out that it wouldn’t work as I doesn’t have MFC framework install in my Windows. Now I had discovered Boost.Test for this critical mission. The first contact on the new discovery, I have following code ready to charge:
#define BOOST_TEST_MODULE Hello
#include <boost/test/unit_test.hpp>

int add(int i, int j)
{
    return i+j;
}

BOOST_AUTO_TEST_CASE(Case1)
{
    BOOST_CHECK(add(2,2) == 4);
}
Interestingly, the test doesn’t get executed, but the main entry point of the program, int main(int argc, char* argv[]) was called. I spent the whole day reading through the documentation still has not got any clue on it. Until I remove the main entry point, and something were shown on the screen:
Running 1 test case...

*** No errors detected
Press <return> to close this window...
This is pretty exciting as I got a first unit test up and running. Thinking out from the plan, I need a separate project just for the unit test.

Saturday, November 14, 2015

initializationError occurred in unit testing

What a bad day.

It has been so long I never run my unit test since many versions has been update to the source code. According to experts, unit test must run once in a while to ensure the codes are still working as expected. But today when I execute the unit test, it shows me an initializationError. What the heck!! What is wrong with my code? This error was occurred even before any unit test codes were run.

As I check in the forum, this may cause by the classpath containing two different versions of Hamcrest. But looking at my classpath, I don’t see two Hamcrest whereas I see two Junit libraries in the classpath, one provided by Eclipse and another one provided by Powermock. Would this be the root cause of this error? Hmmm… try to remove the one provided by Eclipse, it works! What the heck!

Thus, the conclusion would be either use the Junit provided by Eclipse or import my own Junit.

Tuesday, November 10, 2015

Duplicate section has different size

Looking at the following error, I think I have messed up the build.
C:\Tool\boost_1_54_0\stage\lib\libboost_filesystem-mgw48-mt-1_54.a(operations.o):-1: 
error: duplicate section `.rdata$_ZTSN5boost6detail17sp_counted_impl_pINS_10filesystem6detail11dir_itr_impEEE[__ZTSN5boost6detail17sp_counted_impl_pINS_10filesystem6detail11dir_itr_impEEE]' 
has different size
I was rebuilding the Boost unit test framework, once done, when I try to build my application, this error comes out. As I search in the forum, it is due to the object file and executable file were out of date, meaning to say that the linker unable to link them together, thus compiler will make some noise.

I do not have much choice to solve this error, rebuild everything is the only way.

Hibernate pagination

Pagination pattern is very popular used in application development. Its usage is to reduce memory footprint on the application server while retrieving huge data from database. In SQL, it could be done in following way:
select * from (
   select r, blah, blah, blah from (
      select rownum as row, tabA.* from tableA tabA
   )
   where row < pageNumber*rowPerPage
)
where row >= pageNumber-1*rowPerPage
Unfortunately, I wasn’t using Spring JdbcTemplate for the work. To recap, I have my jdbcTemplate being configured in such a way:
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:/comp/env/jdbc/MyApp"/>
        <property name="lookupOnStartup" value="false"/>
        <property name="cache" value="true"/>
        <property name="proxyInterface" value="javax.sql.DataSource"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
Instead, I was using Hibernate for the work. To recap, I have the Hibernate session being configured as following way:
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <property name="dataSource">
            <ref bean="dataSource"/>
        </property>

        <property name="hibernateProperties">
            …
        </property>

       <property name="annotatedClasses">
            …
        </property>
    </bean>

    <bean id="theDAO" class="org.huahsin.theDAOImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
In order to achieve the same thing as in SQL, I have the Hibernate query done in the following way:
public List getFunction(int pageNumber, int rowPerPage) {
   Criteria criteria = theDAO.getCurrentSession().createCriteria(ModelA.class, "modA");
   criteria.setMaxResults(rowPerPage);
   criteria.setFirstResult((pageNumber - 1) * rowPerPage);
   return criteria.list();
}