public void testForeignKeyColumnBinding() {
    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass oneClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestOneSide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String name \n"
                    + "    String description \n"
                    + "}"));
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestManySide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String name \n"
                    + "    TestOneSide testOneSide \n"
                    + "\n"
                    + "    static mapping = {\n"
                    + "        columns {\n"
                    + "            testOneSide column:'EXPECTED_COLUMN_NAME'"
                    + "        }\n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config =
        getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()});

    PersistentClass persistentClass = config.getClassMapping("TestManySide");

    Column column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next();
    assertEquals("EXPECTED_COLUMN_NAME", column.getName());
  }
  public void testDefaultNamingStrategy() {

    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass oneClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestOneSide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String fooName \n"
                    + "    String barDescriPtion \n"
                    + "}"));
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestManySide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    TestOneSide testOneSide \n"
                    + "\n"
                    + "    static mapping = {\n"
                    + "        columns {\n"
                    + "            testOneSide column:'EXPECTED_COLUMN_NAME'"
                    + "        }\n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config =
        getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()});

    PersistentClass persistentClass = config.getClassMapping("TestOneSide");
    assertEquals("test_one_side", persistentClass.getTable().getName());

    Column column = (Column) persistentClass.getProperty("id").getColumnIterator().next();
    assertEquals("id", column.getName());

    column = (Column) persistentClass.getProperty("version").getColumnIterator().next();
    assertEquals("version", column.getName());

    column = (Column) persistentClass.getProperty("fooName").getColumnIterator().next();
    assertEquals("foo_name", column.getName());

    column = (Column) persistentClass.getProperty("barDescriPtion").getColumnIterator().next();
    assertEquals("bar_descri_ption", column.getName());

    persistentClass = config.getClassMapping("TestManySide");
    assertEquals("test_many_side", persistentClass.getTable().getName());

    column = (Column) persistentClass.getProperty("id").getColumnIterator().next();
    assertEquals("id", column.getName());

    column = (Column) persistentClass.getProperty("version").getColumnIterator().next();
    assertEquals("version", column.getName());

    column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next();
    assertEquals("EXPECTED_COLUMN_NAME", column.getName());
  }
Beispiel #3
0
  @Override
  public void doExecute(TestContext context) {
    try {
      ClassLoader parent = getClass().getClassLoader();
      GroovyClassLoader loader = new GroovyClassLoader(parent);

      assertScriptProvided();

      String rawCode =
          StringUtils.hasText(script)
              ? script.trim()
              : FileUtils.readToString(FileUtils.getFileResource(scriptResourcePath, context));
      String code = context.replaceDynamicContentInString(rawCode.trim());

      // load groovy code
      Class<?> groovyClass = loader.parseClass(code);
      // Instantiate an object from groovy code
      GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();

      // only apply default script template in case we have feature enabled and code is not a class,
      // too
      if (useScriptTemplate && groovyObject.getClass().getSimpleName().startsWith("script")) {
        // build new script with surrounding template
        code =
            TemplateBasedScriptBuilder.fromTemplateResource(
                    FileUtils.getFileResource(scriptTemplatePath, context))
                .withCode(code)
                .build();

        groovyClass = loader.parseClass(code);
        groovyObject = (GroovyObject) groovyClass.newInstance();
      }

      if (log.isDebugEnabled()) {
        log.debug("Executing Groovy script:\n" + code);
      }

      // execute the Groovy script
      if (groovyObject instanceof ScriptExecutor) {
        ((ScriptExecutor) groovyObject).execute(context);
      } else {
        groovyObject.invokeMethod("run", new Object[] {});
      }

      log.info("Groovy script execution successfully");
    } catch (CitrusRuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new CitrusRuntimeException(e);
    }
  }
  /**
   * Parse the template's (Groovy) script. The script must implement {@link IEmailDataScript}.
   *
   * @param keyVals
   * @return
   */
  public Map<String, String> parseScript(Map<String, String> keyVals) {

    Map<String, String> resultMap = new HashMap<String, String>();
    if (null == _script || "".equals(_script)) {
      return resultMap;
    }

    ClassLoader parent = getClass().getClassLoader();
    GroovyClassLoader loader = new GroovyClassLoader(parent);
    Class<?> clazz = loader.parseClass(_script, "EmailDataScript");

    IEmailDataScript scriptDelegate;
    try {
      scriptDelegate = (IEmailDataScript) clazz.newInstance();
      resultMap = scriptDelegate.getEmailData((HashMap<String, String>) keyVals);

      if (MapUtils.isEmpty(resultMap)) {
        // This may not necessarily be an error for some parameter values.
        LOGGER.warn(
            "sendTemplateEmail no data returned from Groovy script for templateID: " + _templateId);
      }
    } catch (InstantiationException e) {
      LOGGER.error(DetailedException.getMessageOrType(e));
    } catch (IllegalAccessException e) {
      LOGGER.error(DetailedException.getMessageOrType(e));
    } catch (CompilationFailedException e) {
      LOGGER.error(DetailedException.getMessageOrType(e));
    }

    return resultMap;
  }
