EzDevInfo.com

groovy interview questions

Top groovy frequently asked interview questions

shortcut for creating a Map from a List in groovy?

I'd like some sorthand for this:

Map rowToMap(row) {
    def rowMap = [:];
    row.columns.each{ rowMap[it.name] = it.val }
    return rowMap;
}

given the way the GDK stuff is, I'd expect to be able to do something like:

Map rowToMap(row) {
    row.columns.collectMap{ [it.name,it.val] }
}

but I haven't seen anything in the docs... am I missing something? or am I just way too lazy?


Source: (StackOverflow)

Break from groovy each closure

Is it possible to "break" from a Groovy each Closure?

Or should I be using a classic loop instead?


Source: (StackOverflow)

Advertisements

Groovy / grails how to determine a data type?

What is the best way to determine the data type in groovy?

I'd like to format the output differently if it's a date, etc.


Source: (StackOverflow)

Is Grails (now) worth it?

I know this is a duplicate, however, the Grails world has moved on considerably since that question was asked more than a year ago, as has the IDE support in Eclipse, so please don't just blindly close it.

I thought the answer was yes and have embarked on a new project with Grails 1.2.0 and have flirted with the Groovy/Grails bits of the STS Eclipse Integration.

I think the question deserves revisiting after a year of Grails evolution, when the answer was definitely mixed.

So, as an experienced Java web developer I have these questions and would appreciate my assumptions being challenged:

  • Is Grails now worth it vs. Ruby or roll your own?
  • Has it overcome its buggy start?
  • Does it really confer rapid development benefits? (I admit I am struggling now I am past the extensive baseline configuration to make my bespoke app which is not list and page oriented)
  • Does it perform for real world production apps? (It feels heavy)
  • Is the Eclipse plug-in better than it was and fit for purpose? (I think not yet)

Thanks

EDIT: I am learning as I go and I have a couple of significant gripes to make about living with the framework - rather than framework capabilities themselves. I am adding these because I think they should be considerations and are based on my experience and opinion, and may help someone who is trying to decide whether to go grails. I may also be showing my lack of experience with the framework, so none of this is meant as out and out criticisms. I am an experienced developer and this is what I have found:

Debugging is really hard. In fact it is almost impossible, especially as a beginner in the framework, which is when you need your trusty debugger friend the most. I have spent way more time than I ought to tracking down problems of syntactical errors in some part of the code to do with referring to domain fields which cause silent failures somewhere in the stack.

Logging is frankly awful. You have two modes, "nothing useful" and "an inordinate amount of useless stuff". My debug log was 128Mb after a single page request and contains nothing about my error. The whole issue of logging needs reconsideration in the framework in my opinion.

The STS Eclipse IDE is of marginal value. Other than syntax hilighting it is not much use. You can't debug the code so it is a glorified editor. The code hints are patchy and there is no GSP support at all as far as I can see. It also is the slowest Eclipse plug-in I have on my desktop - by about 2 minutes to start up. It is shockingly slow. I have reverted to a text editor (which you'll notice all the online tutorial videos do too) and some custom syntax hilighting.

I have some serious concerns about performance. A bit too early to say, but I am already finding myself tweaking the database because of hibernate. Perhaps that's to be expected, but I am really having to keep my domain model simple for the conventions to yield performant queries.

And one last one, the convention that your logical domain model and your physical database model should be identical is not a smart default and unlikely ever to be the case in the real world. I know you can separate the two, but it creates a degree of complexity which I think could be avoided if the conventions were extended. There is inadequate documentation about composition and what you need to do to make it work in practice.


Source: (StackOverflow)

How is the performance of Groovy compared with Java?

What the performance of Groovy compared with Java?


Source: (StackOverflow)

How can I return a 404/50x status code from a Grails Controller?

I have a controller that needs to return a 404 page and status code on certain conditions. I can't seem to find out how to do this in Grails. A coworker recommended this method:

response.sendError(HttpServletResponse.SC_NOT_FOUND)

which works perfectly fine, but it's not very Grails-like. I know Rails' render method take a status argument, but Grails' render has no such functionality. Is there something I'm missing, what's the best way to accomplish this?


Source: (StackOverflow)

Resetting the UP-TO-DATE property of gradle tasks?

Is there a way I can force a gradle task to run again, or reset all tasks back to the not UP-TO-DATE state?


Source: (StackOverflow)

Groovy executing shell commands

Groovy adds the execute method to String to make executing shells fairly easy;

println "ls".execute().text

but if an error happens, then there is no resulting output. Is there an easy way to get both the standard error and standard out? (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?)

It would be nice to have something like;

 def x = shellDo("ls /tmp/NoFile")
 println "out: ${x.out} err:${x.err}"

Source: (StackOverflow)

Scala vs. Groovy vs. Clojure [closed]

Can someone please explain the major differences between Scala, Groovy and Clojure. I know each of these compiles to run on the JVM but I'd like a simple comparison between them.


Source: (StackOverflow)

Groovy String to int

I have a String that represents an integer value and would like to convert it to an int. Is there a groovy equivalent of Java's Integer.parseInt(String)?


