List of usage examples for java.lang Exception getCause
public synchronized Throwable getCause()
From source file:jp.classmethod.aws.dynamodb.DynamoDbSpringInterfaceTest.java
License:asdf
@Test(expected = NonTransientDataAccessResourceException.class) public void testTruncateTableDoesntExist() { dynamoDBLocalRule.getAmazonDynamoDB().deleteTable(BookDynamoDbRepository.TABLE_NAME); try {//from w ww . ja va 2 s .c o m sut.deleteAll(); } catch (Exception e) { assertThat(e.getCause(), is(instanceOf(ResourceNotFoundException.class))); sut.afterPropertiesSet(); throw e; } fail(); }
From source file:com.taobao.datax.plugins.writer.oraclejdbcwriter.OracleJdbcWriter.java
@Override public int prepare(PluginParam param) { this.setParam(param); DBSource.register(this.sourceUniqKey, this.genProperties()); if (StringUtils.isBlank(this.pre)) return PluginStatus.SUCCESS.value(); Statement stmt = null;//from ww w. j a va 2 s. co m try { this.connection = DBSource.getConnection(this.sourceUniqKey); stmt = this.connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); for (String subSql : this.pre.split(";")) { this.logger.info(String.format("Excute prepare sql %s .", subSql)); stmt.execute(subSql); } this.connection.commit(); return PluginStatus.SUCCESS.value(); } catch (Exception e) { throw new DataExchangeException(e.getCause()); } finally { try { if (null != stmt) { stmt.close(); } if (null != this.connection) { this.connection.close(); this.connection = null; } } catch (SQLException e) { } } }
From source file:es.bsc.demiurge.ws.rest.DemiurgeRestV1.java
@GET @Path("/flavours") @Produces(MediaType.APPLICATION_JSON)/*from ww w . j av a 2 s . co m*/ public String getFlavours() { ByteArrayOutputStream bos; ObjectMapper mapper = new ObjectMapper(); bos = new ByteArrayOutputStream(); try { mapper.writeValue(bos, vmManager.getFlavours()); return bos.toString(); } catch (Exception ex) { log.error(ex.getMessage(), ex); throw new WebApplicationException(ex.getMessage(), ex.getCause()); } finally { try { bos.close(); } catch (IOException e) { log.warn(e.getMessage(), e); } } }
From source file:com.ibm.team.build.internal.hjplugin.RTCLoginInfo.java
/** * Figure out the info needed to log into RTC based on a variety of ways to authenticate * It is expected that supplied values have been validated to some degree * @param project The project to be built (hence credentials needed for) may be * <code>null</code> when dealing with the global case * @param buildToolkitPath The path of the build toolkit. Could be <code>null</code> * if not using a password file/*from w w w. ja v a2 s .c o m*/ * @param serverUri The server to log into. Required * @param userId The user id to use. May be <code>null</code> when working with * credentials * @param password The password to use. May be <code>null</code> when working with * credentials or a password file. * @param passwordFile The file containing the password. May be <code>null</code> * when working with credentials or a password. * @param credentialsId The id of Jenkins credentials. May be <code>null</code> * when working with userId & either password/password file * @param timeout The time out to use (in seconds). Required * @throws Exception When something goes wrong determining the credentials. */ public RTCLoginInfo(Job<?, ?> project, String buildToolkitPath, String serverUri, String userId, String password, String passwordFile, String credentialsId, int timeout) throws InvalidCredentialsException { credentialsId = Util.fixEmptyAndTrim(credentialsId); password = Util.fixEmptyAndTrim(password); passwordFile = Util.fixEmptyAndTrim(passwordFile); userId = Util.fixEmptyAndTrim(userId); if (credentialsId != null) { // figure out userid & password from the credentials if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("Looking up credentials for " + //$NON-NLS-1$ "credentialId=\"" + credentialsId + //$NON-NLS-1$ "\" serverURI=\"" + serverUri + //$NON-NLS-1$ "\" project=" + (project == null ? "null" : "\"" + project.getName() + "\"")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$ } List<StandardUsernamePasswordCredentials> allMatchingCredentials = CredentialsProvider .lookupCredentials(StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM, URIRequirementBuilder.fromUri(serverUri).build()); StandardUsernamePasswordCredentials credentials = CredentialsMatchers .firstOrNull(allMatchingCredentials, CredentialsMatchers.withId(credentialsId)); if (credentials != null) { this.userId = credentials.getUsername(); this.password = credentials.getPassword().getPlainText(); } else { throw new InvalidCredentialsException(Messages.RTCLoginInfo_creds_unresolvable()); } } else { this.userId = userId; if (this.userId == null) { if (passwordFile == null && password == null) { throw new InvalidCredentialsException(Messages.RTCLoginInfo_missing_creds()); } else { throw new InvalidCredentialsException(Messages.RTCLoginInfo_missing_userid()); } } if (passwordFile != null) { // figure out the password in the file if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("Looking up credentials for " + //$NON-NLS-1$ "userId=\"" + userId + //$NON-NLS-1$ "\" passwordFile=\"" + passwordFile); //$NON-NLS-1$ } try { RTCFacadeWrapper facade = RTCFacadeFactory.getFacade(buildToolkitPath, null); this.password = (String) facade.invoke("determinePassword", new Class[] { //$NON-NLS-1$ File.class, // passwordFile, Locale.class // clientLocale }, new File(passwordFile), LocaleProvider.getLocale()); } catch (Exception e) { Throwable eToReport = e; if (eToReport instanceof InvocationTargetException && e.getCause() != null) { eToReport = e.getCause(); } if (LOGGER.isLoggable(Level.FINER)) { LOGGER.log(Level.FINER, "Failed to resolve password from passwordFile=\"" + passwordFile //$NON-NLS-1$ + "\" : " + eToReport.getMessage(), e); //$NON-NLS-1$ } throw new InvalidCredentialsException( Messages.RTCLoginInfo_missing_password(passwordFile, eToReport.getMessage()), e); } } else if (password != null) { // password was given if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("Credentials supplied for " + //$NON-NLS-1$ "userId=\"" + userId + //$NON-NLS-1$ "\" password=" + (password == null ? "null" : "non-null")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } this.password = password; } else { // no password info supplied if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("No password supplied for " + //$NON-NLS-1$ "userId=\"" + userId + //$NON-NLS-1$ "\" password=" + (password == null ? "null" : "non-null")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } throw new InvalidCredentialsException(Messages.RTCLoginInfo_supply_password_file_or_password()); } } this.serverUri = serverUri; this.timeout = timeout; }
From source file:com.metamx.rdiclient.RdiClientImplTest.java
@Test public void testExceptionOnPost() throws Exception { final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JodaModule()); final Serializer<MmxAuctionSummary> serializer = new JacksonSerializer<>(objectMapper); final RdiClientImpl<MmxAuctionSummary> rdiClient = makeRdiClient(serializer, 1); mockClient.setGoHandler(new GoHandler() { @Override//from w w w.j a va 2 s . c o m protected <Intermediate, Final> ListenableFuture<Final> go(Request<Intermediate, Final> request) throws Exception { return Futures.immediateFailedFuture(new IOException("Something Crazy Happened!")); } }.times(4)); rdiClient.start(); final ListenableFuture<RdiResponse> result = rdiClient.send(sampleEventBasic); Exception e = null; try { result.get(); } catch (Exception e2) { e = e2; } Assert.assertTrue(e instanceof ExecutionException); Assert.assertTrue(e.getCause() instanceof RdiException); Assert.assertTrue(e.getCause().getCause() instanceof IOException); rdiClient.close(); }
From source file:org.nuxeo.box.api.service.BoxServiceImpl.java
/** * @return a Box Exception Response in JSON */// www.ja v a 2s . com @Override public String getJSONBoxException(Exception e, int status) { NXBoxJsonException boxException = new NXBoxJsonException(); // Message boxException.setCode(e.getMessage()); // Detailed Message boxException.setMessage(e.getCause() != null ? e.getCause().getMessage() : null); boxException.setStatus(status); ObjectMapper mapper = new ObjectMapper(); String jsonExceptionResponse = StringUtils.EMPTY; try { jsonExceptionResponse = mapper.writeValueAsString(boxException); } catch (JsonProcessingException e1) { throw new BoxRestException("error when marshalling server " + "exception:", e1, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } return jsonExceptionResponse; }
From source file:org.dspace.services.events.SystemEventService.java
/** * Fires off a local event immediately.//www .j ava2 s. c o m * This is internal so the event should have already been validated. * * @param event a valid event */ private void fireLocalEvent(Event event) { // send event to all interested listeners for (EventListener listener : listenersMap.values()) { // filter the event if the listener has filter rules if (listener != null && filterEvent(listener, event)) { // passed filters so send the event to this listener try { listener.receiveEvent(event); } catch (Exception e) { log.warn("Listener (" + listener + ")[" + listener.getClass().getName() + "] failed to recieve event (" + event + "): " + e.getMessage() + ":" + e.getCause()); } } } }
From source file:org.apache.synapse.transport.nhttp.Axis2HttpRequest.java
/** * Start streaming the message into the Pipe, so that the contents could be read off the source * channel returned by getSourceChannel() * * @throws AxisFault on error// w w w. java 2 s.com */ public void streamMessageContents() throws AxisFault { if (log.isDebugEnabled()) { log.debug("Start streaming outgoing http request : [Message ID : " + msgContext.getMessageID() + "]"); if (log.isTraceEnabled()) { log.trace("Message [Request Message ID : " + msgContext.getMessageID() + "] " + "[Request Message Payload : [ " + msgContext.getEnvelope() + "]"); } } NHttpConfiguration cfg = NHttpConfiguration.getInstance(); int senderTimeout = cfg.getProperty(NhttpConstants.SO_TIMEOUT_SENDER, 60000); long startTime = System.currentTimeMillis(); synchronized (this) { while (!readyToStream && !completed) { try { this.wait(senderTimeout + 10000); if ((startTime + senderTimeout + 5000) < System.currentTimeMillis()) { handleException("Thread " + Thread.currentThread().getName() + " is blocked longer than the send timeout when trying to send the message :" + msgContext.getMessageID() + ". Releasing thread", new AxisFault("Sender thread was not notified within send timeout")); } } catch (InterruptedException ignore) { } } } if (!completed) { OutputStream out = new ContentOutputStream(outputBuffer); try { if (msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) { writeMessageFromTempData(out); } else { if (chunked) { messageFormatter.writeTo(msgContext, format, out, false); } else { writeMessageFromTempData(out); } } } catch (Exception e) { Throwable t = e.getCause(); if (t != null && t.getCause() != null && t.getCause() instanceof ClosedChannelException) { if (log.isDebugEnabled()) { log.debug("Ignore closed channel exception, as the " + "SessionRequestCallback handles this exception"); } } else { Integer errorCode = msgContext == null ? null : (Integer) msgContext.getProperty(NhttpConstants.ERROR_CODE); if (errorCode == null || errorCode == NhttpConstants.SEND_ABORT) { if (log.isDebugEnabled()) { log.debug("Remote server aborted request being sent, and responded"); } } else { if (e instanceof AxisFault) { throw (AxisFault) e; } else { handleException("Error streaming message context", e); } } } } finally { try { out.flush(); out.close(); } catch (IOException e) { handleException("Error closing outgoing message stream", e); } setSendingCompleted(true); } } }
From source file:com.evolveum.midpoint.provisioning.test.mock.SynchornizationServiceMock.java
@Override public void notifyChange(ResourceObjectShadowChangeDescription change, Task task, OperationResult parentResult) {/*from w w w . ja va2 s. c o m*/ LOGGER.debug("Notify change mock called with {}", change); // Some basic sanity checks assertNotNull("No change", change); assertNotNull("No task", task); assertNotNull("No resource", change.getResource()); assertNotNull("No parent result", parentResult); assertTrue("Either current shadow or delta must be present", change.getCurrentShadow() != null || change.getObjectDelta() != null); if (change.getCurrentShadow() != null) { ShadowType currentShadowType = change.getCurrentShadow().asObjectable(); if (currentShadowType != null) { // not a useful check..the current shadow could be null assertNotNull("Current shadow does not have an OID", change.getCurrentShadow().getOid()); assertNotNull("Current shadow does not have resourceRef", currentShadowType.getResourceRef()); assertNotNull("Current shadow has null attributes", currentShadowType.getAttributes()); assertFalse("Current shadow has empty attributes", ShadowUtil.getAttributesContainer(currentShadowType).isEmpty()); // Check if the shadow is already present in repo try { repositoryService.getObject(currentShadowType.getClass(), currentShadowType.getOid(), null, new OperationResult("mockSyncService.notifyChange")); } catch (Exception e) { AssertJUnit.fail("Got exception while trying to read current shadow " + currentShadowType + ": " + e.getCause() + ": " + e.getMessage()); } // Check resource String resourceOid = ShadowUtil.getResourceOid(currentShadowType); assertFalse("No resource OID in current shadow " + currentShadowType, StringUtils.isBlank(resourceOid)); try { repositoryService.getObject(ResourceType.class, resourceOid, null, new OperationResult("mockSyncService.notifyChange")); } catch (Exception e) { AssertJUnit.fail("Got exception while trying to read resource " + resourceOid + " as specified in current shadow " + currentShadowType + ": " + e.getCause() + ": " + e.getMessage()); } if (change.getCurrentShadow().asObjectable().getKind() == ShadowKindType.ACCOUNT) { ShadowType account = change.getCurrentShadow().asObjectable(); if (supportActivation) { assertNotNull("Current shadow does not have activation", account.getActivation()); assertNotNull("Current shadow activation status is null", account.getActivation().getAdministrativeStatus()); } else { assertNull("Activation sneaked into current shadow", account.getActivation()); } } } } if (change.getOldShadow() != null) { assertNotNull("Old shadow does not have an OID", change.getOldShadow().getOid()); assertNotNull("Old shadow does not have an resourceRef", change.getOldShadow().asObjectable().getResourceRef()); } if (change.getObjectDelta() != null) { assertNotNull("Delta has null OID", change.getObjectDelta().getOid()); } if (changeChecker != null) { changeChecker.check(change); } // remember ... callCountNotifyChange++; lastChange = change; }
From source file:it.polimi.tower4clouds.rules.RulesValidator.java
private Set<Problem> validateCondition(MonitoringRule rule) { Set<Problem> problems = new HashSet<Problem>(); if (rule.getCondition() == null) return problems; String condition = rule.getCondition().getValue(); if (condition != null) { ANTLRInputStream input = new ANTLRInputStream(condition); ConditionLexer lexer = new ConditionLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); ConditionParser parser = new ConditionParser(tokens); parser.setErrorHandler(new ErrorStrategy()); parser.removeErrorListeners();// w w w . j a v a 2 s.c o m lexer.removeErrorListeners(); try { parser.expression(); } catch (Exception e) { Problem problem = new Problem(); problem.setElementId(rule.getId()); problem.setTagName("condition"); problem.setError(EnumErrorType.CONDITION_LEXICAL_ERROR); if (e.getCause().toString().contains("NoViableAltException")) { Token token = ((NoViableAltException) (e.getCause())).getOffendingToken(); problem.setDescription( "Lexical error: '" + condition.substring(0, token.getCharPositionInLine()) + " " + condition.substring(token.getCharPositionInLine()) + "'"); } else if (e instanceof InputMismatchException) { problem.setDescription("Input Mismatch Exception"); } else if (e instanceof FailedPredicateException) { problem.setDescription("Failed Predicate Exception"); } else { problem.setDescription("Unknown recognition error! Exception: " + e.getClass().getName()); } problems.add(problem); } } return problems; }