Wednesday, June 24, 2015

mongodb find queries


Mongodb Find queries


db.card.find();======it will display all documents
db.card.findOne();=====it will disply first document
db.card.find({title:"Chicken monchow soup"});=specific document with all fields





db.user_profile.find({"mobileNo":9988776655,"countryCode":"91"})==one document

db.user_profile.find({"mobileNo":9988776655,"countryCode":"91","mobileNo":8112300662,"countryCode":"91"})===two documnets


db.user_profile.find({mobileNo:{$in:[9988776655,8112300662]}})===specific document based on matching values



 db.user_profile.find(
{$or:[
        {"mobileNo": 9988776655, "countryCode":"91"},
        {"mobileNo": 8112300662,"countryCode":"1"} ,===========based on country code
    ]})

List of Regular Expressions Symbols



 Character Classes

Character classes are used to define the content of the pattern. E.g. what should the pattern look for?
.   Dot, any character (may or may not match line terminators, read on)

\d   A digit: [0-9]
\D   A non-digit: [^0-9]
\s   A whitespace character: [ \t\n\x0B\f\r]
\S   A non-whitespace character: [^\s]
\w   A word character: [a-zA-Z_0-9]
\W   A non-word character: [^\w]

However; notice that in Java, you will need to “double escape” these backslashes.
String pattern = "\\d \\D \\W \\w \\S \\s";

Quantifiers

Quantifiers can be used to specify the number or length that part of a pattern should match or repeat. A quantifier will bind to the expression group to its immediate left.

*      Match 0 or more times
+      Match 1 or more times
?      Match 1 or 0 times
{n}    Match exactly n times
{n,}   Match at least n times
{n,m}  Match at least n but not more than m times

Meta-characters

Meta-characters are used to group, divide, and perform special operations in patterns.

\   Escape the next meta-character (it becomes a normal/literal character)
^   Match the beginning of the line
.   Match any character (except newline)
$   Match the end of the line (or before newline at the end)
|   Alternation (‘or’ statement)
()   Grouping
[]   Custom character class

Monday, June 22, 2015

Reading properties from property util classes


Ex:

application.properties

template_card_image_path=D:/smilesurance-plain.png
hooper_code=234
service_id=01
business_code=SMILIN
images_path=D:/Smiline/cards/
corporate_name=Hackett Group
card_validity=Valid till:

PropertyUtils .java

package com.hps.platform.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hps.platform.utility.service.MessageService;

public class PropertyUtils {

private static final Logger LOGGER = LoggerFactory.getLogger(MessageService.class);
private static PropertyUtils propertyUtilsInstance;
private static Properties properties;

static{
propertyUtilsInstance = new PropertyUtils();
}

private PropertyUtils() {
if (properties == null) {
try {
properties = loadProperties();
} catch (IOException e) {
LOGGER.error("Threw a BadException, full stack trace follows:",e);
e.printStackTrace();
}
}
}

private Properties loadProperties() throws IOException {
Properties properties = new Properties();
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.properties");
if (inputStream == null) {
throw new FileNotFoundException("not loaded!");
}
properties.load(inputStream);
return properties;
}

public static Properties getProperties() {
return properties;
}

}


we can read the properties in the following way

public static String image_template_path PropertyUtils.getProperties().getProperty("template_card_image_path");
public static String corporateName = PropertyUtils.getProperties().getProperty("corporate_name");
public static String saved_image_path =PropertyUtils.getProperties().getProperty("images_path");


Saturday, June 20, 2015

Retrieving multiple records using spring jdbc+mysql

(type1 without passing any parameters to query and getting all rows)

String SELECT_NAME_CARDID_EXPIRY=""select *from user_enrollment_data";

DAO
public List<FailedRecords> getAllRecords();


DaoImpl

public List<FailedRecords> getAllRecords() {
return mysqlJdbcTemplate.query
(SELECT_NAME_CARDID_EXPIRY, 
new NullRecordRowMapper());  

}

NullRecordRowMapper

public class NullRecordRowMapper implements RowMapper<FailedRecords> {

@Override
public FailedRecords mapRow(ResultSet resultSet, int line)
throws SQLException {
NullRecordsExtractor userExtractor = new NullRecordsExtractor();
return userExtractor.extractData(resultSet);
}
}

NullRecordsExtractor 

Here  FailedRecords  pojo it contains database fileds

