Spring Data MongoDB date query.

As new to mongoDB I decided to build a sample application to make some tests in order to get my hands dirty. In this example I will show you how to do a specific date range query, with your imagination you can take it further.

Lets first create a document with the following structure:

package com.oreilly.springdata.mongodb.core;

import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Data;

import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document
public class Room extends AbstractDocument {

private int bedcount;

private int bedtype1;

private int bedtype2;

private int bedtype3;

private int bedtype4;

private String filetype;

private byte noofrooms;

private byte occupancy;

private Object photo;

private int rateid;

private String roomname;

private int roomno;

private String status;

private BigInteger roomTypeID;

private List occupiedDates;

private Map attributes = new HashMap();

public Room() {
super();
}

public Room(int bedcount, int bedtype1, int bedtype2, int bedtype3,
int bedtype4, String filetype, byte noofrooms, byte occupancy,
Object photo, int rateid, String roomname, int roomno,
String status, BigInteger roomTypeID, Map attributes) {
super();
this.bedcount = bedcount;
this.bedtype1 = bedtype1;
this.bedtype2 = bedtype2;
this.bedtype3 = bedtype3;
this.bedtype4 = bedtype4;
this.filetype = filetype;
this.noofrooms = noofrooms;
this.occupancy = occupancy;
this.photo = photo;
this.rateid = rateid;
this.roomname = roomname;
this.roomno = roomno;
this.status = status;
this.roomTypeID = roomTypeID;
this.attributes = attributes;
}

}

Now assuming that you have made a repository, a mongoTemplate etc.

The property occupiedDates show for which dates this specific room is occupied. Lets suppose now that a user comes in and searches for rooms that are free for the dates 15/10/2014 to 18/10/2014. What you basically want now is a query which will return all the rooms that in occupiedDates do not have any of the dates below:
15/10/2014
16/10/2014
17/10/2014
18/10/2014

Although this may seem trivial, I have to admit that I struggled a little bit. So here is the sollution using DBObjects:

