org.codehaus.commons.compiler.CompileException Java Examples

The following examples show how to use org.codehaus.commons.compiler.CompileException. 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: UserDefinedJavaClassMeta.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "unchecked" )
public void cookClasses() {
  cookErrors.clear();
  ClassLoader clsloader = null;
  for ( UserDefinedJavaClassDef def : getDefinitions() ) {
    if ( def.isActive() ) {
      try {
        Class<?> cookedClass = cookClass( def, clsloader );
        clsloader = cookedClass.getClassLoader();
        if ( def.isTransformClass() ) {
          cookedTransformClass = (Class<TransformClassBase>) cookedClass;
        }

      } catch ( Throwable e ) {
        CompileException exception = new CompileException( e.getMessage(), null );
        exception.setStackTrace( new StackTraceElement[] {} );
        cookErrors.add( exception );
      }
    }
  }
  changed = false;
}
 
Example #2
Source File: RexExecutable.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static Function1<DataContext, Object[]> compile(String code,
    Object reason) {
  try {
    final ClassBodyEvaluator cbe = new ClassBodyEvaluator();
    cbe.setClassName(GENERATED_CLASS_NAME);
    cbe.setExtendedClass(Utilities.class);
    cbe.setImplementedInterfaces(new Class[] {Function1.class, Serializable.class});
    cbe.setParentClassLoader(RexExecutable.class.getClassLoader());
    cbe.cook(new Scanner(null, new StringReader(code)));
    Class c = cbe.getClazz();
    //noinspection unchecked
    final Constructor<Function1<DataContext, Object[]>> constructor =
        c.getConstructor();
    return constructor.newInstance();
  } catch (CompileException | IOException | InstantiationException
      | IllegalAccessException | InvocationTargetException
      | NoSuchMethodException e) {
    throw new RuntimeException("While compiling " + reason, e);
  }
}
 
Example #3
Source File: HiveEnumerableInterpretable.java    From marble with Apache License 2.0 6 votes vote down vote up
static Bindable getBindable(ClassDeclaration expr, String s, int fieldCount)
    throws CompileException, IOException {
  ICompilerFactory compilerFactory;
  try {
    compilerFactory = CompilerFactoryFactory.getDefaultCompilerFactory();
  } catch (Exception e) {
    throw new IllegalStateException(
        "Unable to instantiate java compiler", e);
  }
  IClassBodyEvaluator cbe = compilerFactory.newClassBodyEvaluator();
  cbe.setClassName(expr.name);
  cbe.setExtendedClass(Utilities.class);
  cbe.setImplementedInterfaces(
      fieldCount == 1
          ? new Class[]{Bindable.class, Typed.class}
          : new Class[]{ArrayBindable.class});
  cbe.setParentClassLoader(EnumerableInterpretable.class.getClassLoader());
  if (CalcitePrepareImpl.DEBUG) {
    // Add line numbers to the generated janino class
    cbe.setDebuggingInformation(true, true, true);
  }
  return (Bindable) cbe.createInstance(new StringReader(s));
}
 
Example #4
Source File: UserDefinedJavaClassMeta.java    From hop with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "unchecked" )
public void cookClasses() {
  cookErrors.clear();
  ClassLoader clsloader = null;
  for ( UserDefinedJavaClassDef def : getDefinitions() ) {
    if ( def.isActive() ) {
      try {
        Class<?> cookedClass = cookClass( def, clsloader );
        clsloader = cookedClass.getClassLoader();
        if ( def.isTransformClass() ) {
          cookedTransformClass = (Class<TransformClassBase>) cookedClass;
        }

      } catch ( Throwable e ) {
        CompileException exception = new CompileException( e.getMessage(), null );
        exception.setStackTrace( new StackTraceElement[] {} );
        cookErrors.add( exception );
      }
    }
  }
  changed = false;
}
 
