@Override public int addBook(Book book) { // TODO Auto-generated method stub int rows = 0; String INSERT_BOOK = "insert into book values(:bookName,:ISBN,:publication,:price,:description,:author)"; Map<String,Object>params=new HashMap<String,Object>(); params.put("bookName", book.getBookName()); params.put("ISBN", book.getISBN()); params.put("publication", book.getPublication()); params.put("price",book.getPrice()); params.put("description",book.getDescription()); params.put("author", book.getAuthor()); rows=namedTemplate.update(INSERT_BOOK,params); PermissionDeniedDataAccessException accessException; return rows; }
@RequestMapping(value = "/login.do", method = RequestMethod.POST) public String login(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response, @RequestParam("passwordSHA256") String passwordSHA256) { // 因为这个登录逻辑很简单, 于是直接写在Controller里 而不是写在专门的Service里. try { final String lStrPasswordSha256 = ConfigurationUtil.get("admin.password_sha256").trim(); if (passwordSHA256.equalsIgnoreCase(lStrPasswordSha256)) { Calendar lCalendar = Calendar.getInstance(); lCalendar.setTimeInMillis(System.currentTimeMillis()); // Add 3 minutes from now, so session will expired after 3 minutes. lCalendar.add(Calendar.MINUTE, 3); request.getSession().setAttribute(ApplicationConstants.KEY_SESSION_EXPIRES_ON, lCalendar.getTimeInMillis()); return "redirect:/admin/dashboard/"; } response.setStatus(HttpServletResponse.SC_FORBIDDEN); throw new PermissionDeniedDataAccessException("Wrong password", null); } catch (Exception e) { mLogger.info(e.toString(), e); String lStrViewPath = login_view(); modelMap.put("objException", e); return lStrViewPath; } }
public final VistaUserDetails login(final String vistaId, final String division, final String accessCode, final String verifyCode, String newVerifyCode, String confirmNewVerifyCode, final String remoteAddress, String remoteHostName) throws BadCredentialsException, DataAccessException { if (!hasLength(vistaId)) throw new BadCredentialsException("missing vistaId"); if (!hasLength(division)) throw new BadCredentialsException("missing division"); if (!hasLength(accessCode)) throw new BadCredentialsException("missing access code"); if (!hasLength(verifyCode)) throw new BadCredentialsException("missing verify code"); if (!hasLength(remoteAddress)) throw new BadCredentialsException("missing remote address"); if (!hasLength(remoteHostName)) throw new BadCredentialsException("missing remote hostname"); try { /* * We're using this special variable to get around nested connection requests (our connection pool only allows one connection for a given key at a time.) */ ConnectionInfo info = getRpcTemplate().execute(new ConnectionInfoCallback(), RpcUriUtils.VISTA_RPC_BROKER_SCHEME + "://" + RpcUriUtils.toAuthority(vistaId, division, accessCode, verifyCode, newVerifyCode, confirmNewVerifyCode, remoteAddress, remoteHostName)); if (info != null) { return createVistaUserDetails(info.getHost(), vistaId, division, info.getUserDetails()); } } catch (PermissionDeniedDataAccessException e) { translateException(e); } return null; }
/** {@inheritDoc} */ public Requisition get(final String name) { checkGroupName(name); final File importFile = getImportFile(name); if (!importFile.exists()) { return null; } if (!importFile.canRead()) { throw new PermissionDeniedDataAccessException("Unable to read file "+importFile, null); } return CastorUtils.unmarshalWithTranslatedExceptions(Requisition.class, new FileSystemResource(importFile)); }
/** {@inheritDoc} */ public void save(final String groupName, final Requisition group) { checkGroupName(groupName); final File importFile = getImportFile(groupName); if (importFile.exists()) { final Requisition currentData = get(groupName); if (currentData.getDateStamp().compare(group.getDateStamp()) > 0) { throw new OptimisticLockingFailureException("Data in file "+importFile+" is newer than data to be saved!"); } } final FileWriter writer; try { writer = new FileWriter(importFile); } catch (final IOException e) { throw new PermissionDeniedDataAccessException("Unable to write file "+importFile, e); } CastorUtils.marshalWithTranslatedExceptions(group, writer); }
/** {@inheritDoc} */ public void save(final String groupName, final Requisition group) { checkGroupName(groupName); final File importFile = getImportFile(groupName); if (importFile.exists()) { final Requisition currentData = get(groupName); if (currentData.getDateStamp().compare(group.getDateStamp()) > 0) { throw new OptimisticLockingFailureException("Data in file "+importFile+" is newer than data to be saved!"); } } final FileWriter writer; try { writer = new FileWriter(importFile); } catch (final IOException e) { throw new PermissionDeniedDataAccessException("Unable to write file "+importFile, e); } group.updateDateStamp(); CastorUtils.marshalWithTranslatedExceptions(group, writer); }
@Override protected DataAccessException doTranslate(String task, String sql, SQLException ex) { if (ex instanceof SQLTransientException) { if (ex instanceof SQLTransientConnectionException) { return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLTransactionRollbackException) { return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLTimeoutException) { return new QueryTimeoutException(buildMessage(task, sql, ex), ex); } } else if (ex instanceof SQLNonTransientException) { if (ex instanceof SQLNonTransientConnectionException) { return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLDataException) { return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLIntegrityConstraintViolationException) { return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLInvalidAuthorizationSpecException) { return new PermissionDeniedDataAccessException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLSyntaxErrorException) { return new BadSqlGrammarException(task, sql, ex); } else if (ex instanceof SQLFeatureNotSupportedException) { return new InvalidDataAccessApiUsageException(buildMessage(task, sql, ex), ex); } } else if (ex instanceof SQLRecoverableException) { return new RecoverableDataAccessException(buildMessage(task, sql, ex), ex); } // Fallback to Spring's own SQL state translation... return null; }
@DataProvider public Object[][] statuses() { TitanMigrationManager happyMigrationManager = new TitanMigrationManager(); TitanMigrationManager sadMigrationManager = new TitanMigrationManager(); Whitebox.setInternalState(happyMigrationManager, IS_MIGRATION_COMPLETE_FIELD_NAME, true); Whitebox.setInternalState(sadMigrationManager, IS_MIGRATION_COMPLETE_FIELD_NAME, false); return new Object[][] { new Object[] { mockDbWithUp(), Status.UP, AcsMonitoringUtilities.HealthCode.AVAILABLE, happyMigrationManager }, { mockDbWithException(new TransientDataAccessResourceException("")), Status.DOWN, AcsMonitoringUtilities.HealthCode.UNAVAILABLE, happyMigrationManager }, { mockDbWithException(new QueryTimeoutException("")), Status.DOWN, AcsMonitoringUtilities.HealthCode.UNAVAILABLE, happyMigrationManager }, { mockDbWithException(new DataSourceLookupFailureException("")), Status.DOWN, AcsMonitoringUtilities.HealthCode.UNREACHABLE, happyMigrationManager }, { mockDbWithException(new PermissionDeniedDataAccessException("", null)), Status.DOWN, AcsMonitoringUtilities.HealthCode.MISCONFIGURATION, happyMigrationManager }, { mockDbWithException(new ConcurrencyFailureException("")), Status.DOWN, AcsMonitoringUtilities.HealthCode.ERROR, happyMigrationManager }, { mockDbWithUp(), Status.DOWN, AcsMonitoringUtilities.HealthCode.MIGRATION_INCOMPLETE, sadMigrationManager }, }; }
@Override public DataAccessException translateExceptionIfPossible(RuntimeException ex) { if (ex.getCause() instanceof SolrServerException) { SolrServerException solrServerException = (SolrServerException) ex.getCause(); if (solrServerException.getCause() instanceof SolrException) { SolrException solrException = (SolrException) solrServerException.getCause(); // solr 4.x moved ParseExecption from org.apache.lucene.queryParser to org.apache.lucene.queryparser.classic // therefore compare ShortClassName instead of using instanceof expression if (solrException.getCause() != null && ClassUtils.getShortName(solrException.getCause().getClass()).equalsIgnoreCase("ParseException")) { return new InvalidDataAccessApiUsageException((solrException.getCause()).getMessage(), solrException.getCause()); } else { ErrorCode errorCode = ErrorCode.getErrorCode(solrException.code()); switch (errorCode) { case NOT_FOUND: case SERVICE_UNAVAILABLE: case SERVER_ERROR: return new DataAccessResourceFailureException(solrException.getMessage(), solrException); case FORBIDDEN: case UNAUTHORIZED: return new PermissionDeniedDataAccessException(solrException.getMessage(), solrException); case BAD_REQUEST: return new InvalidDataAccessApiUsageException(solrException.getMessage(), solrException); case UNKNOWN: return new UncategorizedSolrException(solrException.getMessage(), solrException); default: break; } } } else if (solrServerException.getCause() instanceof ConnectException) { return new DataAccessResourceFailureException(solrServerException.getCause().getMessage(), solrServerException.getCause()); } } return null; }
protected void translateException(PermissionDeniedDataAccessException e) throws DataAccessException { if (e.getCause() instanceof gov.va.hmp.vista.rpc.broker.protocol.BadCredentialsException) { throw new BadCredentialsException(e.getCause().getMessage()); } else if (e.getCause() instanceof VerifyCodeExpiredException) { throw new CredentialsExpiredException(e.getCause().getMessage()); } else if (e.getCause() instanceof RpcContextAccessDeniedException) { throw new AuthenticationServiceException(e.getCause().getMessage(), e.getCause()); } else if (e.getCause() instanceof ChangeVerifyCodeException) { throw new AuthenticationServiceException(e.getCause().getMessage(), e.getCause()); } else if (e.getCause() instanceof gov.va.hmp.vista.rpc.broker.protocol.LockedException) { throw new LockedException(e.getCause().getMessage()); } else{ throw e; } }
@Test public void testBadCredentials() { when(mockRpcTemplate.execute(any(ConnectionCallback.class), eq("vrpcb://" + RpcUriUtils.toAuthority(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME)))).thenThrow(new PermissionDeniedDataAccessException("", new BadCredentialsException())); try { s.login(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, null, null, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME); fail("expected a Spring Security BadCredentialsException"); } catch (org.springframework.security.authentication.BadCredentialsException e) { // NOOP } verify(mockRpcTemplate).execute(any(ConnectionCallback.class), eq("vrpcb://" + RpcUriUtils.toAuthority(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME))); }
@Test public void testVerifyCodeExpired() { when(mockRpcTemplate.execute(any(ConnectionCallback.class), eq("vrpcb://" + RpcUriUtils.toAuthority(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME)))).thenThrow(new PermissionDeniedDataAccessException("",new VerifyCodeExpiredException())); try { s.login(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, null, null, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME); fail("expected a Spring Security BadCredentialsException"); } catch (CredentialsExpiredException e) { // NOOP } verify(mockRpcTemplate).execute(any(ConnectionCallback.class), eq("vrpcb://" + RpcUriUtils.toAuthority(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME))); }
@Test public void testLocked() { when(mockRpcTemplate.execute(any(ConnectionCallback.class), eq("vrpcb://" + RpcUriUtils.toAuthority(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME)))).thenThrow(new PermissionDeniedDataAccessException("", new LockedException("sfdsfwesdfsdf"))); try { s.login(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, null, null, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME); fail("expected a Spring Security BadCredentialsException"); } catch (org.springframework.security.authentication.LockedException e) { // NOOP } verify(mockRpcTemplate).execute(any(ConnectionCallback.class), eq("vrpcb://" + RpcUriUtils.toAuthority(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME))); }
@Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { if (shouldResolveException(request, response, handler, ex)) { ModelAndView modelAndView = super.doResolveException(request, response, handler, ex); if (modelAndView == null) { if (ex instanceof NotFoundException) { modelAndView = handleNotFound((NotFoundException) ex, request, response); } else if (ex instanceof BadRequestException) { modelAndView = handleBadRequest(ex, request, response); } else if (ex instanceof PermissionDeniedDataAccessException) { SecurityContext ctx = SecurityContextHolder.getContext(); Authentication auth = ctx.getAuthentication(); if(auth instanceof VistaAuthenticationToken && StringUtils.hasText(((VistaAuthenticationToken)auth).getAppHandle())) { modelAndView = handleCCOWTokenTimeout(ex, request, response); } else { modelAndView = handleBadCredentials(ex, request, response); } request.getSession().invalidate(); } else { modelAndView = handleInternalServerError(ex, request, response); } } return modelAndView; } return null; }
@ExceptionHandler({ PermissionDeniedDataAccessException.class }) @ResponseBody public ResponseEntity<E> handlePermissionDeniedDataAccessException(final PermissionDeniedDataAccessException ex, final WebRequest request) { final HttpStatus status = HttpStatus.UNAUTHORIZED; final E errorResponse = createErrorResponse(status, i18n(request, "rest-error.PermissionDeniedDataAccessException")); logException(ex, errorResponse, request); return new ResponseEntity<>(errorResponse, status); }
@Override protected DataAccessException doTranslate(String task, String sql, SQLException ex) { if (ex instanceof SQLTransientException) { if (ex instanceof SQLTransactionRollbackException) { return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex); } if (ex instanceof SQLTransientConnectionException) { return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex); } if (ex instanceof SQLTimeoutException) { return new QueryTimeoutException(buildMessage(task, sql, ex), ex); } } else if (ex instanceof SQLNonTransientException) { if (ex instanceof SQLDataException) { return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLFeatureNotSupportedException) { return new InvalidDataAccessApiUsageException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLIntegrityConstraintViolationException) { return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLInvalidAuthorizationSpecException) { return new PermissionDeniedDataAccessException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLNonTransientConnectionException) { return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLSyntaxErrorException) { return new BadSqlGrammarException(task, sql, ex); } } else if (ex instanceof SQLRecoverableException) { return new RecoverableDataAccessException(buildMessage(task, sql, ex), ex); } // Fallback to Spring's own SQL state translation... return null; }
@Override public DataAccessException translateExceptionIfPossible(RuntimeException ex) { if (ex.getCause() instanceof SolrServerException) { SolrServerException solrServerException = (SolrServerException) ex.getCause(); if (solrServerException.getCause() instanceof SolrException) { SolrException solrException = (SolrException) solrServerException.getCause(); // solr 4.x moved ParseExecption from org.apache.lucene.queryParser to org.apache.lucene.queryparser.classic // therefore compare ShortClassName instead of using instanceof expression if (solrException.getCause() != null && ClassUtils.getShortName(solrException.getCause().getClass()).equalsIgnoreCase("ParseException")) { return new InvalidDataAccessApiUsageException((solrException.getCause()).getMessage(), solrException.getCause()); } else { ErrorCode errorCode = SolrException.ErrorCode.getErrorCode(solrException.code()); switch (errorCode) { case NOT_FOUND: case SERVICE_UNAVAILABLE: case SERVER_ERROR: return new DataAccessResourceFailureException(solrException.getMessage(), solrException); case FORBIDDEN: case UNAUTHORIZED: return new PermissionDeniedDataAccessException(solrException.getMessage(), solrException); case BAD_REQUEST: return new InvalidDataAccessApiUsageException(solrException.getMessage(), solrException); case UNKNOWN: return new UncategorizedSolrException(solrException.getMessage(), solrException); default: break; } } } else if (solrServerException.getCause() instanceof ConnectException) { return new DataAccessResourceFailureException(solrServerException.getCause().getMessage(), solrServerException.getCause()); } } return null; }
/** * <p>saveResponseTimeData</p> * * @param locationMonitor a {@link java.lang.String} object. * @param monSvc a {@link org.opennms.netmgt.model.OnmsMonitoredService} object. * @param responseTime a double. * @param pkg a {@link org.opennms.netmgt.config.poller.Package} object. */ @Override public void saveResponseTimeData(final String locationMonitor, final OnmsMonitoredService monSvc, final double responseTime, final Package pkg) { final String svcName = monSvc.getServiceName(); final Service svc = m_pollerConfig.getServiceInPackage(svcName, pkg); final String dsName = getServiceParameter(svc, "ds-name"); if (dsName == null) { return; } final String rrdRepository = getServiceParameter(svc, "rrd-repository"); if (rrdRepository == null) { return; } final String rrdDir = rrdRepository+File.separatorChar+"distributed"+File.separatorChar+locationMonitor+File.separator+str(monSvc.getIpAddress()); try { final File rrdFile = new File(rrdDir, dsName); if (!rrdFile.exists()) { RrdUtils.createRRD(locationMonitor, rrdDir, dsName, m_pollerConfig.getStep(pkg), "GAUGE", 600, "U", "U", m_pollerConfig.getRRAList(pkg)); } RrdUtils.updateRRD(locationMonitor, rrdDir, dsName, System.currentTimeMillis(), String.valueOf(responseTime)); } catch (final RrdException e) { throw new PermissionDeniedDataAccessException("Unable to store rrdData from "+locationMonitor+" for service "+monSvc, e); } }
/** {@inheritDoc} */ public void saveResponseTimeData(final String locationMonitor, final OnmsMonitoredService monSvc, final double responseTime, final Package pkg) { getReadLock().lock(); try { final String svcName = monSvc.getServiceName(); final Service svc = getServiceInPackage(svcName, pkg); final String dsName = getServiceParameter(svc, "ds-name"); if (dsName == null) { return; } final String rrdRepository = getServiceParameter(svc, "rrd-repository"); if (rrdRepository == null) { return; } final String rrdDir = rrdRepository+File.separatorChar+"distributed"+File.separatorChar+locationMonitor+File.separator+str(monSvc.getIpAddress()); try { final File rrdFile = new File(rrdDir, dsName); if (!rrdFile.exists()) { RrdUtils.createRRD(locationMonitor, rrdDir, dsName, getStep(pkg), "GAUGE", 600, "U", "U", getRRAList(pkg)); } RrdUtils.updateRRD(locationMonitor, rrdDir, dsName, System.currentTimeMillis(), String.valueOf(responseTime)); } catch (final RrdException e) { throw new PermissionDeniedDataAccessException("Unable to store rrdData from "+locationMonitor+" for service "+monSvc, e); } } finally { getReadLock().unlock(); } }
@Test public void errorCodeTranslation() { SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES); SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 0); DataIntegrityViolationException divex = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx); assertEquals(dataIntegrityViolationEx, divex.getCause()); SQLException featureNotSupEx = SQLExceptionSubclassFactory.newSQLFeatureNotSupportedException("", "", 0); InvalidDataAccessApiUsageException idaex = (InvalidDataAccessApiUsageException) sext.translate("task", "SQL", featureNotSupEx); assertEquals(featureNotSupEx, idaex.getCause()); SQLException dataIntegrityViolationEx2 = SQLExceptionSubclassFactory.newSQLIntegrityConstraintViolationException("", "", 0); DataIntegrityViolationException divex2 = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx2); assertEquals(dataIntegrityViolationEx2, divex2.getCause()); SQLException permissionDeniedEx = SQLExceptionSubclassFactory.newSQLInvalidAuthorizationSpecException("", "", 0); PermissionDeniedDataAccessException pdaex = (PermissionDeniedDataAccessException) sext.translate("task", "SQL", permissionDeniedEx); assertEquals(permissionDeniedEx, pdaex.getCause()); SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLNonTransientConnectionException("", "", 0); DataAccessResourceFailureException darex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataAccessResourceEx); assertEquals(dataAccessResourceEx, darex.getCause()); SQLException badSqlEx2 = SQLExceptionSubclassFactory.newSQLSyntaxErrorException("", "", 0); BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", badSqlEx2); assertEquals("SQL2", bsgex2.getSql()); assertEquals(badSqlEx2, bsgex2.getSQLException()); SQLException tranRollbackEx = SQLExceptionSubclassFactory.newSQLTransactionRollbackException("", "", 0); ConcurrencyFailureException cfex = (ConcurrencyFailureException) sext.translate("task", "SQL", tranRollbackEx); assertEquals(tranRollbackEx, cfex.getCause()); SQLException transientConnEx = SQLExceptionSubclassFactory.newSQLTransientConnectionException("", "", 0); TransientDataAccessResourceException tdarex = (TransientDataAccessResourceException) sext.translate("task", "SQL", transientConnEx); assertEquals(transientConnEx, tdarex.getCause()); SQLException transientConnEx2 = SQLExceptionSubclassFactory.newSQLTimeoutException("", "", 0); QueryTimeoutException tdarex2 = (QueryTimeoutException) sext.translate("task", "SQL", transientConnEx2); assertEquals(transientConnEx2, tdarex2.getCause()); SQLException recoverableEx = SQLExceptionSubclassFactory.newSQLRecoverableException("", "", 0); RecoverableDataAccessException rdaex2 = (RecoverableDataAccessException) sext.translate("task", "SQL", recoverableEx); assertEquals(recoverableEx, rdaex2.getCause()); // Test classic error code translation. We should move there next if the exception we pass in is not one // of the new sub-classes. SQLException sexEct = new SQLException("", "", 1); BadSqlGrammarException bsgEct = (BadSqlGrammarException) sext.translate("task", "SQL-ECT", sexEct); assertEquals("SQL-ECT", bsgEct.getSql()); assertEquals(sexEct, bsgEct.getSQLException()); // Test fallback. We assume that no database will ever return this error code, // but 07xxx will be bad grammar picked up by the fallback SQLState translator SQLException sexFbt = new SQLException("", "07xxx", 666666666); BadSqlGrammarException bsgFbt = (BadSqlGrammarException) sext.translate("task", "SQL-FBT", sexFbt); assertEquals("SQL-FBT", bsgFbt.getSql()); assertEquals(sexFbt, bsgFbt.getSQLException()); // and 08xxx will be data resource failure (non-transient) picked up by the fallback SQLState translator SQLException sexFbt2 = new SQLException("", "08xxx", 666666666); DataAccessResourceFailureException darfFbt = (DataAccessResourceFailureException) sext.translate("task", "SQL-FBT2", sexFbt2); assertEquals(sexFbt2, darfFbt.getCause()); }
public void testErrorCodeTranslation() { if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_16) { return; } SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES); SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 0); DataIntegrityViolationException divex = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx); assertEquals(dataIntegrityViolationEx, divex.getCause()); SQLException featureNotSupEx = SQLExceptionSubclassFactory.newSQLFeatureNotSupportedException("", "", 0); InvalidDataAccessApiUsageException idaex = (InvalidDataAccessApiUsageException) sext.translate("task", "SQL", featureNotSupEx); assertEquals(featureNotSupEx, idaex.getCause()); SQLException dataIntegrityViolationEx2 = SQLExceptionSubclassFactory.newSQLIntegrityConstraintViolationException("", "", 0); DataIntegrityViolationException divex2 = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx2); assertEquals(dataIntegrityViolationEx2, divex2.getCause()); SQLException permissionDeniedEx = SQLExceptionSubclassFactory.newSQLInvalidAuthorizationSpecException("", "", 0); PermissionDeniedDataAccessException pdaex = (PermissionDeniedDataAccessException) sext.translate("task", "SQL", permissionDeniedEx); assertEquals(permissionDeniedEx, pdaex.getCause()); SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLNonTransientConnectionException("", "", 0); DataAccessResourceFailureException darex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataAccessResourceEx); assertEquals(dataAccessResourceEx, darex.getCause()); SQLException badSqlEx2 = SQLExceptionSubclassFactory.newSQLSyntaxErrorException("", "", 0); BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", badSqlEx2); assertEquals("SQL2", bsgex2.getSql()); assertEquals(badSqlEx2, bsgex2.getSQLException()); SQLException tranRollbackEx = SQLExceptionSubclassFactory.newSQLTransactionRollbackException("", "", 0); ConcurrencyFailureException cfex = (ConcurrencyFailureException) sext.translate("task", "SQL", tranRollbackEx); assertEquals(tranRollbackEx, cfex.getCause()); SQLException transientConnEx = SQLExceptionSubclassFactory.newSQLTransientConnectionException("", "", 0); TransientDataAccessResourceException tdarex = (TransientDataAccessResourceException) sext.translate("task", "SQL", transientConnEx); assertEquals(transientConnEx, tdarex.getCause()); SQLException transientConnEx2 = SQLExceptionSubclassFactory.newSQLTimeoutException("", "", 0); QueryTimeoutException tdarex2 = (QueryTimeoutException) sext.translate("task", "SQL", transientConnEx2); assertEquals(transientConnEx2, tdarex2.getCause()); SQLException recoverableEx = SQLExceptionSubclassFactory.newSQLRecoverableException("", "", 0); RecoverableDataAccessException rdaex2 = (RecoverableDataAccessException) sext.translate("task", "SQL", recoverableEx); assertEquals(recoverableEx, rdaex2.getCause()); // Test classic error code translation. We should move there next if the exception we pass in is not one // of the new sub-classes. SQLException sexEct = new SQLException("", "", 1); BadSqlGrammarException bsgEct = (BadSqlGrammarException) sext.translate("task", "SQL-ECT", sexEct); assertEquals("SQL-ECT", bsgEct.getSql()); assertEquals(sexEct, bsgEct.getSQLException()); // Test fallback. We assume that no database will ever return this error code, // but 07xxx will be bad grammar picked up by the fallback SQLState translator SQLException sexFbt = new SQLException("", "07xxx", 666666666); BadSqlGrammarException bsgFbt = (BadSqlGrammarException) sext.translate("task", "SQL-FBT", sexFbt); assertEquals("SQL-FBT", bsgFbt.getSql()); assertEquals(sexFbt, bsgFbt.getSQLException()); // and 08xxx will be data resource failure (non-transient) picked up by the fallback SQLState translator SQLException sexFbt2 = new SQLException("", "08xxx", 666666666); DataAccessResourceFailureException darfFbt = (DataAccessResourceFailureException) sext.translate("task", "SQL-FBT2", sexFbt2); assertEquals(sexFbt2, darfFbt.getCause()); }
@Test public void testForbiddenError() { Assert.assertThat(exceptionTranslator.translateExceptionIfPossible(createWrappedSolrServerExceptionFor( ErrorCode.FORBIDDEN, "message")), IsInstanceOf.instanceOf(PermissionDeniedDataAccessException.class)); }
@Test public void testUnauthorizedError() { Assert.assertThat(exceptionTranslator.translateExceptionIfPossible(createWrappedSolrServerExceptionFor( ErrorCode.UNAUTHORIZED, "message")), IsInstanceOf.instanceOf(PermissionDeniedDataAccessException.class)); }