public static ModifyServiceResponseType modifyService(final ModifyServiceType request) throws Exception { final ModifyServiceResponseType reply = request.getReply(); try { if (NamedTransition.INSTANCE.apply(request)) { reply.markWinning(); } else { Component.State nextState = Component.State.valueOf(request.getState().toUpperCase()); ServiceConfiguration config = findService(request.getName()); Topology.transition(nextState).apply(config).get(); reply.markWinning(); } } catch (Exception ex) { Exceptions.maybeInterrupted(ex); throw new EucalyptusCloudException( "Failed to execute request transition: " + request.getState() + "\nDue to:\n" + Throwables.getRootCause(ex).getMessage() + "\nPossible arguments are: \n" + "TRANSITIONS\n\t" + Joiner.on("\n\t").join(Topology.Transitions.values()) + "STATES\n\t" + Joiner.on("\n\t").join(Component.State.values()), ex); } return reply; }
@Override public void uncaughtException(Thread t, Throwable e) { /* In case of fatal errors we shut down. The wrapper script * will restart the domain. Notice that there is no guarantee * that the fatal error will not reoccur during shutdown and * in that case the shutdown may fail. We may want to consider * refining the shutdown logic such that in recovers if the * fatal error reoccurs. */ if (e instanceof VirtualMachineError) { _oomSafetyBuffer = null; kill(); _log.error( AlarmMarkerFactory.getMarker( PredefinedAlarm.FATAL_JVM_ERROR, getCellDomainName(), getCellName()), "Restarting due to fatal JVM error", e); return; } Throwable root = Throwables.getRootCause(e); if (root instanceof FileNotFoundException) { if (root.getMessage().contains("Too many open files")) { _log.error( AlarmMarkerFactory.getMarker( PredefinedAlarm.OUT_OF_FILE_DESCRIPTORS, getCellDomainName(), getCellName()), "Uncaught exception in thread " + t.getName(), e); return; } } _log.error("Uncaught exception in thread " + t.getName(), e); }
@Override public SOid fromString(final String from) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("fromString(from=%s)", from)); } final SOid oid; final Stopwatch stopwatch = Stopwatch.createStarted(); try { final String split[] = from.split(":"); Assert.isTrue( split.length == 3, String.format("OID[%s] is invalid, it should be in format A:B:C", from)); final String oidPrefix = split[TYPE_PREFIX_INDEX]; final Class<?> oidClass = Class.forName(split[CLASS_NAME_INDEX]); final String oidId = split[ID_INDEX]; oid = this.getOidObject(oidPrefix, oidClass, oidId); } catch (Exception exp) { LOGGER.error( String.format("fromString(from=%s) failed...", from), Throwables.getRootCause(exp)); throw exp; } stopwatch.stop(); if (LOGGER.isTraceEnabled()) { final long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS); LOGGER.trace( String.format("fromString(from=%s) to SOid(oid=%s) took %d ms", from, oid, elapsed)); } return oid; }
// since surefire and eclipse don't otherwise guarantee the order, we are // starting this one alphabetically before create2nodes.. @Test(enabled = true, dependsOnMethods = "testImagesCache") public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { String tag = this.tag + "run"; try { client.destroyNodesMatching(NodePredicates.withTag(tag)); } catch (Exception e) { } TemplateOptions options = client.templateOptions().blockOnPort(22, 120); try { Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, options); Credentials good = nodes.iterator().next().getCredentials(); assert good.account != null; assert good.key != null; Image image = Iterables.get(nodes, 0).getImage(); try { Map<? extends NodeMetadata, ExecResponse> responses = runScriptWithCreds(tag, image.getOsFamily(), new Credentials(good.account, "romeo")); assert false : "shouldn't pass with a bad password\n" + responses; } catch (RunScriptOnNodesException e) { assert Throwables.getRootCause(e).getMessage().contains("Auth fail") : e; } runScriptWithCreds(tag, image.getOsFamily(), good); checkNodes(nodes, tag); } finally { client.destroyNodesMatching(NodePredicates.withTag(tag)); } }
@JavascriptEnabled @Test @Ignore(value = {CHROME, HTMLUNIT, IE, PHANTOMJS, SAFARI}) public void shouldCatchErrorsWithMessageAndStacktraceWhenExecutingInitialScript() { driver.get(pages.ajaxyPage); String js = "function functionB() { throw Error('errormessage'); };" + "function functionA() { functionB(); };" + "functionA();"; try { executor.executeAsyncScript(js); fail("Expected an exception"); } catch (WebDriverException e) { assertThat(e.getMessage(), containsString("errormessage")); Throwable rootCause = Throwables.getRootCause(e); assertThat(rootCause.getMessage(), containsString("errormessage")); StackTraceElement[] st = rootCause.getStackTrace(); boolean seen = false; for (StackTraceElement s : st) { if (s.getMethodName().equals("functionB")) { seen = true; } } assertTrue("Stacktrace has not js method info", seen); } }
/** Test of chain method, of class ExceptionChain. */ @Test public void testChain() { System.out.println("chain"); Throwable t = new RuntimeException("", new SocketTimeoutException("Boo timeout")); Throwable newRootCause = new TimeoutException("Booo"); Throwable result = ExceptionChain.chain(t, newRootCause); result.printStackTrace(); Assert.assertEquals(newRootCause, Throwables.getRootCause(result)); Assert.assertEquals(3, Throwables.getCausalChain(result).size()); }
private String getExceptionMessage(Throwable throwable, Integer statusCode) { if (throwable != null) { return Throwables.getRootCause(throwable).getMessage(); } logger.info("statusCode : " + statusCode); if (statusCode != null) { HttpStatus httpStatus = HttpStatus.valueOf(statusCode); return httpStatus.getReasonPhrase(); } else { return ""; } }
// Test that an exception thrown while handling a successful async connection get reported // as a failure on the client future. @Test public void testClientCreateFailure() throws InterruptedException, ExecutionException, TTransportException { try { createClient(MalformedService.class, syncServer).get(); fail("Should not be able to successfully create a client for MalformedService.class"); } catch (ExecutionException e) { Throwable rootCause = Throwables.getRootCause(e); assertTrue(rootCause instanceof IllegalArgumentException); assertTrue(rootCause.getMessage().startsWith("Type can not be coerced to a Thrift type")); } }
public PaymentTransaction getPaymentTransactionWithRowLock(long paymentTransactionId) { PaymentTransaction paymentTransaction = null; EntityManager forActiveEntities = getEntityManagerForActiveEntities(); Query createQuery = forActiveEntities.createQuery("select pt from PaymentTransaction pt where pt.id=:id"); createQuery.setParameter("id", paymentTransactionId); createQuery.setLockMode(LockModeType.PESSIMISTIC_WRITE); try { paymentTransaction = (PaymentTransaction) createQuery.getSingleResult(); } catch (NoResultException nre) { log.error( "Exception while executing PaymentDao.getPaymentTransactionWithRowLock():No payment transaction found for id ={}", paymentTransactionId, Throwables.getRootCause(nre)); } catch (NonUniqueResultException nue) { log.error( "Exception while executing PaymentDao.getPaymentTransactionWithRowLock():Multiple payment transactions found for id ={}", paymentTransactionId, Throwables.getRootCause(nue)); } return paymentTransaction; }
@Override public VistaVeteranClinicalReminder extractData(String record) { // IEN^PRINT NAME^DUE DATE/TIME^LAST OCCURRENCE DATE/TIME // 500047^Hepatitis C risk Factor Screening^DUE NOW^^2^1^1^^^^0 if (StringUtils.isBlank(record)) { return null; } VistaVeteranClinicalReminder vistaVeteranClinicalReminder = new VistaVeteranClinicalReminder(); String[] fields = StringUtils.splitPreserveAllTokens(record, '^'); // 0. IEN vistaVeteranClinicalReminder.setClinicalReminderIen(fields[0]); // 1. Name vistaVeteranClinicalReminder.setName(fields[1]); // 2. Due Date if (StringUtils.isNotBlank(fields[2])) { if (!"DUE NOW".equalsIgnoreCase(fields[2])) { Date dueDate = VistaUtils.convertVistaDate(fields[2]); if (dueDate != null) { vistaVeteranClinicalReminder.setDueDateString( clinicalReminderDueDateFormat.format(dueDate)); } } else { vistaVeteranClinicalReminder.setDueDateString(fields[2]); } } // So, if piece 6 (5th index) is set to 1... then the reminder is “Due”. We can see this // reflected in the document Liz sent.... // 918^Evaluation of + PTSD Screen^DUE NOW^^2^1^1^^^^1 <—Says “Due Now”, and piece 6 is set // to “1” for “Due” // <—snip—> // 265^Screen for PTSD^3151124.083813^3141124.083813^2^1^1^^^^1 <—Says due “3141124.083813”, // and piece 6 is set to “1” for “Due” int dueNowStatus = 0; // not due try { dueNowStatus = Integer.parseInt(fields[5]); } catch (NumberFormatException nfe) { logger.error(Throwables.getRootCause(nfe).getMessage()); } vistaVeteranClinicalReminder.setDueNow(dueNowStatus == 1); return vistaVeteranClinicalReminder; }
@Override public AdvancedAction apply(@Nonnull final Exception input) { Throwable rootCause = com.google.common.base.Throwables.getRootCause(input); if (rootCause instanceof RuntimeException) { return AdvancedAction.ABORT; } if (rootCause instanceof SQLTransientException || rootCause instanceof SQLRecoverableException || rootCause instanceof IOException || rootCause instanceof TimeoutException) { LOG.debug("Exception encountered, retrying...", input); return AdvancedAction.RETRY; } return AdvancedAction.ABORT; }
protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds( final String tag, OsFamily osFamily, Credentials creds) throws RunScriptOnNodesException { try { return client.runScriptOnNodesMatching( NodePredicates.runningWithTag(tag), buildScript(osFamily).getBytes(), RunScriptOptions.Builder.overrideCredentialsWith(creds)); } catch (SshException e) { if (Throwables.getRootCause(e).getMessage().contains("Auth fail")) { // System.err.printf("bad credentials: %s:%s for %s%n", // creds.account, creds.key, client // .listNodesDetailsMatching(tag)); } throw e; } }
private Delete parse(final String statement) { Delete delete; try { Statement stmt; stmt = CCJSqlParserUtil.parse(statement); checkArgument(stmt instanceof Delete, "Expected DELETE statement: %s", statement); delete = (Delete) stmt; } catch (JSQLParserException e) { Throwables.propagateIfInstanceOf(Throwables.getRootCause(e), IllegalArgumentException.class); throw new IllegalArgumentException("Unable to parse query: " + e.getMessage(), e); } checkArgument(null == delete.getLimit(), "LIMIT is not supported for DELETE statements"); checkArgument( null == delete.getOrderByElements(), "ORDER BY is not supported for DELETE statements"); return delete; }
/** * Creates a new remote context. * * @param provider * @param account nullable, if credentials are present in the overrides * @param key nullable, if credentials are present in the overrides * @param modules Configuration you'd like to pass to the context. Ex. ImmutableSet.<Module>of(new * ExecutorServiceModule(myexecutor)) * @param overrides properties to override defaults with. * @return initialized context ready for use */ @SuppressWarnings("unchecked") public T createContext( String provider, @Nullable String account, @Nullable String key, Iterable<? extends Module> modules, Properties overrides) { checkNotNull(provider, "provider"); checkNotNull(modules, "modules"); checkNotNull(overrides, "overrides"); String propertiesBuilderKey = String.format("%s.propertiesbuilder", provider); String propertiesBuilderClassName = checkNotNull( properties.getProperty(propertiesBuilderKey), provider + " service not supported"); String contextBuilderKey = String.format("%s.contextbuilder", provider); String contextBuilderClassName = checkNotNull(properties.getProperty(contextBuilderKey), contextBuilderKey); String endpointKey = String.format("%s.endpoint", provider); String endpoint = properties.getProperty(endpointKey); try { Class<PropertiesBuilder> propertiesBuilderClass = (Class<PropertiesBuilder>) Class.forName(propertiesBuilderClassName); Class<B> contextBuilderClass = (Class<B>) Class.forName(contextBuilderClassName); PropertiesBuilder builder = propertiesBuilderClass.getConstructor(Properties.class).newInstance(overrides); if (key != null) builder.withCredentials(account, key); if (endpoint != null) builder.withEndpoint(URI.create(endpoint)); B contextBuilder = (B) contextBuilderClass .getConstructor(String.class, Properties.class) .newInstance(provider, builder.build()) .withModules(Iterables.toArray(modules, Module.class)); return build(contextBuilder); } catch (ProvisionException e) { Throwable throwable = Utils.firstRootCauseOrOriginalException(e); Throwables.propagate(throwable); assert false : "exception should have propogated " + e; return null; } catch (Exception e) { Throwables.propagate(Throwables.getRootCause(e)); assert false : "exception should have propogated " + e; return null; } }
@Override public void uncaughtException(Thread thread, Throwable exception) { try { Log.wtf("CORE_CONTROLLER::", Throwables.getRootCause(exception)); Log.i("CORE_CONTROLLER::", "Exception Details:", exception); try { Toast.makeText( context, "An almost fatal exception occurred." + exception.getLocalizedMessage(), Toast.LENGTH_LONG) .show(); } catch (Exception ex) { Log.i(ExtensibleOpMode.TAG, ex.getLocalizedMessage()); } AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + delay, pendingIntent); System.exit(2); } catch (Exception e) { Log.wtf("CORE_CONTROLLER::", e); } }
// Handle a SelectionKey which was selected // Runs unlocked as the caller is single-threaded (or if not, should enforce that handleKey is // only called // atomically for a given ConnectionHandler) public static void handleKey(SelectionKey key) { ConnectionHandler handler = ((ConnectionHandler) key.attachment()); try { if (handler == null) return; if (!key.isValid()) { handler.closeConnection(); // Key has been cancelled, make sure the socket gets closed return; } if (key.isReadable()) { // Do a socket read and invoke the parser's receiveBytes message int read = handler.channel.read(handler.readBuff); if (read == 0) return; // Was probably waiting on a write else if (read == -1) { // Socket was closed key.cancel(); handler.closeConnection(); return; } // "flip" the buffer - setting the limit to the current position and setting position to 0 handler.readBuff.flip(); // Use parser.receiveBytes's return value as a check that it stopped reading at the right // location int bytesConsumed = checkNotNull(handler.parser).receiveBytes(handler.readBuff); checkState(handler.readBuff.position() == bytesConsumed); // Now drop the bytes which were read by compacting readBuff (resetting limit and keeping // relative // position) handler.readBuff.compact(); } if (key.isWritable()) handler.tryWriteBytes(); } catch (Exception e) { // This can happen eg if the channel closes while the thread is about to get killed // (ClosedByInterruptException), or if handler.parser.receiveBytes throws something log.error("Error handling SelectionKey: {}", Throwables.getRootCause(e).getMessage()); handler.closeConnection(); } }
@Override public boolean validate(final DatagramChannel object, final Exception e) throws Exception { return e == null || !(Throwables.getRootCause(e) instanceof IOException); }
private static void checkInterrupted(Exception e) { Throwable cause = Throwables.getRootCause(e); if (cause instanceof InterruptedException || cause instanceof InterruptedIOException) { throw new AnalysisException("Analysis cancelled", e); } }
public synchronized boolean ensureCerts(InstanceDescriptor id) throws Exception { boolean sslEnabled = false; for (Map.Entry<String, InstanceDescriptor.InstanceDescriptorPort> entry : id.ports.entrySet()) { if (entry.getValue().sslEnabled) { sslEnabled = true; break; } } boolean generated = false; if (sslEnabled) { SelfSigningCertGenerator generator = new SelfSigningCertGenerator(); String password = passwordStore.password(id.instanceKey); File certFile = instancePath.certs("sslKeystore"); boolean generateSSL = false; try { if (!certFile.exists() || !generator.validate(id.instanceKey, password, certFile)) { generateSSL = true; } } catch (IOException x) { if (Throwables.getRootCause(x) instanceof UnrecoverableKeyException) { LOG.warn( "Looks like password changed so existing certs will be replaced with regenerate certs."); generateSSL = true; } else { throw x; } } if (generateSSL) { FileUtils.deleteQuietly(certFile); generator.create(id.instanceKey, password, certFile); generated = true; } } File oauthKeystoreFile = instancePath.certs("oauthKeystore"); File oauthPublicKeyFile = instancePath.certs("oauthPublicKey"); String password = passwordStore.password(id.instanceKey); RSAKeyPairGenerator generator = new RSAKeyPairGenerator(); boolean generateOauth = false; try { if (id.publicKey == null || !id.publicKey.equals( generator.getPublicKey( id.instanceKey, password, oauthKeystoreFile, oauthPublicKeyFile))) { generateOauth = true; } } catch (IOException x) { if (Throwables.getRootCause(x) instanceof UnrecoverableKeyException) { LOG.warn( "Looks like password changed so existing oauth certs will be replaced with regenerate certs."); generateOauth = true; } else { throw x; } } if (generateOauth) { FileUtils.deleteQuietly(oauthKeystoreFile); FileUtils.deleteQuietly(oauthPublicKeyFile); generator.create(id.instanceKey, password, oauthKeystoreFile, oauthPublicKeyFile); upenaClient.updateKeyPair( id.instanceKey, generator.getPublicKey(id.instanceKey, password, oauthKeystoreFile, oauthPublicKeyFile)); } return generated; }
/** * Prints the message of the root cause of the {@link Throwable} as a build failure. * * @see #printBuildFailure(String) */ public void printBuildFailureWithoutStacktrace(Throwable t) { LOG.warn(t, "Build error caused by exception"); printBuildFailureInternal(Throwables.getRootCause(t).getMessage()); }
public Layer<T> transform(final Layer<T> source) throws IOException, XMLStreamException { this.source = source; this.target = configuration.start(source); try { source.stream( new Text.Consumer() { @Override public void consume(Reader sourceReader) throws IOException { XMLStreamReader xmlStream = null; try { xmlStream = xmlInputFactory.createXMLStreamReader(sourceReader); final Stack<XMLEntity> entities = new Stack<XMLEntity>(); start(); while (xmlStream.hasNext()) { final int event = xmlStream.next(); mapOffsetDelta(0, xmlStream.getLocation().getCharacterOffset() - sourceOffset); switch (event) { case XMLStreamConstants.START_ELEMENT: endText(); nextSibling(); start(entities.push(XMLEntity.newElement(xmlStream))); break; case XMLStreamConstants.END_ELEMENT: endText(); end(entities.pop()); break; case XMLStreamConstants.COMMENT: endText(); nextSibling(); emptyEntity(XMLEntity.newComment(xmlStream)); break; case XMLStreamConstants.PROCESSING_INSTRUCTION: endText(); nextSibling(); emptyEntity(XMLEntity.newPI(xmlStream)); break; case XMLStreamConstants.CHARACTERS: case XMLStreamConstants.ENTITY_REFERENCE: case XMLStreamConstants.CDATA: newText(xmlStream.getText()); break; } } end(); } catch (XMLStreamException e) { throw Throwables.propagate(e); } finally { XML.closeQuietly(xmlStream); } } }); Reader textReader = null; try { configuration.end(target, textReader = read()); return target; } finally { Closeables.close(textReader, false); } } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, IOException.class); Throwables.propagateIfInstanceOf(Throwables.getRootCause(t), XMLStreamException.class); throw Throwables.propagate(t); } }
/** Handle exceptions thrown by handlers. */ @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class) public ModelAndView exception(Exception exception, WebRequest request) { ModelAndView modelAndView = new ModelAndView("error/general"); modelAndView.addObject("errorMessage", Throwables.getRootCause(exception)); return modelAndView; }
public void testGetRootCause_DoubleWrapped() { SomeCheckedException cause = new SomeCheckedException(); SomeChainingException exception = new SomeChainingException(new SomeChainingException(cause)); assertSame(cause, Throwables.getRootCause(exception)); }
@ExceptionHandler(Throwable.class) @Order(Ordered.LOWEST_PRECEDENCE) public ModelAndView defaultHandler(HttpServletRequest req, Throwable e) throws Exception { log.error("Exception at request " + req.getRequestURL(), e); return processException(Throwables.getRootCause(e).getMessage()); }
public void testGetRootCause_NoCause() { SomeCheckedException exception = new SomeCheckedException(); assertSame(exception, Throwables.getRootCause(exception)); }