Saturday, 16 April 2016

package com.gb.md.common

class SMS {
Long accountId
String message
Long mobileNumber
String status

static constraints = {
accountId nullable:true
}

static mapping = {
message type: 'text'
}

}

======================================================================================================================================

package com.gb.md.common

import org.springframework.context.i18n.LocaleContextHolder as LCH

class MassCommunicationController extends BaseController{

def messageSource
def smsService
def mailService

def sendSMS(mobileNumber,message){
   //println "------mobileNumber  "+mobileNumber+" message "+message
def sendStatus = "Not Sent"
def userName = messageSource.getMessage('com.gb.md.sms.userName',null,LCH.getLocale())
def password = messageSource.getMessage('com.gb.md.sms.password',null,LCH.getLocale())
def senderId = messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale())
def parameters =  [to:mobileNumber, sender:senderId, message: message,userName:userName,password:password]
//connection opened
def connection = smsService.urlConnection(messageSource.getMessage('com.gb.md.sms.sendUrl',null,LCH.getLocale()),parameters)
parameters = "username="+userName+"&password="+password+"&to="+mobileNumber+"&from="+senderId+"&message="+message
def sendSms = true
def checkMap = checkSMSCredentials()
sendSms = checkMap.get('result')
//println "----- "+sendSms
if(userName && senderId && password && sendSms) sendStatus = smsService.writeStream(connection,parameters)
//println "send status : "+sendStatus
(sendStatus.trim().equalsIgnoreCase("Message GID=<br />ID=") || sendStatus.trim() == "" || sendStatus == 'Invalid user credentials' || sendStatus.trim() == "Not Sent") ? (sendStatus="Not Sent") : (sendStatus="Sent")

def smsObj = new SMS(
status:sendStatus,
   message:message,
   mobileNumber:mobileNumber
   )

smsObj.accountId = session?.loggedInUser?.account?.id
if(sendStatus=="Sent" && checkMap.get('updateSmsAccount')){

def obj = SMSAccount.findByAccountId(smsObj.accountId)
obj.remainingSms -= (Math.ceil(message.toString().length() / (messageSource.getMessage('com.gb.md.sms.maxcount',null,LCH.getLocale()) as int)))
obj.save(flush:true)
}

smsObj.save(flush:true)
return sendStatus
}

def getSMSCount(params){
def userName = messageSource.getMessage('com.gb.md.sms.userName',null,LCH.getLocale())
def password = messageSource.getMessage('com.gb.md.sms.password',null,LCH.getLocale())
def parameters = "username="+userName+"&password="+password
def connection = smsService.urlConnection(messageSource.getMessage('com.gb.md.sms.sendUrl',null,LCH.getLocale()),null)
return smsService.writeStream(connection,parameters)
}

def checkSMSCredentials(){
def map = [:]
try{
if(session?.loggedInUser == null || session?.loggedInUser?.accountRoles?.role?.id < 4){
map.put('result',true)
}
else if(session?.loggedInUser && session?.loggedInUser?.user?.status == 'Waiting For Verification Code'){
map.put('result',true)
}
else if(session?.loggedInUser?.user?.status == 'Active' && session?.loggedInUser?.user?.approval && session?.loggedInUser?.accountRoles?.role?.id > 3){
def smsAccount = SMSAccount.findByAccountId(session?.loggedInUser?.account?.id)
if(!getAuthorizationByAccount()?.generalSms){
map.put('result',false)
}
else if(smsAccount && smsAccount?.remainingSms == 0){
map.put('result',false)
map.put('msg','SMS credits not available')
}
else{
map.put('result',true)
map.put('updateSmsAccount',true)
}
}
else{
map.put('result',false)
}
}
catch(Exception e){
println e.printStackTrace()
}
return map
}

def sendEmail(toMail,sub,bodyData) {
try{
def roleId
if(session?.loggedInUser != null)  roleId = session?.loggedInUser?.accountRoles?.role?.id
if(toMail.toString().length() == 0) {
toMail = 'vamsikrishna@greenbuds.co.in'
sub = 'Exception from meedcotor'
}
if(session.loggedInUser == null || (((roleId == 4 || roleId == 8 || roleId == 9)) && getAuthorizationByAccount()?.generalEmail) || roleId==5 || roleId==7 || roleId==2 || roleId==3  ){
mailService.sendMail {
from messageSource.getMessage('com.gb.md.mail.from',null,LCH.getLocale())
to toMail
subject sub
body bodyData
}
}
}
catch(Exception e){
println e.printStackTrace()
}
}