Beispiel #5
0
  public void initialise() throws InitialisationException {
    try {
      GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader());
      // defaults to the logical name of the Transformer can be changed by explicit setting of the
      // scriptName
      if (script == null) {
        script = getName() + ".groovy";
      }
      if (scriptLocation == null) {
        scriptLocation = loader.getResource(script);
      }

      if (scriptLocation == null) {
        File file = new File(script);
        if (file.exists()) {
          scriptLocation = file.toURL();
        } else {
          throw new InitialisationException(
              new Message(Messages.CANT_LOAD_X_FROM_CLASSPATH_FILE, "Groovy Script: " + script),
              this);
        }
      }
      logger.info("Loading Groovy transformer with script " + scriptLocation.toExternalForm());
      Class groovyClass = loader.parseClass(new GroovyCodeSource(scriptLocation));
      transformer = (GroovyObject) groovyClass.newInstance();
    } catch (Exception e) {
      throw new InitialisationException(
          new Message(Messages.FAILED_TO_CREATE_X, "Groovy transformer"), e, this);
    }
  }
 public static <T> T newInstance(String fileName) throws ScriptExecutionFailedException {
   GroovyObject groovyObject = null;
   try {
     File f = new File(fileName);
     if (!f.exists()) {
       f =
           new File(
               SubDirectory.SCRIPTS
                   + File.separator
                   + fileName
                   + (fileName.endsWith(".groovy") ? "" : ".groovy"));
     }
     GroovyClassLoader loader = getGroovyClassLoader();
     Class groovyClass = loader.parseClass(f);
     groovyObject = (GroovyObject) groovyClass.newInstance();
   } catch (Exception e) {
     LOG.error(e, e);
     throw new ScriptExecutionFailedException(e);
   }
   try {
     return (T) groovyObject;
   } catch (ClassCastException e) {
     LOG.debug(e, e);
     throw new ScriptExecutionFailedException(e.getMessage(), e);
   }
 }
 public void loadResource(final InputStream inputStream) throws ResourceInitializationException {
   ClassLoader parent = getClass().getClassLoader();
   GroovyClassLoader groovyClassLoader = new GroovyClassLoader(parent);
   try {
     String scriptString = getScriptHeader();
     StringWriter writer = new StringWriter();
     IOUtils.copy(inputStream, writer);
     scriptString += "\n" + writer.toString();
     scriptString += "\n" + getScriptFooter();
     Class<?> groovyClass = groovyClassLoader.parseClass(scriptString);
     LOGGER.info("Loading groovy variant rules");
     this.script = (GroovyObject) groovyClass.newInstance();
     this.script.invokeMethod("init", new Object[] {});
     initProfilingWithZeroCount();
     LOGGER.info("Groovy variant rules loaded.");
   } catch (Exception e) {
     LOGGER.error("Could not load the groovy variant rules resource");
     throw new ResourceInitializationException(e);
   } finally {
     try {
       groovyClassLoader.close();
     } catch (IOException e) {
       LOGGER.warn("Could not close groovy class loader");
     }
   }
 }
  public void testInsertableUpdateableHibernateMapping() throws Exception {
    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestInsertableUpdateableDomain {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String testString1 \n"
                    + "    String testString2 \n"
                    + "\n"
                    + "    static mapping = {\n"
                    + "       testString1 insertable:false, updateable:false \n"
                    + "       testString2 updateable:false, insertable:false \n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config =
        getDomainConfig(cl, new Class[] {domainClass.getClazz()});

    PersistentClass persistentClass = config.getClassMapping("TestInsertableUpdateableDomain");

    Property property1 = persistentClass.getProperty("testString1");
    assertEquals(false, property1.isInsertable());
    assertEquals(false, property1.isUpdateable());

    Property property2 = persistentClass.getProperty("testString2");
    assertEquals(false, property2.isUpdateable());
    assertEquals(false, property2.isInsertable());
  }
  /**
   * Attempts to compile the given InputStream into a Groovy script using the given name
   *
   * @param in The InputStream to read the Groovy code from
   * @param name The name of the class to use
   * @param pageName The page name
   * @param metaInfo
   * @return The compiled java.lang.Class, which is an instance of groovy.lang.Script
   */
  private Class<?> compileGroovyPage(
      InputStream in, String name, String pageName, GroovyPageMetaInfo metaInfo) {
    GroovyClassLoader groovyClassLoader = findOrInitGroovyClassLoader();

    // Compile the script into an object
    Class<?> scriptClass;
    try {
      scriptClass = groovyClassLoader.parseClass(DefaultGroovyMethods.getText(in), name);
    } catch (CompilationFailedException e) {
      LOG.error("Compilation error compiling GSP [" + name + "]:" + e.getMessage(), e);

      int lineNumber = GrailsExceptionResolver.extractLineNumber(e);

      final int[] lineMappings = metaInfo.getLineNumbers();
      if (lineNumber > 0 && lineNumber < lineMappings.length) {
        lineNumber = lineMappings[lineNumber - 1];
      }
      throw new GroovyPagesException(
          "Could not parse script [" + name + "]: " + e.getMessage(), e, lineNumber, pageName);
    } catch (IOException e) {
      throw new GroovyPagesException(
          "IO exception parsing script [" + name + "]: " + e.getMessage(), e);
    }
    return scriptClass;
  }
Beispiel #10
0
    public void parse(String filterAsString) {
      String groovyString =
          "public class GroovyMatcher {\n"
              + "public org.jbehave.core.model.Meta meta\n"
              + "  public boolean match() {\n"
              + "    return ("
              + filterAsString.substring("groovy: ".length())
              + ")\n"
              + "  }\n"
              + "  def propertyMissing(String name) {\n"
              + "    if (!meta.hasProperty(name)) {\n"
              + "      return false\n"
              + "    }\n"
              + "    def v = meta.getProperty(name)\n"
              + "    if (v.equals('')) {\n"
              + "      return true\n"
              + "    }\n"
              + "    return v\n"
              + "  }\n"
              + "}";

      GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader());
      groovyClass = loader.parseClass(groovyString);
      try {
        match = groovyClass.getDeclaredMethod("match");
        metaField = groovyClass.getField("meta");
      } catch (NoSuchFieldException e) {
        // can never occur as we control the groovy string
      } catch (NoSuchMethodException e) {
        // can never occur as we control the groovy string
      }
    }
  public void testGenerateViews() throws Exception {
    GrailsTemplateGenerator generator;

    GroovyClassLoader gcl = new GroovyClassLoader(Thread.currentThread().getContextClassLoader());

    generator = new DefaultGrailsTemplateGenerator();

    Class dc =
        gcl.parseClass(
            "class Test { "
                + "\n Long id;"
                + "\n Long version;"
                + "\n String name;"
                + "\n TimeZone tz;"
                + "\n Locale locale;"
                + "\n Currency currency;"
                + "\n Boolean active;"
                + "\n Date age  }");
    GrailsDomainClass domainClass = new DefaultGrailsDomainClass(dc);

    generator.generateViews(domainClass, "test");

    assertTrue(new File("test/grails-app/views/test/show.gsp").exists());
    assertTrue(new File("test/grails-app/views/test/list.gsp").exists());
    assertTrue(new File("test/grails-app/views/test/edit.gsp").exists());
    assertTrue(new File("test/grails-app/views/test/create.gsp").exists());
  }
  public void testDecoratedByApplicationConvention() throws Exception {
    GrailsWebRequest webRequest = buildMockRequest();
    MockApplicationContext appCtx = (MockApplicationContext) webRequest.getApplicationContext();
    appCtx.registerMockResource(
        "WEB-INF/grails-app/views/layouts/application.gsp",
        "<html><body><h1>Default Layout</h1><g:layoutBody /></body></html>");

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "orders/list");
    ServletContext context = webRequest.getServletContext();
    GroovyClassLoader gcl = new GroovyClassLoader();

    // create mock controller
    GroovyObject controller =
        (GroovyObject)
            gcl.parseClass(
                    "class FooController {\n"
                        + "def controllerName = 'foo'\n"
                        + "def actionUri = '/foo/fooAction'\n"
                        + "}")
                .newInstance();

    request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller);
    GrailsLayoutDecoratorMapper m = new GrailsLayoutDecoratorMapper();
    Config c = new Config(new MockServletConfig(context));
    m.init(c, null, null);
    HTMLPageParser parser = new HTMLPageParser();
    String html = "<html><head><title>Foo title</title></head><body>here is the body</body></html>";

    Page page = parser.parse(html.toCharArray());
    Decorator d = m.getDecorator(request, page);
    assertNotNull(d);
    assertEquals("/WEB-INF/grails-app/views/layouts/application.gsp", d.getPage());
    assertEquals("application", d.getName());
  }
