Example usage for org.springframework.util ReflectionUtils rethrowRuntimeException

List of usage examples for org.springframework.util ReflectionUtils rethrowRuntimeException

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils rethrowRuntimeException.

Prototype

public static void rethrowRuntimeException(Throwable ex) 

Source Link

Document

Rethrow the given Throwable exception , which is presumably the target exception of an InvocationTargetException .

Usage

From source file:com.dianping.squirrel.client.util.ClassUtils.java

/**
 * construct instance violently/*from  ww w . jav  a 2  s.  com*/
 * 
 * @param <T>
 * @param clazz
 * @param parameters
 * @return
 */
public static <T> T newInstance(Class<T> clazz, Object... parameters) {
    try {
        if (parameters == null) {
            parameters = new Object[0];
        }
        int paramLen = parameters.length;
        Class<?>[] parameterTypes = new Class<?>[paramLen];
        for (int i = 0; i < paramLen; i++) {
            parameterTypes[i] = parameters[i].getClass();
        }
        Constructor<T> constructor = getMatchingDeclaredConstructor(clazz, parameterTypes);
        boolean accessible = constructor.isAccessible();
        if (accessible) {
            return constructor.newInstance(parameters);
        } else {
            synchronized (constructor) {
                try {
                    constructor.setAccessible(true);
                    return constructor.newInstance(parameters);
                } finally {
                    constructor.setAccessible(accessible);
                }
            }
        }
    } catch (Exception e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    throw new IllegalStateException("Should never get here");
}

From source file:de.codecentric.boot.admin.zuul.filters.post.SendResponseFilter.java

@Override
public Object run() {
    try {//www.j a v a2s. c om
        addResponseHeaders();
        writeResponse();
    } catch (Exception ex) {
        ReflectionUtils.rethrowRuntimeException(ex);
    }
    return null;
}

From source file:com.orange.cloud.servicebroker.filter.securitygroups.filter.CreateSecurityGroup.java

@Override
public void run(CreateServiceInstanceBindingRequest request, CreateServiceInstanceAppBindingResponse response) {
    Assert.notNull(response);//from   w  w w.  j ava  2  s .c o m
    Assert.notNull(response.getCredentials());

    final Destination destination = ConnectionInfoFactory.fromCredentials(response.getCredentials());

    if (!trustedDestinationSpecification.isSatisfiedBy(destination)) {
        log.warn("Cannot open security group for destination {}. Destination is out of allowed range [{}].",
                destination, trustedDestinationSpecification);
        throw new NotAllowedDestination(destination);
    }
    log.debug("creating security group for credentials {}.", response.getCredentials());
    try {
        final SecurityGroupEntity securityGroup = Mono
                .when(getRuleDescription(cloudFoundryClient, request.getBindingId(),
                        request.getServiceInstanceId()),
                        getSpaceId(cloudFoundryClient, request.getBoundAppGuid()))
                .then(function((description, spaceId) -> create(getSecurityGroupName(request), destination,
                        description, spaceId)))
                .doOnError(t -> log.error("Fail to create security group. Error details {}", t)).block();

        log.debug("Security Group {} created", securityGroup.getName());
    } catch (Exception e) {
        log.error("Fail to create Security Group. Error details {}", e);
        ReflectionUtils.rethrowRuntimeException(e);
    }

}

From source file:com.wavemaker.tools.data.ExportDB.java

@Override
protected void customRun() {

    init();/*from w  w w .  j a  va  2  s.  c o m*/

    final Configuration cfg = new Configuration();

    // cfg.addDirectory(this.hbmFilesDir);

    this.hbmFilesDir.find().files().performOperation(new ResourceOperation<com.wavemaker.tools.io.File>() {

        @Override
        public void perform(com.wavemaker.tools.io.File file) {
            if (file.getName().endsWith(".hbm.xml")) {
                cfg.addInputStream(file.getContent().asInputStream());
            }
        }
    });

    Properties connectionProperties = getHibernateConnectionProperties();

    cfg.addProperties(connectionProperties);

    SchemaExport export = null;
    SchemaUpdate update = null;
    File ddlFile = null;

    try {
        if (this.overrideTable) {
            Callable<SchemaExport> t = new Callable<SchemaExport>() {

                @Override
                public SchemaExport call() {
                    return new SchemaExport(cfg);
                }
            };

            if (this.classesDir == null) {
                try {
                    export = t.call();
                } catch (Exception e) {
                    ReflectionUtils.rethrowRuntimeException(e);
                }
            } else {
                export = ResourceClassLoaderUtils.runInClassLoaderContext(true, t, this.classesDir);
            }

            ddlFile = File.createTempFile("ddl", ".sql");
            ddlFile.deleteOnExit();

            export.setOutputFile(ddlFile.getAbsolutePath());
            export.setDelimiter(";");
            export.setFormat(true);

            String extraddl = prepareForExport(this.exportToDatabase);

            export.create(this.verbose, this.exportToDatabase);

            this.errors = CastUtils.cast(export.getExceptions());
            this.errors = filterError(this.errors, connectionProperties);

            this.ddl = IOUtils.read(ddlFile);

            if (!ObjectUtils.isNullOrEmpty(extraddl)) {
                this.ddl = extraddl + "\n" + this.ddl;
            }
        } else {
            Callable<SchemaUpdate> t = new Callable<SchemaUpdate>() {

                @Override
                public SchemaUpdate call() {
                    return new SchemaUpdate(cfg);
                }
            };

            if (this.classesDir == null) {
                try {
                    update = t.call();
                } catch (Exception e) {
                    ReflectionUtils.rethrowRuntimeException(e);
                }
            } else {
                update = ResourceClassLoaderUtils.runInClassLoaderContext(t, this.classesDir);
            }

            prepareForExport(this.exportToDatabase);

            Connection conn = JDBCUtils.getConnection(this.connectionUrl.toString(), this.username,
                    this.password, this.driverClassName);

            Dialect dialect = Dialect.getDialect(connectionProperties);

            DatabaseMetadata meta = new DatabaseMetadata(conn, dialect);

            String[] updateSQL = cfg.generateSchemaUpdateScript(dialect, meta);

            update.execute(this.verbose, this.exportToDatabase);

            this.errors = CastUtils.cast(update.getExceptions());
            StringBuilder sb = new StringBuilder();
            for (String line : updateSQL) {
                sb = sb.append(line);
                sb = sb.append("\n");
            }
            this.ddl = sb.toString();

        }
    } catch (IOException ex) {
        throw new DataServiceRuntimeException(ex);
    } catch (SQLException qex) {
        throw new DataServiceRuntimeException(qex);
    } catch (RuntimeException rex) {
        if (rex.getCause() != null && rex.getCause().getMessage().contains(NO_SUITABLE_DRIVER)
                && WMAppContext.getInstance().isCloudFoundry()) {
            String msg = rex.getMessage() + " - " + UNKNOWN_DATABASE;
            throw new DataServiceRuntimeException(msg);
        } else {
            throw new DataServiceRuntimeException(rex);
        }
    } finally {
        try {
            ddlFile.delete();
        } catch (Exception ignore) {
        }
    }
}

From source file:org.grails.web.errors.GrailsWrappedRuntimeException.java

/**
 * @param servletContext The ServletContext instance
 * @param t The exception that was thrown
 *///from w  w  w  .j  a v  a  2 s.  c o  m
public GrailsWrappedRuntimeException(ServletContext servletContext, Throwable t) {
    super(t.getMessage(), t);
    this.cause = t;
    Throwable cause = t;

    FastStringPrintWriter pw = FastStringPrintWriter.newInstance();
    cause.printStackTrace(pw);
    stackTrace = pw.toString();

    while (cause.getCause() != cause) {
        if (cause.getCause() == null) {
            break;
        }
        cause = cause.getCause();
    }

    stackTraceLines = stackTrace.split("\\n");

    if (cause instanceof MultipleCompilationErrorsException) {
        MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) cause;
        Object message = mcee.getErrorCollector().getErrors().iterator().next();
        if (message instanceof SyntaxErrorMessage) {
            SyntaxErrorMessage sem = (SyntaxErrorMessage) message;
            lineNumber = sem.getCause().getLine();
            className = sem.getCause().getSourceLocator();
            sem.write(pw);
        }
    } else {
        Matcher m1 = PARSE_DETAILS_STEP1.matcher(stackTrace);
        Matcher m2 = PARSE_DETAILS_STEP2.matcher(stackTrace);
        Matcher gsp = PARSE_GSP_DETAILS_STEP1.matcher(stackTrace);
        try {
            if (gsp.find()) {
                className = gsp.group(2);
                lineNumber = Integer.parseInt(gsp.group(3));
                gspFile = URL_PREFIX + "views/" + gsp.group(1) + '/' + className;
            } else {
                if (m1.find()) {
                    do {
                        className = m1.group(1);
                        lineNumber = Integer.parseInt(m1.group(2));
                    } while (m1.find());
                } else {
                    while (m2.find()) {
                        className = m2.group(1);
                        lineNumber = Integer.parseInt(m2.group(2));
                    }
                }
            }
        } catch (NumberFormatException nfex) {
            // ignore
        }
    }

    LineNumberReader reader = null;
    try {
        checkIfSourceCodeAware(t);
        checkIfSourceCodeAware(cause);

        if (getLineNumber() > -1) {
            String fileLocation;
            String url = null;

            if (fileName != null) {
                fileLocation = fileName;
            } else {
                String urlPrefix = "";
                if (gspFile == null) {
                    fileName = className.replace('.', '/') + ".groovy";

                    GrailsApplication application = WebApplicationContextUtils
                            .getRequiredWebApplicationContext(servletContext)
                            .getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class);
                    // @todo Refactor this to get the urlPrefix from the ArtefactHandler
                    if (application.isArtefactOfType(ControllerArtefactHandler.TYPE, className)) {
                        urlPrefix += "/controllers/";
                    } else if (application.isArtefactOfType(TagLibArtefactHandler.TYPE, className)) {
                        urlPrefix += "/taglib/";
                    } else if (application.isArtefactOfType(ServiceArtefactHandler.TYPE, className)) {
                        urlPrefix += "/services/";
                    }
                    url = URL_PREFIX + urlPrefix + fileName;
                } else {
                    url = gspFile;
                    GrailsApplicationAttributes attrs = null;
                    try {
                        attrs = grailsApplicationAttributesConstructor.newInstance(servletContext);
                    } catch (Exception e) {
                        ReflectionUtils.rethrowRuntimeException(e);
                    }
                    ResourceAwareTemplateEngine engine = attrs.getPagesTemplateEngine();
                    lineNumber = engine.mapStackLineNumber(url, lineNumber);
                }
                fileLocation = "grails-app" + urlPrefix + fileName;
            }

            InputStream in = null;
            if (!GrailsStringUtils.isBlank(url)) {
                in = servletContext.getResourceAsStream(url);
                LOG.debug("Attempting to display code snippet found in url " + url);
            }
            if (in == null) {
                Resource r = null;
                try {
                    r = resolver.getResource(fileLocation);
                    in = r.getInputStream();
                } catch (Throwable e) {
                    r = resolver.getResource("file:" + fileLocation);
                    if (r.exists()) {
                        try {
                            in = r.getInputStream();
                        } catch (IOException e1) {
                            // ignore
                        }
                    }
                }
            }

            if (in != null) {
                reader = new LineNumberReader(new InputStreamReader(in, "UTF-8"));
                String currentLine = reader.readLine();
                StringBuilder buf = new StringBuilder();
                while (currentLine != null) {
                    int currentLineNumber = reader.getLineNumber();
                    if ((lineNumber > 0 && currentLineNumber == lineNumber - 1)
                            || (currentLineNumber == lineNumber)) {
                        buf.append(currentLineNumber).append(": ").append(currentLine).append("\n");
                    } else if (currentLineNumber == lineNumber + 1) {
                        buf.append(currentLineNumber).append(": ").append(currentLine);
                        break;
                    }
                    currentLine = reader.readLine();
                }
                codeSnippet = buf.toString().split("\n");
            }
        }
    } catch (IOException e) {
        LOG.warn("[GrailsWrappedRuntimeException] I/O error reading line diagnostics: " + e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.springframework.boot.SpringApplication.java

/**
 * Run the Spring application, creating and refreshing a new
 * {@link ApplicationContext}./*ww w  .j a  va  2s .co m*/
 * @param args the application arguments (usually passed from a Java main method)
 * @return a running {@link ApplicationContext}
 */
public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    configureHeadlessProperty();
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.started();
    try {
        context = doRun(listeners, args);
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
        }
        return context;
    } catch (Throwable ex) {
        try {
            listeners.finished(context, ex);
            this.log.error("Application startup failed", ex);
        } finally {
            if (context != null) {
                context.close();
            }
        }
        ReflectionUtils.rethrowRuntimeException(ex);
        return context;
    }
}

