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();
}

Saturday, November 7, 2015

CppUnit require MFC library on Windows environment?!!

Anyone done any unit testing on C++? Am I speaking on my own?

Well, I was influenced by the unit testing I did in Java. After many years of working on C/C++ program, now only got to realize I was actually missing unit testing in the development. I was so curious why none of them mention this before? Or maybe they felt that unit testing is a waste? Or they don’t even care? But in Java world, they are so concern about unit testing. Anyhow, I just download a copy of the unit testing framework – CppUnit, and putting it into my very personal, private, secret project.

Just a site note when getting the source of CppUnit, never download from the website, it was a trap. This is because the files are suffixed with “,v” in the file extension. The real source ca be download through SVN. Once done, build it. There is no free lunch in the open source world.

When I was about to build, Oh No!! How to build on Windows machine? configure and make are only workable command in Linux…

Well, the instruction was in the file with file name start with INSTALL, there are many of them. In my case, I’m building it in a Windows environment, thus I’ll look for the INSTALL-WIN32.txt. Follow the instructions mention in that file to build CppUnit. Unfortunately, the building of CppUnit has failed due to the missing of afxwin.h. Since I’m using visual studio express edition, this edition doesn’t have MFC installed, thus it wouldn’t have that header file.

Crap! What a bad day.

Thursday, November 5, 2015

Automatically trigger event when user has done editing

In the existing use case behavior, the update event function is triggered when the user is pressing enter key while the cursor still focusing in the text field.
<h:form id="theform">
   <p:inputText id="search" value="#{controller.text}" placeholder="Press enter to search" onkeypress="if(event.keyCode == 13) { searchCommand(); return false; }" />
   <p:remoteCommand name="searchCommand" actionListener="#{controller.doSearch}" update="dataTable" />
   <p:commandButton onclick="searchCommand()" value="saerch" update="dataTable" />
</h:form>
When the field is reset, the user has to press enter key again in order to trigger the update field. I felt this behavior was so annoying, it would be much better if the field could automatically trigger the update event function when the user has done editing. Thus, I was to use an Ajax listener to do this.
<h:form id="theform">
   <p:inputText id="search" value="#{controller.searchText}" placeholder="Press enter to search">
      <p:ajax listener="#{controller.doSearch}" update="dataTable" />
   </p:inputText>
   <p:remoteCommand name="searchCommand" actionListener="#{controller.doSearch}" update="dataTable" />
   <p:commandButton onclick="searchCommand()" value="saerch" update="dataTable" />
</h:form>
AHhhh~ This was nice, now I feel complete.

Sunday, November 1, 2015

Building Boost with MinGW compiler

Does it really hard to build Boost libraries with MinGW compiler on Windows?

I have the Windows version Boost library build for Microsoft compiler, when I tried to link them in QT creator, as shown below, was failed even though I have configured the build kit to the Microsoft compiler in QT creator.
win32 {
   INCLUDEPATH += C:/Tool/boost_1_54_0
   LIBS += -LC:/Tool/boost_1_54_0/lib64-msvc-11.0 -lboost_filesystem-vc110-1_54
}
Looking on the Internet, the majority of them are using MinGW version of Boost library whenever working on QT, not the Microsoft version. To build a MinGW version of Boost, it wasn't that straight forward as following command.
c:\tool\boost_1_54_0>bootstrap.bat

c:\tool\boost_1_54_0>b2.exe --toolset=gcc
I did try on the command mention above, but end up nothing were being generated in stage/lib. I then found there is a workaround for building the MinGW version of Boost:

Step 1
Go to <BOOST_ROOT>/tools/build/v2/engine, and fire the command: build.bat mingw. This will generate bin.ntx86 folder under the same path.

Step 2
Set environment variable: set PATH=%PATH%;<BOOST_ROOT>/tools/build/v2/engine/bin.ntx86. Without this Windows will not recognize who is bjam.

Step 3
Set environment variable: set PATH=%PATH%;<MinGW_ROOT>/bin. Without this the compiler will not recognize who is gcc.

Step 4
Fire the command: bjam toolset=gcc. This should generate a bunch of libraries with file name that contain mgw with .a extension.

One last note, bjam command will require mingw32-libz to be installed with MinGW compiler before Boost is start building. Once done, reconfigure the .pro file with following code:

win32 {
   INCLUDEPATH += C:/Tool/boost_1_54_0
   LIBS += -LC:/Tool/boost_1_54_0/stage/lib -lboost_filesystem-mgw48-mt-1_54
}