Beispiel #13
0
  private Class<?> createGroovyClass(String filename)
      throws CompilationFailedException, IOException {
    GroovyClassLoader gcl = new GroovyClassLoader();

    String file = System.getProperty("opennms.home") + "/etc/selenium/" + filename;
    System.err.println("File name: " + file);
    return gcl.parseClass(new File(file));
  }
  public void testIsDomainClass() {

    GroovyClassLoader gcl = new GroovyClassLoader();
    Class<?> c = gcl.parseClass("class Test { Long id;Long version;}\n");

    ArtefactHandler handler = new DomainClassArtefactHandler();
    assertTrue(handler.isArtefact(c));
  }
  public void testGenerateController() throws Exception {
    GrailsTemplateGenerator generator;

    GroovyClassLoader gcl = new GroovyClassLoader(Thread.currentThread().getContextClassLoader());

    generator = new DefaultGrailsTemplateGenerator();

    Class dc = gcl.parseClass("class Test { \n Long id;\n  Long version;  }");
    GrailsDomainClass domainClass = new DefaultGrailsDomainClass(dc);

    File generatedFile = new File("test/grails-app/controllers/TestController.groovy");
    if (generatedFile.exists()) {
      generatedFile.delete();
    }

    StringWriter sw = new StringWriter();
    generator.generateController(domainClass, sw);

    String text = sw.toString();

    Class controllerClass = gcl.parseClass(text);
    BeanWrapper bean = new BeanWrapperImpl(controllerClass.newInstance());

    assertEquals("TestController", controllerClass.getName());

    assertTrue(bean.isReadableProperty("list"));
    assertTrue(bean.isReadableProperty("update"));
    assertTrue(bean.isReadableProperty("create"));
    assertTrue(bean.isReadableProperty("list"));
    assertTrue(bean.isReadableProperty("show"));
    assertTrue(bean.isReadableProperty("edit"));
    assertTrue(bean.isReadableProperty("delete"));

    Object propertyValue =
        GrailsClassUtils.getStaticPropertyValue(controllerClass, "allowedMethods");
    assertTrue("allowedMethods property was the wrong type", propertyValue instanceof Map);
    Map map = (Map) propertyValue;
    assertTrue("allowedMethods did not contain the delete action", map.containsKey("delete"));
    assertTrue("allowedMethods did not contain the save action", map.containsKey("save"));
    assertTrue("allowedMethods did not contain the update action", map.containsKey("update"));

    assertEquals("allowedMethods had incorrect value for delete action", "POST", map.get("delete"));
    assertEquals("allowedMethods had incorrect value for save action", "POST", map.get("save"));
    assertEquals("allowedMethods had incorrect value for update action", "POST", map.get("update"));
  }
