下面列出了怎么用com.google.inject.ProvisionException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public DBStore get() {
DBStore dbStore;
File reconDbDir =
reconUtils.getReconDbDir(configuration, OZONE_RECON_DB_DIR);
File lastKnownContainerKeyDb =
reconUtils.getLastKnownDB(reconDbDir, RECON_CONTAINER_KEY_DB);
if (lastKnownContainerKeyDb != null) {
LOG.info("Last known container-key DB : {}",
lastKnownContainerKeyDb.getAbsolutePath());
dbStore = initializeDBStore(configuration, reconUtils,
lastKnownContainerKeyDb.getName());
} else {
dbStore = getNewDBStore(configuration, reconUtils);
}
if (dbStore == null) {
throw new ProvisionException("Unable to provide instance of DBStore " +
"store.");
}
return dbStore;
}
private <I> Method findPostConstruct(final Class<? super I> rawType) {
Method postConstructFound = null;
for (final Method method : rawType.getDeclaredMethods()) {
if (method.isAnnotationPresent(PostConstruct.class)) {
if (method.getParameterTypes().length != 0) {
throw new ProvisionException("A method annotated with @PostConstruct must not have any parameters");
}
if (method.getExceptionTypes().length > 0) {
throw new ProvisionException("A method annotated with @PostConstruct must not throw any checked exceptions");
}
if (Modifier.isStatic(method.getModifiers())) {
throw new ProvisionException("A method annotated with @PostConstruct must not be static");
}
if (postConstructFound != null) {
throw new ProvisionException("More than one @PostConstruct method found for class " + rawType);
}
postConstructFound = method;
}
}
return postConstructFound;
}
private <I> void invokePostConstruct(final TypeEncounter<I> encounter, final Method postConstruct) {
encounter.register(new InjectionListener<I>() {
@Override
public void afterInjection(final I injectee) {
try {
postConstruct.setAccessible(true);
postConstruct.invoke(injectee);
} catch (final IllegalAccessException | InvocationTargetException e) {
if (e.getCause() instanceof UnrecoverableException) {
if (((UnrecoverableException) e.getCause()).isShowException()) {
log.error("An unrecoverable Exception occurred. Exiting HiveMQ", e);
}
System.exit(1);
}
throw new ProvisionException("An error occurred while calling @PostConstruct", e);
}
}
});
}
@Test
public void ifCommmandIsInvalidExceptionIsThrown() throws IOException {
String command = "invalid";
Map<String, Object> opts = new HashMap<>();
opts.put(BROWSER, CHROME);
opts.put(DRIVER, chromedriverFile.getAbsolutePath());
opts.put(APPLICATION, configurationFile.getAbsolutePath());
opts.put(URL, localhostUrl);
opts.put(CASE, caseFile.getAbsolutePath());
opts.put(SCREEN, screenString);
opts.put(TIMEOUT, timeoutString);
opts.put(PRECISION, precisionString);
Module module = new DefaultModule(command, opts);
Injector injector = Guice.createInjector(module);
try {
RequestFilter instance = injector.getInstance(
Key.get(new TypeLiteral<IOProvider<RequestFilter>>() {})).get();
} catch (ProvisionException e) {
assertTrue(e.getCause() instanceof NoSuchCommandException);
}
}
@Test
public void ifCommmandIsInvalidResponseExceptionIsThrown() throws IOException, URISyntaxException {
String command = "invalid";
Map<String, Object> opts = new HashMap<>();
opts.put(BROWSER, CHROME);
opts.put(DRIVER, chromedriverFile.getAbsolutePath());
opts.put(APPLICATION, configurationFile.getAbsolutePath());
opts.put(URL, localhostUrl);
opts.put(CASE, caseFile.getAbsolutePath());
opts.put(SCREEN, screenString);
opts.put(TIMEOUT, timeoutString);
opts.put(PRECISION, precisionString);
Module module = new DefaultModule(command, opts);
Injector injector = Guice.createInjector(module);
try {
IOProvider<ResponseFilter> instance = injector.getInstance(new Key<IOProvider<ResponseFilter>>() {});
instance.get();
} catch (ProvisionException e) {
assertTrue(e.getCause() instanceof NoSuchCommandException);
}
}
@Override
public Client get() {
Settings settings = Settings.builder()
.put("client.transport.ignore_cluster_name", true)
.put("client.transport.sniff", true)
.build();
TransportClient tc = new PreBuiltTransportClient(settings);
List<URI> clusterAddresses = configuration.getURIs();
if (clusterAddresses.isEmpty()) {
logger.warn(ElasticSearchConfiguration.ELASTIC_SEARCH_URL_PROPERTY_NAME +
" is not set. Indexing will remain DISABLED.");
}
for (URI hostAddress : clusterAddresses) {
int port = Optional.ofNullable(hostAddress.getPort()).orElse(9200);
try {
tc.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostAddress.getHost()), port));
} catch (UnknownHostException uhe){
throw new ProvisionException("Invalid host" + hostAddress.getHost(), uhe);
}
}
return tc;
}
@Override
public Client get() {
Settings settings = Settings.builder()
.put("client.transport.ignore_cluster_name", true)
.put("client.transport.sniff", true)
.build();
TransportClient tc = new PreBuiltTransportClient(settings);
List<URI> clusterAddresses = configuration.getURIs();
if (clusterAddresses.isEmpty()) {
logger.warn(ElasticSearchConfiguration.ELASTIC_SEARCH_URL_PROPERTY_NAME +
" is not set. Indexing will remain DISABLED.");
}
for (URI hostAddress : clusterAddresses) {
int port = Optional.ofNullable(hostAddress.getPort()).orElse(9200);
try {
tc.addTransportAddress(new TransportAddress(InetAddress.getByName(hostAddress.getHost()), port));
} catch (Exception e) {
throw new ProvisionException("Invalid host" + hostAddress.getHost(), e);
}
}
return tc;
}
@Override
@Nullable
public ClientInfo getCurrentThreadClientInfo() {
try {
HttpServletRequest request = httpRequestProvider.get();
return ClientInfo
.builder()
.userId(UserIdHelper.get())
.remoteIP(request.getRemoteAddr())
.userAgent(request.getHeader(HttpHeaders.USER_AGENT))
.path(request.getServletPath())
.build();
}
catch (ProvisionException | OutOfScopeException e) {
// ignore; this happens when called out of scope of http request
return null;
}
}
private <T, S> void startServiceIfApplicable(T instance, ServiceLifecycleActions<S> withActions) {
if (services.contains(instance)) {
return;
}
if (withActions == null) {
services.add(instance);
return;
}
S service = withActions.castIfActionable(instance);
if (service != null) {
try {
withActions.onStart(service);
services.add(service);
} catch (Exception e) {
try {
stopServices(withActions, e);
} catch (Exception e1) {
e = e1;
}
throw new ProvisionException("While starting service " + instance.getClass(), e);
}
}
}
@Test
public void errorOnStartup() throws Exception {
Guicer guicer = messageGuicer(
bind(DummyInterfaces.Alpha.class, DummyErroringServices.ErroringAlpha.class, true),
bind(DummyInterfaces.Beta.class, DummyErroringServices.ErroringBeta.class, false),
bind(DummyInterfaces.Gamma.class, DummyErroringServices.ErroringGamma.class, false)
);
try{
startRequiredServices(guicer);
fail("should have caught ErroringException");
} catch (ProvisionException e) {
assertEventualCause(e, DummyErroringServices.ErroringException.class);
assertEquals(
"messages",
joined(
"starting ErroringAlpha",
"starting ErroringBeta",
"starting ErroringGamma",
"started ErroringGamma",
"stopping ErroringGamma",
"stopped ErroringGamma"
),
Strings.join(DummyInterfaces.messages())
);
}
}
private <T> void verifyClazzIsConfigurable(Class<T> clazz)
{
final List<BeanPropertyDefinition> beanDefs = jsonMapper.getSerializationConfig()
.introspect(jsonMapper.constructType(clazz))
.findProperties();
for (BeanPropertyDefinition beanDef : beanDefs) {
final AnnotatedField field = beanDef.getField();
if (field == null || !field.hasAnnotation(JsonProperty.class)) {
throw new ProvisionException(
String.format(
"JsonConfigurator requires Jackson-annotated Config objects to have field annotations. %s doesn't",
clazz
)
);
}
}
}
@Test
public void testGetScopedInstance() {
Injector injector = setupInjectorWithScope();
JoynrMessageScope scope = injector.getInstance(JoynrMessageScope.class);
scope.activate();
try {
ScopedInstance instance = injector.getInstance(ScopedInstance.class);
logger.debug("On first getInstance got: {}", instance);
assertNotNull(instance);
assertNull(instance.getValue());
instance.setValue("myValue");
ScopedInstance secondInstance = injector.getInstance(ScopedInstance.class);
logger.debug("On second getInstance got: {}", secondInstance);
assertNotNull(secondInstance);
assertEquals("myValue", secondInstance.getValue());
} finally {
scope.deactivate();
}
try {
injector.getInstance(ScopedInstance.class);
fail("Should not be able to get scoped bean from inactive scope.");
} catch (ProvisionException e) {
// expected
assertTrue(e.getCause() instanceof IllegalStateException);
}
}
private <I> Method findPreDestroy(final Class<? super I> rawType) {
Method predestroyFound = null;
for (final Method method : rawType.getDeclaredMethods()) {
if (method.isAnnotationPresent(PreDestroy.class)) {
if (method.getParameterTypes().length != 0) {
throw new ProvisionException("A method annotated with @PreDestroy must not have any parameters");
}
if (predestroyFound != null) {
throw new ProvisionException("More than one @PreDestroy method found for class " + rawType);
}
predestroyFound = method;
}
}
return predestroyFound;
}
@VisibleForTesting
static void handleUncaughtException(final Thread t, final Throwable e) {
if (e instanceof UnrecoverableException) {
if (((UnrecoverableException) e).isShowException()) {
log.error("An unrecoverable Exception occurred. Exiting HiveMQ", t, e);
}
System.exit(1);
} else if (e instanceof CreationException) {
if (e.getCause() instanceof UnrecoverableException) {
log.error("An unrecoverable Exception occurred. Exiting HiveMQ");
System.exit(1);
}
final CreationException creationException = (CreationException) e;
checkGuiceErrorsForUnrecoverable(creationException.getErrorMessages());
} else if (e instanceof ProvisionException) {
if (e.getCause() instanceof UnrecoverableException) {
log.error("An unrecoverable Exception occurred. Exiting HiveMQ");
System.exit(1);
}
final ProvisionException provisionException = (ProvisionException) e;
checkGuiceErrorsForUnrecoverable(provisionException.getErrorMessages());
}
final Throwable rootCause = Throwables.getRootCause(e);
if (rootCause instanceof UnrecoverableException) {
final boolean showException = ((UnrecoverableException) rootCause).isShowException();
if (showException) {
log.error("Cause: ", e);
}
} else {
log.error("Uncaught Error:", e);
}
}
@Test
public void test_provisionException() {
exit.expectSystemExitWithStatus(1);
final ProvisionException provisionException = new ProvisionException(Collections.singletonList(new Message(
"test",
new UnrecoverableException(false))));
HiveMQExceptionHandlerBootstrap.handleUncaughtException(Thread.currentThread(), provisionException);
}
private static Class<?> extractContainedType(TypeLiteral<?> type, int index) {
ParameterizedType containerType = (ParameterizedType) type.getType();
Type containedType = containerType.getActualTypeArguments()[index];
if(containedType instanceof Class) {
return (Class<?>) containedType;
}
if(containedType instanceof ParameterizedType) {
ParameterizedType pContainedType = (ParameterizedType) containedType;
for(Type subtype: pContainedType.getActualTypeArguments()) {
checkWildcard(subtype, pContainedType);
}
return (Class<?>) pContainedType.getRawType();
}
throw new ProvisionException("Unable to determine value type of map, contained type: [" + containedType + "]. This must either be a non-generic object or a generic with all ? for the types.");
}
private static void checkWildcard(Type subtype, ParameterizedType parentType) {
if(subtype instanceof WildcardType) {
// TODO check bounds
return;
}
throw new ProvisionException("Invalid plugin binding [" + parentType + "]. Types may only be non-generic or generics with a wildcard (?) specification.");
}
@Override
protected MapModuleParser<T> parser() {
try {
return Delegates.newStaticMethodDelegate(
new ResolvableType<MapModuleParser<T>>(){}.in(getClass()),
rawType
);
} catch(NoSuchMethodError e) {
throw new ProvisionException(e.getMessage(), e);
}
}
public static RuntimeException wrapException(Throwable e) {
if(e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if(e instanceof Error) {
throw (Error) e;
} else {
throw new ProvisionException("Provisioning error", e);
}
}
public static <E extends Throwable> E unwrapException(Class<E> type, ProvisionException e) throws E {
if(e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
} else if(type.isInstance(e.getCause())) {
throw (E) e.getCause();
} else {
throw e;
}
}
public static <T, E extends Throwable> T unwrappingExceptions(Class<E> exception, Provider<T> block) throws E {
try {
return block.get();
} catch(ProvisionException e) {
throw unwrapException(exception, e);
}
}
public static <E extends Throwable> void unwrappingExceptions(Class<E> exception, ThrowingRunnable<E> block) throws E {
try {
block.runThrows();
} catch(ProvisionException e) {
throw unwrapException(exception, e);
}
}
public static <T, E extends Throwable> T unwrappingExceptions(Class<E> exception, ThrowingSupplier<T, E> block) throws E {
try {
return block.getThrows();
} catch(ProvisionException e) {
throw unwrapException(exception, e);
}
}
@Override
public boolean supportsParameter(ParameterContext parameterContext,
ExtensionContext extensionContext)
throws ParameterResolutionException {
Parameter parameter = parameterContext.getParameter();
if (getBindingAnnotations(parameter).size() > 1) {
return false;
}
Key<?> key = getKey(
extensionContext.getTestClass(),
parameter);
Optional<Injector> optInjector = getInjectorForParameterResolution(extensionContext);
return optInjector.filter(injector -> {
// Do not bind String without explicit bindings.
if (key.equals(Key.get(String.class)) && injector.getExistingBinding(key) == null) {
return false;
}
try {
injector.getInstance(key);
return true;
} catch (ConfigurationException | ProvisionException e) {
// If we throw a ParameterResolutionException here instead of returning false, we'll block
// other ParameterResolvers from being able to work.
return false;
}
}).isPresent();
}
@Test
public void invalidBrowserThrowsExceptionWhenDriver() throws IOException, URISyntaxException {
String command = RECORD;
Map<String, Object> opts = new HashMap<>();
opts.put(BROWSER, "asd");
Module module = new DefaultModule(command, opts);
Injector injector = Guice.createInjector(module);
try {
WebDriverSupplier instance = injector.getInstance(WebDriverSupplier.class);
} catch (ProvisionException e) {
assertTrue(e.getCause() instanceof BrowserTypeNotSupportedException);
}
}
@Test
public void invalidBrowserThrowsExceptionWhenDriverServiceSupplier() throws IOException, URISyntaxException {
String command = RECORD;
Map<String, Object> opts = new HashMap<>();
opts.put(BROWSER, "asd");
Module module = new DefaultModule(command, opts);
Injector injector = Guice.createInjector(module);
try {
DriverServiceSupplier instance = injector.getInstance(DriverServiceSupplier.class);
} catch (ProvisionException e) {
assertTrue(e.getCause() instanceof BrowserTypeNotSupportedException);
}
}
@Test(expected = ProvisionException.class)
public void testStartThrows() throws Exception {
final GuiceServiceModule guiceServiceHandler = new GuiceServiceModule();
final Injector injector = Guice.createInjector(guiceServiceHandler, new SimpleGraphModule());
// will throw a ProvisionException
injector.getInstance(ThrowsExceptionDuringStart.class);
}
@Override
public ShardSupplier get() {
if(configuration.getAvailabilityZone() == null) {
throw new ProvisionException(
"Availability zone is not defined. Ensure Configuration.getAvailabilityZone() returns a non-null " +
"and non-empty value."
);
}
String localDC = configuration.getAvailabilityZone().replaceAll(configuration.getRegion(), "");
return new DynoShardSupplier(hostSupplier, configuration.getRegion(), localDC);
}
/**
* Gets an instance from Guice for the provided class. Any missing flags or bindings will be
* printed in the error message if there was a problem retrieving the class instance.
*
* @param cls The class type to retrieve from the Guice injector.
* @param <T> The type of the class that is being returned.
* @return The class instance retrieved from Guice.
*/
public <T> T get(Class<T> cls) {
try {
return injector.getInstance(cls);
} catch (ProvisionException e) {
System.err.println("Could not start application:");
for (Message msg : e.getErrorMessages()) {
System.err.println(" " + msg.toString());
}
System.exit(1);
}
throw new IllegalStateException("Did not get an instance, and did not get an exception?");
}
@Override
public T get() {
if (delegate == null) {
throw new ProvisionException("Missing contribution for " + clazz.getName());
}
return delegate.get();
}