Example #5
Source File: DremioDiagnosticListener.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
  if (diagnostic.getKind() == javax.tools.Diagnostic.Kind.ERROR) {
    String message = diagnostic.toString() + " (" + diagnostic.getCode() + ")";
    logger.error(message);
    Location loc = new Location( //
        diagnostic.getSource().toString(), //
        (short) diagnostic.getLineNumber(), //
        (short) diagnostic.getColumnNumber() //
    );
    // Wrap the exception in a RuntimeException, because "report()"
    // does not declare checked exceptions.
    throw new RuntimeException(new CompileException(message, loc));
  } else if (logger.isTraceEnabled()) {
    logger.trace(diagnostic.toString() + " (" + diagnostic.getCode() + ")");
  }
}
 
Example #6
Source File: RexExecutable.java    From Quicksql with MIT License 6 votes vote down vote up
private static Function1<DataContext, Object[]> compile(String code,
    Object reason) {
  try {
    final ClassBodyEvaluator cbe = new ClassBodyEvaluator();
    cbe.setClassName(GENERATED_CLASS_NAME);
    cbe.setExtendedClass(Utilities.class);
    cbe.setImplementedInterfaces(new Class[] {Function1.class, Serializable.class});
    cbe.setParentClassLoader(RexExecutable.class.getClassLoader());
    cbe.cook(new Scanner(null, new StringReader(code)));
    Class c = cbe.getClazz();
    //noinspection unchecked
    final Constructor<Function1<DataContext, Object[]>> constructor =
        c.getConstructor();
    return constructor.newInstance();
  } catch (CompileException | IOException | InstantiationException
      | IllegalAccessException | InvocationTargetException
      | NoSuchMethodException e) {
    throw new RuntimeException("While compiling " + reason, e);
  }
}
 
Example #7
Source File: JaninoClassCompiler.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
protected ClassBytes[] getByteCode(final ClassNames className, final String sourcecode, boolean debug)
    throws CompileException, IOException, ClassNotFoundException, ClassTransformationException {
  StringReader reader = new StringReader(sourcecode);
  Scanner scanner = new Scanner((String) null, reader);
  Java.CompilationUnit compilationUnit = new Parser(scanner).parseCompilationUnit();
  ClassFile[] classFiles = new UnitCompiler(compilationUnit, compilationClassLoader)
                                .compileUnit(debug, debug, debug);

  ClassBytes[] byteCodes = new ClassBytes[classFiles.length];
  for(int i = 0; i < classFiles.length; i++){
    ClassFile file = classFiles[i];
    byteCodes[i] = new ClassBytes(file.getThisClassName(), file.toByteArray());
  }
  return byteCodes;
}
 
Example #8
Source File: AbstractClassCompiler.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
  public ClassBytes[] getClassByteCode(ClassNames className, String sourceCode, boolean debug)
      throws CompileException, IOException, ClassNotFoundException, ClassTransformationException {
    if (getLogger().isDebugEnabled()) {
      getLogger().debug("Compiling (source size={}):\n{}", DremioStringUtils.readable(sourceCode.length()),
          debug ? prefixLineNumbers(sourceCode) : debug);

/* uncomment this to get a dump of the generated source in /tmp
      // This can be used to write out the generated operator classes for debugging purposes
      // TODO: should these be put into a directory named with the query id and/or fragment id
      final int lastSlash = className.slash.lastIndexOf('/');
      final File dir = new File("/tmp", className.slash.substring(0, lastSlash));
      dir.mkdirs();
      final File file = new File(dir, className.slash.substring(lastSlash + 1) + ".java");
      final FileWriter writer = new FileWriter(file);
      writer.write(sourceCode);
      writer.close();
*/
    }
    return getByteCode(className, sourceCode, debug);
  }
 
