Search in sources :

Example 11 with InvocationTargetException

use of java.lang.reflect.InvocationTargetException in project hadoop by apache.

the class ObjectWritable method tryInstantiateProtobuf.

/**
   * Try to instantiate a protocol buffer of the given message class
   * from the given input stream.
   * 
   * @param protoClass the class of the generated protocol buffer
   * @param dataIn the input stream to read from
   * @return the instantiated Message instance
   * @throws IOException if an IO problem occurs
   */
private static Message tryInstantiateProtobuf(Class<?> protoClass, DataInput dataIn) throws IOException {
    try {
        if (dataIn instanceof InputStream) {
            // We can use the built-in parseDelimitedFrom and not have to re-copy
            // the data
            Method parseMethod = getStaticProtobufMethod(protoClass, "parseDelimitedFrom", InputStream.class);
            return (Message) parseMethod.invoke(null, (InputStream) dataIn);
        } else {
            // Have to read it into a buffer first, since protobuf doesn't deal
            // with the DataInput interface directly.
            // Read the size delimiter that writeDelimitedTo writes
            int size = ProtoUtil.readRawVarint32(dataIn);
            if (size < 0) {
                throw new IOException("Invalid size: " + size);
            }
            byte[] data = new byte[size];
            dataIn.readFully(data);
            Method parseMethod = getStaticProtobufMethod(protoClass, "parseFrom", byte[].class);
            return (Message) parseMethod.invoke(null, data);
        }
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof IOException) {
            throw (IOException) e.getCause();
        } else {
            throw new IOException(e.getCause());
        }
    } catch (IllegalAccessException iae) {
        throw new AssertionError("Could not access parse method in " + protoClass);
    }
}
Also used : Message(com.google.protobuf.Message) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 12 with InvocationTargetException

use of java.lang.reflect.InvocationTargetException in project hadoop by apache.

the class RunJar method run.

public void run(String[] args) throws Throwable {
    String usage = "RunJar jarFile [mainClass] args...";
    if (args.length < 1) {
        System.err.println(usage);
        System.exit(-1);
    }
    int firstArg = 0;
    String fileName = args[firstArg++];
    File file = new File(fileName);
    if (!file.exists() || !file.isFile()) {
        System.err.println("JAR does not exist or is not a normal file: " + file.getCanonicalPath());
        System.exit(-1);
    }
    String mainClassName = null;
    JarFile jarFile;
    try {
        jarFile = new JarFile(fileName);
    } catch (IOException io) {
        throw new IOException("Error opening job jar: " + fileName).initCause(io);
    }
    Manifest manifest = jarFile.getManifest();
    if (manifest != null) {
        mainClassName = manifest.getMainAttributes().getValue("Main-Class");
    }
    jarFile.close();
    if (mainClassName == null) {
        if (args.length < 2) {
            System.err.println(usage);
            System.exit(-1);
        }
        mainClassName = args[firstArg++];
    }
    mainClassName = mainClassName.replaceAll("/", ".");
    File tmpDir = new File(System.getProperty("java.io.tmpdir"));
    ensureDirectory(tmpDir);
    final File workDir;
    try {
        workDir = File.createTempFile("hadoop-unjar", "", tmpDir);
    } catch (IOException ioe) {
        // If user has insufficient perms to write to tmpDir, default
        // "Permission denied" message doesn't specify a filename.
        System.err.println("Error creating temp dir in java.io.tmpdir " + tmpDir + " due to " + ioe.getMessage());
        System.exit(-1);
        return;
    }
    if (!workDir.delete()) {
        System.err.println("Delete failed for " + workDir);
        System.exit(-1);
    }
    ensureDirectory(workDir);
    ShutdownHookManager.get().addShutdownHook(new Runnable() {

        @Override
        public void run() {
            FileUtil.fullyDelete(workDir);
        }
    }, SHUTDOWN_HOOK_PRIORITY);
    unJar(file, workDir);
    ClassLoader loader = createClassLoader(file, workDir);
    Thread.currentThread().setContextClassLoader(loader);
    Class<?> mainClass = Class.forName(mainClassName, true, loader);
    Method main = mainClass.getMethod("main", String[].class);
    List<String> newArgsSubList = Arrays.asList(args).subList(firstArg, args.length);
    String[] newArgs = newArgsSubList.toArray(new String[newArgsSubList.size()]);
    try {
        main.invoke(null, new Object[] { newArgs });
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }
}
Also used : IOException(java.io.IOException) Method(java.lang.reflect.Method) JarFile(java.util.jar.JarFile) Manifest(java.util.jar.Manifest) InvocationTargetException(java.lang.reflect.InvocationTargetException) URLClassLoader(java.net.URLClassLoader) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 13 with InvocationTargetException