From source file:org.springframework.boot.SpringApplicationRunListeners.java

private void callFinishedListener(SpringApplicationRunListener listener, ConfigurableApplicationContext context,
        Throwable exception) {//w  w w . j av a2  s .co m
    try {
        listener.finished(context, exception);
    } catch (Throwable ex) {
        if (exception == null) {
            ReflectionUtils.rethrowRuntimeException(ex);
        }
        if (this.log.isDebugEnabled()) {
            this.log.error("Error handling failed", ex);
        } else {
            String message = ex.getMessage();
            message = (message == null ? "no error message" : message);
            this.log.warn("Error handling failed (" + message + ")");
        }
    }
}

From source file:org.springframework.cloud.aws.paramstore.AwsParamStorePropertySourceLocator.java

@Override
public PropertySource<?> locate(Environment environment) {
    if (!(environment instanceof ConfigurableEnvironment)) {
        return null;
    }//from  w w  w . j  av a  2  s  .c o  m

    ConfigurableEnvironment env = (ConfigurableEnvironment) environment;

    String appName = properties.getName();

    if (appName == null) {
        appName = env.getProperty("spring.application.name");
    }

    List<String> profiles = Arrays.asList(env.getActiveProfiles());

    String prefix = this.properties.getPrefix();

    String defaultContext = prefix + "/" + this.properties.getDefaultContext();
    this.contexts.add(defaultContext + "/");
    addProfiles(this.contexts, defaultContext, profiles);

    String baseContext = prefix + "/" + appName;
    this.contexts.add(baseContext + "/");
    addProfiles(this.contexts, baseContext, profiles);

    Collections.reverse(this.contexts);

    CompositePropertySource composite = new CompositePropertySource("aws-param-store");

    for (String propertySourceContext : this.contexts) {
        try {
            composite.addPropertySource(create(propertySourceContext));
        } catch (Exception e) {
            if (this.properties.isFailFast()) {
                logger.error(
                        "Fail fast is set and there was an error reading configuration from AWS Parameter Store:\n"
                                + e.getMessage());
                ReflectionUtils.rethrowRuntimeException(e);
            } else {
                logger.warn("Unable to load AWS config from " + propertySourceContext, e);
            }
        }
    }

    return composite;
}