Source: (StackOverflow)

How to read a file in Groovy into a string?

I need to read a file from the file system and load the entire contents into a string in a groovy controller, what's the easiest way to do that?


Source: (StackOverflow)

Hidden features of Groovy?

It seems like Groovy was forgotten in this thread so I'll just ask the same question for Groovy.

  • Try to limit answers to Groovy core
  • One feature per answer
  • Give an example and short description of the feature, not just a link to documentation
  • Label the feature using bold title as the first line

See also:

  1. Hidden features of Python
  2. Hidden features of Ruby
  3. Hidden features of Perl
  4. Hidden features of Java

Source: (StackOverflow)

Loop through Map in Groovy?

I have a very simple task I am trying to do in Groovy but cannot seem to get it to work. I am just trying to loop through a map object in groovy and print out the key and value but this code does not work.

//A simple map
def map = [
           'iPhone':'iWebOS',
           'Android':'2.3.3',
           'Nokia':'Symbian',
           'Windows':'WM8'
           ]

//Print the values 
for(s in map) {
    println s + ":" + map[s]
}

I am trying to get the output to look like this:

iPhone:iWebOS
Android:2.3.3
Nokia:Symbian
Windows:WM8

Could someone please elaborate on how to do this??


Source: (StackOverflow)

Clojure 1.2.1/1.3/1.4 'proxy generated in Grails 2.0.0 runtime fails. 1.2.0 is fine

So I have a weird situation here.

I'm working on extending the Grails Clojure plugin in Grails 2.0.0 (and 2.1.0-SNAPSHOT) and I wanted to update it to Clojure 1.3.0 and add clojure.tools.logging.

Clojure throws an exception during compilation of a proxy of a ByteArrayOutputStream in clojure.tools.logging's log-stream function:

ClassCastException: clojure.asm.Type cannot be cast to clojure.lang.IFn

( https://gist.github.com/a6ae681c37091a3d2379 )

I went and removed clojure.tools.logging and wrote a stripped down proxy of Object:

(proxy [java.lang.Object] [] (toString [] "proxy's toString"))

and it also threw that same ClassCastException and message.

I tried to print a macroexpand-1 of the proxy and got the same thing.

I reverted to Clojure 1.2.0 and proxy worked fine again.

I tried a number of incarnations of 1.4.0 and they exhibit the same behavior as 1.3.0. 1.2.1 also throws some sort of exception but I'm trying to hit 1.3.0 so I didn't spend much time with that.

The stack trace points to the 'gen-method function defined in one of the let forms of generate-proxy in core_proxy.clj.

I added a small smattering of println's around there to see if I could catch what was happening. Maybe this next statement will betray a huge misunderstanding of the reader on my part but simply adding those printlns changed the compile time behavior in a way I totally didn't expect. The exception location and exception type completely changed, even though all the Clojure tests in mvn package continue to pass.

For instance, just adding a single println to gen-method right before it starts generating bytecode caused Clojure to throw

ClassCastException: clojure.lang.PersistentArrayMap cannot be cast to java.lang.Class

( https://gist.github.com/5a7a40929a6c4a104bd5 )

I've seen various other errors depending on where I put the println(s) but this is the most prevalent.

Obviously some aspect of Grails and Clojure are not meshing correctly here, but I am not seeing the connection. At first I suspected ASM incompatibility but since Clojure has its own ASM namespace, I can't see that being the issue. But maybe I'm wrong, I've been staring at clojure.lang.Compiler, proxy and generate-proxy for days now trying to get this to work and I've pretty much stopped making forward progress because I've run out of steam :(

Thanks in advance for any assistance. I'll provide anything I can, I'd really like to get this to work.

I apologize for the lack of links, apparently SO won't let me post more than 2 because I'm new. You can copy and paste from below:

Grails Clojure - github.com/grails-plugins/grails-clojure

Clojure Tools Logging - github.com/clojure/tools.logging/blob/master/src/main/clojure/clojure/tools/logging.clj line 133 is the 'proxy


Source: (StackOverflow)

Hibernate: Automatically creating/updating the db tables based on entity classes

I have the following entity class (in Groovy):

import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType

@Entity
public class ServerNode {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  Long id

  String firstName
  String lastName


}

and my persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">

    <persistence-unit name="NewPersistenceUnit">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/Icarus"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hbm2ddl.auto" value="create"/>
        </properties>
        <class>net.interaxia.icarus.data.models.ServerNode</class>
    </persistence-unit>
</persistence>

and the script:

import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import javax.persistence.Persistence
import net.interaxia.icarus.data.models.ServerNode

def factory = Persistence.createEntityManagerFactory("NewPersistenceUnit")
def manager = factory.createEntityManager()

manager.getTransaction().begin()

manager.persist new ServerNode(firstName: "Test", lastName: "Server")

manager.getTransaction().commit()

the database 'Icarus' exists, but currently has no tables. I would like Hibernate to automatically create and/or update the tables based on the entity classes. How would i accomplish this?


Source: (StackOverflow)