public class NullRecordsExtractor  implements ResultSetExtractor<FailedRecords>{
public FailedRecords extractData(ResultSet resultSet) throws SQLException,  
DataAccessException {  

FailedRecords failedRecords = new FailedRecords();  
failedRecords.setId(resultSet.getString(1));
failedRecords.setBusinessCode(resultSet.getString(2));
failedRecords.setCsvData(resultSet.getString(3));
failedRecords.setCardId(resultSet.getString(4));
failedRecords.setCardExpiry(resultSet.getString(5));
failedRecords.setMailStatus(resultSet.getString(6));

failedRecords.setSmsStatus(resultSet.getString(7));
failedRecords.setMobileNo(resultSet.getString(8));
failedRecords.setCreatedDate(resultSet.getDate(9));

/*String firstName=csvData.split(",")[1];
String lastName=csvData.split(",")[2];
System.out.println(firstName+" "+lastName);*/
return failedRecords;  
}  

}  


type2(passing single paramter and getting single row)

String  SELECT_TOTAL_FAMILY=" public final String SELECT_TOTAL_FAMILY="select *from user_enrollment_data where mail_status is null and mobile_no=?";


DAO

public List<FailedRecords> getFamilyMembers(String mobileNo);

DaoImpl

public List<FailedRecords> getFamilyMembers(String mobileNo) {  
return mysqlJdbcTemplate.query
(SELECT_TOTAL_FAMILY,
new Object[] { mobileNo }, 
new NullRecordRowMapper());  

}

same  NullRecordRowMapper and NullRecordsExtractor 










Tuesday, June 16, 2015

Jasper reports example with java beans without database


Use jasper reports library

<pre name="code" class="java">

DataBean.java

public class DataBean {
private String name;
private String occupation;
private String place;
private String country;
//setters and getters
}

DataBeanMaker.java

package com.report.javabean;
import java.util.ArrayList;
public class DataBeanMaker {

public ArrayList<DataBean> getDataBeanList() {

ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

dataBeanList.add(produce("umar farooq", "Manager", "karnool", "india"));
dataBeanList.add(produce("mohan", "SSE", "vizag", "india"));
dataBeanList.add(produce("Srikanth tirumala", "CEO", "hyderabad", "India"));
dataBeanList.add(produce("ruby", "Co-Founder", "karnool", "India"));
dataBeanList.add(produce("subbu", "SSE" , "nelure", "india"));
dataBeanList.add(produce("mustak", "SE" , "karnool", "india"));
dataBeanList.add(produce("satya", "SE", "nalgonda", "india"));
dataBeanList.add(produce("kiran", "SSE" , "east", "india"));
dataBeanList.add(produce("sujatha", "HR" , "hyderabad", "india"));

return dataBeanList;
}

private DataBean produce(String name, String occupation, String place, String country) {

DataBean dataBean = new DataBean();
dataBean.setName(name);
dataBean.setOccupation(occupation);
dataBean.setPlace(place);
dataBean.setCountry(country);

return dataBean;
}



}

Repoter.java

package com.report.javabean;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
public class Reporter {

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
InputStream inputStream = new FileInputStream ("reports/test_jasper.xml");

DataBeanMaker dataBeanMaker = new DataBeanMaker();
ArrayList<DataBean> dataBeanList = dataBeanMaker.getDataBeanList();

JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataBeanList);

Map parameters = new HashMap();

JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "D:/demo.pdf");
}
}