Example #9
Source File: FunctionInitializer.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private CompilationUnit get(Class<?> c) throws IOException {
    URL u = getSourceURL(c);
    try (Reader reader = Resources.asCharSource(u, UTF_8).openStream()) {
      String body = CharStreams.toString(reader);

      // TODO: Hack to remove annotations so Janino doesn't choke. Need to reconsider this problem...
      body = body.replaceAll("@\\w+(?:\\([^\\\\]*?\\))?", "");
      for(Replacement r : REPLACERS){
        body = r.apply(body);
      }
//       System.out.println("original");
      // System.out.println(body);;
      // System.out.println("decompiled");
      // System.out.println(decompile(c));

      try {
        return new Parser(new Scanner(null, new StringReader(body))).parseCompilationUnit();
      } catch (CompileException e) {
        logger.warn("Failure while parsing function class:\n{}", body, e);
        return null;
      }

    }

  }
 
Example #10
Source File: AbstractClassCompiler.java    From Bats with Apache License 2.0 6 votes vote down vote up
public byte[][] getClassByteCode(ClassNames className, String sourceCode)
      throws CompileException, IOException, ClassNotFoundException, ClassTransformationException {
    if (getLogger().isDebugEnabled()) {
      getLogger().debug("Compiling (source size={}):\n{}", DrillStringUtils.readable(sourceCode.length()), prefixLineNumbers(sourceCode));

/* uncomment this to get a dump of the generated source in /tmp
      // This can be used to write out the generated operator classes for debugging purposes
      // TODO: should these be put into a directory named with the query id and/or fragment id
      final int lastSlash = className.slash.lastIndexOf('/');
      final File dir = new File("/tmp", className.slash.substring(0, lastSlash));
      dir.mkdirs();
      final File file = new File(dir, className.slash.substring(lastSlash + 1) + ".java");
      final FileWriter writer = new FileWriter(file);
      writer.write(sourceCode);
      writer.close();
*/
    }
    return getByteCode(className, sourceCode);
  }
 
Example #11
Source File: ClassCompilerSelector.java    From Bats with Apache License 2.0 6 votes vote down vote up
byte[][] getClassByteCode(ClassNames className, String sourceCode)
      throws CompileException, ClassNotFoundException, ClassTransformationException, IOException {

    byte[][] bc = getCompiler(sourceCode).getClassByteCode(className, sourceCode);

    // Uncomment the following to save the generated byte codes.
    // Use the JDK javap command to view the generated code.
    // This is the code from the compiler before byte code manipulations.
    // For a similar block to display byte codes after manipulation,
    // see QueryClassLoader.

//    final File baseDir = new File( new File( System.getProperty("java.io.tmpdir") ), "classes" );
//    for ( int i = 0;  i < bc.length;  i++ ) {
//      File classFile = new File( baseDir, className.slash + i + ".class" );
//      classFile.getParentFile().mkdirs();
//      try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(classFile))) {
//        out.write(bc[i]);
//      }
//    }
//    System.out.println( "Classes saved to: " + baseDir.getAbsolutePath() );

    return bc;
  }
 
Example #12
Source File: BeamCalcRel.java    From beam with Apache License 2.0 6 votes vote down vote up
ScriptEvaluator compile() {
  ScriptEvaluator se = new ScriptEvaluator();
  se.setParameters(
      new String[] {outputSchemaParam.name, processContextParam.name, DataContext.ROOT.name},
      new Class[] {
        (Class) outputSchemaParam.getType(),
        (Class) processContextParam.getType(),
        (Class) DataContext.ROOT.getType()
      });
  try {
    se.cook(processElementBlock);
  } catch (CompileException e) {
    throw new UnsupportedOperationException(
        "Could not compile CalcFn: " + processElementBlock, e);
  }
  return se;
}
 
Example #13
Source File: RexToJavaCompiler.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the instance of the class defined in {@link ClassDeclaration}
 * @param expr Interface whose instance needs to be created.
 * @param s The java code that implements the interface which should be used to create the instance.
 * @return The object of the class which implements the interface {@link Expression} with the code that is passed as input.
 * @throws CompileException
 * @throws IOException
 */
