groovy.util.ResourceException Java Examples

The following examples show how to use groovy.util.ResourceException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClasspathResourceConnector.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public URLConnection getResourceConnection(String name) throws ResourceException {
   try {
      if(this.directory != null) {
         name = this.directory + name;
      }

      URL conn = loader.getResource(name);
      if(conn == null) {
         if (name.startsWith("file:")) {
            URI fileUri = URI.create(name);
            File file = new File(fileUri);
            if (file.isFile()) {
               conn = fileUri.toURL();
               return conn.openConnection();
            }
         }
         throw new ResourceException("Resource not found [classpath:/" + name + "]");
      }
      return conn.openConnection();
   }
   catch (IOException e) {
      throw new ResourceException("Unable to open classpath:/" + name, e);
   }
}
 
Example #2
Source File: LibvirtKvmAgentHook.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public Object handle(Object arg) throws ResourceException, ScriptException {
    if (!isInitialized()) {
        s_logger.warn("Groovy scripting engine is not initialized. Data transformation skipped.");
        return arg;
    }

    GroovyObject cls = (GroovyObject) this.gse.run(this.script, binding);
    if (null == cls) {
        s_logger.warn("Groovy object is not received from script '" + this.script + "'.");
        return arg;
    } else {
        Object[] params = {s_logger, arg};
        try {
            Object res = cls.invokeMethod(this.method, params);
            return res;
        } catch (MissingMethodExceptionNoStack e) {
            s_logger.error("Error occured when calling method from groovy script, {}", e);
            return arg;
        }
    }
}
 
Example #3
Source File: AbstractHttpServlet.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected String removeNamePrefix(String name) throws ResourceException {
    if (namePrefix == null) {
        generateNamePrefixOnce();
    }
    if (name.startsWith(namePrefix)) {//usualy name has text
        return name.substring(namePrefix.length());
    }
    return name;
}
 
Example #4
Source File: AbstractHttpServlet.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Interface method for ResourceContainer. This is used by the GroovyScriptEngine.
 */
public URLConnection getResourceConnection (String name) throws ResourceException {
    name = removeNamePrefix(name).replace('\\', '/');

    //remove the leading / as we are trying with a leading / now
    if (name.startsWith("WEB-INF/groovy/")) {
        name = name.substring(15);//just for uniformity
    } else if (name.startsWith("/")) {
        name = name.substring(1);
    }

    /*
    * Try to locate the resource and return an opened connection to it.
    */
    try {
        URL url = servletContext.getResource('/' + name);
        if (url == null) {
            url = servletContext.getResource("/WEB-INF/groovy/" + name);
        }
        if (url == null) {
            throw new ResourceException("Resource \"" + name + "\" not found!");
        }
        return url.openConnection();
    } catch (IOException e) {
        throw new ResourceException("Problems getting resource named \"" + name + "\"!", e);
    }
}
 
Example #5
Source File: MyJointCompilationApp.java    From tutorials with MIT License 5 votes vote down vote up
private void addWithGroovyScriptEngine(int x, int y) throws IllegalAccessException,
  InstantiationException, ResourceException, ScriptException {
    Class<GroovyObject> calcClass = engine.loadScriptByName("CalcMath.groovy");
    GroovyObject calc = calcClass.newInstance();
    //WARNING the following will throw a ClassCastException
    //((CalcMath)calc).calcSum(1,2);
    Object result = calc.invokeMethod("calcSum", new Object[] { x, y });
    LOG.info("Result of CalcMath.calcSum() method is {}", result);
}
 
Example #6
Source File: MyJointCompilationApp.java    From tutorials with MIT License 5 votes vote down vote up
private void addWithDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException,
  ResourceException, ScriptException, javax.script.ScriptException {
    LOG.info("Invocation of a dynamic groovy script...");
    addWithGroovyShell(5, 10);
    LOG.info("Invocation of the run method of a dynamic groovy script...");
    addWithGroovyShellRun();
    LOG.info("Invocation of a dynamic groovy class loaded with GroovyClassLoader...");
    addWithGroovyClassLoader(10, 30);
    LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine...");
    addWithGroovyScriptEngine(15, 0);
    LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine JSR223...");
    addWithEngineFactory(5, 6);
}
 
Example #7
Source File: MyJointCompilationApp.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
  ResourceException, ScriptException, IOException, javax.script.ScriptException {
    MyJointCompilationApp myJointCompilationApp = new MyJointCompilationApp();
    LOG.info("Example of addition operation via Groovy scripts integration with Java.");
    myJointCompilationApp.addWithStaticCompiledClasses();
    myJointCompilationApp.addWithDynamicCompiledClasses();
}
 
Example #8
Source File: GroovyScriptFactory.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Script getScript(String url) throws ScriptException {
    return siteContext.getCacheTemplate().getObject(siteContext.getContext(), () -> {
        try {
            return new GroovyScript(url,scriptEngine.loadScriptByName(url), globalVariables);
        } catch (Exception e) {
            Throwable cause = e.getCause();
            if (e instanceof ResourceException && cause instanceof FileNotFoundException) {
                throw new ScriptNotFoundException(cause.getMessage(), cause);
            } else {
                throw new ScriptException(e.getMessage(), e);
            }
        }
    }, url, CACHE_CONST_KEY_ELEM_SCRIPT);
}
 