Beispiel #16
0
 /**
  * Called when one of the monitored files are created, deleted or modified.
  *
  * @param file File which has been changed.
  */
 public void fileChanged(File file) throws IOException {
   try {
     GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader());
     Class groovyClass = loader.parseClass(new GroovyCodeSource(file));
     component = (GroovyObject) groovyClass.newInstance();
   } catch (Exception e) {
     throw new IOException("Failed to reload groovy script: " + e.getMessage());
   }
 }
 /**
  * Parses the groovy script into a class. We store the Class instead of the script proper so that
  * it doesn't invoke race conditions on multiple executions of the script.
  */
 private void createGroovyClass() {
   try {
     GroovyClassLoader loader = new GroovyClassLoader(getClassLoader());
     InputStream scriptIs = getScriptInputStream();
     GroovyCodeSource groovyCodeSource =
         new GroovyCodeSource(scriptIs, "nanocontainer.groovy", "groovyGeneratedForNanoContainer");
     scriptClass = loader.parseClass(groovyCodeSource);
   } catch (CompilationFailedException e) {
     throw new GroovyCompilationException("Compilation Failed '" + e.getMessage() + "'", e);
   } catch (IOException e) {
     throw new NanoContainerMarkupException(e);
   }
 }
 @SuppressWarnings("rawtypes")
 public List evaluateMappings(Resource resource) {
   InputStream inputStream = null;
   try {
     inputStream = resource.getInputStream();
     return evaluateMappings(classLoader.parseClass(DefaultGroovyMethods.getText(inputStream)));
   } catch (IOException e) {
     throw new UrlMappingException(
         "Unable to read mapping file [" + resource.getFilename() + "]: " + e.getMessage(), e);
   } finally {
     IOUtils.closeQuietly(inputStream);
   }
 }
 /**
  * Creates a new instance of PolicyEnforcementLayer.
  *
  * @param upperLayer The upper layer (normally Tuple Space layer)
  * @param policy The policy to be enforced
  * @throws DepSpaceException If policy enforcer can not be instantiated
  */
 @SuppressWarnings("rawtypes")
 public PolicyEnforcementLayer(DepSpaceServer upperLayer, String policy) throws DepSpaceException {
   this.upperLayer = upperLayer;
   GroovyClassLoader classLoader;
   classLoader = new GroovyClassLoader(getClass().getClassLoader());
   try {
     Class policyClass = classLoader.parseClass(policy);
     this.policyEnforcer = (PolicyEnforcer) policyClass.newInstance();
     this.policyEnforcer.setLayer(this);
   } catch (Exception e) {
     throw new DepSpaceException("Cannot instantiate policy enforcer: " + e);
   }
 }