use of java.lang.reflect.InvocationTargetException in project groovy by apache.

the class ConversionHandler method invoke.

/**
     * This method is a default implementation for the invoke method given in
     * InvocationHandler. Any call to a method with a declaring class that is
     * not Object, excluding toString() and default methods is redirected to invokeCustom.
     * <p>
     * Methods like equals and hashcode are called on the class itself instead
     * of the delegate because they are considered fundamental methods that should
     * not be overwritten. The toString() method gets special treatment as it is
     * deemed to be a method that you might wish to override when called from Groovy.
     * Interface default methods from Java 8 on the other hand are considered being
     * default implementations you don't normally want to change. So they are called
     * directly too
     * </p><p>
     * In many scenarios, it is better to overwrite the invokeCustom method where
     * the core Object related methods are filtered out.
     *</p>
     * @param proxy  the proxy
     * @param method the method
     * @param args   the arguments
     * @return the result of the invocation by method or delegate
     * @throws Throwable if caused by the delegate or the method
     * @see #invokeCustom(Object, Method, Object[])
     * @see InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
     */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (handleCache != null && isDefaultMethod(method)) {
        VMPlugin plugin = VMPluginFactory.getPlugin();
        Object handle = handleCache.get(method);
        if (handle == null) {
            handle = plugin.getInvokeSpecialHandle(method, proxy);
            handleCache.put(method, handle);
        }
        return plugin.invokeHandle(handle, args);
    }
    if (!checkMethod(method)) {
        try {
            if (method.getDeclaringClass() == GroovyObject.class) {
                if ("getMetaClass".equals(method.getName())) {
                    return getMetaClass(proxy);
                } else if ("setMetaClass".equals(method.getName())) {
                    return setMetaClass((MetaClass) args[0]);
                }
            }
            return invokeCustom(proxy, method, args);
        } catch (GroovyRuntimeException gre) {
            throw ScriptBytecodeAdapter.unwrap(gre);
        }
    }
    try {
        return method.invoke(this, args);
    } catch (InvocationTargetException ite) {
        throw ite.getTargetException();
    }
}
Also used : MetaClass(groovy.lang.MetaClass) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) GroovyObject(groovy.lang.GroovyObject) VMPlugin(org.codehaus.groovy.vmplugin.VMPlugin) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 14 with InvocationTargetException

use of java.lang.reflect.InvocationTargetException in project groovy by apache.

the class JavacJavaCompiler method compile.

