Grails problem and solution

By | June 5th 2019 01:09:04 PM | viewed 646 times

How to print variavle in java or grails

 println("hi kkk");

How to match password in grails

def springSecurityService

if(user.password == springSecurityService.encodePassword(params.currentPassword)){
  println("User Password and params password is same")
} else {
  println("User Password and params password are not equal")
}

or

def passwordEncoder
passwordEncoder.isPasswordValid(user.password, params.currentPassword, null)

Select box using enum class

<g:select id="genderAlkp" name="irAplc.${irAplc?.id}.genderAlkp" class="form-control mfalse" from="${com.setting.SetnAlkp.createCriteria().list() {
							and { eq('keyword', com.enums.KeywordType.GENDER) }
 }}" optionKey="id" optionValue="title" value="${irAplcInstance?.genderAlkp?.id}"  noSelection="['': 'Select One']"/>
 or
 <g:select id="religionAlkp" name="irAplc.${irAplc?.id}.religionAlkp" class="form-control mfalse"
   from="${com.setting.SetnAlkp.executeQuery("from SetnAlkp where keyword=com.enums.KeywordType.RELIGION")}" 
   optionKey="id" optionValue="title"  value="${irAplcInstance?.religionAlkp?.id}"  
   noSelection="['': 'Select One']"/>

Select box using from an object

<g:select id="firmInfo" name="firmInfo.id" from="${com.icab.firms.FirmInfo.list()}" optionKey="id" required="" value="${firmArticledStudentInstance?.firmInfo?.id}" class="many-to-one"/>
 

String to date and generate employee id

package customInterface


public interface DateAndTimeInterface {

    def currentGmtDateAndTime()
    def currentGmtDateAndTimeWithTime()
    def customDateAndTime(def dateAndTime)
    def customDateAndTimeBng(def dateAndTime)
    def customDateAndTimeBngSlash(def dateAndTime)
    def customDateAndTimeYMD(def dateAndTime)
    def customDateAndTimeBng2(def dateAndTime)
    def processKey(String processType,String empid)
    def findDayNumberOfDateObject(def dateObject)
    def findCalenderObject(Object dateObject)


}



package customInterface.ImplementInterface

import customInterface.DateAndTimeInterface

class DateAndTime implements DateAndTimeInterface{

    def currentGmtDateAndTime(){

        def ymdFmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
        def receive = ymdFmt.format(new Date())                   // for auto date creation
        def dateTimeFormat = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        def receiveDate = dateTimeFormat.parse("${receive} 00:00:00");

        return receiveDate

    }

    def currentGmtDateAndTimeWithTime(){

        def ymdFmt = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")   // HH 24 hours and hh 12 hours
        def receive = ymdFmt.format(new Date())                   // for auto date creation
        def dateTimeFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        def receiveDate = dateTimeFormat.parse("${receive} HH:mm:ss");

        return receiveDate
    }
  
    def customDateAndTime(def dateAndTime){
        def df = new java.text.SimpleDateFormat("MM-dd-yyyy");    // same to javascript date formate
        java.util.Date fromDate = df.parse(dateAndTime);
        return fromDate

    }
    def customDateAndTimeYMD(def dateAndTime){
        def df = new java.text.SimpleDateFormat("MM-dd-yyyy");    // same to javascript date formate
        java.util.Date fromDate = df.parse(dateAndTime.toString());
        return fromDate

    }
    def customDateAndTimeBng(def dateAndTime){
        def df = new java.text.SimpleDateFormat("dd-MM-yyyy");    // same to javascript date formate
        java.util.Date fromDate = df.parse(dateAndTime);
        return fromDate

    }

    def customDateAndTimeBngSlash(def dateAndTime){
        def df = new java.text.SimpleDateFormat("dd/MM/yyyy");    // same to javascript date formate
        java.util.Date fromDate = df.parse(dateAndTime);
        return fromDate

    }

    def customDateAndTimeBng2(def dateAndTime){
        def df = new java.text.SimpleDateFormat("dd-MM-yyyy hh:mm:ss");    // same to javascript date formate
        java.util.Date fromDate = df.parse("${dateAndTime} 00:00:00");
        return fromDate

    }

    def processKey(String processType,String empid){

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());

        //cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));   monthly first date
        //return cal.getTime();

        //int totalWeekOfMonth = cal.get(Calendar.WEEK_OF_MONTH);
        //int firstDayOfMonth = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //int lastDayOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //int currentDayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        // int dayofWeek = cal.get(Calendar.DAY_OF_WEEK);
        String processkey ="${cal.get(Calendar.SECOND)+"-"+cal.get(Calendar.MINUTE)+"-"+cal.get(Calendar.HOUR)+"-"+cal.get(Calendar.DAY_OF_MONTH)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.YEAR)+"-"+processType.toLowerCase()+"-"+empid}"

        return processkey

    }

    def findDayNumberOfDateObject(Object dateObject){

        Calendar cal = Calendar.getInstance();
        cal.setTime(dateObject);

        Integer day =cal.get(Calendar.DAY_OF_MONTH);

        return day;

    }

    def findCalenderObject(Object dateObject){

        Calendar cal = Calendar.getInstance();
        cal.setTime(dateObject);
        return cal;

    }

}