test_jasper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.1.0.final using JasperReports Library version 6.1.0  -->
<!-- 2015-06-17T10:42:17 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="scriptlet" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="30" rightMargin="30" topMargin="30" bottomMargin="30" whenResourceMissingType="Empty" uuid="4a933c9b-78d7-426f-8fd8-e27159b11caa">
<property name="com.jasperassistant.designer.Grid" value="false"/>
<property name="com.jasperassistant.designer.SnapToGrid" value="false"/>
<property name="com.jasperassistant.designer.GridWidth" value="12"/>
<property name="com.jasperassistant.designer.GridHeight" value="12"/>
<queryString>
<![CDATA[]]>
</queryString>
<field name="country" class="java.lang.String">
<fieldDescription><![CDATA[country]]></fieldDescription>
</field>
<field name="occupation" class="java.lang.String">
<fieldDescription><![CDATA[occupation]]></fieldDescription>
</field>
<field name="name" class="java.lang.String">
<fieldDescription><![CDATA[name]]></fieldDescription>
</field>
<field name="place" class="java.lang.String">
<fieldDescription><![CDATA[place]]></fieldDescription>
</field>
<group name="dummy">
<groupExpression><![CDATA["dummy"]]></groupExpression>
<groupHeader>
<band height="23">
<staticText>
<reportElement mode="Opaque" x="0" y="5" width="535" height="15" backcolor="#70A9A9" uuid="d6b37903-6581-4be2-acd8-a34e03d4a65f"/>
<box>
<bottomPen lineWidth="5.0" lineColor="#CCCCCC"/>
</box>
<text><![CDATA[]]></text>
</staticText>
<staticText>
<reportElement x="136" y="5" width="150" height="15" uuid="bc77d454-a4ad-4acd-a45c-7781a1cc9db3"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font isBold="true"/>
</textElement>
<text><![CDATA[Occupation]]></text>
</staticText>
<staticText>
<reportElement x="286" y="5" width="128" height="15" uuid="9a0b1647-7c70-46d2-9904-b6c8ec2516bc"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Place]]></text>
</staticText>
<staticText>
<reportElement x="414" y="5" width="121" height="15" uuid="1d3dc13e-6844-4551-87c4-a84942396de6"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font isBold="true"/>
</textElement>
<text><![CDATA[Country]]></text>
</staticText>
<staticText>
<reportElement x="0" y="5" width="136" height="15" uuid="35ea54b3-46ba-4a00-b209-0f0caae22199"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font isBold="true"/>
</textElement>
<text><![CDATA[Name]]></text>
</staticText>
</band>
</groupHeader>
</group>
<detail>
<band height="16">
<staticText>
<reportElement mode="Opaque" x="0" y="0" width="535" height="14" backcolor="#E5ECF9" uuid="2b45dbc9-215c-453e-b263-22419173a2a6"/>
<box>
<bottomPen lineWidth="0.25" lineColor="#CCCCCC"/>
</box>
<text><![CDATA[]]></text>
</staticText>
<textField>
<reportElement x="136" y="0" width="150" height="15" uuid="2321034b-fef7-4c07-9605-0a40e48a0080"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{occupation}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="286" y="0" width="128" height="15" uuid="472e0b06-bb32-458f-8073-a637449a060f"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{place}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="414" y="0" width="121" height="15" uuid="6de7ba67-0d5c-48bb-9817-6390fc7a9e13"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font size="9"/>
</textElement>
<textFieldExpression><![CDATA[$F{country}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="0" y="0" width="136" height="15" uuid="d592ad48-a319-4939-860f-733d28e312a2"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
</band>
</detail>

</jasperReport>

</pre>

Simple Jasper report example with jdbc



main class


package net.sf.dynamicreports.examples;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.exception.DRException;

/**
 * SQL
 *

CREATE TABLE `customers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) DEFAULT NULL,
  `last_name` varchar(50) DEFAULT NULL,
  `date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;

  INSERT INTO `test`.`customers` (`first_name`, `last_name`, `date`) VALUES ('Ricardo', 'Mariaca', CURRENT_DATE);
INSERT INTO `test`.`customers` (`first_name`, `last_name`, `date`) VALUES ('YONG', 'MOOK KIM', CURRENT_DATE);

 */
public class SimpleReportExample {

public static void main(String[] args) {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
} catch (SQLException e) {
e.printStackTrace();
return;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}

JasperReportBuilder report = DynamicReports.report();//a new report
report
 .columns(
  Columns.column("Customer Id", "id", DataTypes.integerType())
  .setHorizontalAlignment(HorizontalAlignment.LEFT),
  Columns.column("First Name", "first_name", DataTypes.stringType()),
  Columns.column("Last Name", "last_name", DataTypes.stringType()),
  Columns.column("Date", "date", DataTypes.dateType())
  .setHorizontalAlignment(HorizontalAlignment.LEFT)
  )
 .title(//title of the report
  Components.text("SimpleReportExample")
  .setHorizontalAlignment(HorizontalAlignment.CENTER))
 .pageFooter(Components.pageXofY())//show page number on the page footer
 .setDataSource("SELECT id, first_name, last_name, date FROM customers", connection);

try {
report.show();//show the report
report.toPdf(new FileOutputStream("D:/Text.pdf"));//export the report to a pdf file
} catch (DRException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Sunday, June 14, 2015

Running console application(main program) using Maven(pom.xml)


The following pom.xml is suitable to run main programs in java using maven

pom.xml

 <build>
<plugins>
<plugin>
<artifactId>maven-plugin-plugin</artifactId>
<version>2.3</version>
<configuration>
<goalPrefix>clean</goalPrefix>
<goalPrefix>install</goalPrefix>
<goalPrefix>run</goalPrefix>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.email.TestApp</mainClass>
</configuration>
</plugin>

</plugins>
</build>
    

Unknown Lifecycle Phase Error in Maven Build


Problem

[ERROR] Unknown lifecycle phase "test1". You must specify a valid lifecycle phase or a goal

in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-

version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources,

process-sources, generate-resources, process-resources, compile, process-classes, generate-

test-sources, process-test-sources, generate-test-resources, process-test-resources, test-

compile, process-test-classes, test, prepare-packagepackage, pre-integration-test,

integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean,

 pre-site, site, post-site, site-deploy. -> [Help 1]

If you look at the above error “Unknown lifecycle phase”, your build could not detect the pre-defined lifecycle phase used by Maven. Maven has the following phases:
  • validate – validate the project is correct and all necessary information is available
  • compile – compile the source code of the project
  • test – test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package – take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test – process and deploy the package if necessary into an environment where integration tests can be run
  • verify – run any checks to verify the package is valid and meets quality criteria
  • install – install the package into the local repository, for use as a dependency in other projects locally
  • deploy – done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects
    Solution is: package

Friday, June 12, 2015

Simple restful service using jersey+json format


Resource class


package com.hps.resources;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hps.model.HelloRequest;
import com.hps.model.HelloResponse;

@Path("/admin")
public class MessageResource {
@GET
@Path("{parameter}")
public Response responseMsg( @PathParam("parameter") String parameter,
@DefaultValue("Nothing to say") @QueryParam("value") String value) throws JsonProcessingException, UnknownHostException {
String output = "Hello from: " + parameter + " : " + value;
return Response.status(200).entity(output).build();
}
@POST
@Path("/action")
@Produces(MediaType.APPLICATION_JSON)
public Response produceJson(HelloRequest helloRequest) throws JsonProcessingException, UnknownHostException{
String output = "Hello from: " + helloRequest.getParameter() + " : " +helloRequest.getMessage();

HelloResponse reponse = new HelloResponse(output);
reponse.setStatus(Response.Status.CREATED.getStatusCode());
return Response.status(200).entity(reponse).build();
}


}

HelloRequest.java



@XmlRootElement
public class HelloRequest {
private String message;
private String parameter;
//getters and setter methods
}

HelloResponse.java

public class HelloResponse {
private String message;
private int status;
//getters and setters
}


MyApplication.java(this will produce the json response)


import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.filter.LoggingFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;

@ApplicationPath("/")
public class MyApplication extends Application {

@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(MessageResource.class);
return classes;
}
@Override
public Set<Object> getSingletons() {
final Set<Object> instances = new HashSet<Object>();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
instances.add(new JacksonJsonProvider(mapper));
instances.add(new LoggingFilter());
return instances;
}
}

web.xml



<servlet>
        <servlet-name>rest</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
          <param-name>javax.ws.rs.Application</param-name>
          <param-value>com.hps.resources.MyApplication</param-value>
        </init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>







Inserting and Retrieving images in MongoDB without GridFs Library

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class SaveImageApp {
public static void main(String[] args)
{
SaveImageApp o = new SaveImageApp();
o.withoutUsingGridFS();
}
public  void withoutUsingGridFS()
{
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("imagedb");
DBCollection collection = db.getCollection("dummyColl");

String filename = "C:/TEOProjectWorkspace/Mongodb/hoopertext.png";
String empname ="hooper";
insert(empname,filename,collection);
String destfilename = "C:/TEOProjectWorkspace/Mongodb/hoopertext.png";
retrieve(empname, destfilename, collection);

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}

public   void insert(String empname, String filename, DBCollection collection)
{
try
{
File imageFile = new File(filename);
FileInputStream f = new FileInputStream(imageFile);
byte b[] = new byte[f.available()];
f.read(b);

//    Binary data = new Binary(b);
BasicDBObject o = new BasicDBObject();
o.append("name",empname).append("photo",b);
collection.insert(o);
System.out.println("Inserted record.");
f.close();

} catch (IOException e) {
e.printStackTrace();
}
}
void retrieve(String name, String filename, DBCollection collection)
{
byte c[];
try
{
DBObject obj = collection.findOne(new BasicDBObject("name", name));
String n = (String)obj.get("name");
c = (byte[])obj.get("photo");
FileOutputStream fout = new FileOutputStream(filename);
fout.write(c);
fout.flush();
System.out.println("Photo of "+name+" retrieved and stored at "+filename);
fout.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}