Beispiel #20
0
  @SuppressWarnings("unchecked")
  public Class<GroovyParserRecipe> setupGroovyScript(final String recipePath) {

    InputStreamReader reader =
        new InputStreamReader(TestELFGML.class.getResourceAsStream(recipePath));

    GroovyCodeSource codeSource = new GroovyCodeSource(reader, recipePath, ".");

    Class<GroovyParserRecipe> recipeClazz =
        (Class<GroovyParserRecipe>) gcl.parseClass(codeSource, true);

    return recipeClazz;
  }
 /* (non-Javadoc)
  * @see org.codehaus.groovy.grails.plugins.AbstractGrailsPlugin#refresh()
  */
 @Override
 public void refresh() {
   // do nothing
   Resource descriptor = getDescriptor();
   if (application != null && descriptor != null) {
     ClassLoader parent = application.getClassLoader();
     GroovyClassLoader gcl = new GroovyClassLoader(parent);
     try {
       initialisePlugin(gcl.parseClass(descriptor.getFile()));
     } catch (Exception e) {
       LOG.error("Error refreshing plugin: " + e.getMessage(), e);
     }
   }
 }
  /** Test that static constraints work */
  @SuppressWarnings("rawtypes")
  public void testNullableConstraint() throws Exception {
    String bookClassSource =
        "package org.codehaus.groovy.grails.validation\n"
            + "class Book {\n"
            + "   Long id\n"
            + "   Long version\n"
            + "   String title\n"
            + "   String description\n"
            + "   Author author\n"
            + "   Author assistent\n"
            + "   Set chapters\n"
            + "   Map remarks\n"
            + "   static hasMany = [chapters:Chapter]\n"
            + "   static constraints = {\n"
            + "      description(nullable: true)\n"
            + "      assistent(nullable: true)\n"
            + "   }\n"
            + "}\n"
            + "class Author {\n"
            + "   Long id\n"
            + "   Long version\n"
            + "   String name\n"
            + "}\n"
            + "class Chapter {\n"
            + "   Long id\n"
            + "   Long version\n"
            + "   String text\n"
            + "}";

    GroovyClassLoader gcl = new GroovyClassLoader();

    DefaultGrailsDomainClass bookClass =
        new DefaultGrailsDomainClass(gcl.parseClass(bookClassSource, "Book"));

    Map constraints = bookClass.getConstrainedProperties();
    Constrained p = (Constrained) constraints.get("title");
    assertFalse("Title property should be required", p.isNullable());
    p = (Constrained) constraints.get("description");
    assertTrue("Description property should be optional", p.isNullable());
    p = (Constrained) constraints.get("author");
    assertFalse("Author property should be required", p.isNullable());
    p = (Constrained) constraints.get("assistent");
    assertTrue("Assistent property should be optional", p.isNullable());
    // Test that Collections and Maps are nullable by default
    p = (Constrained) constraints.get("chapters");
    assertTrue("Chapters property should be optional", p.isNullable());
    p = (Constrained) constraints.get("remarks");
    assertTrue("Remarks property should be optional", p.isNullable());
  }
  public void testDomainClassBinding() {
    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "public class BinderTestClass {\n"
                    + "    Long id; \n"
                    + "    Long version; \n"
                    + "\n"
                    + "    String firstName; \n"
                    + "    String lastName; \n"
                    + "    String comment; \n"
                    + "    Integer age;\n"
                    + "    boolean active = true"
                    + "\n"
                    + "    static constraints = {\n"
                    + "        firstName(nullable:true,size:4..15)\n"
                    + "        lastName(nullable:false)\n"
                    + "        age(nullable:true)\n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config = getDomainConfig(cl, cl.getLoadedClasses());

    // Test database mappings
    PersistentClass persistentClass = config.getClassMapping("BinderTestClass");
    assertTrue(
        "Property [firstName] must be optional in db mapping",
        persistentClass.getProperty("firstName").isOptional());
    assertFalse(
        "Property [lastName] must be required in db mapping",
        persistentClass.getProperty("lastName").isOptional());
    // Property must be required by default
    assertFalse(
        "Property [comment] must be required in db mapping",
        persistentClass.getProperty("comment").isOptional());

    // Test properties
    assertTrue(
        "Property [firstName] must be optional",
        domainClass.getPropertyByName("firstName").isOptional());
    assertFalse(
        "Property [lastName] must be optional",
        domainClass.getPropertyByName("lastName").isOptional());
    assertFalse(
        "Property [comment] must be required",
        domainClass.getPropertyByName("comment").isOptional());
    assertTrue(
        "Property [age] must be optional", domainClass.getPropertyByName("age").isOptional());
  }
 /** Evaluate an expression. */
 public Object eval(String source, int lineNo, int columnNo, Object script) throws BSFException {
   try {
     Class scriptClass = evalScripts.get(script);
     if (scriptClass == null) {
       scriptClass = loader.parseClass(script.toString(), source);
       evalScripts.put(script, scriptClass);
     } else {
       LOG.fine("eval() - Using cached script...");
     }
     // can't cache the script because the context may be different.
     // but don't bother loading parsing the class again
     Script s = InvokerHelper.createScript(scriptClass, context);
     return s.run();
   } catch (Exception e) {
     throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e);
   }
 }
  /** Execute a script. */
  public void exec(String source, int lineNo, int columnNo, Object script) throws BSFException {
    try {
      //          shell.run(script.toString(), source, EMPTY_ARGS);

      Class scriptClass = execScripts.get(script);
      if (scriptClass == null) {
        scriptClass = loader.parseClass(script.toString(), source);
        execScripts.put(script, scriptClass);
      } else {
        LOG.fine("exec() - Using cached version of class...");
      }
      InvokerHelper.invokeMethod(scriptClass, "main", EMPTY_ARGS);
    } catch (Exception e) {
      LOG.log(Level.WARNING, "BSF trace", e);
      throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e);
    }
  }
