keskiviikko 3. huhtikuuta 2013

Reading JPG from disk and rendering it as image/jpeg in Grails

getImage is a controller action, getPictureBytes just reads a file and returns it as a byte array.

def getImage(String filename) {
  def bytes = getPictureBytes(filename)
  response.setContentType('image/jpeg');
  response.outputStream << bytes
}

private getPictureBytes(String filename) throws FileNotFoundException {
 def bytes

 try {
  bytes = new File(grailsApplication.config.picturePath + filename).readBytes()
 } catch (FileNotFoundException e) {
  // If an assigned file was not found, still attempt to return a default image.
  def context = grailsAttributes.getApplicationContext()
  bytes = context.getResource("/images/default-image.jpg").getFile().readBytes()
 }

 bytes
}

tiistai 29. maaliskuuta 2011

Getting & setting cookies in Grails

Setting:


import javax.servlet.http.Cookie
def c = new Cookie(someName, someValue)
c.maxAge = someNumberInSeconds
response.addCookie(c)

Getting:


request.cookies.each { println "${it.name} == ${it.value} }

perjantai 25. maaliskuuta 2011

ERROR errors.GrailsExceptionResolver - No signature of method: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.g

If you get this exception when trying to read uploaded files, you know you're missing enctype="multipart/form-data" from the form tag.


2011-03-25 09:45:25,798 [http-8080-2] ERROR errors.GrailsExceptionResolver - No signature of method: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile() is applicable for argument types: (java.lang.String) values: [file]
Possible solutions: getXML(), getAt(java.lang.String), getAt(java.lang.String), getLocale(), getJSON(), getHeader(java.lang.String)
groovy.lang.MissingMethodException: No signature of method: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile() is applicable for argument types: (java.lang.String) values: [file]
Possible solutions: getXML(), getAt(java.lang.String), getAt(java.lang.String), getLocale(), getJSON(), getHeader(java.lang.String)
at check.ProductScreenBinaryController$_closure7.doCall(check.ProductScreenBinaryController:85)
at check.ProductScreenBinaryController$_closure7.doCall(check.ProductScreenBinaryController)
at java.lang.Thread.run(Thread.java:680)

keskiviikko 9. maaliskuuta 2011

Deep JSON conversion woes

Need to do deep JSON conversion? Use this:

JSON.use("deep") {
def converter = results as JSON
converter.prettyPrint = true
render converter.toString()
}

If you get the Misplaced key -error, add the following line to Config.groovy:
grails.converters.json.circular.reference.behaviour = "INSERT_NULL"

tiistai 8. maaliskuuta 2011

ls colors in OSX

Just a quick tip, or more a reminder for myself: to get nice colors for ls, set the following environment variables in the shell conf file:

export CLICOLOR=1
export LSCOLORS=Exfxcxdxbxegedabagacad

tiistai 23. marraskuuta 2010

Regular SQL query result mapped to Grails domain class

It's often needed to do a regular SQL query if Criteria or HQL query isn't flexible enough. This is achieved with Hibernate's org.hibernate.SessionFactory class function createSQLQuery. However query's list-method returns a List of objects inside of a List by default instead of List of domain instances. Luckily org.hibernate.SQLQuery class has a method named addEntity which can be used to map results to specific domain class.

Our domain class:
package fi.company.domain
class Product {
   String name
   int price
}


Service that uses sql
import org.hibernate.SessionFactory
import org.hibernate.Session
import org.hibernate.SQLQuery
class ProductSearchService {
   SessionFactory sessionFactory
   boolean transactional = false


   List<Product> searchProducts(Map params) {
      Session session = sessionFactory.getCurrentSession()
      SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM product WHERE ...")
      sqlQuery.addEntity(fi.company.domain.Product.class)
      return sqlQuery.list()
   }
}

maanantai 9. elokuuta 2010

Delete records with Hibernate Criteria Builder

A neat way of deleting records with createCriteria and Groovy:
def c = Agency.createCriteria().list {
eq("agency", "XXX")
}*.delete()
Source: http://stackoverflow.com/questions/2232621/how-do-you-bulk-delete-records-in-grails-gorm