static Expression getExpression(ClassDeclaration expr, String s) throws CompileException, IOException {
  ICompilerFactory compilerFactory;
  try {
    compilerFactory = CompilerFactoryFactory.getDefaultCompilerFactory();
  } catch (Exception e) {
    throw new IllegalStateException("Unable to instantiate java compiler", e);
  }
  IClassBodyEvaluator cbe = compilerFactory.newClassBodyEvaluator();
  cbe.setClassName(expr.name);
  cbe.setImplementedInterfaces(expr.implemented.toArray(new Class[expr.implemented.size()]));
  cbe.setParentClassLoader(RexToJavaCompiler.class.getClassLoader());
  cbe.setDebuggingInformation(true, true, true);

  return (org.apache.samza.sql.data.Expression) cbe.createInstance(new StringReader(s));
}
 
Example #14
Source File: DrillDiagnosticListener.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
  if (diagnostic.getKind() == javax.tools.Diagnostic.Kind.ERROR) {
    String message = diagnostic.toString() + " (" + diagnostic.getCode() + ")";
    logger.error(message);
    Location loc = new Location( //
        diagnostic.getSource().toString(), //
        (short) diagnostic.getLineNumber(), //
        (short) diagnostic.getColumnNumber() //
    );
    // Wrap the exception in a RuntimeException, because "report()"
    // does not declare checked exceptions.
    throw new RuntimeException(new CompileException(message, loc));
  } else if (logger.isTraceEnabled()) {
    logger.trace(diagnostic.toString() + " (" + diagnostic.getCode() + ")");
  }
}
 
Example #15
Source File: JaninoConnectionTest.java    From scriptella-etl with Apache License 2.0 6 votes vote down vote up
/**
 * This test creates a Janino connection that executes simple valid and invalid scripts.
 */
public void testScript() {
    JaninoConnection c = new JaninoConnection(new ConnectionParameters(new MockConnectionEl(), MockDriverContext.INSTANCE));
    field = 0;
    c.executeScript(new StringResource(JaninoConnectionTest.class.getName() + ".field=1;"), null);
    try {
        c.executeScript(new StringResource(JaninoConnectionTest.class.getName() + ".nosuchfield=1;"), null);
        fail("This script should fail");
    } catch (ProviderException e) {
        Throwable ne = e.getNativeException();
        assertTrue(ne instanceof CompileException);
        //OK
    }
    c.close();
    assertEquals(1, field);
}
 
Example #16
Source File: RexExecutable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static Function1<DataContext, Object[]> compile(String code,
    Object reason) {
  try {
    final ClassBodyEvaluator cbe = new ClassBodyEvaluator();
    cbe.setClassName(GENERATED_CLASS_NAME);
    cbe.setExtendedClass(Utilities.class);
    cbe.setImplementedInterfaces(new Class[] {Function1.class, Serializable.class});
    cbe.setParentClassLoader(RexExecutable.class.getClassLoader());
    cbe.cook(new Scanner(null, new StringReader(code)));
    Class c = cbe.getClazz();
    //noinspection unchecked
    final Constructor<Function1<DataContext, Object[]>> constructor =
        c.getConstructor();
    return constructor.newInstance();
  } catch (CompileException | IOException | InstantiationException
      | IllegalAccessException | InvocationTargetException
      | NoSuchMethodException e) {
    throw new RuntimeException("While compiling " + reason, e);
  }
}
 
Example #17
Source File: JaninoRexCompiler.java    From calcite with Apache License 2.0 6 votes vote down vote up
static Scalar getScalar(ClassDeclaration expr, String s)
    throws CompileException, IOException {
  ICompilerFactory compilerFactory;
  try {
    compilerFactory = CompilerFactoryFactory.getDefaultCompilerFactory();
  } catch (Exception e) {
    throw new IllegalStateException(
        "Unable to instantiate java compiler", e);
  }
  IClassBodyEvaluator cbe = compilerFactory.newClassBodyEvaluator();
  cbe.setClassName(expr.name);
  cbe.setImplementedInterfaces(new Class[]{Scalar.class});
  cbe.setParentClassLoader(JaninoRexCompiler.class.getClassLoader());
  if (CalciteSystemProperty.DEBUG.value()) {
    // Add line numbers to the generated janino class
    cbe.setDebuggingInformation(true, true, true);
  }
  return (Scalar) cbe.createInstance(new StringReader(s));
}
 