def sendEmailTemplate(toMail,template,sub,params){
try{
def roleId
def frommail = messageSource.getMessage('com.gb.md.mail.from',null,LCH.getLocale())
def checkPrevilige = false
//@janaki
if(params.doctorMailId) frommail = params.doctorMailId
if(params.action == "sendMessages"){
frommail = params.frommail
sub = params.sub
}

if(toMail.toString().length() == 0) {
toMail = 'vamsikrishna@greenbuds.co.in'
sub = 'Exception from meedcotor'
}
if(session?.loggedInUser != null) roleId = session?.loggedInUser?.accountRoles?.role?.id
if(roleId == 4 || roleId == 8 || roleId == 9){
if(params.source == 'Appointments') checkPrevilige = getAuthorizationByAccount()?.appointmentEmail
else checkPrevilige = getAuthorizationByAccount()?.generalEmail
}
if(session.loggedInUser == null || checkPrevilige || roleId==5 || roleId==7 || roleId==2 || roleId==3 ){
mailService.sendMail {
multipart true
to toMail
from frommail
subject sub
html  g.render( template: template,params:params)
}
}
}
catch(Exception e){
println e.printStackTrace()
}
}

def sendEmailWithAttachment(params){
try{
def file = params.file
mailService.sendMail {
multipart true
to params.toMail
from params.fromMail
subject params.mailSubject
body "You can find the Invoice Receipt"
attachBytes "${file}.pdf", 'application/pdf', new File(servletContext.getRealPath("/reports1/${file}.pdf")).readBytes()
}
}
catch(Exception e){
println e.printStackTrace()
}
}
}

==============================================================================================

package com.gb.md.common

import com.gb.md.common.BaseService
import org.springframework.context.i18n.LocaleContextHolder as LCH

/**
 *
 * @author acheemakurthi
 *
 */
