Wednesday, July 1, 2015

User registration form with CAPTCHA using django-simple-captcha using python

sample web registration in python




  1. import web

  2. # Init our application, this is just about the most basic setup
  3. render = web.template.render('/var/www/templates/')
  4. urls = ('/', 'Index')
  5. app = web.application(urls, globals())

  6. class Index:
  7.     # Create a basic form shared by the class methods
  8.     def __init__(self):
  9.        self.registerForm = web.form.Form(
  10.             # We're adding some fields and a submit button
  11.             # Each field has a validator, which verifies its correctness
  12.             # In this case we check if the field is not null
  13.             # Other attributes are available: description, id, HTML class name, etc
  14.             # See http://webpy.org/form for reference
  15.             web.form.Textbox('username', web.form.notnull, description='User name'),
  16.             web.form.Password('password', web.form.notnull, description='Password'),
  17.             web.form.Password('repeat_password', web.form.notnull,
  18.                               description='Repeat password'),
  19.             web.form.Button('Register'),

  20.             # Whole forms can have validators, too
  21.             # Here, we check if password fields have the same content
  22.             validators = [web.form.Validator("Passwords didn't match.", lambda i:
  23.                                              i.password == i.repeat_password)]
  24.         )

  25.     # GET method is used when there is no form data sent to the server
  26.     def GET(self):
  27.         form = self.registerForm()
  28.         return render.form(content=form)

  29.     # POST method carries form data
  30.     def POST(self):
  31.         # Notice how flawlessly web.py form works, receiving all the data for us
  32.         form = self.registerForm()

  33.         if(not form.validates()):
  34.             return render.form(content=form)
  35.         else:
  36.             return "Form successfuly sent! Username: %s, password: %s" % \
  37.                 (form.d.username, form.d.password)

  38. application = app.wsgifunc()

  39. if __name__=="__main__":
  40.     app.run()




  41. user.py


  42. # Django settings for app project.

  43. # Import the os.path module for doing manipulation with file paths.
  44. import os.path

  45. DEBUG = True
  46. TEMPLATE_DEBUG = DEBUG

  47. ADMINS = (
  48.     # ('Your Name', 'your_email@example.com'),
  49. )

  50. MANAGERS = ADMINS

  51. DATABASES = {
  52.     'default': {
  53.         'ENGINE': 'django.db.backends.sqlite3', # # Using sqlite3
  54.         'NAME': '/var/www/mydb', # Absolute path to the database file
  55.         # The following settings are not used with sqlite3:
  56.         'USER': '',
  57.         'PASSWORD': '',
  58.         'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
  59.         'PORT': '',                      # Set to empty string for default.
  60.     }
  61. }

  62. # Hosts/domain names that are valid for this site; required if DEBUG is False
  63. # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
  64. ALLOWED_HOSTS = []

  65. # Local time zone for this installation. Choices can be found here:
  66. # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
  67. # although not all choices may be available on all operating systems.
  68. # In a Windows environment this must be set to your system time zone.
  69. TIME_ZONE = 'America/Los_Angeles'

  70. # Language code for this installation. All choices can be found here:
  71. # http://www.i18nguy.com/unicode/language-identifiers.html
  72. LANGUAGE_CODE = 'en-us'

  73. SITE_ID = 1

  74. # If you set this to False, Django will make some optimizations so as not
  75. # to load the internationalization machinery.
  76. USE_I18N = True

  77. # If you set this to False, Django will not format dates, numbers and
  78. # calendars according to the current locale.
  79. USE_L10N = True

  80. # If you set this to False, Django will not use timezone-aware datetimes.
  81. USE_TZ = True

  82. # Absolute filesystem path to the directory that will hold user-uploaded files.
  83. # Example: "/var/www/example.com/media/"
  84. MEDIA_ROOT = ''

  85. # URL that handles the media served from MEDIA_ROOT. Make sure to use a
  86. # trailing slash.
  87. # Examples: "http://example.com/media/", "http://media.example.com/"
  88. MEDIA_URL = ''

  89. # Absolute path to the directory static files should be collected to.
  90. # Don't put anything in this directory yourself; store your static files
  91. # in apps' "static/" subdirectories and in STATICFILES_DIRS.
  92. # Example: "/var/www/example.com/static/"
  93. STATIC_ROOT = '/var/www/app/static/'

  94. # URL prefix for static files.
  95. # Example: "http://example.com/static/", "http://static.example.com/"
  96. STATIC_URL = '/static/'

  97. # Additional locations of static files
  98. STATICFILES_DIRS = (
  99.     # Put strings here, like "/home/html/static" or "C:/www/django/static".
  100.     # Always use forward slashes, even on Windows.
  101.     # Don't forget to use absolute paths, not relative paths.
  102. )

  103. # List of finder classes that know how to find static files in
  104. # various locations.
  105. STATICFILES_FINDERS = (
  106.     'django.contrib.staticfiles.finders.FileSystemFinder',
  107.     'django.contrib.staticfiles.finders.AppDirectoriesFinder',
  108. #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
  109. )

  110. # Make this unique, and don't share it with anybody.
  111. SECRET_KEY = 'vw7__ve*_3j^edw+@9k9(24_efqjnul-k=84yis*ew$xstr&*!'

  112. # List of callables that know how to import templates from various sources.
  113. TEMPLATE_LOADERS = (
  114.     'django.template.loaders.filesystem.Loader',
  115.     'django.template.loaders.app_directories.Loader',
  116. #     'django.template.loaders.eggs.Loader',
  117. )

  118. MIDDLEWARE_CLASSES = (
  119.     'django.middleware.common.CommonMiddleware',
  120.     'django.contrib.sessions.middleware.SessionMiddleware',
  121.     'django.middleware.csrf.CsrfViewMiddleware',
  122.     'django.contrib.auth.middleware.AuthenticationMiddleware',
  123.     'django.contrib.messages.middleware.MessageMiddleware',
  124.     # Uncomment the next line for simple clickjacking protection:
  125.     # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  126. )

  127. ROOT_URLCONF = 'app.urls'

  128. # Python dotted path to the WSGI application used by Django's runserver.
  129. WSGI_APPLICATION = 'app.wsgi.application'

  130. TEMPLATE_DIRS = (
  131.     # Include the "templates" directory in the current directory.
  132.     os.path.join(os.path.dirname(__file__), "templates"),
  133.     # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
  134.     # Always use forward slashes, even on Windows.
  135.     # Don't forget to use absolute paths, not relative paths.
  136. )

  137. INSTALLED_APPS = (
  138.     'django.contrib.auth',
  139.     'django.contrib.contenttypes',
  140.     'django.contrib.sessions',
  141.     'django.contrib.sites',
  142.     'django.contrib.messages',
  143.     'django.contrib.staticfiles',
  144.     'captcha', # Include the django-simple-captcha application
  145.     'registration', # Include the registration
  146.     # Uncomment the next line to enable the admin:
  147.     # 'django.contrib.admin',
  148.     # Uncomment the next line to enable admin documentation:
  149.     # 'django.contrib.admindocs',
  150. )

  151. # A sample logging configuration. The only tangible logging
  152. # performed by this configuration is to send an email to
  153. # the site admins on every HTTP 500 error when DEBUG=False.
  154. # See http://docs.djangoproject.com/en/dev/topics/logging for
  155. # more details on how to customize your logging configuration.
  156. LOGGING = {
  157.     'version': 1,
  158.     'disable_existing_loggers': False,
  159.     'filters': {
  160.         'require_debug_false': {
  161.             '()': 'django.utils.log.RequireDebugFalse'
  162.         }
  163.     },
  164.     'handlers': {
  165.         'mail_admins': {
  166.             'level': 'ERROR',
  167.             'filters': ['require_debug_false'],
  168.             'class': 'django.utils.log.AdminEmailHandler'
  169.         }
  170.     },
  171.     'loggers': {
  172.         'django.request': {
  173.             'handlers': ['mail_admins'],
  174.             'level': 'ERROR',
  175.             'propagate': True,
  176.         },
  177.     }

  178. }

Pythan hello rest full service in pycharm IDE



echo_service:

import tornado.ioloop
import pyrestful.rest

from pyrestful import mediatypes
from pyrestful.rest import get
class EchoService(pyrestful.rest.RestHandler):
      @get(_path="/echo/{name}", _produces=mediatypes.APPLICATION_JSON)
      def sayHello(self, name):
           return {"Hello":name}

if __name__ == "__main__":

           print "Start the echo service"           app = pyrestful.rest.RestService([EchoService])
           app.listen(8080)
           tornado.ioloop.IOLoop.instance().start()
           print "\nStop the echo service"




new_service


__author__ = 'LENOVO'from datetime import date
import tornado.escape
import tornado.ioloop
import tornado.web

class VersionHandler(tornado.web.RequestHandler):
    def get(self):
        response = { 'version': '3.5.1',
                     'last_build':  date.today().isoformat() }
        self.write(response)

class GetGameByIdHandler(tornado.web.RequestHandler):
    def get(self, id):
        response = { 'id': int(id),
                     'name': 'satya',
                     'release_date': date.today().isoformat() }
        self.write(response)

application = tornado.web.Application([
    (r"/getgamebyid/([0-9]+)", GetGameByIdHandler),
    (r"/version", VersionHandler)
])

class GetNamebySal(tornado.web.RequestHandler):
    def get(self, sal):
        response = { 'id': int(sal),
                     'name': 'satya',
                     'release_date': date.today().isoformat() }
        self.write(response)

application = tornado.web.Application([
    (r"/getnamebysal/([0-9]+)", GetNamebySal),
    (r"/version", VersionHandler)
])

if __name__ == "__main__":
    print "starting service"    application.listen(8080)
    tornado.ioloop.IOLoop.instance().start()

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