Beispiel #26
0
 /**
  * Parses a script
  *
  * @param clazzName
  * @param sourceCode
  * @return
  */
 public String parseScript(String clazzName, String sourceCode) {
   String compilationError = null;
   int lastIndexOf = clazzName.lastIndexOf(".");
   String codeBase = clazzName;
   if (lastIndexOf != -1) {
     codeBase = clazzName.substring(0, lastIndexOf);
   }
   GroovyCodeSource groovyCodeSource = new GroovyCodeSource(sourceCode, clazzName, codeBase);
   try {
     Class<?> parsedClass = groovyClassLoader.parseClass(groovyCodeSource, false);
     availableClasses.put(clazzName, parsedClass);
   } catch (CompilationFailedException e) {
     compilationError = "Compilation for " + clazzName + " failed with " + e.getMessage();
     LOGGER.warn(compilationError);
   } catch (Exception ex) {
     compilationError = "Parsing class " + clazzName + " failed with " + ex.getMessage();
     LOGGER.warn(compilationError);
   }
   return compilationError;
 }
  @SuppressWarnings("rawtypes")
  private void ensureConstraintsPresent(
      String[] classSource, int classIndexToTest, int constraintCount) throws Exception {
    // We need to do a real test here to make sure
    GroovyClassLoader gcl = new GroovyClassLoader();
    Class[] classes = new Class[classSource.length];
    for (int i = 0; i < classSource.length; i++) {
      classes[i] = gcl.parseClass(classSource[i]);
    }

    DefaultGrailsDomainClass domainClass = new DefaultGrailsDomainClass(classes[classIndexToTest]);

    Map constraints = domainClass.getConstrainedProperties();

    ConstrainedProperty p = (ConstrainedProperty) constraints.get("name");
    Collection cons = p.getAppliedConstraints();

    assertEquals(
        "Incorrect number of constraints extracted: " + constraints, constraintCount, cons.size());
  }
  @SuppressWarnings({"rawtypes"})
  public Response createCatalogEntryFromGroovyCode(String groovyCode) {
    ClassLoader parent = getCatalog().getRootClassLoader();
    GroovyClassLoader loader = new GroovyClassLoader(parent);

    Class clazz = loader.parseClass(groovyCode);

    if (AbstractEntity.class.isAssignableFrom(clazz)) {
      CatalogItem<?> item = getCatalog().addItem(clazz);
      log.info("REST created " + item);
      return Response.created(URI.create("entities/" + clazz.getName())).build();

    } else if (AbstractPolicy.class.isAssignableFrom(clazz)) {
      CatalogItem<?> item = getCatalog().addItem(clazz);
      log.info("REST created " + item);
      return Response.created(URI.create("policies/" + clazz.getName())).build();
    }

    throw WebResourceUtils.preconditionFailed(
        "Unsupported type superclass " + clazz.getSuperclass() + "; expects Entity or Policy");
  }