class SmsService extends BaseService{

def messageSource

SmsService(){
super(SMS.class)
}

/**
* responsible to open the connection to sms service
* @return urlConnection
*/
def urlConnection(smsUrl, properties = null){
// Client Meedoctor Url
// http://sms.meedoctor.in/api/sendmsg.php?user=meedoctor1&pass=meedoctor&sender=MEEDOC&phone=9299452498&text=hisms&priority=sdnd&stype=normal
HttpURLConnection urlConnection = null;
def userName = messageSource.getMessage('com.gb.md.sms.userName',null,LCH.getLocale())
def password = messageSource.getMessage('com.gb.md.sms.password',null,LCH.getLocale())
def parameters = ""
if(properties){
parameters = "username=$userName&password=$password&to=${properties.to}&from=${properties.sender}&message=${properties.message}"
}
else parameters = "username=$userName&password=$password"
def mainUrl = smsUrl + parameters
URL url = new URL(mainUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
return urlConnection
}

/**
* Give the response of an action
* @param connection
* @return
*/
def readStream(connection){
BufferedReader buff = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
String respons = "";
while ((line = buff.readLine()) != null) {
respons = respons + line;
}
buff.close();
return respons
}

/**
* Connecting to the link
* @param connection
* @param data
* @return
*/
def writeStream(connection, data = null){
BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
out.write(data.getBytes());
out.flush();
out.close();
readStream(connection)
}
}

==================================================================================================================================================

package com.gb.md.common

import groovy.sql.Sql

import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

import org.springframework.context.i18n.LocaleContextHolder as LCH

class NotificationService extends BaseService{
def mailService
def dataSource
def messageSource
def smsService

def scheduleForVaccination(){
Runnable runnable = new Runnable() {
public void run() {
vaccinationDetails()
aboutToExpire()
accountExpired()
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor()
service.scheduleAtFixedRate(runnable, 0, 24, TimeUnit.HOURS);
}

def vaccinationDetails(){
def sql = new Sql(dataSource)
def childs = sql.rows("select * from child_details ch")
childs.each{
def vaccinationDetails = []
def sdfFormat = new SimpleDateFormat('yyyy-MM-dd');
def date = sdfFormat.format(new Date())
vaccinationDetails = sql.rows("select * from vaccination_details vd where vd.alert_date like '"+date+" 00:00:00"+"' ")
def patient = sql.rows("select * from registration r where r.account_id = "+it.created_by+"")
if(it.sms == true){
vaccinationDetails.each{vd->
if(vd.alert_status){
def smsChk = true
def sms = new SMS()
sms.mobileNumber = patient[0].mobile as Long
def message = "Hi "+patient[0].user_name+", This Is the Vaccination Notification For Your Child: Vaccination Name : "+vd.vaccination+" , Vaccination Date : "+vd?.alert_date
sms.message = message
def sendStatus = ""
def parameters =  [to:sms.mobileNumber, sender:messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString(), message:sms.message] //grailsApplication.config.app.sms.senderId
//connection opened
def connection = smsService.urlConnection(messageSource.getMessage('com.gb.md.sms.sendUrl',null,LCH.getLocale()),parameters)
parameters = "&to="+patient[0].mobile+"&sender="+messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString()+"&message="+message //grailsApplication.config.app.sms.senderId
(sendStatus.trim().equalsIgnoreCase("Message GID=<br />ID=") || sendStatus.trim() == "") ? (sms.status="Not Sent") : (sms.status="Sent")
smsService.save(sms)
}
}
}
if(it.email == true){
vaccinationDetails.each{vd->
if(vd.alert_status){
sendEmailTemplate(patient[0].email,'/modules/patient/facesheet/vaccination/_vaccineNotificationTemplate',"Vaccination Alert",patient,vd,false)
}
}
}
if(it.phone_call == true){
def user =  sql.rows("select r.email from registration r where r.id = 2")
vaccinationDetails.each{vd->
if(vd.alert_status){
sendEmailTemplate(user.email,'/modules/patient/facesheet/vaccination/_vaccineNotificationTemplate',"Vaccination Alert",patient,vd,true)
}
}
}
}

sql.close()
}

/**
* Notify users about account expire with in 7 days through email
* @return
*/
def aboutToExpire(){
def sql = new Sql(dataSource)
def users = sql.rows("select r.*  from registration r where r.expiry_date between CURDATE() and DATE_ADD(CURDATE(), INTERVAL 7 DAY)")
users.each{
if(it.email){
def msg = "Your account is about to expire on"+" "+it.expiry_date
//sendEmail(it.email,"Account Expiry Alert",msg)
def map = [:]
map.put("expire", msg)
sendNotificationEmailTemplate(it.email,'/mailtemplates/_accountExpireTemplate',"Account Expiry Alert",map)
}
}
sql.close()
}

/**
* To Send Email on account expiry
* @return
*/
def accountExpired(){
def sql = new Sql(dataSource)
def users = sql.rows("select r.*  from registration r where Date(r.expiry_date) <= CURDATE()")
users.each{
if(it.email){
def msg = "Your account has been expired Please contact admin "
//sendEmail(it.email,"Account Expired!",msg)
def map = [:]
map.put("expired", msg)
sendNotificationEmailTemplate(it.email,'/mailtemplates/_accountExpireTemplate',"Account Expired Alert",map)

}
}
sql.close()
}

def sendEmailTemplate(toMail,view,sub,patient,vd,check){
mailService.sendMail {
multipart true
to toMail
from messageSource.getMessage('com.gb.md.mail.from',null,LCH.getLocale())
subject sub
body  ( view: view,model:[patient:patient,vd:vd,check:check])
}
}

def sendNotificationEmailTemplate(toMail,view,sub,map){
mailService.sendMail {
multipart true
to toMail
from messageSource.getMessage('com.gb.md.mail.from',null,LCH.getLocale())
subject sub
body  ( view: view,model:[map:map])
}
}

/**
* send email without template
* @param toMail
* @param sub
* @param msg
* @return
*/
def sendEmail(toMail,sub,msg){
mailService.sendMail {
multipart true
to toMail
from messageSource.getMessage('com.gb.md.mail.from',null,LCH.getLocale())
subject sub
body "NOTE : "+msg
}
}

/**
* @janaki
*/
def getAlerts(){
Runnable runnable = new Runnable() {
public void run() {
alertDetails()
followUp()
remainders()
}
};

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor()
service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.MINUTES);
}

/**
* @janaki
*/
def alertDetails(){
def sdfFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm');
def date = sdfFormat.format(new Date())
def sql = new Sql(dataSource)
def alertDetails = []
def map = [:]
alertDetails = sql.rows("select  al.email as emailstatus,al.sms,al.alert_message alertMessage,r.account_id as accountId,r.email as email,r.mobile,al.alert_time as alertTime,r.user_name as userName from alerts al,registration r where al.created_by = r.account_id and al.alert_time like '"+date+":00' ")
if(alertDetails){
alertDetails.each{
def accountId = it.accountId as Long
//for sending email
if(it.emailstatus == true){
//sendEmail(it.email,"Alert",it.alertMessage)
map.put("userName", "Hello "+it.userName+" this is your alert mail")
map.put("alertTime", it.alertTime)
map.put("alertMessage",it.alertMessage)
sendNotificationEmailTemplate(it.email,'/mailtemplates/_alertTemplate',"Your Alert",map)
}
// for sending SMS
if(it.sms == true){
def smscount = sql.rows("select * from smsaccount a where a.account_id = "+accountId)

if(smscount[0][3] > 0){
def smsChk = true
def sms = new SMS()
sms.mobileNumber = it.mobile as Long
sms.message = it.alertMessage
def message = it.alertMessage
def sendStatus = ""
def parameters =  [to:sms.mobileNumber, sender:messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString(), message:sms.message] //grailsApplication.config.app.sms.senderId
//connection opened
def connection = smsService.urlConnection(messageSource.getMessage('com.gb.md.sms.sendUrl',null,LCH.getLocale()),parameters)
parameters = "&to="+it.mobile+"&sender="+messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString()+"&message="+message //grailsApplication.config.app.sms.senderId
sendStatus = smsService.writeStream(connection,parameters)
(sendStatus.trim().equalsIgnoreCase("Message GID=<br />ID=") || sendStatus.trim() == "" || sendStatus == 'Invalid user credentials') ? (sms.status="Not Sent") : (sms.status="Sent")
smsService.save(sms)
//update the remaining sms count
if(sms.status == 'Sent') {
def msgcount = (Math.ceil(sms.message.toString().length() / (messageSource.getMessage('com.gb.md.sms.maxcount',null,LCH.getLocale()) as int)))
sql.executeUpdate("update smsaccount a set a.remaining_sms = a.remaining_sms - "+msgcount+"  where a.account_id = "+accountId)
}
else{
}
}
}
}
}
sql.close()
}

/**
* Janaki for followUp
* @return
*/
def followUp(){
def sdfFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm');
def date = sdfFormat.format(new Date())
def sql = new Sql(dataSource)
def map = [:]
def followupDetails = []
def qury = "SELECT fp.follow_date as followDate,fpt.name as followName,fp.created_by as accountId,fp.patient_id,fp.patient_name as patientName,dp.email as patientEmail,fp.comments,r.user_name as doctorName,pf.fname as firstName,pf.lname as lastName,cd.clinic_name as clinicName,a.followup_sms as fpsms,a.followup_email as fpemail,"+
"cd.clinic_addr as clinicAddress,c.name as cityName,s.name as stateName,cd.phone,cd.mobile FROM follow_up fp, follow_up_type fpt,doctor_patients dp,registration r,authorization_rules a,"+
"clinic_details cd,professional_details pf,cities c,state s WHERE fp.created_by = dp.doctor_account_id AND fp.`status` = '1' AND fpt.`status` = '1' AND r.account_id = fpt.doctor_id AND a.account_id = fp.created_by and "+
"fp.patient_id = dp.patient_id AND pf.account_id = r.account_id AND c.state_id = s.id and c.id = cd.clinic_city_id and cd.id = fp.clinic_id and cd.account_id = fpt.doctor_id and fp.follow_date LIKE '"+date+":00' "
followupDetails = sql.rows(qury)

if(followupDetails){
followupDetails.each{
//for sending email
//sendEmail(it.email,"followup","hello this is general mails")
if(it.fpemail == true) {
map.put("patientName", "Hello "+it.patientName+" this is your FollowUp mail")
map.put("followDate", it.followDate)
map.put("followName",it.followName)
map.put("comments", it.comments)
map.put("doctorName",it.firstName+" "+it.lastName)
map.put("clinicName", it.clinicName)
map.put("clinicAddress",it.clinicAddress)
map.put("city", it.cityName)
map.put("state",it.stateName)
map.put("phone", it.phone)
//map.put("mobile", it.mobile)
sendNotificationEmailTemplate(it.patientEmail,'/mailtemplates/_followUpEmailTemplate',"Patient FollowUp",map)

}

if(it.fpsms == true) {
def smscount = SMSAccount.findByAccountId(it.accountId)
if(smscount.remainingSms > 0){
def smsChk = true
   def sms = new SMS()
   sms.mobileNumber = it.mobile as Long
   sms.message = 'Note :Patient Name:'+it.patientName+',followup Date:'+it.followDate+',Follow Name:'+it.followName+',Comments:'+it.comments+',Doctor Name:'+it.doctorName
   def message = 'Note :Patient Name:'+it.patientName+',followup Date:'+it.followDate+',Follow Name:'+it.followName+',Comments:'+it.comments+',Doctor Name:'+it.doctorName
   def sendStatus = ""
   def parameters =  [to:sms.mobileNumber, sender:messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString(), message:sms.message] //grailsApplication.config.app.sms.senderId
   //connection opened
    def connection = smsService.urlConnection(messageSource.getMessage('com.gb.md.sms.sendUrl',null,LCH.getLocale()),parameters)
   parameters = "&to="+it.mobile+"&sender="+messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString()+"&message="+message //grailsApplication.config.app.sms.senderId
   (sendStatus.trim().equalsIgnoreCase("Message GID=<br />ID=") || sendStatus.trim() == "") ? (sms.status="Not Sent") : (sms.status="Sent")
   smsService.save(sms)
   //update the remaining sms count
  if(sms.status == 'Sent') {
smscount.remainingSms--
smscount.save(flush:true)
  }
 else{
 }
}
}
}
}
sql.close()
}

def remainders(){
def sdfFormat = new SimpleDateFormat('dd/MM/yyyy HH:mm');
def currentdate = sdfFormat.format(new Date())
Date date1 = sdfFormat.parse(currentdate)
def curdatemilliseconds = date1.getTime()
def sql = new Sql(dataSource)
def remainders = sql.rows("select  r.event_name as eventName,r.event_type as eventType,rg.email,rg.user_name as userName from  events r,registration rg  where r.event_type = 'Remainders' and (r.start_time-19800000) = '"+curdatemilliseconds+"' and r.account_id = rg.account_id")
if(remainders){
remainders.each{rt->
sendNotificationEmailTemplate(rt.email,'/mailtemplates/_remainderTemplate',"Doctor Remainder",rt)
}
}
sql.close()
}

}

=========================================================================================================================================================

In Build Config

compile ":uploadr:1.0.0"

display image:

<img src="<g:createLink controller="doctors" action="viewImage" params='[img: "${clinic?.pic1}"]'/>"  class="img-responsive" style="height: 100px;"/>

<input  type="file" name="pic1" id="clinicpic1">

$("#clinicpic1").change(function(){
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageForPic1;
reader.readAsDataURL(this.files[0]);
}
});


$('#clinicpic1').fileupload({
   url:"${request.getContextPath()}/settings/upload",
   formData: {accountId: $('#accountId').val(), clinicId: $('#doc_clinicId').val(), pic:'pic1'},
   dataType: 'json',
   maxNumberOfFiles: 1,
   maxFileSize: 5000000, // 5 MB
   previewMaxWidth: 250,
   previewMaxHeight: 250,
   add: function (e, data) {
    data.submit().success(function (result, textStatus, jqXHR) {
$('.pull-right .alert').addClass('alert-success').show().empty().html('Successfully Uploaded!').fadeOut(3000)            
       }).error(function (jqXHR, textStatus, errorThrown) {
        $('.pull-right .alert').addClass('alert-danger').show().empty().html('Upload Failed!').fadeOut(3000)
       }).complete(function (result, textStatus, jqXHR) {
});
},
   drop: function (e, data) {
    e.preventDefault();
    //disabling drag and drop
   }
});

def viewImage(){
try{
def file = new File(params.img)
def img = file.bytes
response.contentType = 'image/jpg,image/png' // or the appropriate image content type
response.outputStream << img
response.outputStream.flush()
}catch(Exception e){
}
}
=========================================================================================================================================================

//upload pics for clinics
def upload(){
def file
if(params.pic == 'pic1') file = request.getFile('pic1')
if(params.pic == 'pic2') file = request.getFile('pic2')
if(params.pic == 'pic3') file = request.getFile('pic3')
if(params.pic == 'pic4') file = request.getFile('pic4')
if(params.pic == 'pic5') file = request.getFile('pic5')
if(params.pic == 'pic6') file = request.getFile('pic6')
if(params.pic == 'pic7') file = request.getFile('pic7')
if(params.pic == 'clinicLogo') file = request.getFile('clinicLogo')

if(file.empty) {
render (status: 500, text: 'File is empty')
return
}
String extractedName = FilenameUtils.removeExtension(file.originalFilename);
String extension = FilenameUtils.getExtension(file.originalFilename);
def fileName = extractedName  + "." + extension
def storage = messageSource.getMessage('com.gb.md.clinicpicloaction',null,LCH.getLocale()).toString()+params.clinicId
def folder = new File(storage)
def imagePath = storage+'/'+params.pic+'.'+extension

if( !folder.exists())  folder.mkdirs()
if(extension) file.transferTo(new File(imagePath))

def clinic = ClinicDetails.get(params.clinicId as Long)
if(params.pic == 'pic1') clinic.pic1 = imagePath
if(params.pic == 'pic2') clinic.pic2 = imagePath
if(params.pic == 'pic3') clinic.pic3 = imagePath
if(params.pic == 'pic4') clinic.pic4 = imagePath
if(params.pic == 'pic5') clinic.pic5 = imagePath
if(params.pic == 'pic6') clinic.pic6 = imagePath
if(params.pic == 'pic7') clinic.pic7 = imagePath
if(params.pic == 'clinicLogo') clinic.clinicLogo = imagePath

clinic.save(flush:true)
render ([clinic:clinic] as JSON)
}

http://grandhivamsikrishna.blogspot.in/2016/02/static-file-download-in-grails.html

Thursday, 14 April 2016

abstract class BaseController {
def springSecurityService
def loggedInUser
def baseSetupService

//maintain loggedInUser AccountId
def getLoggedInUser(){
this.loggedInUser = session?.loggedInUser
return loggedInUser
}
}


package com.gb.md.common

abstract class BaseEntity {

static dynamicProperties = true

Long createdBy
Date createdOn

transient springSecurityService

static transients = ['springSecurityService']
def storage = [:]

static constraints = { }

def beforeValidate(){
initDefaults()
}

def beforeInsert() {
initDefaults()
}

def beforeUpdate() {
initDefaults()
}

def initDefaults(){
if(!createdBy){
createdBy = springSecurityService?.currentUser ? springSecurityService.currentUser.id : 0
}
if(!createdOn){
createdOn = new Date()
}
}

def propertyMissing(String name, value) {
storage[name] = value
}

def propertyMissing(String name) {
storage[name]
}
}

Wednesday, 13 April 2016

Steps to Integrate Jasper in grails

Step1: first we have to add jasper plugin in BuildConfig.groovy
-> compile ”:jasper:1.10.0"
Step 2: clean and build the path
and add the corresponding jars in lib folder
commons-beanutils-1.9.2, commons-collections-3.2, commons-digester-2.1,
commons-logging-1.2, itext-2.1.7, jasperreports-5.6.0
Step 3: Code in controller
example:
import org.codehaus.groovy.grails.plugins.jasper.JasperReportDef
import com.gb.Account
class HomeController {
def reportService

def index() {
render view:“welcome”
}

def generateReport() {
def a=[20,30]
JasperReportDef  report = reportService.buildReportDefinition(params, request.getLocale(),a,“sample”)
generateResponse(report)
}

def generateResponse = {reportDef ->
if (!reportDef.fileFormat.inline && !reportDef.parameters._inline) {
response.setHeader(“Content-disposition”, “attachment; filename=” + (reportDef.parameters._name ?: reportDef.name) + “.” + reportDef.fileFormat.extension)
response.contentType = reportDef.fileFormat.mimeTyp
response.characterEncoding = “UTF-8”
response.outputStream << reportDef.contentStream.toByteArray()
} else {
render(text: reportDef.contentStream, contentType: reportDef.fileFormat.mimeTyp, encoding: reportDef.parameters.encoding ? reportDef.parameters.encoding : 'UTF-8’)
}
}
}
Step:4
We have to add service file as ReportService.groovy in services
—————————————————————————————————-
import groovy.sql.Sql
import java.lang.reflect.Field
import java.sql.Connection
import net.sf.jasperreports.engine.JRExporter
import net.sf.jasperreports.engine.JRExporterParameter
import net.sf.jasperreports.engine.JasperCompileManager
import net.sf.jasperreports.engine.JasperFillManager
import net.sf.jasperreports.engine.JasperPrint
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter
import net.sf.jasperreports.engine.export.JRTextExporterParameter
import net.sf.jasperreports.engine.export.JRXlsExporterParameter
import net.sf.jasperreports.engine.util.JRProperties
import org.codehaus.groovy.grails.plugins.jasper.JasperExportFormat
import org.codehaus.groovy.grails.plugins.jasper.JasperReportDef
import org.springframework.core.io.Resource
import com.gb.common.BaseService
class ReportService extends BaseService{
def dataSource
static final boolean FORCE_TEMP_FOLDER = false
JasperReportDef buildReportDefinition(parameters, locale, testModel,reportName) {
JasperReportDef reportDef = new JasperReportDef(name: reportName, parameters: parameters, locale: locale)
reportDef.fileFormat = JasperExportFormat.determineFileFormat(“PDF”)
reportDef.reportData = getReportData(testModel, parameters)
reportDef.contentStream = generateReport(reportDef)
reportDef.jasperPrinter = generatePrinter(reportDef)
return reportDef
}
private Collection getReportData(testModel, parameters) {
Collection reportData
if (testModel) {
try {
reportData = testModel
} catch (Throwable e) {
throw new Exception(“Expected chainModel.data parameter to be a Collection, but it was ${chainModel.data.class.name}”, e)
}
} else {
testModel = getProperties().containsKey('model’) ? model : null
if (testModel?.data) {
try {
reportData = testModel.data
} catch (Throwable e) {
throw new Exception(“Expected model.data parameter to be a Collection, but it was ${model.data.class.name}”, e)
}
} else if (parameters?.data) {
try {
reportData = parameters.data
} catch (Throwable e) {
throw new Exception(“Expected data parameter to be a Collection, but it was ${parameters.data.class.name}”, e)
}
}
}
return reportData
}
@Deprecated
ByteArrayOutputStream generateReport(String jasperReportDir, JasperExportFormat format, Collection reportData, Map parameters) {
JasperReportDef reportDef = new JasperReportDef(name: parameters._file, folder: jasperReportDir, reportData: reportData, fileFormat: format, parameters: parameters)
return generateReport(reportDef)
}
/**
* Generate a report based on a single jasper file.
* @param format , target format
* @param reportDef , jasper report object
* return ByteArrayOutStreamByteArrayOutStream with the generated Report
*/
ByteArrayOutputStream generateReport(JasperReportDef reportDef) {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream()
JRExporter exporter = generateExporter(reportDef)
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, byteArray)
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, “UTF-8”)
def jasperPrint = reportDef.jasperPrinter
if (jasperPrint==null) {
reportDef.jasperPrinter = generatePrinter(reportDef)
}
exporter.setParameter(JRExporterParameter.JASPER_PRINT, reportDef.jasperPrinter)
exporter.exportReport()
return byteArray
}
/**
* Generate a single report based on a list of jasper files.
* @param format , target format
* @param reports , a List with report objects
* @param parameters , additional parameters
* return ByteArrayOutStream with the generated Report
*/
ByteArrayOutputStream generateReport(List<JasperReportDef> reports) {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream()
JRExporter exporter = generateExporter(reports.first())
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, byteArray)
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, “UTF-8”)
def printers = reports.collect { report -> generatePrinter(report) }
exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, printers)
exporter.exportReport()
return byteArray
}
/**
* Forces the Jasper Reports  temp folder to be “~/.grails/.jasper” and ensures that such a folder exists.
* The user (however the app server is logged in) is much more likely to have read/write/delete rights here than the
* default location that Jasper Reports uses.
*/
protected void forceTempFolder() {
/* TODO This is currently disabled, because it doesn’t work. Jasper Reports seems to always use the current
* folder (.) no matter what.  (I’ll be filing a bug report against Jasper Reports itself shortly - Craig Jones 16-Aug-2008)
*/
if (FORCE_TEMP_FOLDER) {
// Look up the home folder explicitly (don’t trust that tilde notation will work).
String userHomeDir = System.getProperty('user.home’)
File tempFolder = new File(userHomeDir, “/.grails/.jasper”)
// This is the current official means for setting the temp folder for jasper reports to use when compiling
// reports on the fly, but it doesn’t work
JRProperties.setProperty(JRProperties.COMPILER_TEMP_DIR, tempFolder.getAbsolutePath())
// This is a deprecated means for setting the temp folder that supposedly still works (still in the Jasper
// Reports source code trunk as of 14-Aug-2008, and, in fact, takes precedence over the official method);
// however, it doesn’t work either.
System.setProperty(“jasper.reports.compile.temp”, tempFolder.getAbsolutePath())
if (!tempFolder.exists()) {
def ant = new AntBuilder()
ant.mkdir(dir: tempFolder.getAbsolutePath())
if (!tempFolder.exists()) {
throw new Exception(“Unable to create temp folder: ${tempFolder.getPath()}”)
}
}
}
}
/**
* Generate a exporter with for a JasperReportDef. Note that SUBREPORT_DIR an locale have default
* values.
* @param reportDef
* @return JRExporter
*/
private JRExporter generateExporter(JasperReportDef reportDef) {
if (reportDef.parameters.SUBREPORT_DIR == null) {
reportDef.parameters.SUBREPORT_DIR = reportDef.getFilePath()
}
if (reportDef.parameters.locale) {
if (reportDef.parameters.locale instanceof String) {
reportDef.parameters.REPORT_LOCALE = getLocaleFromString(reportDef.parameters.locale)
} else if (reportDef.parameters.locale instanceof Locale) {
reportDef.parameters.REPORT_LOCALE = reportDef.parameters.locale
}
} else if (reportDef.locale) {
reportDef.parameters.REPORT_LOCALE = reportDef.locale
} else {
reportDef.parameters.REPORT_LOCALE = Locale.getDefault()
}
JRExporter exporter = JasperExportFormat.getExporter(reportDef.fileFormat)
Field[] fields = JasperExportFormat.getExporterFields(reportDef.fileFormat)
Boolean useDefaultParameters = reportDef.parameters.useDefaultParameters.equals(“true”)
if (useDefaultParameters) {
applyDefaultParameters(exporter, reportDef.fileFormat)
}
if (fields) {
applyCustomParameters(fields, exporter, reportDef.parameters)
}
return exporter
}
/**
* Generate a JasperPrint object for a given report.
* @param reportDefinition , the report
* @param parameters , additional parameters
* @return JasperPrint , jasperreport printer
*/
private JasperPrint generatePrinter(JasperReportDef reportDef) {
JasperPrint jasperPrint
Resource resource = reportDef.getReport()
if (reportDef.reportData != null && !reportDef.reportData.isEmpty()) {
JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(reportDef.reportData)
if (resource.getFilename().endsWith(’.jasper’)) {
jasperPrint = JasperFillManager.fillReport(resource.inputStream, reportDef.parameters, jrBeanCollectionDataSource)
}
else {
forceTempFolder()
jasperPrint = JasperFillManager.fillReport(JasperCompileManager.compileReport(resource.inputStream), reportDef.parameters, jrBeanCollectionDataSource)
}
}
else {
Sql sql = new Sql(dataSource)
Connection connection = dataSource?.getConnection()
try {
if (resource.getFilename().endsWith(’.jasper’)) {
jasperPrint = JasperFillManager.fillReport(resource.inputStream, reportDef.parameters, connection)
}
else {
forceTempFolder()
jasperPrint = JasperFillManager.fillReport(JasperCompileManager.compileReport(resource.inputStream), reportDef.parameters,  connection)
}
}
finally {
sql.close()
connection.close()
}
}
return jasperPrint
}
/**
* Apply additional parameters to the exporter. If the user submits a parameter that is not available for
* the file format this parameter is ignored.
* @param fields , available fields for the choosen file format
* @param exporter , the exporter object
* @param parameter , the parameters to apply
*/
private void applyCustomParameters(Field[] fields, JRExporter exporter, Map<String, Object> parameters) {
def fieldNames = fields.collect {it.getName()}
parameters.each { p ->
if (fieldNames.contains(p.getKey())) {
def fld = Class.forName(fields.find {it.name = p.getKey()}.clazz.name).getField(p.getKey())
exporter.setParameter(fld.get(fld.root.class), p.getValue())
}
}
}
/**
* Apply the default parameters for a bunch of file format and only if useDefaultParameters is enabled.
* @param exporter , the JRExporter
* @param format , the target file format
*/
private void applyDefaultParameters(JRExporter exporter, JasperExportFormat format) {
switch (format) {
case JasperExportFormat.HTML_FORMAT:
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, false)
break
case JasperExportFormat.XLS_FORMAT:
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, true)
exporter.setParameter(JRXlsExporterParameter.IS_AUTO_DETECT_CELL_TYPE, true)
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, false)
exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, true)
break
case JasperExportFormat.TEXT_FORMAT:
exporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 80)
exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 60)
exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 60)
break
}
}
/**
* Convert a String to a Locale.
* @param localeString , a string
* @returns Locale
*/
static Locale getLocaleFromString(String localeString) {
if (localeString == null) {
return null
}
localeString = localeString.trim()
// Extract language
int languageIndex = localeString.indexOf(’_’)
String language
if (languageIndex == -1) {  // No further “_” so is “{language}” only
return new Locale(localeString, “”)
}
language = localeString.substring(0, languageIndex)
// Extract country
int countryIndex = localeString.indexOf(’_’, languageIndex + 1)
String country
if (countryIndex == -1) {     // No further “_” so is “{language}_{country}”
country = localeString.substring(languageIndex + 1)
return new Locale(language, country)
}
// Assume all remaining is the variant so is “{language}_{country}_{variant}”
country = localeString.substring(languageIndex + 1, countryIndex)
String variant = localeString.substring(countryIndex + 1)
return new Locale(language, country, variant)
}
}