Monday, 27 June 2016

Why this keyword is not applicable in static context

this key word is useful to access current instance of class. static values and methods are common to all instance of classes. so, static never depend on any class. it is common to all instances of classes.

What is immutable?

the objects which are initialise only once and never modify those objects values, those objects are called immutable.

Tuesday, 21 June 2016

Excel Sheets Data saved in database

def servletContext = ServletContextHolder.servletContext
if(State.findAll().size() == 0){
//upload states
new File(servletContext.getRealPath("/dataCsv/states.csv")).eachLine {
new State(name:it.split(',')[0]).save()
}
}

def states = State.list()
//upload Cities
if(Cities.findAll().size() == 0){
new File(servletContext.getRealPath("/dataCsv/Cities.csv")).eachLine {token->
states.each{st->
def record =  token.split(',')
if(st.id == record[1] as Long){
new Cities(stateId:st.id,name:record[0]).save()
}
}
}
}

File Upload, Display and Download

File Upload:

Step 1:

html code

<input type="file" class="form-control" name="img" id="img"/>

Step 2:

controller side

properties.imgFile = request.getFile('img')
MultipartFile img;
def file = properties.imgFile
String extractedName = FilenameUtils.removeExtension(file.originalFilename)
String extension = FilenameUtils.getExtension(file.originalFilename)
def fileName = account.id +"."+extension//Get An Account ID On the Image Name
def storage =  messageSource.getMessage('com.gb.storageLocation',null,LCH.getLocale())
def folder = new File(storage)
def imagePath = storage+File.separator+fileName
if( !folder.exists())  folder.mkdirs()
if(extension) {
file.transferTo(new File(imagePath))
account.img = imagePath
}


Display:

html code

<img  class="ts-avatar hidden-side" alt="" src="<g:createLink controller="Setups" action="viewImage" params='[title: "${session?.loggedInUser?.account?.img}"]'/>"/>

controller side

def viewImage(){
try{
def file = new File(params.title)
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){
}
}

Download:

def downloadExcel(fileName) {
def file = new File(servletContext.getRealPath("/dataCsv/"+fileName))
if (file.exists()) {
response.setContentType("application/vnd.ms-excel")
if(params.action == "productListExcelDownload") response.setHeader('Content-Disposition', "Filename="+"ProductList")
else  response.setHeader('Content-Disposition', "Filename="+fileName)
response.outputStream << file.bytes
if(params.action == "productListExcelDownload") {
String realPath  = ServletContextHolder.servletContext.getRealPath(File.separator+"dataCsv"+File.separator+"ProductList");
File f =new File (realPath);
if(f.isDirectory()) {
f.deleteDir()
}
}
}
return
}