Beispiel #29
0
 /**
  * Returns a {@link GroovyClassLoader} that contains all scripts from the database. This method is
  * synchronized, so you can call scripts even though they are just being reloaded from the
  * database.
  */
 private void getGroovyScripts() {
   try {
     InputStream grooving = null;
     StringBuilder sb = new StringBuilder();
     try {
       URL groovyURL =
           ApplicationBean.getInstance()
               .getServletContext()
               .getResource("/WEB-INF/classes/plugins/groovy/system/DefaultActionHandler.groovy");
       grooving = groovyURL.openStream();
       byte[] buffer = new byte[2048];
       int length;
       while ((length = grooving.read(buffer)) != -1) {
         sb.append(new String(buffer, 0, length));
       }
       grooving.close();
     } catch (Exception exx) {
       LOGGER.warn(
           "Could not load "
               + Constants.getGroovyURL()
               + "DefaultActionHandler.groovy. This is normal for the test environment.");
     }
     // get the sources from DB and parse them...
     Class<?> parsedClass = groovyClassLoader.parseClass(sb.toString());
     availableClasses.put("plugins.groovy.system.DefaultActionHandler", parsedClass);
     // class names to get on database...
     List<TScriptsBean> scriptBeansList = ScriptAdminBL.getAllScripts();
     if (scriptBeansList != null) {
       for (TScriptsBean scriptsBean : scriptBeansList) {
         Integer scriptType = scriptsBean.getScriptType();
         if (scriptType == null || !scriptType.equals(TScriptsBean.SCRIPT_TYPE.PARAMETER_SCRIPT)) {
           parseScript(scriptsBean.getClazzName(), scriptsBean.getSourceCode());
         }
       }
     }
   } catch (Exception ex) {
     LOGGER.warn("Problem loading Groovy scripts. This is normal for the test environment.");
   }
 }
Beispiel #30
0
 /**
  * Loads the script for this component
  *
  * @param script the script file location
  * @throws InitialisationException if anything fails while starting up
  */
 protected void loadInterpreter(String script) throws InitialisationException {
   try {
     File f = new File(script);
     if (f.exists()) {
       fileChanged(f);
     } else {
       GroovyClassLoader loader =
           new GroovyClassLoader(Thread.currentThread().getContextClassLoader());
       URL url = ClassHelper.getResource(script, getClass());
       if (url == null) {
         throw new InitialisationException(
             new Message(Messages.FAILED_LOAD_X, "Groovy script: " + script), this);
       }
       Class groovyClass = loader.parseClass(new GroovyCodeSource(url));
       component = (GroovyObject) groovyClass.newInstance();
     }
   } catch (Exception e) {
     if (e instanceof InitialisationException) throw (InitialisationException) e;
     throw new InitialisationException(
         new Message(Messages.FAILED_LOAD_X, "Groovy component"), e, this);
   }
 }