/** Prepends the list of sources to the given {@link Message} */ static Message mergeSources(List<Object> sources, Message message) { List<Object> messageSources = message.getSources(); // It is possible that the end of getSources() and the beginning of message.getSources() are // equivalent, in this case we should drop the repeated source when joining the lists. The // most likely scenario where this would happen is when a scoped binding throws an exception, // due to the fact that InternalFactoryToProviderAdapter applies the binding source when // merging errors. if (!sources.isEmpty() && !messageSources.isEmpty() && Objects.equal(messageSources.get(0), sources.get(sources.size() - 1))) { messageSources = messageSources.subList(1, messageSources.size()); } return new Message( ImmutableList.builder().addAll(sources).addAll(messageSources).build(), message.getMessage(), message.getCause()); }
protected void annotateInjectorExceptions(Collection<Message> messages) { for (Message message : messages) { //noinspection ThrowableResultOfMethodCallIgnored final Throwable rootCause = ExceptionUtils.getRootCause(message.getCause()); if (rootCause instanceof NodeIdPersistenceException) { LOG.error(UI.wallString( "Unable to read or persist your NodeId file. This means your node id file (" + configuration.getNodeIdFile() + ") is not readable or writable by the current user. The following exception might give more information: " + message)); System.exit(-1); } else if (rootCause instanceof AccessDeniedException) { LOG.error(UI.wallString("Unable to access file " + rootCause.getMessage())); System.exit(-2); } else { // other guice error, still print the raw messages // TODO this could potentially print duplicate messages depending on what a subclass does... LOG.error("Guice error (more detail on log level debug): {}", message.getMessage()); if (rootCause != null) { LOG.debug("Stacktrace:", rootCause); } } } }
fmt.format("Encountered circular dependency spanning several threads."); if (proxyCreationError != null) { fmt.format(" %s", proxyCreationError.getMessage()); fmt.format("%s is holding locks the following singletons in the cycle:%n", lockedThread); for (Key<?> lockedKey : lockedKeys) { fmt.format("%s%n", Errors.convert(lockedKey)); return new Message(Thread.currentThread(), sb.toString());
public void testGetCauseCreation() { AuthorizationException aex = createMock(AuthorizationException.class); Message message = new Message(ImmutableList.of(), "test", aex); CreationException pex = new CreationException(ImmutableSet.of(message)); assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), aex); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropagateCreationExceptionAuthorizationException() throws Throwable { Exception e = new AuthorizationException(); propagateIfPossible( new CreationException(ImmutableSet.of(new Message(ImmutableList.of(), "Error in custom provider", e))), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
@Test public void TestFormatError() { Problems problems = new Problems(); problems.addError("message %d", "NaN"); Message[] errors = problems.getErrors().toArray(new Message[] {}); assertEquals(errors.length, 1); assertContainsAllOf(errors[0].toString(), "Error", "message %d", "NaN", "IllegalFormatConversionException"); assertEquals(problems.getWarnings().size(), 0, "Found unexpected warnings in problem object"); try { problems.throwIfHasErrors(); fail("Expected exception from problems object"); } catch (ConfigurationException e) { assertContains(e.getMessage(), "message %d [NaN]"); } }
static <T> T checkNotNull(T reference, String name) { if (reference != null) { return reference; } NullPointerException npe = new NullPointerException(name); throw new ConfigurationException(ImmutableSet.of(new Message(ImmutableList.of(), npe.toString(), npe))); } }
/** * Throws a ConfigurationException with an NullPointerExceptions as the cause if the given * reference is {@code null}. */ static <T> T checkNotNull(T reference, String name) { if (reference != null) { return reference; } NullPointerException npe = new NullPointerException(name); throw new ConfigurationException(ImmutableSet.of(new Message(npe.toString(), npe))); }
/** * Throws a ConfigurationException with a formatted {@link Message} if this condition is {@code * false}. */ static void checkConfiguration(boolean condition, String format, Object... args) { if (condition) { return; } throw new ConfigurationException(ImmutableSet.of(new Message(Errors.format(format, args)))); }
@Test public void testRequiresExplicitBindings() throws Exception { Bootstrap bootstrap = new Bootstrap(); try { bootstrap.initialize().getInstance(Instance.class); Assert.fail("should require explicit bindings"); } catch (ConfigurationException e) { Assertions.assertContains(e.getErrorMessages().iterator().next().getMessage(), "Explicit bindings are required"); } }
/** * When serialized, we eagerly convert sources to strings. This hurts our formatting, but it * guarantees that the receiving end will be able to read the message. */ private Object writeReplace() throws ObjectStreamException { Object[] sourcesAsStrings = sources.toArray(); for (int i = 0; i < sourcesAsStrings.length; i++) { sourcesAsStrings[i] = Errors.convert(sourcesAsStrings[i]).toString(); } return new Message(ImmutableList.copyOf(sourcesAsStrings), message, cause); }
/** Returns the formatted message for an exception with the specified messages. */ public static String format(String heading, Collection<Message> errorMessages) { Formatter fmt = new Formatter().format(heading).format(":%n%n"); int index = 1; boolean displayCauses = getOnlyCause(errorMessages) == null; for (Message errorMessage : errorMessages) { fmt.format("%s) %s%n", index++, errorMessage.getMessage()); List<Object> dependencies = errorMessage.getSources(); for (int i = dependencies.size() - 1; i >= 0; i--) { Object source = dependencies.get(i); formatSource(fmt, source); } Throwable cause = errorMessage.getCause(); if (displayCauses && cause != null) { StringWriter writer = new StringWriter(); cause.printStackTrace(new PrintWriter(writer)); fmt.format("Caused by: %s", writer.getBuffer()); } fmt.format("%n"); } if (errorMessages.size() == 1) { fmt.format("1 error"); } else { fmt.format("%s errors", errorMessages.size()); } return fmt.toString(); }
for (Message errorMessage : errorMessages) { int thisIdx = index++; fmt.format("%s) %s%n", thisIdx, errorMessage.getMessage()); List<Object> dependencies = errorMessage.getSources(); for (int i = dependencies.size() - 1; i >= 0; i--) { Object source = dependencies.get(i); Throwable cause = errorMessage.getCause(); if (displayCauses && cause != null) { Equivalence.Wrapper<Throwable> causeEquivalence = ThrowableEquivalence.INSTANCE.wrap(cause);
@Override public Boolean visit(Message message) { if (message.getCause() != null) { String rootMessage = getRootMessage(message.getCause()); logger.log( Level.INFO, "An exception was caught and reported. Message: " + rootMessage, message.getCause()); } errors.addMessage(message); return true; }
static void checkConfiguration(boolean condition, String format, Object... args) { if (condition) { return; } throw new ConfigurationException(ImmutableSet.of(new Message(Errors.format(format, args)))); }
@Test public void testPropertySetting() throws Exception { IMocksControl control = createControl(); TypeEncounter<SomeInjectableBean> encounter = control.createMock(TypeEncounter.class); Provider<Injector> injectorProvider = control.createMock(Provider.class); Injector injector = control.createMock(Injector.class); expect(encounter.getProvider(Injector.class)).andReturn(injectorProvider); expect(injectorProvider.get()).andReturn(injector).anyTimes(); Capture<MembersInjector<SomeInjectableBean>> capture = new Capture<MembersInjector<SomeInjectableBean>>(); encounter.register(and(anyObject(MembersInjector.class), capture(capture))); SecurityManager securityManager = control.createMock(SecurityManager.class); String property = "myPropertyValue"; expect(injector.getInstance(Key.get(SecurityManager.class))).andReturn(securityManager); expect(injector.getInstance(Key.get(String.class, Names.named("shiro.myProperty")))).andReturn(property); expect(injector.getInstance(Key.get(String.class, Names.named("shiro.unavailableProperty")))) .andThrow(new ConfigurationException(Collections.singleton(new Message("Not Available!")))); expect((Map)injector.getInstance(BeanTypeListener.MAP_KEY)).andReturn(Collections.EMPTY_MAP).anyTimes(); control.replay(); BeanTypeListener underTest = new BeanTypeListener(); underTest.hear(TypeLiteral.get(SomeInjectableBean.class), encounter); SomeInjectableBean bean = new SomeInjectableBean(); capture.getValue().injectMembers(bean); assertSame(securityManager, bean.securityManager); assertSame(property, bean.myProperty); assertNull(bean.unavailableProperty); control.verify(); }