Example #9
Source File: ContentStoreResourceConnector.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public URLConnection getResourceConnection(String name) throws ResourceException {
    try {
        return urlStreamHandler.createUrl(name).openConnection();
    } catch (Exception e) {
        throw new ResourceException("Unable to open URL connection to '" + name + "'", e);
    }
}
 
Example #10
Source File: GroovyServiceSpec.java    From termsuite-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testMatch() throws IOException, ResourceException, ScriptException {
	Assert.assertTrue(expr("s[0].lemma == t[1].lemma", term2, term3));
	Assert.assertFalse(expr("s[0].lemma == t[1].lemma", term1, term3));
	Assert.assertFalse(expr("s[0].lemma == t[1].lemma", term1, term2));
}
 
Example #11
Source File: GroovyEvalFunc.java    From spork with Apache License 2.0 4 votes vote down vote up
public GroovyEvalFunc(String path, String namespace, String methodName, Object target) throws IOException {
  String fqmn = "".equals(namespace) ? methodName : namespace + ScriptEngine.NAMESPACE_SEPARATOR + methodName;

  Class c = scriptClasses.get(path);

  if (null == c) {
    try {
      c = GroovyScriptEngine.getEngine().loadScriptByName(new File(path).toURI().toString());
    } catch (ScriptException se) {
      throw new IOException(se);
    } catch (ResourceException re) {
      throw new IOException(re);
    }
  }

  scriptClasses.put(path, c);

  Method[] methods = c.getMethods();

  int matches = 0;

  for (Method m : methods) {
    if (m.getName().equals(methodName)) {
      this.method = m;
      matches++;
    }
  }

  if (null == this.method) {
    throw new IOException("Method " + methodName + " was not found in '" + path + "'");
  }

  if (matches > 1) {
    throw new IOException("There are " + matches + " methods with name '" + methodName + "', please make sure method names are unique within the Groovy class.");
  }

  //
  // Extract schema
  //

  Annotation[] annotations = this.method.getAnnotations();

  for (Annotation annotation : annotations) {
    if (annotation.annotationType().equals(OutputSchemaFunction.class)) {
      this.schemaFunction = new GroovyEvalFuncObject(path, namespace, ((OutputSchemaFunction) annotation).value());
      break;
    } else if (annotation.annotationType().equals(OutputSchema.class)) {
      this.schema = Utils.getSchemaFromString(((OutputSchema) annotation).value());
      break;
    }
  }

  //
  // For static method, invocation target is null, for non
  // static method, create/set invocation target unless passed
  // to the constructor
  //

  if (!Modifier.isStatic(this.method.getModifiers())) {
    if (null != target) {
      this.invocationTarget = target;
    } else {
      try {
        this.invocationTarget = c.newInstance();
      } catch (InstantiationException ie) {
        throw new IOException(ie);
      } catch (IllegalAccessException iae) {
        throw new IOException(iae);
      }
    }
  }
}
 
Example #12
Source File: LibvirtKvmAgentHookTest.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public void testTransform() throws IOException, ResourceException, ScriptException {
    LibvirtKvmAgentHook t = new LibvirtKvmAgentHook(dir, script, method);
    assertEquals(t.isInitialized(), true);
    String result = (String)t.handle(source);
    assertEquals(result, source + source);
}
 
Example #13
Source File: LibvirtKvmAgentHookTest.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public void testWrongMethod() throws IOException, ResourceException, ScriptException {
    LibvirtKvmAgentHook t = new LibvirtKvmAgentHook(dir, script, "methodX");
    assertEquals(t.isInitialized(), true);
    assertEquals(t.handle(source), source);
}
 
Example #14
Source File: LibvirtKvmAgentHookTest.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public void testNullMethod() throws IOException, ResourceException, ScriptException {
    LibvirtKvmAgentHook t = new LibvirtKvmAgentHook(dir, script, methodNull);
    assertEquals(t.isInitialized(), true);
    assertEquals(t.handle(source), null);
}
 
Example #15
Source File: LibvirtKvmAgentHookTest.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public void testWrongScript() throws IOException, ResourceException, ScriptException {
    LibvirtKvmAgentHook t = new LibvirtKvmAgentHook(dir, "wrong-script.groovy", method);
    assertEquals(t.isInitialized(), false);
    assertEquals(t.handle(source), source);
}
 
Example #16
Source File: LibvirtKvmAgentHookTest.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public void testWrongDir() throws IOException, ResourceException, ScriptException {
    LibvirtKvmAgentHook t = new LibvirtKvmAgentHook("/" + UUID.randomUUID().toString() + "-dir", script, method);
    assertEquals(t.isInitialized(), false);
    assertEquals(t.handle(source), source);
}