com.bennavetta.appsite.processor.GroovyProcessor.java Source code

Java tutorial

Introduction

Here is the source code for com.bennavetta.appsite.processor.GroovyProcessor.java

Source

/**
 * Copyright 2013 Ben Navetta <ben@bennavetta.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bennavetta.appsite.processor;

import groovy.lang.GroovyShell;

import java.io.OutputStream;
import java.io.PrintStream;

import com.bennavetta.appsite.processing.Request;
import com.bennavetta.appsite.processing.Response;
import com.bennavetta.appsite.processor.scripting.Script;
import com.bennavetta.appsite.processor.scripting.ScriptCompiler;
import com.bennavetta.appsite.processor.scripting.ScriptFactory;
import com.bennavetta.appsite.processor.scripting.ScriptingProcessor;
import com.google.common.net.MediaType;

public class GroovyProcessor extends ScriptingProcessor {
    public class GroovyScript implements Script {
        private groovy.lang.Script script;

        public GroovyScript(groovy.lang.Script script) {
            this.script = script;
        }

        @Override
        public void run(Request request, Response response, OutputStream out) {
            script.setProperty("request", request);
            script.setProperty("response", response);
            script.setProperty("out", new PrintStream(out)); // http://stackoverflow.com/a/1531726/1725688
            script.run();
        }
    }

    protected class GroovyCompiler implements ScriptCompiler {
        private GroovyShell shell = new GroovyShell();

        @Override
        public Script compile(String source) {
            return new GroovyScript(shell.parse(source));
        }
    }

    @Override
    public boolean canProcess(String path, MediaType type, Request request, Response response) {
        if (path.endsWith(".groovy"))
            return true;
        if (type.toString().contains("groovy") && type.toString().contains("template")) // don't process groovy templates
            return true;
        return false;
    }

    @Override
    protected ScriptFactory createFactory() {
        return new ScriptFactory(new GroovyCompiler());
    }

}