File upload source code

package customInterface

public interface AboutFileUploadDownloadInterface {
       def aboutPictureUp(def picFileObj,def picUploadPath)
       def aboutPictureUpMultipart(def picFileObj,def picUploadPath)
       def aboutPictureCropWithMultipart(def picFileObj,def picUploadPath,def with, def height)
       def aboutCvUp(def cvFileObj,def cvUploadPath)
       def aboutFileUpMultipart(def picFileObj,def picUploadPath)
}

package customInterface.ImplementInterface


import customInterface.AboutFileUploadDownloadInterface

import javax.imageio.ImageIO
import java.awt.image.BufferedImage


class AboutFileUploadDownload implements AboutFileUploadDownloadInterface {

    def filename =''
    def fullPath =''
    def contentType =''
    def size =''

    def picContentType = ["image/gif","image/jpeg","image/png","image/bmp","image/tiff"]
    def cvContentType = ["application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/pdf"]
    def allContentType = ["image/gif","image/jpeg","image/png","image/bmp","image/tiff","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/pdf","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation"]

    def picMaxFileSize = 1*1024*1024*1   // 1 byte*1024 = 1 kilotyte*1024 = 1 megabyte
    def cvMaxFileSize = 1*1024*1024*15   // 1 byte*1024 = 1 kilotyte*1024 = 1 megabyte
    def allMaxFileSize = 1*1024*1024*50   // 1 byte*1024 = 1 kilotyte*1024 = 50 megabyte


    def aboutPictureUp(def picFileObj,def picUploadPath){
	
	     def up = null

        if(picFileObj.empty) {

                return null

            } else {


                this.filename = picFileObj.originalFilename

                def ext = this.filename.substring(this.filename.lastIndexOf('.'))
                def docFileTitle = UUID.randomUUID().toString()
                this.filename = docFileTitle + ext

                this.fullPath = picUploadPath +"//"+filename

                this.size = picFileObj.size

                this.contentType = picFileObj.contentType


                up = new File(this.fullPath)

                     Boolean fileExist = new File(this.fullPath).exists()
                     Boolean contentTy = this.picContentType.any { it =~this.contentType}
                     Boolean fSize = this.size <= this.picMaxFileSize

                    if(fileExist){

                        return 2

                    }else if(! contentTy){

                        return 3

                    }else if(! fSize){

                        return 4

                    }else{

                        if(up) {

                            picFileObj.transferTo(up)
							up = null
							picFileObj = null

                            return this.filename


                        }else{

                            return 0
                        }

                    }
               }
    }

    def aboutPictureUpMultipart(def picFileObj,def picUploadPath){

        if(picFileObj.empty) {

            return null

        } else {



            this.filename = picFileObj.originalFilename

            def ext = this.filename.substring(this.filename.lastIndexOf('.'))
            def docFileTitle = UUID.randomUUID().toString()
            this.filename = docFileTitle + ext

            this.fullPath = picUploadPath+"//" +filename

            this.size = picFileObj.size

            this.contentType = picFileObj.contentType


            assert this.picContentType.any { it =~this.contentType}
            assert this.size <= this.picMaxFileSize

            def up = new File(this.fullPath)

            assert ! new File(this.fullPath).exists()

            if(up) {

                picFileObj.transferTo(up)

                return this.filename


            }else{

                return false
            }
        }
    }

    def aboutPictureCropWithMultipart(def picFileObj,def picUploadPath,def with, def height){

        if(picFileObj.empty) {
            // flash.message = "File cannot be empty"
            return null
        } else {

            this.filename = picFileObj.originalFilename

            def ext = this.filename.substring(this.filename.lastIndexOf('.'))
            def docFileTitle = UUID.randomUUID().toString()
            this.filename = docFileTitle + ext

            this.fullPath = picUploadPath+"//" +filename

            this.size = picFileObj.size

            this.contentType = picFileObj.contentType


            assert this.picContentType.any { it =~this.contentType}
            assert this.size <= this.picMaxFileSize
            def up = new File(this.fullPath)
            picFileObj.transferTo(up)


            if(up) {



                           def up2 = new File(this.fullPath)
                              // croup image
                        BufferedImage image = ImageIO.read(up2)
                           System.out.println("Original Image Dimension: "+image.getWidth()+"x"+image.getHeight());

                        BufferedImage SubImgage = image.getSubimage(300, 150, with, height);
                           System.out.println("Cropped Image Dimension: "+SubImgage.getWidth()+"x"+SubImgage.getHeight());

                        ImageIO.write(SubImgage, "jpg", up2);
                          System.out.println("Image cropped successfully: "+up2.getPath());
                            // end croup image



                 return this.filename


            }else{

                return false
            }
        }

    }

