Java Code Examples for org.springframework.util.ReflectionUtils#rethrowRuntimeException()

The following examples show how to use org.springframework.util.ReflectionUtils#rethrowRuntimeException() . 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: ConsulServiceRegistry.java    From spring-cloud-consul with Apache License 2.0 7 votes vote down vote up
@Override
public void register(ConsulRegistration reg) {
	log.info("Registering service with consul: " + reg.getService());
	try {
		this.client.agentServiceRegister(reg.getService(),
				this.properties.getAclToken());
		NewService service = reg.getService();
		if (this.heartbeatProperties.isEnabled() && this.ttlScheduler != null
				&& service.getCheck() != null
				&& service.getCheck().getTtl() != null) {
			this.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);
	}
}
 
Example 2
Source File: ZookeeperPropertySource.java    From spring-cloud-zookeeper with Apache License 2.0 6 votes vote down vote up
private byte[] getPropertyBytes(String fullPath) {
	try {
		byte[] bytes = null;
		try {
			bytes = this.getSource().getData().forPath(fullPath);
		}
		catch (KeeperException e) {
			if (e.code() != KeeperException.Code.NONODE) { // not found
				throw e;
			}
		}
		return bytes;
	}
	catch (Exception exception) {
		ReflectionUtils.rethrowRuntimeException(exception);
	}
	return null;
}
 