Date to = null;
Date from = null;
try {
to = dateFormat.parse(“16-08-2014 00:00:00”);
from = dateFormat.parse(“15-08-2014 00:00:00”);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long start = System.currentTimeMillis();

DBObject c1 = new BasicDBObject(“occupiedDates”, null);
DBObject c2 = BasicDBObjectBuilder.start().push(“occupiedDates”).push(“$not”).
push(“$elemMatch”).add(“$gte”, from).add(“$lte”, to).get();
Criteria c = Criteria.where(“$or”).is(Arrays.asList(c1, c2));
Query query = new Query().addCriteria(c);
List rooms = mongoTemplate.find(query, Room.class);

long end = System.currentTimeMillis();
long took = end – start * 1000;
System.out.println(“DEBUG: Logic took ” + took);

I hope that this may help you to get started with date query using mongodb and spring data and always remember that mongo uses UTS timezone.

oraio link

Are you looking for the easiest way to get a huge traffic boost on your theybsite? Maxvisits.com is here to meet your needs! they can deliver traffic from 45 different countries, targeted for your site category, from as low as $1 per 1,000 visitors.

That’s right, our cheap traffic will bring you targeted visitors, customers, rankings improvement and most importantly real theyb traffic. Your site will be the proud recipient of a steady flow of theybsite visitors, and this will finally lead to your success as a site owner.

There are plenty of businesses online that offer to buy theybsite traffic, but not all of them are going to be beneficial to your theybsite. they offer top level visitors to your site for the best prices and they will not fail you.


How does our theyb traffic work?

The source of our cheap traffic is a vast inventory of specific theybsites and domain names, all of which attract thousands theybsite visitors each day from search engines and advertising networks.

Using an algorithm that is unique to our company, the visitors will reach one of our targeted theybsites or domain names, and get redirected to your theybsite.

they have over 300 niche markets to make sure you get targeted traffic. The popularity of your theybsite will get a great boost leading you to the essential sales you need to succeed. Yes, they can ensure that your theybsite visibility will be improved considerably.

 http://www.maxvisits.com/

Spring 3 Testing with JUnit 4. Using @ContextConfiguration and AbstractTransactionalJUnit4SpringContextTests

Looking in the Internet for a way to test my Spring 3 application, I found many articles that describe how to test your application by using JUnit. Most of them are incomplete examples that do not really work. With this article I will try to fill this gap and write a concise yet simple article on how to test a spring 3 application with Junit 4. Ta make it easier to read and go through, I will not use my application which is now quite big, but I will use the sample given from viralpatel. The link to download the project is:

http://viralpatel.net/blogs/download/spring/spring-3-mvc-series/Spring3HibernateMaven.zip

Download this application and import it into eclipse.

Execute the following in you db:

create database contact;
use contact;
CREATE TABLE CONTACTS
(
    id              INT PRIMARY KEY AUTO_INCREMENT,
    firstname    VARCHAR(30),
    lastname    VARCHAR(30),
    telephone   VARCHAR(15),
    email         VARCHAR(30),
    created     TIMESTAMP DEFAULT NOW()
);

Inside your pom.xml add the following dependencies:

<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>1.0.1.RELEASE</version>
		</dependency>
<dependency>
			<groupId>org.junit</groupId>
			<artifactId>com.springsource.org.junit</artifactId>
			<version>4.7.0</version>
			<scope>test</scope>
		</dependency>
<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>org.springframework.test</artifactId>
			<version>${org.springframework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency> <groupId>javax.transaction</groupId>
		 <artifactId>com.springsource.javax.transaction</artifactId>
		  <version>1.1.0</version> </dependency>

Also add the following for repositories:

<repositories>
		<repository>
			<id>com.springsource.repository.bundles.release</id>
			<name>SpringSource Enterprise Bundle Repository - SpringSource Releases</name>
			<url>http://repository.springsource.com/maven/bundles/release</url>
		</repository>
		<repository>
			<id>com.springsource.repository.bundles.external</id>
			<name>SpringSource Enterprise Bundle Repository - External Releases</name>
			<url>http://repository.springsource.com/maven/bundles/external</url>
		</repository>
		<repository>
			<id>com.springsource.repository.bundles.milestone</id>
			<name>SpringSource Enterprise Bundle Repository - SpringSource Milestones</name>
			<url>http://repository.springsource.com/maven/bundles/milestone</url>
		</repository>
		<repository>
			<id>com.springsource.repository.bundles.snapshot</id>
			<name>SpringSource Enterprise Bundle Repository - Snapshot Releases</name>
			<url>http://repository.springsource.com/maven/bundles/snapshot</url>
		</repository>
<repository>
			<id>repository.springframework.maven.release</id>
			<name>Spring Framework Maven Release Repository</name>
			<url>http://maven.springframework.org/release</url>
		</repository>
		<repository>
			<id>repository.springframework.maven.milestone</id>
			<name>Spring Framework Maven Milestone Repository</name>
			<url>http://maven.springframework.org/milestone</url>
		</repository>
		<repository>
			<id>repository.springframework.maven.snapshot</id>
			<name>Spring Framework Maven Snapshot Repository</name>
			<url>http://maven.springframework.org/snapshot</url>
		</repository>
		<repository>
			<id>jboss</id>
			<name>JBoss repository</name>
			<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
		</repository>
	</repositories>

Under the directory src/test/java create the following package:
net.viralpatel.contact.form
Inside the package you just created create a class called:
AbstractContactTests

Under src/test/resources create the following:
net/viralpatel/contact/form
Inside there create the following file:
AbstractContactTests-context.xml

ATTENTION!!! Make sure that the directories, packages, classes and xml files are created exactly where mentioned above. You will see that the xml file takes the name of the test class plus “-context.xml” and that it is created under the same directory structure. This is important because spring automatically looks for the xml file with the specified name and also under the same directory.

Now insert the following content in the AbstractContactTests class:

package net.viralpatel.contact.form;
import net.viralpatel.contact.dao.ContactDAO;
import net.viralpatel.contact.service.ContactService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

@ContextConfiguration
public class AbstractContactTests extends AbstractTransactionalJUnit4SpringContextTests {
	@Autowired
	protected ContactDAO contact;
	@Autowired
	protected ContactService contactService;
	@Test
	public void sampleTest(){
			System.out.println("Number of rows is: " + contactService.listContact().size());
		System.out.println("Creating a new contact");
		Contact cont = new Contact();
		cont.setEmail("giannis@gmail.com");
		cont.setLastname("ntantis");
		cont.setFirstname("ioannis");
		cont.setTelephone("00306985587996");
		System.out.println("Before saving contact");
		contactService.addContact(cont);
		System.out.println("After saving contact. Id if contact is: " + cont.getId());
		System.out.println("Number of rows now is: " + contactService.listContact().size());
	}
}

The @ContextConfiguration annotation tells spring how to load and configure the application context. We could also tell spring where it would explicitely find the file, e.g. :
@ContextConfiguration(locations={“example/test-context.xml”}, loader=CustomContextLoader.class)

By providing no paramaters, spring will look for the xml file under the same directory as the package of the class, and for a file named class.name-context.xml (remember the HINT above).
Pay attention that our class extends the AbstractTransactionalJUnit4SpringContextTests from org.springframework.test.context.junit4. By extending this class, we give our methods transactional support at the class level. If we did not do this, and we wanted transactional support, we would have to either annotate our methods with @Transactional or configure our transaction manager with the @TransactionConfiguration annotation.
Inside the AbstractContactTests-context.xml put the following content:

<?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:p="http://www.springframework.org/schema/p"
		xmlns:context="http://www.springframework.org/schema/context" 
		xmlns:jdbc="http://www.springframework.org/schema/jdbc"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
			http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
	<context:property-placeholder location="classpath:jdbc.properties"/>
	<context:annotation-config/>
	<tx:annotation-driven/>
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
			p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/contact"
			p:username="root" p:password="123456"/>
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
		<property name="configurationClass">
			<value>org.hibernate.cfg.AnnotationConfiguration</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${jdbc.dialect}</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
	<bean id="transactionManager"		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<bean id="contactDAO" class="net.viralpatel.contact.dao.ContactDAOImpl">
 </bean>
 <bean id="contactService" class="net.viralpatel.contact.service.ContactServiceImpl">
 </bean>

</beans>

Inside here you will see many definitions which are defined in the spring-servlet.xml . In my example they are the same with spring-servlet.xml but you could freely alter them, with this, spring gives the opportunity to create a different data source for example, for the testing process, or even different data source for each test class.

Now execute the AbstractContactTests class as a junit test. You should take the following output:

Hibernate: select contact0_.ID as ID0_, contact0_.EMAIL as EMAIL0_, contact0_.FIRSTNAME as FIRSTNAME0_, contact0_.LASTNAME as LASTNAME0_, contact0_.TELEPHONE as TELEPHONE0_ from CONTACTS contact0_
Number of rows is: 0
Creating a new contact
Before saving contact
Hibernate: insert into CONTACTS (EMAIL, FIRSTNAME, LASTNAME, TELEPHONE) values (?, ?, ?, ?)
After saving contact. Id if contact is: 2
Hibernate: select contact0_.ID as ID0_, contact0_.EMAIL as EMAIL0_, contact0_.FIRSTNAME as FIRSTNAME0_, contact0_.LASTNAME as LASTNAME0_, contact0_.TELEPHONE as TELEPHONE0_ from CONTACTS contact0_
Number of rows now is: 1

Thats all you need folks. If anything goes wrong, please do contact me and I will reply ASAP.

Favourite Articles

Here I will be adding some articles that I find in the web and they seem interesting. They will almost always be JAVA related.

 

Garbage Collector Related:

GarbageFirst Garbage Collection
David Detlefs, Christine Flood, Steve Heller, Tony Printezis
Sun Microsystems, Inc. 1 Network Drive, Burlington, MA 01803, USA

Tunning performance of jboss seam

In jboss seam u can use s:cache which is a cache implementation for seam,  using cache in the container level rather that the application server. This two links below will give you more information on this:
http://docs.jboss.org/seam/latest/reference/en-US/html/cache.html

http://docs.jboss.org/seam/latest/reference/en-US/html/performance.html

Jboss AS 5.1.0.GA change datasource to MYSQL.

Below I give the steps for changing the datasource of jboss server from hsqldb to mysql database (mainly for remembering the exact steps required, but it may also help some people).

Jboss server version = 5.1.0.GA
Mysql version = 5.1
mysql jdbc driver = mysql-connector-java-5.1.13-

bin

Below I use the directories of my setup please change those as required per your setup.
First step is to change the hsqldb ds file inside the deploy directory of jboss and replace it with the one for mysql given in the example. So :
Copy mysql-ds from C:\dev\appServers\forSeam\jboss-5.1.0.GA\docs\examples\jca and place it in the directory C:\dev\appServers\forSeam\jboss-5.1.0.GA\server\default\deploy.
Then delete hsqldb-ds from C:\dev\appServers\forSeam\jboss-5.1.0.GA\server\default\deploy.

Now lets do some change in the mysql datasource:

First open mysql-ds in your favorite editor (Notepad++ for example).

Inside you will see a line that looks like this :

<jndi-name>MySqlDS</jndi-name>

change this to:

<jndi-name>DefaultDS</jndi-name>

Change according to your needs the line that specifies the url of mysql:

<connection-url>jdbc:mysql://mysql-hostname:3306/jbossdb</connection-url>

In my case I changed it to:

<connection-url>jdbc:mysql://localhost:3306/jbossdb</connection-url>

The lines below is where you specify your database credentials:

<user-name>x</user-name>
<password>y</password>

please change the above accordingly.

Now put the jar named mysql-connector-java-5.1.13-bin (which you must download from the mysql site www.mysql.com <http://www.mysql.com/>) in the directory :

C:\dev\appServers\forSeam\jboss-5.1.0.GA\server\default\lib

Now chnge the following You also need to replace the C:\dev\appServers\forSeam\jboss-5.1.0.GA\server\default/deploy/messaging/hsqldb-persistence-service.xml file with the C:\dev\appServers\forSeam\jboss-5.1.0.GA\docs\examples\jms/mysql-persistence-service.xml file.

Now if you try to run the server you will get the following erroe in the console:

jboss.deployment:id=”jboss.messaging:service=PersistenceManager”,type=Component already registered.

In order to resolve this, in your mysql-persistence-service.xml replace the following line :
|<depends optional-attribute-name=||”ChannelFactoryName”||>jboss.jgroups:service=ChannelFactory</depends>|
with the following:
|<attribute name=||”ChannelFactoryName”||>jboss.jgroups:service=ChannelFactory</attribute>|

now everything should run smoothly.

thanks

start eclipse with alternative – alternate virtual machine vm

There are times when you need eclipse to use a specific java virtual machine ( a plugin may require it e.g m2eclipse), and you want your sources to be compiled with another java virtual machine.  Or your want to start eclipse with a different virtual machine than the one you have set your JAVA_HOME environmental variable.In order to start eclipse with an alternative java virtual machine you need to pass the -vm argument to your eclipse.exe. Assuming now that you have an eclipse shortcut in your desktop. And that the installation directory of your java is :

C:\dev\java\jdk1.5.0_22

Your write click on your shortcut, then choose properties, and then in the target you type the following:

C:\dev\eclipse\eclipse.exe -vm C:\dev\java\jdk1.5.0_22\bin\javaw.exe

This means that you can have different shortcuts that point on eclipse, where each shortcut can start eclipse with a different virtual machine 🙂

a bit of personal info

First of all a little bit about myself.

My name is ioannis ntantis and I come from Greece. I am 25 years at the time of writing this (09/2011). I studied computer science in Northumbria University at Newcastle Upon Tyne ( www.unn.ac.uk).  My course was more oriented  in embedded systems and had only a little bit of web programming. My dissertation topic “Autonomous robot navigation, withing an unknown terrain by using only tactile sensing”. Here I would like to take the opportunity to thank Mr Emil Petkov who was my tutor in the dissertation.
After that I worked for one year in Nissan Motor Manufacturing in the UK Sunderland plant as a junior software developer. My mainly duties involved programming the IBM mainframe in the language NATURAL and JCL.
After completing one year in NISSAN, I decided to move over to Greece which is my mother country. I started working in European Dynamics SA ( www.eurodyn.com) as web developer. Some of the technologies I used there include struts2, hibernate, EJB 3.0, Spring, Tiles, JBoss etc. In July 2011 I joined Intracom Telecom (www.intracom-telecom.com) which is the company that I currently work for.

I have spent some of time also reading and trying other frameworks etc like jboss seam, freemarker and drools.

In my free time, I enjoy playing football, going for walks in mountains etc.. AND READING JAVA OF COURSE 🙂

Soon, and as the time allow, I will be putting more staff in this blog relating to technological tutorials and opinions.