    def aboutCvUp(def cvFileObj,def cvUploadPath){

        if(cvFileObj.empty) {

            //flash.message = "File cannot be empty"

            return null

        } else {


            this.filename = cvFileObj.originalFilename

            this.fullPath = cvUploadPath+"//"+filename

            this.size = cvFileObj.size

            this.contentType = cvFileObj.contentType


            assert this.cvContentType.any { it =~this.contentType}
            assert this.size <= this.cvMaxFileSize

            def up = new File(this.fullPath)

            if(up) {

                cvFileObj.transferTo(up)

                return this.filename


            }else{

                return false
            }
        }
    }

    def aboutFileUpMultipart(def picFileObj,def picUploadPath){

        if(picFileObj.empty) {

            // flash.message = "File cannot be empty"

            return null

        } else {

            this.filename = picFileObj.originalFilename

            /*def ext = this.filename.substring(this.filename.lastIndexOf('.'))
            def docFileTitle = UUID.randomUUID().toString()
            this.filename = docFileTitle + ext*/

            this.fullPath = picUploadPath+"//" +filename

            this.size = picFileObj.size

            this.contentType = picFileObj.contentType


            assert this.allContentType.any { it =~this.contentType}
            assert this.size <= this.allMaxFileSize

            def up = new File(this.fullPath)

            if(new File(this.fullPath).exists()){

                return false

            }else{

                    if(up) {

                        picFileObj.transferTo(up)

                        return this.filename


                    }else{

                        return false
                    }

            }
        }
    }

   

}

Random code generation

package customInterface

public interface CodeInterface {
   public String diferrentCodeGen(int size,int incNo,String prefix);

}

package customInterface.ImplementInterface

import customInterface.*

class Code implements CodeInterface {