public void compile(List<String> files, CompilationUnit cu) {
    String[] javacParameters = makeParameters(files, cu.getClassLoader());
    StringWriter javacOutput = null;
    int javacReturnValue = 0;
    try {
        Class javac = findJavac(cu);
        Method method = null;
        try {
            method = javac.getMethod("compile", new Class[] { String[].class, PrintWriter.class });
            javacOutput = new StringWriter();
            PrintWriter writer = new PrintWriter(javacOutput);
            Object ret = method.invoke(null, javacParameters, writer);
            javacReturnValue = (Integer) ret;
        } catch (NoSuchMethodException e) {
        }
        if (method == null) {
            method = javac.getMethod("compile", new Class[] { String[].class });
            Object ret = method.invoke(null, new Object[] { javacParameters });
            javacReturnValue = (Integer) ret;
        }
    } catch (InvocationTargetException ite) {
        cu.getErrorCollector().addFatalError(new ExceptionMessage((Exception) ite.getCause(), true, cu));
    } catch (Exception e) {
        cu.getErrorCollector().addFatalError(new ExceptionMessage(e, true, cu));
    }
    if (javacReturnValue != 0) {
        switch(javacReturnValue) {
            case 1:
                addJavacError("Compile error during compilation with javac.", cu, javacOutput);
                break;
            case 2:
                addJavacError("Invalid commandline usage for javac.", cu, javacOutput);
                break;
            case 3:
                addJavacError("System error during compilation with javac.", cu, javacOutput);
                break;
            case 4:
                addJavacError("Abnormal termination of javac.", cu, javacOutput);
                break;
            default:
                addJavacError("unexpected return value by javac.", cu, javacOutput);
                break;
        }
    } else {
        // print warnings if any
        System.out.print(javacOutput);
    }
}
Also used : ExceptionMessage(org.codehaus.groovy.control.messages.ExceptionMessage) StringWriter(java.io.StringWriter) GroovyObject(groovy.lang.GroovyObject) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) URISyntaxException(java.net.URISyntaxException) InvocationTargetException(java.lang.reflect.InvocationTargetException) PrintWriter(java.io.PrintWriter)

Example 15 with InvocationTargetException

use of java.lang.reflect.InvocationTargetException in project flink by apache.

the class MetricUtils method instantiateCPUMetrics.

private static void instantiateCPUMetrics(MetricGroup metrics) {
    try {
        final OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
        final Method fetchCPULoadMethod = Class.forName("com.sun.management.OperatingSystemMXBean").getMethod("getProcessCpuLoad");
        // verify that we can invoke the method
        fetchCPULoadMethod.invoke(mxBean);
        final Method fetchCPUTimeMethod = Class.forName("com.sun.management.OperatingSystemMXBean").getMethod("getProcessCpuTime");
        // verify that we can invoke the method
        fetchCPUTimeMethod.invoke(mxBean);
        metrics.gauge("Load", new Gauge<Double>() {

            @Override
            public Double getValue() {
                try {
                    return (Double) fetchCPULoadMethod.invoke(mxBean);
                } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) {
                    return -1.0;
                }
            }
        });
        metrics.gauge("Time", new Gauge<Long>() {

            @Override
            public Long getValue() {
                try {
                    return (Long) fetchCPUTimeMethod.invoke(mxBean);
                } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) {
                    return -1L;
                }
            }
        });
    } catch (ClassNotFoundException | InvocationTargetException | SecurityException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException ignored) {
        LOG.warn("Cannot access com.sun.management.OperatingSystemMXBean.getProcessCpuLoad()" + " - CPU load metrics will not be available.");
        // make sure that a metric still exists for the given name
        metrics.gauge("Load", new Gauge<Double>() {

            @Override
            public Double getValue() {
                return -1.0;
            }
        });
        metrics.gauge("Time", new Gauge<Long>() {

            @Override
            public Long getValue() {
                return -1L;
            }
        });
    }
}
Also used : Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) Gauge(org.apache.flink.metrics.Gauge) OperatingSystemMXBean(java.lang.management.OperatingSystemMXBean)

Aggregations

InvocationTargetException (java.lang.reflect.InvocationTargetException)1714 Method (java.lang.reflect.Method)784 IOException (java.io.IOException)193 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)146 ArrayList (java.util.ArrayList)136 IRunnableWithProgress (org.eclipse.jface.operation.IRunnableWithProgress)130 Test (org.junit.Test)129 Constructor (java.lang.reflect.Constructor)116 File (java.io.File)97 HashMap (java.util.HashMap)75 Field (java.lang.reflect.Field)71 ProgressMonitorDialog (org.eclipse.jface.dialogs.ProgressMonitorDialog)69 List (java.util.List)61 Map (java.util.Map)60 CoreException (org.eclipse.core.runtime.CoreException)60 IStatus (org.eclipse.core.runtime.IStatus)43 AccessibleObject (java.lang.reflect.AccessibleObject)34 DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)34 URLClassLoader (java.net.URLClassLoader)32 Status (org.eclipse.core.runtime.Status)30