From source file:org.springframework.cloud.aws.secretsmanager.AwsSecretsManagerPropertySourceLocator.java

@Override
public PropertySource<?> locate(Environment environment) {
    if (!(environment instanceof ConfigurableEnvironment)) {
        return null;
    }/*from   www  . ja v a 2  s .c  o m*/

    ConfigurableEnvironment env = (ConfigurableEnvironment) environment;

    String appName = properties.getName();

    if (appName == null) {
        appName = env.getProperty("spring.application.name");
    }

    List<String> profiles = Arrays.asList(env.getActiveProfiles());

    String prefix = this.properties.getPrefix();

    String defaultContext = prefix + "/" + this.properties.getDefaultContext();
    this.contexts.add(defaultContext);
    addProfiles(this.contexts, defaultContext, profiles);

    String baseContext = prefix + "/" + appName;
    this.contexts.add(baseContext);
    addProfiles(this.contexts, baseContext, profiles);

    Collections.reverse(this.contexts);

    CompositePropertySource composite = new CompositePropertySource("aws-secrets-manager");

    for (String propertySourceContext : this.contexts) {
        try {
            composite.addPropertySource(create(propertySourceContext));
        } catch (Exception e) {
            if (this.properties.isFailFast()) {
                logger.error(
                        "Fail fast is set and there was an error reading configuration from AWS Secrets Manager:\n"
                                + e.getMessage());
                ReflectionUtils.rethrowRuntimeException(e);
            } else {
                logger.warn("Unable to load AWS secret from " + propertySourceContext, e);
            }
        }
    }

    return composite;
}

From source file:org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry.java

@Override
public void register(ConsulRegistration reg) {
    log.info("Registering service with consul: " + reg.getService());
    try {/*from   w  w w  .  ja v  a2  s  . c  o m*/
        client.agentServiceRegister(reg.getService(), properties.getAclToken());
        if (heartbeatProperties.isEnabled() && ttlScheduler != null) {
            ttlScheduler.add(reg.getInstanceId());
        }
    } catch (ConsulException e) {
        if (this.properties.isFailFast()) {
            log.error("Error registering service with consul: " + reg.getService(), e);
            ReflectionUtils.rethrowRuntimeException(e);
        }
        log.warn("Failfast is false. Error registering service with consul: " + reg.getService(), e);
    }
}