    public String diferrentCodeGen(int size,int incNo,String prefix){

        String code ='';
        int sublength = 0;

        if( ! prefix.isEmpty()){
            sublength += prefix.length()+(incNo.toString().length());  // seze:50000,inc_no:20,prefix:code

                    if(sublength < size && sublength >= 1){
                        def i= 0;

                        while (i= 1){
                        def i= 0;

                        while (i

Custom Mail sending

package umail;

import java.util.Properties;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.Message.RecipientType;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;


public class CustomMail {
    private String from;
    private String to;
    private String subject;
    private String text;



     CustomMail(String from, String to, String subject, String text){
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.text = text;
    }



    public void send(){

        Properties props = new Properties();

        props.put("mail.smtp.host", "bobsled.nocdirect.com");

        props.put("mail.smtp.port", "25");

        Session mailSession = Session.getDefaultInstance(props);

        Message simpleMessage = new MimeMessage(mailSession);

        InternetAddress fromAddress = null;

        InternetAddress toAddress = null;

        try {

            fromAddress = new InternetAddress(from);

            toAddress = new InternetAddress(to);

        } catch (AddressException e) {

            e.printStackTrace();

        }


        try {

            simpleMessage.setFrom(fromAddress);

            simpleMessage.setRecipient(RecipientType.TO, toAddress);

            simpleMessage.setSubject(subject);

            simpleMessage.setContent(text,"text/html; charset=utf-8");

            Transport.send(simpleMessage);

        } catch (MessagingException e) {

            e.printStackTrace();
        }
    }
}


or

package mailUKM

import com.sun.istack.internal.ByteArrayDataSource

import javax.activation.DataHandler
import javax.activation.DataSource
import javax.activation.FileDataSource
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart


class EmailProcessorUKM {
    String d_email ,
           d_user,
           d_password ,
           d_host ,
           d_port ;
    public EmailProcessorUKM(){
        init();
    }
    public init(){
               
        d_email = "ukmodak@ibcs-primax.com";
        d_user = "ukmodak";
        d_password = "ukmodak321";
        d_host = "bobsled.nocdirect.com";
        d_port = "25";
    }
    private class SMTPAuthenticator extends javax.mail.Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(d_user, d_password);
        }
    }

    void sendMessageUKM(String mailTo,String cc,String subject,String msgBody){
        String m_to = mailTo,
               m_subject = subject,
               m_text = msgBody;
        Properties props = new Properties();
        props.put("mail.smtp.starttsl.enable","true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.user", d_email);
        props.put("mail.smtp.host", d_host);
        props.put("mail.smtp.port", d_port);
        props.put("mail.smtps.auth", "true");
        props.put("mail.smtps.debug", "true");

        SecurityManager security = System.getSecurityManager();


        try     {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            //session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);
            if (cc?.length() > 0) {
                InternetAddress[] ccIAdressArray = InternetAddress.parse(cc);
                msg.setRecipients(Message.RecipientType.CC, ccIAdressArray);
            }
            msg.setText(m_text);
            msg.setSubject(m_subject);
            msg.setFrom(new InternetAddress(d_email));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
            Transport.send(msg);
        } catch (Exception mex)     {
            mex.printStackTrace();
        }

    }
    void sendMessageUKMWIthAttachmentBytes(String mailTo,String cc,String subject,String msgBody,List mailBytes){
        String m_to = mailTo,
               m_subject = subject,
               m_text = msgBody;
        Properties props = new Properties();
        props.put("mail.smtp.starttsl.enable","true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.user", d_email);
        props.put("mail.smtp.host", d_host);
        props.put("mail.smtp.port", d_port);
        props.put("mail.smtps.auth", "true");
        props.put("mail.smtps.debug", "true");

        SecurityManager security = System.getSecurityManager();


        try     {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            //session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);

            if(mailBytes.size()>0||mailBytes!=null) {
                Multipart multipart = addMailBytes(m_text, mailBytes)
                msg.setContent(multipart);
            }
            else {
                msg.setText(m_text);
            }
            if (cc?.length() > 0) {
                InternetAddress[] ccIAdressArray = InternetAddress.parse(cc);
                msg.setRecipients(Message.RecipientType.CC, ccIAdressArray);
            }
            msg.setSubject(m_subject);
            msg.setFrom(new InternetAddress(d_email));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
            Transport.send(msg);
        } catch (Exception mex)     {
            mex.printStackTrace();
        }

    }
    Multipart addMailBytes(String messageBody, List attachs) {

        // create the message part
        MimeBodyPart messageBodyPart =
                new MimeBodyPart()

        //fill message
        messageBodyPart.setText(messageBody)

        Multipart multipart = new MimeMultipart()
        multipart.addBodyPart(messageBodyPart)

        for (MailByte attachmentx : attachs) {
            messageBodyPart = new MimeBodyPart()
            DataSource dataSource = new javax.mail.util.ByteArrayDataSource(attachmentx.data, attachmentx.type) // "application/pdf"
            messageBodyPart.setDataHandler(new DataHandler(dataSource))
            messageBodyPart.setFileName(attachmentx.fileName)
            multipart.addBodyPart(messageBodyPart)
        }
        return multipart
    }


}

Ho to get login user info

def springSecurityService
String name = springSecurityService?.currentUser?.username;

Ho to create service

Service name and package name always same to controller name and it's package name

Writing business logic in service is faster then controller

To create a business logic go to project root location and run the following command

 grailstest> grails create-service com.auth.AuthUser

After creating the service it will add additional prefix as com.auth.AuthUserService

To call service follow the following code

    def authUserService
	
	 Map mapValue ; 
	 mapValue = authUserService.methodname(params);
	

String processing in java by StringBuilder

 StringBuilder apppendAtring = new StringBuilder();
 
 apppendAtring.append(
					"<input type='hidden' class='form-control' name='prlPayHead.id' value='"+PrlPayHead.findByBreakDownType(com.enums.BreakDownType.valueOf(params?.breakDownType)).id+"'>"+
					"<div class='box-body'>"+
					"<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>"+
					"<div class='form-group fieldcontain'>" +
					"<label for='academicLavel'>" +
					"Payroll Grade" +
					"</label>" +
					"<input type='hidden' name='prlPayrollGrad.id'  value='"+prlPayrollGradInstance?.id+"' />" +
					"\n "+prlPayrollGradInstance?.gradeName+"\n"+
					"</div></div>"+
					"<table class='table dt-default table-bordered table-striped table-hover table-condensed display nowrap th-center th-colored'>"+
					"<thead>"+
					"<tr>"+
					"<th><input type='checkbox' class='ceckAll' name='ceckAll' /></th>"+
					"<th>Sl.</th>"+
					"<th>Head Name</th>"+
					"<th>Percent</th>"+
					"<th>Amount</th>"+
					"<th>Head Type</th>"+
					"</tr>"+
					"</thead>"
				);

How to find client ip address

         //def ip = request.getRemoteAddr()
		 // InetAddress IP=InetAddress.getLocalHost();
		 // def ip =IP.getHostAddress()

       def userAgent = request.getHeader('user-agent')
         InetAddress IP=InetAddress.getLocalHost();
        def ip =IP.getHostAddress()
		
        def sessionId = request?.getSession()?.id

How to find country ip code useing web service


        
  
		URL whatismyip = new URL("http://checkip.amazonaws.com");    // webservice
		def hh = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
		String ip = hh.readLine(); //you get the IP as a String


		URL url = new URL("http://freegeoip.net/json/${ip}");      // webservice
		//URL url = new URL("http://freegeoip.net/json/202.84.32.85");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Accept", "application/json");

		BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

		String output;
		while ((output = br.readLine()) != null) {
		def jsonObject = new JSONObject(output)
		def findingContryCode = jsonObject.country_code



		if(findingContryCode != ''){

		 def countrycode =webGeneralContentInstance?.visibleCountry.split(",")


			 countrycode.eachWithIndex{item,index ->

					if(item.toLowerCase()== findingContryCode.toLowerCase()){
						showContent = "ok"

					}


			 }

		}

		

How to find server root path on windows and linus

        def serverRootPath =null
        def ukk = null
        def memberOptionalPath = null
        def serverRealPath = request.getSession().getServletContext().getRealPath("/")

        if(SystemUtils.IS_OS_WINDOWS){
            serverRootPath = new File(serverRealPath).getParentFile().getParentFile().getParentFile()
            memberOptionalPath = serverRootPath.toString()+"\\lgspwebsiteupload\\"
            //memberOptionalPath = new File(memberOptionalPath).toString()
            ukk = new File(memberOptionalPath).mkdirs() // microsoft

        }else{
            serverRootPath = new File(serverRealPath).getParentFile().getParentFile().getParentFile()
            memberOptionalPath = serverRootPath.toString()+"//lgspwebsiteupload//"
            //memberOptionalPath = new File(memberOptionalPath).toString()
            ukk = new File(memberOptionalPath).mkdir() // microsoft

        }

How to set upload path location outsite server


        def webCommonPathService
        def titleList = params.list("imageTitle")
        def sortingOrder = params.list("sortingOrder")
        def backgroundColor = ((params?.backgroundColor) ? params?.backgroundColor :null)
        def titleColor = ((params?.titleColor) ? params?.titleColor :null)
        def listColor = ((params?.listColor) ? params?.listColor :null)


        List fileList = request.getFiles('imageFile')

        def imagePath = null
        def insert = null
        def aboutFileUploadDownload = new AboutFileUploadDownload()

        def osType = SystemUtils.IS_OS_WINDOWS
        def windowsOrLinusCommonPath = webCommonPathService.windowsOrLinusCommonPath()
        def createFile = null
        def partnershipDeedUploasPath = null

        fileList.eachWithIndex { file, index ->

            if(file){

                if(osType){

                    partnershipDeedUploasPath = windowsOrLinusCommonPath+"\\images\\upload\\webupload\\"+params?.webUploadDirectory
                    createFile = new File(partnershipDeedUploasPath).mkdirs()
                }else{
                    partnershipDeedUploasPath = windowsOrLinusCommonPath+"//images//upload//webupload//"+params?.webUploadDirectory
                    createFile = new File(partnershipDeedUploasPath).mkdir()
                }

                imagePath = aboutFileUploadDownload.aboutPictureUpMultipart(file,partnershipDeedUploasPath)

				
                def createdDate= new DateAndTime().currentGmtDateAndTime()
                def createdBy = springSecurityService?.currentUser?.id

                webImage.setWebUploadDirectory(new WebUploadDirectory().get( params?.webUploadDirectory.toLong()))

                if(titleList[index]){
                    webImage.setImageTitle(titleList[index])
                }

                webImage.setBackgroundColor(backgroundColor)
                webImage.setTitleColor(titleColor)
                webImage.setListColor(listColor)
                webImage.setImagePath(imagePath)
                webImage.setCreatedDate(createdDate)
                webImage.setCreatedBy(new SecUser().get(createdBy.toLong()))
                if(sortingOrder[index]){
                    webImage.setSortingOrder(sortingOrder[index].toInteger())
                }
				
                insert = webImage.save flush: true

            }
        }
		
		
		
package com.web

import grails.transaction.Transactional
import liquibase.util.SystemUtils

@Transactional
class WebCommonPathService {
    def serverCommonPath = null

    def windowsOrLinusCommonPath() {


        def commompatnIns = WebCommonPath.findById(100.toLong())


        if (SystemUtils.IS_OS_WINDOWS) {
            /*this.serverCommonPath = new File("D:\\isppwebcommonapload\\")*/
            this.serverCommonPath = new File(commompatnIns?.windowsPath).toString()

        } else {
            //this.serverCommonPath = new File("/app/isppwebcommonapload/")
            this.serverCommonPath = new File( commompatnIns?.linuxPath).toString()

        }

        return this.serverCommonPath

    }
}
    

How to download doc,pdf and show img outside server path

To view Image add the following function:

def viewImage(params.fileWithPath) {
        if (new File(params.fileWithPath).exists()) {
            def file = new File(params.fileWithPath)
            def img = file.bytes
            response.contentType = 'image/jpg' // or the appropriate image content type
            response.outputStream << img
            response.outputStream.flush()
        }

    }

To view Pdf add the following function

  def viewPdf(params.fileWithPath) {
        def file
        def img
        def ss
        if (new File(params.fileWithPath).exists()) {
            file = new File(params.fileWithPath)
            img = file.bytes
            response.contentType = 'application/pdf' // or the appropriate image content type
            response.outputStream << img
            response.outputStream.flush()

        }else{

            ss = grailsAttributes.getApplicationContext().getResource("/images/nopdf.pdf").getFile()
            file =ss// new File(ss)
            img = file.bytes
            response.contentType = 'application/pdf' // or the appropriate image content type
            response.outputStream << img
            response.outputStream.flush()
        }

    }

How to show File

 def showDoc() {
	def file = new File(MemberFileUpload.findByKeyword("memberAcademicQualification")?.name + "/" + params.fileK)
	if (file.exists()) {
		response.setContentType("application/octet-stream")
		response.setHeader("Content-disposition", "filename=${file.name}")
		response.outputStream << file.bytes
		return
	}

}

How to get field value as array

 def listTitle = params.list("listTitle")
 def listUrl = params.list("url")

How to solve VM memory problem

go to intellij ide run finfiguration and put the following code in VM Parameter field:

-XX:MaxPermSize=512m
or
-XX:PermSize=128m

Grails Core acl tag

hasRole('ROLE_ADMIN')
hasAnyRole('ROLE_USER','ROLE_ADMIN')
hasRole('ROLE_ADMIN') andisFullyAuthenticated()
permitAll
sAuthenticated() or isRememberMe()
sFullyAuthenticated()

def springSecurityService
 def user = springSecurityService.currentUser
 
 ef user = springSecurityService.isLoggedIn() ? springSecurityService.loadCurrentUser() : null
 
(springSecurityService.isLoggedIn()) {
  ...      
  }

  
  def auth = springSecurityService.authentication      String username = auth.username      def authorities = auth.authorities

def principal = springSecurityService.principal      String username = principal.username      def authorities = principal.authorities 

if(person.password != params.password) {    
    params.password = springSecurityService.encodePassword(password, salt)  
    params.salt = salt  
 } 
 
 ringSecurityService.deleteRole role

/*use in gsp template*/

<sec:ifLoggedIn>Welcome Back!</sec:ifLoggedIn>

<sec:ifNotLoggedIn>>Login</g:link></sec:ifNotLoggedIn>

<sec:ifAllGranted roles='ROLE_ADMIN,ROLE_SUPERVISOR'>...secure stuff here...</sec:ifAllGranted>
<sec:ifAnyGranted roles='ROLE_ADMIN,ROLE_SUPERVISOR'>...secure stuff here...</sec:ifAnyGranted>
<sec:ifNotGranted roles='ROLE_USER'>...non-user stuff here...</sec:ifNotGranted>
<sec:loggedInUserInfo field='username'/>

<sec:ifLoggedIn>Welcome Back >!</sec:ifLoggedIn>
<sec:ifNotLoggedIn><g:link controller='login' action='auth'>Login</g:link></sec:ifNotLoggedIn>

<sec:access expression="hasRole('ROLE_USER')">You're a user</sec:access>

<sec:access url='/admin/user'><g:link controller='admin' action='user'>Manage Users</g:link></sec:access>
<sec:access controller='admin' action='user'><g:link controller='admin' action='user'>Manage Users</g:link></sec:access>

<sec:access mapping='manageUsers'>>Manage Users</g:link></sec:access>

<sec:access url='${createLink(controller: 'admin', action: 'user', base: '/')}'><g:link controller='admin' action='user'>Manage Users</g:link></sec:access>

<sec:noAccess expression="hasRole('ROLE_USER')">You're not a user</sec:noAccess>

<sec:link controller='myController' action='myAction'expression="hasRole('ROLE_USER')">My link text</sec:link>

<sec:link controller='myController' action='myAction'>My link text</sec:link>



How to setup ckeditor

First add the following plugins in the location :buildConfig.groovy as follows

plugins {
       
        compile "org.grails.plugins:ckeditor:4.5.4.0"
       
    }

Add the following script in gsp page

<head>
      <ckeditor:resources/>
</head>
	<div>
	<label for="content">
		<g:message code="webGeneralContent.content.label" default="Content" />
		
	</label>
	
	<ckeditor:editor name="content" height="400px" width="100%">
		${webGeneralContentInstance?.content}
	</ckeditor:editor>
	</div>

You have to do some configuration for file manager in config.groovy file as shown below:

ckeditor {
               config = “/js/myckconfig.js”
               skipAllowedItemsCheck = false
               defaultFileBrowser = “ofm”
upload {
              basedir = “/uploads/”
             overwrite = false
link {
           browser = true
           upload = false
           allowed = []
           denied = ['html', 'htm', 'php', 'php2', 'php3', 'php4', 'php5',
					 'phtml', 'pwml', 'inc', 'asp', 'aspx', 'ascx', 'jsp',
					 'cfm', 'cfc', 'pl', 'bat', 'exe', 'com', 'dll', 'vbs', 'js', 'reg',
					 'cgi', 'htaccess', 'asis', 'sh', 'shtml', 'shtm', 'phtm'
					 ]
}
image {
           browser = true
           upload = true
          allowed = ['jpg', 'gif', 'jpeg', 'png']
          denied = []
}
flash {
          browser = false
          upload = false
          allowed = ['swf']
          denied = []
        }
   }
}

Then run the project

How to setup jasper report

First add the following plugins in the location :buildConfig.groovy as follows

    plugins {
        compile ":jasper:1.11.0"
       
    }

Create a controller and add the following code to print a jasper report


package com.jasper

import CustomInterface.ImplementInterface.DateAndTime
import grails.converters.JSON
import grails.transaction.Transactional
import groovy.sql.Sql


import net.sf.jasperreports.engine.*

import java.sql.Connection
import java.sql.SQLException
import java.text.SimpleDateFormat

class JasperController {


    def dataSource
    def springSecurityService
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");


    def printShort() {
        String z = params.id

        def reportFileName = "rpt_icab_member_resume_short_main.jrxml"
        //def reportDirectory = servletContext.getRealPath('/reports/short/') + "/"
		 // server root path

        def serverRootPath = null
        def serverRealPath = request.getSession().getServletContext().getRealPath("/")
        serverRootPath = new File(serverRealPath).getParentFile().getParentFile().getParentFile()
        def memberOptionalPath = serverRootPath.toString() + "//upload///member//profile//"
        memberOptionalPath = new File(memberOptionalPath).toString()


        if (!new File(memberOptionalPath).exists()) {

            if (new File(memberOptionalPath).mkdirs()) {

                memberOptionalPath = new File(memberOptionalPath).mkdirs() // microsoft
            } else {

                memberOptionalPath = new File(memberOptionalPath).mkdir()    // linux
            }


        }
		
		reportDirectory = memberOptionalPath;

        // end server root path

        def reportParams = new LinkedHashMap()
        Connection conn = null;
        reportParams.put("REPORT_DIR", reportDirectory)
        reportParams.put("SUBREPORT_DIR", reportDirectory)
        reportParams.put("P_ENROLLMENT_NO", z)

        try {
            //Connecting to the MySQL database


            conn = dataSource.getConnection();


            String jrxmlFile = reportDirectory + reportFileName
            InputStream input = new FileInputStream(new File(jrxmlFile));

            //Generating the report

            JasperReport jasperReport = JasperCompileManager.compileReport(input);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, reportParams, conn);

            //Exporting the report as a PDF

            JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JRException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

How to setup excel import file

First add the following plugins in the location :buildConfig.groovy as follows

    plugins {
        compile ':excel-import:1.1.0.BUILD-SNAPSHOT'
    }

add the following code in a controller as follows:

package com.setting

import com.auth.AuthUsers
import com.enums.AttandDailyAuthApv
import com.enums.AttandType
import com.hrms.HrCrAssignment
import com.hrms.HrEmpDtl

import com.payrol.HrPrlPeriod

import com.tmp.TmpHrEmpDtl
import com.tmp.TmpTlAtnd
import customInterface.ImplementInterface.Code
import customInterface.ImplementInterface.DateAndTime
import grails.validation.ValidationException
import liquibase.util.SystemUtils
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.xssf.usermodel.XSSFSheet
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.text.SimpleDateFormat

class SetnFileUploaderController extends AuthController {

    def setnFileUploaderService

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy")
    SimpleDateFormat sdfCode = new SimpleDateFormat("ddMMyy")

    Map bakkMap = new LinkedHashMap()

    Map failTexts = new LinkedHashMap<>()

    List errRowList = new ArrayList<>()

    int numPass = 0
    int numFail = 0

    def setnCommonPathService
    def springSecurityService

    Map ALL_TEMPLATE_COLS = [
            'EMPLOYEE_DTL' : ["EMP_ID", "FNAME","LNAME", "FATHERNAME", "MOTHERNAME", "DATEOFBIRTH", "JOININGDATE","GENDERALKP","RELIGIONALKP","MERITALSTSALKP","NATIONALITY","NID","PERMANENTADRS","PRESENTADRS","DISTRICT","MOBILEONE","MOBILETWO","MOBILETHREE","EMAIL","ALTEMAIL"],
            'INCENTIVE_ALLOWANCE': ["EMP_CODE", "PAYROLL_PERIOD_CODE", "AMOUNT", "REMARKS"],
            'ANNUAL_LEAVE'       : ["EMP_CODE", "PAYROLL_PERIOD_CODE", "ACTUAL_PRESENT_DAY", "ANNUAL_LEAVE_ENJOYED_DAY", "DAILY_SALARY", "REMARKS"],
            'INC_DEC_ADJUSTMENT' : ["EMP_CODE", "GROSS", "REMARKS"],
            'PAYROLL_ADJUSTMENT' : ["EMP_CODE", "PAYROLL_ELEMENT_CODE","START_DATE", "END_DATE", "SIGN", "AMOUNT", "REMARKS"],
            'MONTHLY_ATTANDANCE' : ["EMP_ID", "TIME_HR","TIME_MIN", "TIME_SEND", "ATTAND_TYPE", "MESG", "AUTH_APPROVAL","DATE","UPDATE_DATE"]

    ]

    def index() {

        def fullPath = null
        def beforeUploadFileCheck = null
        def delExisPath = null
        def createFile = null
        def fileNameField = null
        def setnFileUploaderInstance = null
        def fileName, fileLoc, uidName, ext

        def osType = SystemUtils.IS_OS_WINDOWS
        def windowsOrLinusCommonPath = setnCommonPathService.windowsOrLinusCommonPath()

        if(request.method=="POST" && params['file'].getOriginalFilename()){

            bakkMap.clear()

            def uploadedFile = params['file']

            def modeOfUpload = params?.modeOfUpload

            def createDate = new DateAndTime().currentGmtDateAndTime()


            beforeUploadFileCheck = SetnFileUploader.findByModeOfUpload(com.enums.ModeOfUpload.valueOf(modeOfUpload))


            if (uploadedFile?.getOriginalFilename()) {

                fileName = uploadedFile?.getOriginalFilename()

                ext = fileName.toString().substring(fileName.toString().lastIndexOf("."))

                if (ext.toString() != ".xlsx") {

                    flash.message ="File extension is NOT supported. Use *.xlsx or *.xls  file only."
                    redirect(action: "index")
                    return false
                }


                uidName = modeOfUpload+UUID.randomUUID().toString() + fileName.toString().substring(fileName.toString().lastIndexOf("."))

                if(osType){

                    fullPath = windowsOrLinusCommonPath+"\\images\\upload\\webupload\\tmp_dataupload_file"

                    if(beforeUploadFileCheck?.fileName){
                        new File(fullPath+"\\"+beforeUploadFileCheck?.fileName).delete()

                    }
                    new File(fullPath).mkdirs()

                    createFile = new File(fullPath+"\\"+uidName)

                }else {

                    fullPath = windowsOrLinusCommonPath + "//images//upload//webupload//tmp_dataupload_file"

                    if (beforeUploadFileCheck?.fileName) {
                         new File(fullPath + "//" + beforeUploadFileCheck?.fileName).delete()
                    }

                    new File(fullPath).mkdirs()

                    createFile = new File(fullPath+"//"+uidName)
                }


                uploadedFile.transferTo(createFile)


                if(beforeUploadFileCheck){
                    beforeUploadFileCheck.setFileName(uidName)
                    beforeUploadFileCheck.setModeOfUpload(com.enums.ModeOfUpload.valueOf(modeOfUpload))
                    beforeUploadFileCheck.setUploadDate(createDate)
                    beforeUploadFileCheck.save(flush:true)

                    setnFileUploaderService.doUpload(createFile)


                }else{

                    setnFileUploaderInstance = new SetnFileUploader()

                    setnFileUploaderInstance.setFileName(uidName)
                    setnFileUploaderInstance.setModeOfUpload(com.enums.ModeOfUpload.valueOf(modeOfUpload))
                    setnFileUploaderInstance.setUploadDate(createDate)
                    setnFileUploaderInstance.save(flush:true)

                    setnFileUploaderService.doUpload(createFile)

                }

                flash.message ="File upload successful"


            }else{

                flash.message ="File is empty. PLease upload file"
                redirect(action: "index")
                return false
            }


            render(view: "index",model:[osType:osType,windowsOrLinusCommonPath:windowsOrLinusCommonPath])

        }else{

            render(view: "index",model:[osType:osType,windowsOrLinusCommonPath:windowsOrLinusCommonPath])
        }


    }

    def view(){

        if(request.method=="GET" && params?.view !=''){

            if(params?.modeOfUpload == com.enums.ModeOfUpload.EMPLOYEE_DTL.toString()){

                redirect controller:'tmpHrEmpDtl',action:'edit'
                return false

            }else if(params?.modeOfUpload == com.enums.ModeOfUpload.EMPLOYEE_ASSIGNMENT.toString()){

            }else if(params?.modeOfUpload == com.enums.ModeOfUpload.MONTHLY_ATTANDANCE.toString()){

                redirect controller:'tmpTlAtnd',action:'edit'
                return false

            }


           // render(view: "view",model:"")

        }else{
            render(view: "view",model:"")
        }

    }

    def downloadFile() {

        File abc = new File(new File(grailsApplication.mainContext.servletContext.getRealPath('//')).parent + File.separator + "metal_hcm_repo" + File.separator + "file_upload_template_doc")

        println("downloadFile abc 406: " + abc)

        String fileName = params["XLFILEDOWNLOAD"] as String
        abc = new File(abc, fileName)

        println("File name with absolutePath name :" + abc)

        if (abc.exists()) {
            response.setContentType("application/octet-stream")
            response.setHeader("Content-disposition", "filename=${abc.name}")
            response.outputStream << abc.bytes
        }
    }


}

add a gsp template to upload file

 <g:form action="index" method="POST" style="clear:both;" enctype="multipart/form-data">
                <fieldset class="form">

                <section class="box-header">
                <g:render template="/layouts/flashMessage"/>
                </section>

                        <fieldSet>

                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" >
                                <div class="col-xs-12 col-sm-6 col-md-4 col-lg-6">
                                    <div class="form-group">
                                        <label for="modeOfUpload">
                                            <g:message code="fileUploader.modeOfUpload.label" default="Mode"/>
                                            <span class="required-indicator">*
                                        
                                        <g:select name="modeOfUpload" from="${com.enums.ModeOfUpload?.values()}"
                                                  keys="${com.enums.ModeOfUpload.values()*.name()}"
                                                  class="form-control"
                                                  noSelection="['': 'Select One']"
                                                  value=""/>
                                    </div>
                                </div>

                                <div class="col-xs-12 col-sm-6 col-md-4 col-lg-6">
                                    <div class="form-group">
                                        <label for="file">
                                            <g:message code="fileUploader.file.label" default="File"/>
                                        </label>
                                        <input type="file" name="file" id="file"/>
                                    </div>
                                </div>
                            </div>


                        </fieldSet>
                    </div>

                </fieldset>
                <fieldset class="buttons">
                    <g:submitButton name="upload" class="btn btn-primary btn-sm save" value="${message(code: 'default.button.upload.label', default: 'Upload')}"/>
                </fieldset>
            </g:form>
bONEandALL
Visitor

Total : 18980

Today :9

Today Visit Country :

  • Germany
  • Singapore
  • United States
  • Russia