Example 3
Source File: CustomErrorZuulFilter.java    From api-gateway-old with Apache License 2.0 6 votes vote down vote up
@Override
public Object run() {
    try {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.set(SEND_ERROR_FILTER_RAN);
        ctx.setResponseStatusCode(500);
        ctx.setResponseBody("forward service error");
        ZuulException exception = findZuulException(ctx.getThrowable());
        HttpServletRequest request = ctx.getRequest();
        request.setAttribute("javax.servlet.error.status_code", exception.nStatusCode);
        LOGGER.warn("Error during filtering", exception);
        request.setAttribute("javax.servlet.error.exception", exception);
        if (StringUtils.hasText(exception.errorCause)) {
            request.setAttribute("javax.servlet.error.message", exception.errorCause);
        }
    } catch (Exception e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    return null;
}
 
Example 4
Source File: GreetingsClientApplication.java    From building-microservices with Apache License 2.0 6 votes vote down vote up
@Override
public Object run() {
    try {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();

        if (!this.rateLimiter.tryAcquire()) {
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            response.getWriter().append(HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
            currentContext.setSendZuulResponse(false);
        }
    } catch (IOException e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    return null;
}
 
Example 5
Source File: SpringApplication.java    From spring-javaformat with Apache License 2.0 6 votes vote down vote up
private void handleRunFailure(ConfigurableApplicationContext context,
		Throwable exception,
		Collection<SpringBootExceptionReporter> exceptionReporters,
		SpringApplicationRunListeners listeners) {
	try {
		try {
			handleExitCode(context, exception);
			if (listeners != null) {
				listeners.failed(context, exception);
			}
		}
		finally {
			reportFailure(exceptionReporters, exception);
			if (context != null) {
				context.close();
			}
		}
	}
	catch (Exception ex) {
		logger.warn("Unable to close ApplicationContext", ex);
	}
	ReflectionUtils.rethrowRuntimeException(exception);
}
 
Example 6
Source File: NetstrapBootApplication.java    From netstrap with Apache License 2.0 6 votes vote down vote up
/**
 * 异常处理
 */
private void handleRunFailure(ConfigurableApplicationContext context,
                              Throwable exception,
                              NetstrapSpringRunListeners listeners) {
    try {
        if (listeners != null) {
            listeners.failed(context, exception);
        }
    } catch (Exception ex) {
        log.warn("Unable to close ApplicationContext", ex);
    } finally {
        if (context != null) {
            context.close();
        }
    }

    ReflectionUtils.rethrowRuntimeException(exception);
}
 
Example 7
Source File: ContextFunctionCatalogAutoConfigurationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
private void create(String jarfile, Class<?> config, String... props) {
	try {
		URL[] urls = new URL[] { new ClassPathResource(jarfile).getURL() };
		ClassUtils.overrideThreadContextClassLoader(
				new URLClassLoader(urls, getClass().getClassLoader()));
		create(config, props);
	}
	catch (Exception e) {
		ReflectionUtils.rethrowRuntimeException(e);
	}
}
 
Example 8
Source File: QueryParamPortPreFilter.java    From sample-zuul-filters with Apache License 2.0 5 votes vote down vote up
public Object run() {
	RequestContext ctx = getCurrentContext();
	HttpServletRequest request = ctx.getRequest();
	// put the serviceId in `RequestContext`
	String port = request.getParameter("port");
	try {
		URL url = UriComponentsBuilder.fromUri(ctx.getRouteHost().toURI())
				.port(new Integer(port))
				.build().toUri().toURL();
		ctx.setRouteHost(url);
	} catch (Exception e) {
		ReflectionUtils.rethrowRuntimeException(e);
	}
	return null;
}
 
Example 9
Source File: ZookeeperPropertySource.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
private void findProperties(String path, List<String> children) {
	try {
		log.trace("entering findProperties for path: " + path);
		if (children == null) {
			children = getChildren(path);
		}
		if (children == null || children.isEmpty()) {
			return;
		}
		for (String child : children) {
			String childPath = path + "/" + child;
			List<String> childPathChildren = getChildren(childPath);

			byte[] bytes = getPropertyBytes(childPath);
			if (bytes == null || bytes.length == 0) {
				if (childPathChildren == null || childPathChildren.isEmpty()) {
					registerKeyValue(childPath, "");
				}
			}
			else {
				registerKeyValue(childPath,
						new String(bytes, Charset.forName("UTF-8")));
			}

			// Check children even if we have found a value for the current znode
			findProperties(childPath, childPathChildren);
		}
		log.trace("leaving findProperties for path: " + path);
	}
	catch (Exception exception) {
		ReflectionUtils.rethrowRuntimeException(exception);
	}
}
 
Example 10
Source File: ZookeeperServiceWatch.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(InstanceRegisteredEvent<?> event) {
	this.cache = TreeCache.newBuilder(this.curator, this.properties.getRoot())
			.build();
	this.cache.getListenable().addListener(this);
	try {
		this.cache.start();
	}
	catch (Exception e) {
		ReflectionUtils.rethrowRuntimeException(e);
	}
}
 
Example 11
Source File: ZookeeperServiceRegistry.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@Override
public void setStatus(ZookeeperRegistration registration, String status) {
	ServiceInstance<ZookeeperInstance> serviceInstance = registration
			.getServiceInstance();
	ZookeeperInstance instance = serviceInstance.getPayload();
	instance.getMetadata().put(INSTANCE_STATUS_KEY, status);
	try {
		getServiceDiscovery().updateService(serviceInstance);
	}
	catch (Exception e) {
		ReflectionUtils.rethrowRuntimeException(e);
	}
}
 
Example 12
Source File: H2Application.java    From spring-cloud-cli with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
	if (this.running.compareAndSet(false, true)) {
		try {
			log.info("Starting H2 Server");
			this.console = new Console();
			this.console.runTool("-tcp", "-tcpAllowOthers", "-tcpPort", getH2Port(this.dataSourceUrl));
		} catch (Exception e) {
			ReflectionUtils.rethrowRuntimeException(e);
		}
	}
}
 
Example 13
Source File: WebSphereUowTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
public T getResult() {
	if (this.exception != null) {
		ReflectionUtils.rethrowRuntimeException(this.exception);
	}
	return this.result;
}
 
Example 14
Source File: ZookeeperPropertySourceLocator.java    From spring-cloud-zookeeper with Apache License 2.0 4 votes vote down vote up
@Override
public PropertySource<?> locate(Environment environment) {
	if (environment instanceof ConfigurableEnvironment) {
		ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
		String appName = env.getProperty("spring.application.name");
		if (appName == null) {
			// use default "application" (which config client does)
			appName = "application";
			log.warn(
					"spring.application.name is not set. Using default of 'application'");
		}
		List<String> profiles = Arrays.asList(env.getActiveProfiles());

		String root = this.properties.getRoot();
		this.contexts = new ArrayList<>();

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

		StringBuilder baseContext = new StringBuilder(root);
		if (!appName.startsWith("/")) {
			baseContext.append("/");
		}
		baseContext.append(appName);
		this.contexts.add(baseContext.toString());
		addProfiles(this.contexts, baseContext.toString(), profiles);

		CompositePropertySource composite = new CompositePropertySource("zookeeper");

		Collections.reverse(this.contexts);

		for (String propertySourceContext : this.contexts) {
			try {
				PropertySource propertySource = create(propertySourceContext);
				composite.addPropertySource(propertySource);
				// TODO: howto call close when /refresh
			}
			catch (Exception e) {
				if (this.properties.isFailFast()) {
					ReflectionUtils.rethrowRuntimeException(e);
				}
				else {
					log.warn("Unable to load zookeeper config from "
							+ propertySourceContext, e);
				}
			}
		}

		return composite;
	}
	return null;
}
 
Example 15
Source File: ConfigWatch.java    From spring-cloud-consul with Apache License 2.0 4 votes vote down vote up
@Timed("consul.watch-config-keys")
public void watchConfigKeyValues() {
	if (this.running.get()) {
		for (String context : this.consulIndexes.keySet()) {

			// turn the context into a Consul folder path (unless our config format
			// are FILES)
			if (this.properties.getFormat() != FILES && !context.endsWith("/")) {
				context = context + "/";
			}

			try {
				Long currentIndex = this.consulIndexes.get(context);
				if (currentIndex == null) {
					currentIndex = -1L;
				}

				log.trace("watching consul for context '" + context + "' with index "
						+ currentIndex);

				// use the consul ACL token if found
				String aclToken = this.properties.getAclToken();
				if (StringUtils.isEmpty(aclToken)) {
					aclToken = null;
				}

				Response<List<GetValue>> response = this.consul.getKVValues(context,
						aclToken,
						new QueryParams(this.properties.getWatch().getWaitTime(),
								currentIndex));

				// if response.value == null, response was a 404, otherwise it was a
				// 200
				// reducing churn if there wasn't anything
				if (response.getValue() != null && !response.getValue().isEmpty()) {
					Long newIndex = response.getConsulIndex();

					if (newIndex != null && !newIndex.equals(currentIndex)) {
						// don't publish the same index again, don't publish the first
						// time (-1) so index can be primed
						if (!this.consulIndexes.containsValue(newIndex)
								&& !currentIndex.equals(-1L)) {
							log.trace("Context " + context + " has new index "
									+ newIndex);
							RefreshEventData data = new RefreshEventData(context,
									currentIndex, newIndex);
							this.publisher.publishEvent(
									new RefreshEvent(this, data, data.toString()));
						}
						else if (log.isTraceEnabled()) {
							log.trace("Event for index already published for context "
									+ context);
						}
						this.consulIndexes.put(context, newIndex);
					}
					else if (log.isTraceEnabled()) {
						log.trace("Same index for context " + context);
					}
				}
				else if (log.isTraceEnabled()) {
					log.trace("No value for context " + context);
				}

			}
			catch (Exception e) {
				// only fail fast on the initial query, otherwise just log the error
				if (this.firstTime && this.properties.isFailFast()) {
					log.error(
							"Fail fast is set and there was an error reading configuration from consul.");
					ReflectionUtils.rethrowRuntimeException(e);
				}
				else if (log.isTraceEnabled()) {
					log.trace("Error querying consul Key/Values for context '"
							+ context + "'", e);
				}
				else if (log.isWarnEnabled()) {
					// simplified one line log message in the event of an agent
					// failure
					log.warn("Error querying consul Key/Values for context '"
							+ context + "'. Message: " + e.getMessage());
				}
			}
		}
	}
	this.firstTime = false;
}
 
Example 16
Source File: AwsParamStorePropertySourceLocator.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Override
public PropertySource<?> locate(Environment environment) {
	if (!(environment instanceof ConfigurableEnvironment)) {
		return null;
	}

	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 appContext = prefix + "/" + appName;
	addProfiles(this.contexts, appContext, profiles);
	this.contexts.add(appContext + "/");

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

	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;
}
 
Example 17
Source File: AwsSecretsManagerPropertySourceLocator.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Override
public PropertySource<?> locate(Environment environment) {
	if (!(environment instanceof ConfigurableEnvironment)) {
		return null;
	}

	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 appContext = prefix + "/" + appName;
	addProfiles(this.contexts, appContext, profiles);
	this.contexts.add(appContext);

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

	CompositePropertySource composite = new CompositePropertySource(
			this.propertySourceName);

	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;
}
 
Example 18
Source File: TaskUtils.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handleError(Throwable t) {
	super.handleError(t);
	ReflectionUtils.rethrowRuntimeException(t);
}
 
Example 19
Source File: WebSphereUowTransactionManager.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public T getResult() {
	if (this.exception != null) {
		ReflectionUtils.rethrowRuntimeException(this.exception);
	}
	return this.result;
}
 
Example 20
Source File: LoggregatorMessageSource.java    From spring-cloud-stream-app-starters with Apache License 2.0 4 votes vote down vote up
@Override
public void onError(Throwable throwable) {
	log.error(String.format("error when streaming logs from %s in %s",
			applicationName, getClass().getName()), throwable);
	ReflectionUtils.rethrowRuntimeException(throwable);
}