Example #18
Source File: TestClassCompilers.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testJaninoCompilation() throws IOException, ClassTransformationException, CompileException, ClassNotFoundException {
  try(URLClassLoader classLoader = new URLClassLoader(new URL[] { classes.toURI().toURL()}, null)) {
    JaninoClassCompiler janinoClassCompiler = new JaninoClassCompiler(classLoader);
    testCompilation(janinoClassCompiler);
  };
}
 
Example #19
Source File: TestClassCompilers.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testJDKCompilation() throws IOException, ClassTransformationException, CompileException, ClassNotFoundException {
  try(URLClassLoader classLoader = new URLClassLoader(new URL[] { classes.toURI().toURL()}, null)) {
    JDKClassCompiler jdkClassCompiler = JDKClassCompiler.newInstance(classLoader);
    testCompilation(jdkClassCompiler);
  };
}
 
Example #20
Source File: TaxiQuerySolution.java    From flink-training-exercises with Apache License 2.0 5 votes vote down vote up
private ExpressionEvaluator cookBooleanExpression(String expression) throws CompileException {
	ExpressionEvaluator ee = new ExpressionEvaluator();
	ee.setParameters(new String[] { "ride", "watermark" }, new Class[] { TaxiRide.class, long.class });
	ee.setExpressionType(boolean.class);
	ee.cook(expression);

	return ee;
}
 
Example #21
Source File: TaxiQueryExercise.java    From flink-training-exercises with Apache License 2.0 5 votes vote down vote up
private ExpressionEvaluator cookBooleanExpression(String expression) throws CompileException {
	ExpressionEvaluator ee = new ExpressionEvaluator();
	ee.setParameters(new String[] { "ride", "watermark" }, new Class[] { TaxiRide.class, long.class });
	ee.setExpressionType(boolean.class);
	ee.cook(expression);

	return ee;
}
 
Example #22
Source File: ClassCompilerSelector.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public ClassBytes[] getClassByteCode(ClassNames className, String sourceCode)
    throws CompileException, ClassNotFoundException, ClassTransformationException, IOException {
  OptionValue value = sessionOptions.getOption(JAVA_COMPILER_OPTION);
  CompilerPolicy policy = (value != null) ? CompilerPolicy.valueOf(value.getStringVal().toUpperCase()) : defaultPolicy;

  value = sessionOptions.getOption(JAVA_COMPILER_JANINO_MAXSIZE_OPTION);
  long janinoThreshold = (value != null) ? value.getNumVal() : defaultJaninoThreshold;

  value = sessionOptions.getOption(JAVA_COMPILER_DEBUG_OPTION);
  boolean debug = (value != null) ? value.getBoolVal() : defaultDebug;

  ClassCompiler classCompiler;
  if (jdkClassCompiler != null &&
      (policy == CompilerPolicy.JDK || (policy == CompilerPolicy.DEFAULT && sourceCode.length() > janinoThreshold))) {
    classCompiler = jdkClassCompiler;
  } else {
    classCompiler = janinoClassCompiler;
  }

  ClassBytes[] bc = classCompiler.getClassByteCode(className, sourceCode, debug);
  /*
   * final String baseDir = System.getProperty("java.io.tmpdir") + File.separator + classCompiler.getClass().getSimpleName();
   * File classFile = new File(baseDir + className.clazz);
   * classFile.getParentFile().mkdirs();
   * BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(classFile));
   * out.write(bc[0]);
   * out.close();
   */
  return bc;
}
 
Example #23
Source File: JDKClassCompiler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
protected ClassBytes[] getByteCode(final ClassNames className, final String sourceCode, boolean debug)
    throws CompileException, IOException, ClassNotFoundException {
  try {
    // Create one Java source file in memory, which will be compiled later.
    DremioJavaFileObject compilationUnit = new DremioJavaFileObject(className.dot, sourceCode);

    Iterable<String> compilerOptions = Iterables.concat(
        ImmutableList.of(debug ? "-g:source,lines,vars" : "-g:none"),
        defaultCompilerOptions
    );
    CompilationTask task = compiler.getTask(null, fileManager, listener, compilerOptions, null, Collections.singleton(compilationUnit));

    // Run the compiler.
    if(!task.call()) {
      throw new CompileException("Compilation failed", null);
    } else if (!compilationUnit.isCompiled()) {
      throw new ClassNotFoundException(className + ": Class file not created by compilation.");
    }
    // all good
    return compilationUnit.getByteCode();
  } catch (RuntimeException rte) {
    // Unwrap the compilation exception and throw it.
    Throwable cause = rte.getCause();
    if (cause != null) {
      cause = cause.getCause();
      if (cause instanceof CompileException) {
        throw (CompileException) cause;
      }
      if (cause instanceof IOException) {
        throw (IOException) cause;
      }
    }
    throw rte;
  }
}
 
Example #24
Source File: EnumerableInterpretable.java    From calcite with Apache License 2.0 5 votes vote down vote up
static Bindable getBindable(ClassDeclaration expr, String s, int fieldCount)
    throws CompileException, IOException, ExecutionException {
  ICompilerFactory compilerFactory;
  try {
    compilerFactory = CompilerFactoryFactory.getDefaultCompilerFactory();
  } catch (Exception e) {
    throw new IllegalStateException(
        "Unable to instantiate java compiler", e);
  }
  final IClassBodyEvaluator cbe = compilerFactory.newClassBodyEvaluator();
  cbe.setClassName(expr.name);
  cbe.setExtendedClass(Utilities.class);
  cbe.setImplementedInterfaces(
      fieldCount == 1
          ? new Class[] {Bindable.class, Typed.class}
          : new Class[] {ArrayBindable.class});
  cbe.setParentClassLoader(EnumerableInterpretable.class.getClassLoader());
  if (CalciteSystemProperty.DEBUG.value()) {
    // Add line numbers to the generated janino class
    cbe.setDebuggingInformation(true, true, true);
  }

  if (CalciteSystemProperty.BINDABLE_CACHE_MAX_SIZE.value() != 0) {
    StaticFieldDetector detector = new StaticFieldDetector();
    expr.accept(detector);
    if (!detector.containsStaticField) {
      return BINDABLE_CACHE.get(s, () -> (Bindable) cbe.createInstance(new StringReader(s)));
    }
  }
  return (Bindable) cbe.createInstance(new StringReader(s));
}
 
Example #25
Source File: ClassTransformer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private Class<?> getExtendedImplementationClass(
    final QueryClassLoader classLoader,
    final TemplateClassDefinition<?> templateDefinition,
    final String entireClass,
    final String materializedClassName) throws ClassTransformationException {

  try {
    final long t1 = System.nanoTime();
    final ClassSet set = new ClassSet(null, templateDefinition.getTemplateClassName(), materializedClassName);
    final ClassBytes[] implementationClasses = classLoader.getClassByteCode(set.generated, entireClass);

    long totalBytecodeSize = 0;
    for (ClassBytes clazz : implementationClasses) {
      totalBytecodeSize += clazz.getBytes().length;
      classLoader.injectByteCode(clazz.getName(), clazz.getBytes());
    }

    Class<?> c = classLoader.findClass(set.generated.dot);
    if (templateDefinition.getExternalInterface().isAssignableFrom(c)) {
      logger.debug("Done compiling (bytecode size={}, time:{} millis).", DremioStringUtils.readable(totalBytecodeSize), (System.nanoTime() - t1) / 1000000);
      return c;
    }

    throw new ClassTransformationException("The requested class did not implement the expected interface.");
  } catch (CompileException | IOException | ClassNotFoundException e) {
    throw new ClassTransformationException(String.format("Failure generating transformation classes for value: \n %s", entireClass), e);
  }
}
 
Example #26
Source File: PushDownExecutor.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private static boolean isExpectedCause(SQLException sqlException) {
    Preconditions.checkArgument(sqlException != null);
    Throwable rootCause = ExceptionUtils.getRootCause(sqlException);

    //SqlValidatorException is not an excepted exception in the origin design.But in the multi pass scene,
    //query pushdown may create tables, and the tables are not in the model, so will throw SqlValidatorException.
    boolean isPushDownUpdateEnabled = KylinConfig.getInstanceFromEnv().isPushDownUpdateEnabled();

    if (isPushDownUpdateEnabled) {
        return (rootCause instanceof NoRealizationFoundException //
                || rootCause instanceof RoutingIndicatorException || rootCause instanceof SqlValidatorException); //
    } else {
        if (rootCause instanceof KylinTimeoutException)
            return false;
        if (rootCause instanceof AccessDeniedException) {
            return false;
        }
        if (rootCause instanceof RoutingIndicatorException) {
            return true;
        }

        if (rootCause instanceof CompileException) {
            return true;
        }

        if (QueryContextFacade.current().isWithoutSyntaxError()) {
            logger.warn("route to push down for met error when running current query", sqlException);
            return true;
        }
    }

    return false;
}
 
Example #27
Source File: JDKClassCompiler.java    From Bats with Apache License 2.0 5 votes vote down vote up
private DrillJavaFileObject doCompile(final ClassNames className, final String sourceCode)
      throws CompileException, IOException, ClassNotFoundException {
  try {
    // Create one Java source file in memory, which will be compiled later.
    DrillJavaFileObject compilationUnit = new DrillJavaFileObject(className.dot, sourceCode);

    CompilationTask task = compiler.getTask(null, fileManager, listener, compilerOptions, null, Collections.singleton(compilationUnit));

    // Run the compiler.
    if(!task.call()) {
      throw new CompileException("Compilation failed", null);
    } else if (!compilationUnit.isCompiled()) {
      throw new ClassNotFoundException(className + ": Class file not created by compilation.");
    }
    // all good
    return compilationUnit;
  } catch (RuntimeException rte) {
    // Unwrap the compilation exception and throw it.
    Throwable cause = rte.getCause();
    if (cause != null) {
      cause = cause.getCause();
      if (cause instanceof CompileException) {
        throw (CompileException) cause;
      }
      if (cause instanceof IOException) {
        throw (IOException) cause;
      }
    }
    throw rte;
  }
}
 
Example #28
Source File: JaninoClassCompiler.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
protected byte[][] getByteCode(final ClassNames className, final String sourceCode)
    throws CompileException, IOException, ClassNotFoundException, ClassTransformationException {
  ClassFile[] classFiles = doCompile(sourceCode);

  byte[][] byteCodes = new byte[classFiles.length][];
  for(int i = 0; i < classFiles.length; i++){
    byteCodes[i] = classFiles[i].toByteArray();
  }
  return byteCodes;
}
 
Example #29
Source File: JaninoClassCompiler.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String,byte[]> compile(final ClassNames className, final String sourceCode)
    throws CompileException, IOException, ClassNotFoundException {

  ClassFile[] classFiles = doCompile(sourceCode);
  Map<String,byte[]> results = new HashMap<>();
  for(int i = 0;  i < classFiles.length;  i++) {
    ClassFile classFile = classFiles[i];
    results.put(classFile.getThisClassName(), classFile.toByteArray());
  }
  return results;
}
 
Example #30
Source File: JaninoClassCompiler.java    From Bats with Apache License 2.0 5 votes vote down vote up
private ClassFile[] doCompile(final String sourceCode)
    throws CompileException, IOException, ClassNotFoundException {
  StringReader reader = new StringReader(sourceCode);
  Scanner scanner = new Scanner((String) null, reader);
  Java.CompilationUnit compilationUnit = new Parser(scanner).parseCompilationUnit();
  return new UnitCompiler(compilationUnit, compilationClassLoader)
                                .compileUnit(this.debug, this.debug, this.debug);
}