JBoss 7: No EJB receiver available - ejb

I'm pretty newbie with JBoss 7. I'm facing strange behaviour. Sometimes, when I try to invoke a session bean, I run into the following exception:
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.util.List myServlet.getData() throws myException' threw an unexpected exception: java.lang.IllegalStateException: No EJB receiver available for handling [appName:myAppNameEE,modulename:myModuleEJB,distinctname:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#3e23bd28
It usually happens when run my GWT application from Eclipse. The exception does not occur always. Sometimes it occurs fewer than others. Sometimes it occurs pretty every time I call a session bean and it's a pain. I read tutorial (https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using+JNDI?_sscc=t) and I am pretty sure to have the jboss-ejb-client.properties in the right place.
my jboss-ejb-client looks like:
endpoint.name=myAppEE/myAppEJB
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=localhost
remote.connection.default.port = 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
it is located in:
myAppEJB\ejbModule\com\myApp\ejb\conf
The businness delegate:
public class myAppServerDelegate extends ServerDelegate{
private Logger logger = Logger.getLogger(myAppServerDelegate.class.getName());
private myAppRemote theSession = null;
public myAppServerDelegate() throws Exception {
try {
theSession = (myAppRemote) getJndiContext().lookup(getJindiLookupName(myAppServerDelegate.class, myAppRemote.class));
} catch (NamingException e) {
throw (e);
}
}
public List<myDataDTO> getAllmyDataBy(String a, String b,
String c, String d,Integer e,
Integer f) throws ServerDelegateException {
return theSession.getAllmyDataBy(a, b, c, d,e,f);
}
public Integer getCountmyDataBy(String a, String b, String c, String d) throws ServerDelegateException {
return theSession.getCountmyDataBy(a, b, c, d);
}
...
public String getServiceMessage() {
return theSession.getServiceMessage();
}
...
}
The session bean:
#Stateless
public class myAppSession implements myAppRemote {
private Logger logger = Logger.getLogger(myAppSession.class.getName());
#PersistenceContext
protected EntityManager entityManager;
#EJB
private myAppHomeLocal beanmyApp;
...
public String getServiceMessage() {
return "MESSAGGIODISERVIZIO";
}
public List<myDataDTO> getAllmyDataBy(String a,String b,
String c, String d,Integer e,
Integer f) throws ServerDelegateException {
logger.info("myAppSession.getAllmyDataBy.");
List<myData> entityList = findByParms(a, b, c, d,e,f);
return myDataAssemblyDTO.getmyDataDTOList(entityList);
}
public Integer getCountmyDataBy(String a,String b, String c, String d) throws ServerDelegateException {
return findByParmsCount(a, b, c, d);
}
...
}
The servlet:
...
#SuppressWarnings("serial")
public class MyGenericServiceImpl extends RemoteServiceServlet implements MyGenericService {
private MyAppServerDelegate myAppServerDelegate = null;
public MyGenericServiceImpl() throws Exception{
super();
myAppServerDelegate = new MyAppServerDelegate();
}
private MyAppServerDelegate getDelegate() {
return myAppServerDelegate;
}
private myGWTException buildLocalExceptionFromServerException(ServerDelegateException sde) {
myGWTException x = new myGWTException();
x.setParms(sde.guiMessage,sde.timestamp,sde.tipoEvento);
return x;
}
#Override
public PagingLoadResult<myDataBean> getAllmyDataBy(String a, String b, String c, PagingLoadConfig plc) throws MyGWTException {
try {
String cs = ((UserSessionBean)this.getThreadLocalRequest().getSession().getAttribute("user")).getCodiceStudio();
List<myDataBean> tsb = MyDataClientAssembly.getMyDataBeanList(myAppServerDelegate.getAllmyDataBy(cs, a, b, c, plc.getOffset(), plc.getLimit()));
return new BasePagingLoadResult<MyDataBean>(tsb, plc.getOffset(), myDataServerDelegate.getCountmyDataBy(cs, a, b, c));
} catch (ServerDelegateException sde) {
throw buildLocalExceptionFromServerException(sde);
}
}
#Override
public String getServiceMessage() {
return getDelegate().getServiceMessage();
}
#Override
public Integer getCountmyDataBy(String a, String b, String c) throws AmbrogioGWTException {
try {
String cs = ((UserSessionBean)this.getThreadLocalRequest().getSession().getAttribute("user")).getCs();
return myAppServerDelegate.getCountmtDataBy(cs, a, b, c);
} catch (ServerDelegateException sde) {
throw buildLocalExceptionFromServerException(sde);
}
}
}
The serverdelegate:
public class ServerDelegate {
static public String getJindiLookupName( Class<?> theBeanClass, Class<?> theSessionClass) throws NamingException {
String jbossServerName = System.getProperty("jboss.server.name");
if (jbossServerName== null || "".equals(jbossServerName)){
return "myAppEE/myAppEJB/"+ theBeanClass.getSimpleName() + "!" + theSessionClass.getName();
}else{
return "java:global/myAppEE/myAppEJB/" + theBeanClass.getSimpleName() + "!" + theSessionClass.getName();
}
}
static public Context getJndiContext() throws NamingException {
System.out.println("ServerDelegate.getJndiContext");
final Properties jndiProperties = new Properties();
String jbossServerName = System.getProperty("jboss.server.name");
if (jbossServerName== null || "".equals(jbossServerName)){
jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, org.jboss.naming.remote.client.InitialContextFactory.class.getName());
jndiProperties.put(Context.PROVIDER_URL, "remote://localhost:4447");
jndiProperties.put("jboss.naming.client.ejb.context", true);
jndiProperties.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
}
return new InitialContext(jndiProperties);
}
}
I can't figure out what's going on. TIA.
Francesco

It could be an issue of using the Local vs Remote interface or a connection issue.
Try enabling the TRACE log level on the org.jboss.ejb.client package. If you already have a log4j.properties in your classpath, include this line:
log4j.logger.org.jboss.ejb.client=TRACE
This post includes other clues for debugging the JBoss EJB client.

There is a list of dependencies I had to include in my mavens pom.xml file. These include
jboss-ejb-client
xnio-nio
jboss-remote-naming
jboss-sasl
jboss-transaction-ap
jboss-marshalling
jboss-marshalling-river
I was able to successfully make my remote request from my standalone java client however I do see the following issues
Jboss 7.1:
13:43:25,028 INFO [stdout] (EJB default - 6) Hello world
13:43:25,825 ERROR [org.jboss.remoting.remote.connection] (Remoting "mycomputername" read-1) JBREM000200: Remote connection failed: java.io.IOException: An existing connection was forcibly closed by the remote host
My java ejb client:
WARN [Remoting "client-endpoint" task-2] (ChannelAssociation.java:320) - Unsupported message received with header 0xffffffff
Reading online people seem to have solved this by updating the version of certain jars. However, I have yet to find a successful solution.
Update: I included the jboss-client.jar in my classpath when deploying a standalone ejb client. Works great.
java -classpath "$JBOSS_HOME/bin/client/jboss-client.jar;./my-ejb-client.jar" com.test.Myclient

In the class MyAppServerDelegate, you will have to instantiate the attribute "theSession" in the following methods rather than in the constructor:
getAllmyDataBy();
getCountmyDataBy();
getServiceMessage();
The result of theSession method invocation should be stored in a temporary variable, and afterwards call getJndiContext().close(), and then return the temporary value.
Every connection has to be explicitly closed. Indeed, the exception occurs when the maximum number of allowed connections has been reached.

Related

Catching Message Handling Exceptions with the #Exceptionhandler

I have two application e.g) A, B
A has a Saga
B is just web application
A sent Command messages to B and
B sent exception for that Command to A's Saga and A's Saga received well
and B have a #ExceptionHandler which I hope to be invoked but it's not working
How can I make them be invoked?
EDIT
this is A application's Saga that sends command messages to B application
and deals with exception which B sent
#Saga
public class OrderSaga {
#Autowired
private transient CommandGateway commandGateway;
#StartSaga
#SagaEventHandler(associationProperty = "orderId")
public void handle(CreateOrderEvent evt) {
String paymentId = UUID.randomUUID().toString();
SagaLifecycle.associateWith("paymentId", paymentId);
commandGateway.send(new CreatedPaymentCommand(paymentId, evt.getUserId(),evt.getFoodPrice())).exceptionally(exp -> {
System.out.println("got it");
System.out.println(exp.getMessage());
return null;
});
}
}
this is B application that throws exception for test
#Aggregate
#NoArgsConstructor
public class PaymentAggregate {
#AggregateIdentifier
private String paymentId;
private String userId;
private PaymentStatus status;
#CommandHandler
public PaymentAggregate(CreatedPaymentCommand cmd) {
throw new IllegalStateException("this exception was came from payment aggregates");
// AggregateLifecycle.apply(new CreatedPaymentEvent(cmd.getPaymentId(),
// cmd.getUserId(),cmd.getMoney()));
}
#ExceptionHandler(resultType = IllegalStateException.class)
public void error(IllegalStateException exp) {
System.out.println(exp.getMessage());
}
// I want this #ExceptionHandler to be invoked
#EventSourcingHandler
public void on(CreatedPaymentEvent evt) {
this.paymentId = evt.getPaymentId();
this.userId = evt.getUserId();
}
}
A application catch exception well like below
2021-08-24 11:46:43.534 WARN 14244 --- [ault-executor-2] o.a.c.gateway.DefaultCommandGateway : Command 'com.common.cmd.CreatedPaymentCommand' resulted in org.axonframework.commandhandling.CommandExecutionException(this exception was came from payment aggregates)
got it
this exception was came from payment aggregates
but B is not I thought that B's #ExceptionHandler will catch that exception
in short, How can I make B's #ExceptionHandler to be invoked
It doesn't work right now because the exception is thrown from the constructor of your aggregate.
As you are using a constructor command handler, there is no instance present yet.
And without an instance, Axon Framework cannot spot the #ExceptionHandler annotated method you've set up.
This is the only missing point for the exception handlers at this stage. Honestly, the reference guide should be a bit more specific about this. I am sure this will change in the future, though.
There's a different approach for having a command handler that constructs the aggregate and that can use the #ExceptionHandler: with the #CreationPolicy annotation. The reference guide has this to say about it, by the way.
Thus, instead of having a constructor command handler, you would set up a regular command handler using the AggregateCreationPolicy.ALWAYS.
That would adjust your sample like so:
#Aggregate
#NoArgsConstructor
public class PaymentAggregate {
#AggregateIdentifier
private String paymentId;
private String userId;
private PaymentStatus status;
#CommandHandler
#CreationPolicy(AggregateCreationPolicy.ALWAYS)
public void handle(CreatedPaymentCommand cmd) {
throw new IllegalStateException("this exception was came from payment aggregates");
// AggregateLifecycle.apply(new CreatedPaymentEvent(cmd.getPaymentId(),
// cmd.getUserId(),cmd.getMoney()));
}
#ExceptionHandler(resultType = IllegalStateException.class)
public void error(IllegalStateException exp) {
System.out.println(exp.getMessage());
}
// I want this #ExceptionHandler to be invoked
#EventSourcingHandler
public void on(CreatedPaymentEvent evt) {
this.paymentId = evt.getPaymentId();
this.userId = evt.getUserId();
}
}
Please give this a try in your application, #YongD.

Why do I get a CannotAcquireResourceException while trying to connect, when I extend AbstractComboPooledDataSource?

In a Tomcat 8.5.15 environment using an Oracle 11 database, I want to implement a data source that handles encrypted passwords in the context.xml. For example, instead of having:
<Resource
auth="Container"
description="MyDataSource"
driverClass="oracle.jdbc.OracleDriver"
maxPoolSize="100"
minPoolSize="10"
acquireIncrement="1"
name="jdbc/MyDataSource"
user="me"
password="mypassword"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:oracle:thin:#mydb:1521:dev12c"
/>
I'd like to have something like the following, where only the password and type have changed:
<Resource
auth="Container"
description="MyDataSource"
driverClass="oracle.jdbc.OracleDriver"
maxPoolSize="100"
minPoolSize="10"
acquireIncrement="1"
name="jdbc/MyDataSource"
user="me"
password="D364FEC1CBC1DAEB91A1D8997D4A2482B"
factory="org.apache.naming.factory.BeanFactory"
type="com.mycompany.EncryptedC3p0WrappingDataSource"
jdbcUrl="jdbc:oracle:thin:#mydb:1521:dev12c"
/>
The main change is my implementation of the EncryptedC3p0WrappingDataSource. C3p0's ComboPooledDataSource is final, so I can't extend it. Instead, I extend it's superclass, AbstractComboPooledDataSource, and implement some additional methods. This class contains a ComboPooledDataSource, which is the wrappedDataSource, and is used for the actual work via delegation.
public class EncryptedC3p0WrappingDataSource
extends AbstractComboPooledDataSource
implements PooledDataSource, Serializable, Referenceable
{
/** The actual C3P0 data source that will be used to connect to the database. */
private ComboPooledDataSource wrappedDataSource = new ComboPooledDataSource();
// TODO Should this be retrieved from a pool? How?
/** The object that does the encryting/decrypting. */
private Encryptor encryptor;
/**Construct the data source, with the necessary Encryptor. */
public EncryptedC3p0WrappingDataSource() {
try {
encryptor = new Encryptor();
} catch (InvalidKeyException | NoSuchAlgorithmException
| NoSuchPaddingException | UnsupportedEncodingException e) {
log.fatal("Error instantiating decryption class.", e);
throw new RuntimeException(e);
}
}
/**
* Set the in-memory password of the wrapped data source to the decrypted password.
* #param encryptedPassword the encrypted password, as read from a file.
*/
public void setPassword(String encryptedPassword) {
try {
String decryptedPassword
= encryptor.decrypt(encryptedPassword, Encryptor.AES_ALGORITHM);
log.info("***************** Successfully decrypted "
+ encryptedPassword + " to " + decryptedPassword);
wrappedDataSource.setPassword(decryptedPassword);
} catch (Exception e) { e.printStackTrace(); }
}
public void setDriverClass(String driverClass) throws PropertyVetoException {
wrappedDataSource.setDriverClass(driverClass);
}
public void setJdbcUrl(String jdbcUrl) {
wrappedDataSource.setJdbcUrl(jdbcUrl);
}
public void setDescription(String description) {
wrappedDataSource.setDescription(description);
}
public void setMaxPoolSize(int maxPoolSize) {
wrappedDataSource.setMaxPoolSize(maxPoolSize);
}
public void setMinPoolSize(int minPoolSize) {
wrappedDataSource.setMinPoolSize(minPoolSize);
}
public void setAcquireIncrement(int acquireIncrement) {
wrappedDataSource.setAcquireIncrement(acquireIncrement);
}
public Connection getConnection() throws SQLException {
return wrappedDataSource.getConnection();
}
public Connection getConnection(String name, String password) throws SQLException {
return wrappedDataSource.getConnection(name, password);
}
}
When I run our application under Tomcat with the first configuration (ComboPooledDataSource), it runs fine. When I try the second configuration (EncryptedC3p0WrappingDataSource), I get the following exception:
2017-07-21 07:57:29,962 FATAL [XXX.DataSourceFactory] Connections could not be acquired from the underlying database!
java.sql.SQLException: Connections could not be acquired from the underlying database!
at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:690)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
at com.mycompany.EncryptedC3p0WrappingDataSource.getConnection(EncryptedC3p0WrappingDataSource.java:116)
...
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1463)
at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:639)
at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:549)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:756)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:683)
... 69 more
I have looked at this extensively in the debugger. The encryption and decryption part appears to be happening correctly. My EncryptedC3p0WrappingDataSource.getConnection() method results in a call to the ComboPooledDataSource.getConnection() method (the inherited AbstractPoolBackedDataSource.getConnection() method, so why am I getting the exception?
UPDATE:
If I modify my get setPassword method to also use setOverrideDefaultPassword:
public void setPassword(String encryptedPassword) {
try {
String decryptedPassword
= encryptor.decrypt(encryptedPassword, Encryptor.AES_ALGORITHM);
log.info("***************** Successfully decrypted "
+ encryptedPassword + " to " + decryptedPassword);
wrappedDataSource.setPassword(decryptedPassword);
wrappedDataSource.setOverrideDefaultPassword(decryptedPassword);
} catch (Exception e) { e.printStackTrace(); }
}
I get a different exception:
Caused by: java.sql.SQLException: com.mchange.v2.c3p0.impl.NewProxyConnection#7e30531e
[wrapping: oracle.jdbc.driver.T4CConnection#51dba714]
is not a wrapper for or implementation of oracle.jdbc.OracleConnection
at com.mchange.v2.c3p0.impl.NewProxyConnection.unwrap(NewProxyConnection.java:1744)
at org.jaffa.security.JDBCSecurityPlugin.executeStoredProcedure(JDBCSecurityPlugin.java:117)
... 67 more
UPDATE 2:
I've posted a closely related, and hopefully simpler, question here.
The error was a result of a class loading problem, where the Oracle classes were being loaded from multiple jars (%CATALINA_HOME%\lib\ojdbc7-12.1.0.2.0.jar and %CATALINA_HOME%\webapps\my-webapp-1.0.0\WEB-INF\lib\ojdbc7-12.1.0.2.0.jar) by different class loaders. When I deleted %CATALINA_HOME%\webapps\my-webapp-1.0.0\WEB-INF\lib\ojdbc7-12.1.0.2.0.jar, my problem went away.
These sources (1, 2, 3) discuss this in more detail.

SoapFault handling with Spring WS client - WebServiceGatewaySupport and WebServiceTemplate

I am trying to write a Spring WS client using WebServiceGatewaySupport. I managed to test the client for a successful request and response. Now I wanted to write test cases for soap faults.
public class MyClient extends WebServiceGatewaySupport {
public ServiceResponse method(ServiceRequest serviceRequest) {
return (ServiceResponse) getWebServiceTemplate().marshalSendAndReceive(serviceRequest);
}
#ActiveProfiles("test")
#RunWith(SpringRunner.class)
#SpringBootTest(classes = SpringTestConfig.class)
#DirtiesContext
public class MyClientTest {
#Autowired
private MyClient myClient;
private MockWebServiceServer mockServer;
#Before
public void createServer() throws Exception {
mockServer = MockWebServiceServer.createServer(myClient);
}
}
My question is how do i stub the soap fault response in the mock server, so that my custom FaultMessageResolver will be able to unmarshall soap fault?
I tried couple of things below, but nothing worked.
// responsePayload being SoapFault wrapped in SoapEnvelope
mockServer.expect(payload(requestPayload))
.andRespond(withSoapEnvelope(responsePayload));
// tried to build error message
mockServer.expect(payload(requestPayload))
.andRespond(withError("soap fault string"));
// tried with Exception
mockServer.expect(payload(requestPayload))
.andRespond(withException(new RuntimeException));
Any help is appreciated. Thanks!
Follow Up:
Ok so, withSoapEnvelope(payload) I managed to get the controller to go to my custom MySoapFaultMessageResolver.
public class MyCustomSoapFaultMessageResolver implements FaultMessageResolver {
private Jaxb2Marshaller jaxb2Marshaller;
#Override
public void resolveFault(WebServiceMessage message) throws IOException {
if (message instanceof SoapMessage) {
SoapMessage soapMessage = (SoapMessage) message;
SoapFaultDetailElement soapFaultDetailElement = (SoapFaultDetailElement) soapMessage.getSoapBody()
.getFault()
.getFaultDetail()
.getDetailEntries()
.next();
Source source = soapFaultDetailElement.getSource();
jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setContextPath("com.company.project.schema");
Object object = jaxb2Marshaller.unmarshal(source);
if (object instanceof CustomerAlreadyExistsFault) {
throw new CustomerAlreadyExistsException(soapMessage);
}
}
}
}
But seriously!!! I had to unmarshall every message and check the instance of it. Being a client I should be thorough with all possible exceptions of the service here, and create custom runtime exceptions and throw it from the resolver. Still at the end, its been caught in WebServiceTemplate and re thrown as just a runtime exception.
You could try with something like this:
#Test
public void yourTestMethod() // with no throw here
{
Source requestPayload = new StringSource("<your request>");
String errorMessage = "Your error message from WS";
mockWebServiceServer
.expect(payload(requestPayload))
.andRespond(withError(errorMessage));
YourRequestClass request = new YourRequestClass();
// TODO: set request properties...
try {
yourClient.callMethod(request);
}
catch (Exception e) {
assertThat(e.getMessage()).isEqualTo(errorMessage);
}
mockWebServiceServer.verify();
}
In this part of code mockWebServiceServer represents the instance of MockWebServiceServer class.

How to test common error ErrorController in spring-boot with junit

In a spring boot project, I'd like to test my ErrorController with Junit.
The code is as the following snippet.
#RestController
public class ApiErrorController implements ErrorController {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiErrorController.class);
#Value("${server.error.path}")
private String errorPath;
#Override
public String getErrorPath() {
return this.errorPath;
}
#RequestMapping("/error")
public ResponseEntity<ErrorResult> error(HttpServletRequest request, HttpServletResponse response) {
String requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri");
LOGGER.info("error handling start url = {}", requestURI);
String servletMessage = (String) request.getAttribute("javax.servlet.error.message");
Integer servletStatus = (Integer) request.getAttribute("javax.servlet.error.status_code");
String[] messages = new String[0];
if (!StringUtils.isNullOrEmpty(servletMessage)) {
messages = new String[] { servletMessage };
}
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
try {
if (servletStatus != null && servletStatus instanceof Integer) {
status = HttpStatus.valueOf(servletStatus);
}
} catch (Exception ex) { // test this exception
LOGGER.warn("http status not converted.{}", request.getAttribute("javax.servlet.error.status_code"), ex);
}
ErrorResult body = new ErrorResult();
body.setMessages(messages);
ResponseEntity<ErrorResult> responseResult = new ResponseEntity<>(body, status);
return responseResult;
}
}
When a business exception happened in my Controller(for example AbcController), then the program goes into the ExceptionControllerAdvice class.
If an exception happened in ExceptionControllerAdvice, then the program goes into the above ApiErrorController class.
Could someone tell me how to test the case that HttpStatus.valueOf(servletStatus) fail?
In addition, I want request.getAttribute("javax.servlet.error.message") return a non-empty string.
How to achieve what I'd like to test?
By the way, I don't want to only test the logic of error method. I'd like to use AbcController I mentioned to make the test. What I want is when a error happens in AbcController, then the error method in ApiErrorController can handle it successfully.
APPEND:
For example, ExceptionControllerAdvice will handle the business exception.
#ControllerAdvice(annotations = RestController.class)
public class ExceptionControllerAdvice {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionControllerAdvice.class);
#ExceptionHandler({ BusinessCloudException.class })
public ResponseEntity<ErrorResult> handleBlCloudException(HttpServletRequest request, HttpServletResponse response,
BlCloudException ex) {
HttpStatus status = ErrorUtils.toHttpStatus(ex.getType());
ErrorResult body = new ErrorResult();
body.setMessages(ex.getMessageArray());
ResponseEntity<ErrorResult> responseResult = new ResponseEntity<>(body, status);
return responseResult;
}
}
If there's an error happened in the handleBlCloudException method, then the program goes into ApiErrorController to handle this error.
How do the program produce the a specific servletStatus and javax.servlet.error.message? How to mock to do this?
First of all there is quite a lot going on in that error method. You might consider moving some of the logic to a specialized class / public methods.
Apart from that i would suggest using Mockito.
Fist of all create a method to encapsulate the HttpStatus retrieval:
HttpStatus getHttpStatusByServletStatus(Integer servletStatus){
return HttpStatus.valueOf(servletStatus);
}
and change your code to :
if (servletStatus != null && servletStatus instanceof Integer) {
status = getHttpStatusByServletStatus(servletStatus);
}
Then the test class:
public ApiErrorControllerTest{
#Spy
private ApiErrorController apiErrorController;
#Mock
HttpServletRequest requestMock;
#Mock
HttpServletResponse responseMock;
#Befire
public void init(){
MockitoAnnotations.initMocks(this);
}
#Test
public void test(){
// Arrange
HttpStatus expectedStatus = // expected status
String expectedErrorMessage = // ..
doReturn(expectedStatus).when(apiErrorController)
.getHttpStatusByServletStatus(Mockito.anyString());
when(requestMock.getAttribute("javax.servlet.error.message"))
.thenReturn(expectedErrorMessage);
// other setup..
// Act
apiErrorController.error(requestMock, responseMock);
// Assertions
}

How to disable Redis Caching at run time if redis connection failed

We have rest api application. We use redis for API response caching and internal method caching. If redis connection then it is making our API down. We want to bypass the redis caching if that redis connection fails or any exception instead of making our API down.
There is a interface CacheErrorHandler but it handles the redis get set operation failures not redis connection problems. We are using Spring 4.1.2.
Let's boil this down a bit. Your application uses caching (implemented with Redis). If the Redis connection is stale/closed or otherwise, then you want the application to bypass caching and (presumably) go directly to an underlying data store (e.g. RDBMS). The application Service logic might look similar to...
#Service
class CustomerService ... {
#Autowired
private CustomerRepository customerRepo;
protected CustomerRepository getCustomerRepo() {
Assert.notNull(customerRepo, "The CustomerRepository was not initialized!");
return customerRepo;
}
#Cacheable(value = "Customers")
public Customer getCustomer(Long customerId) {
return getCustomerRepo().load(customerId);
}
...
}
All that matters in Spring core's Caching Abstraction to ascertain a Cache "miss" is that the value returned is null. As such, Spring Caching Infrastructure will then proceed in calling the actual Service method (i.e. getCustomer). Keep in mind on the return of the getCustomerRepo().load(customerId) call, you also need to handle the case where Spring's Caching Infrastructure attempts to now cache the value.
In the spirit of keeping it simple, we will do without AOP, but you should be able to achieve this using AOP as well (your choice).
All you (should) need is a "custom" RedisCacheManager extending the SDR CacheManager implementation, something like...
package example;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheManager;
...
class MyCustomRedisCacheManager extends RedisCacheManager {
public MyCustomerRedisCacheManager(RedisTemplate redisTemplate) {
super(redisTemplate);
}
#Override
public Cache getCache(String name) {
return new RedisCacheWrapper(super.getCache(name));
}
protected static class RedisCacheWrapper implements Cache {
private final Cache delegate;
public RedisCacheWrapper(Cache redisCache) {
Assert.notNull(redisCache, "'delegate' must not be null");
this.delegate = redisCache;
}
#Override
public Cache.ValueWrapper get(Object key) {
try {
delegate.get(key);
}
catch (Exception e) {
return handleErrors(e);
}
}
#Override
public void put(Object key, Object value) {
try {
delegate.put(key, value);
}
catch (Exception e) {
handleErrors(e);
}
}
// implement clear(), evict(key), get(key, type), getName(), getNativeCache(), putIfAbsent(key, value) accordingly (delegating to the delegate).
protected <T> T handleErrors(Exception e) throws Exception {
if (e instanceof <some RedisConnection Exception type>) {
// log the connection problem
return null;
}
else if (<something different>) { // act appropriately }
...
else {
throw e;
}
}
}
}
So, if Redis is unavailable, perhaps the best you can do is log the problem and proceed to let the Service invocation happen. Clearly, this will hamper performance but at least it will raise awareness that a problem exists. Clearly, this could be tied into a more robust notification system, but it is a crude example of the possibilities. The important thing is, your Service remains available while the other services (e.g. Redis) that the application service depends on, may have failed.
In this implementation (vs. my previous explanation) I chose to delegate to the underlying, actual RedisCache implementation to let the Exception occur, then knowing full well a problem with Redis exists, and so that you can deal with the Exception appropriately. However, if you are a certain that the Exception is related to a connection problem upon inspection, you can return "null" to let Spring Caching Infrastructure proceed as if it were a Cache "miss" (i.e. bad Redis Connection == Cache miss, in this case).
I know something like this should help your problem as I built a similar prototype of a "custom" CacheManager implementation for GemFire and one of Pivotal's customers. In that particular UC, the Cache "miss" had to be triggered by an "out-of-date version" of the application domain object where production had a mix of newer and older application clients connecting to GemFire through Spring's Caching Abstraction. The application domain object fields would change in newer versions of the app for instance.
Anyway, hope this helps or gives you more ideas.
Cheers!
So, I was digging through the core Spring Framework Caching Abstraction source today addressing another question and it seems if a CacheErrorHandler is implemented properly, then perhaps a problematic Redis Connection could still result in the desired behavior, e.g. cache "miss" (triggered with the return of a null value).
See the AbstractCacheInvoker source for more details.
The cache.get(key) should result in an exception due to a faulty Redis Connection and thus Exception handler would be invoked...
catch (RuntimeException e) {
getErrorHandler().handleCacheGetError(e, cache, key);
return null; // If the exception is handled, return a cache miss
}
If the CacheErrorHandler properly handles the Cache "get" error (and does not re-throw the/an Exception), then a null value will be returned indicating a cache "miss".
Thank you #John Blum. My solution in Spring Boot is as follows.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.util.Assert;
import java.util.concurrent.Callable;
class CustomRedisCacheManager extends RedisCacheManager {
private static Logger logger = LoggerFactory.getLogger(CustomRedisCacheManager.class);
public CustomRedisCacheManager(RedisOperations redisOperations) {
super(redisOperations);
}
#Override
public Cache getCache(String name) {
return new RedisCacheWrapper(super.getCache(name));
}
protected static class RedisCacheWrapper implements Cache {
private final Cache delegate;
public RedisCacheWrapper(Cache redisCache) {
Assert.notNull(redisCache, "delegate cache must not be null");
this.delegate = redisCache;
}
#Override
public String getName() {
try {
return delegate.getName();
} catch (Exception e) {
return handleException(e);
}
}
#Override
public Object getNativeCache() {
try {
return delegate.getNativeCache();
} catch (Exception e) {
return handleException(e);
}
}
#Override
public Cache.ValueWrapper get(Object key) {
try {
return delegate.get(key);
} catch (Exception e) {
return handleException(e);
}
}
#Override
public <T> T get(Object o, Class<T> aClass) {
try {
return delegate.get(o, aClass);
} catch (Exception e) {
return handleException(e);
}
}
#Override
public <T> T get(Object o, Callable<T> callable) {
try {
return delegate.get(o, callable);
} catch (Exception e) {
return handleException(e);
}
}
#Override
public void put(Object key, Object value) {
try {
delegate.put(key, value);
} catch (Exception e) {
handleException(e);
}
}
#Override
public ValueWrapper putIfAbsent(Object o, Object o1) {
try {
return delegate.putIfAbsent(o, o1);
} catch (Exception e) {
return handleException(e);
}
}
#Override
public void evict(Object o) {
try {
delegate.evict(o);
} catch (Exception e) {
handleException(e);
}
}
#Override
public void clear() {
try {
delegate.clear();
} catch (Exception e) {
handleException(e);
}
}
private <T> T handleException(Exception e) {
logger.error("handleException", e);
return null;
}
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
#Configuration
public class RedisConfig {
#Bean
public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
CustomRedisCacheManager redisCacheManager = new CustomRedisCacheManager(redisTemplate);
redisCacheManager.setUsePrefix(true);
return redisCacheManager;
}
}
actually my response is directed to Mr. #Vivek Aditya - I faced the same problem: new spring-data-redis api and not constructing RedisCacheManager per RedisTemplate. The only option - based on #John Blum suggestions - was to use aspects. And below is my code.
#Aspect
#Component
public class FailoverRedisCacheAspect {
private static class FailoverRedisCache extends RedisCache {
protected FailoverRedisCache(RedisCache redisCache) {
super(redisCache.getName(), redisCache.getNativeCache(), redisCache.getCacheConfiguration());
}
#Override
public <T> T get(Object key, Callable<T> valueLoader) {
try {
return super.get(key, valueLoader);
} catch (RuntimeException ex) {
return valueFromLoader(key, valueLoader);
}
}
private <T> T valueFromLoader(Object key, Callable<T> valueLoader) {
try {
return valueLoader.call();
} catch (Exception e) {
throw new ValueRetrievalException(key, valueLoader, e);
}
}
}
#Around("execution(* org.springframework.cache.support.AbstractCacheManager.getCache (..))")
public Cache beforeSampleCreation(ProceedingJoinPoint proceedingJoinPoint) {
try {
Cache cache = (Cache) proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
if (cache instanceof RedisCache) {
return new FailoverRedisCache((RedisCache) cache);
} else {
return cache;
}
} catch (Throwable ex) {
return null;
}
}
}
works fine for all reasonable scenarios:
app starts fine with redis down
app (still) works during (sudden) redis outage
when redis starts working again, app sees it
Edit: the code is more like a poc - only for "get", and I don't like reinstantiating FailoverRedisCache every single cache hit - there should be a map.
None of the above worked for us when using Spring Boot 2.3.9.release with Redis. We ended up creating and registering our own customized CacheErrorHandler named CustomCacheErrorHandler to override the default SimpleCacheErrorHandler provided by Spring Framework. This will work perfectly.
#Configuration
public class CachingConfiguration extends CachingConfigurerSupport {
#Override
public CacheErrorHandler errorHandler() {
return new CustomCacheErrorHandler();
}
}
class CustomCacheErrorHandler implements CacheErrorHandler {
Logger log = Logger.get(CustomCacheErrorHandler.class);
#Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object o) {
log.error(e.getMessage(), e);
}
#Override
public void handleCachePutError(RuntimeException e, Cache cache, Object o, Object o1) {
log.error(e.getMessage(), e);
}
#Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object o) {
log.error(e.getMessage(), e);
}
#Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
log.error(e.getMessage(), e);
}
}
I had same problem, but, unfortunately, none of the above solutions work for me. I checked for the problem and found out that the executed command never timed out if there was no connection to Redis. So I start to study lettuce library for a solution. I solve the problem by rejecting the command when there is no connection:
#Bean
public LettuceConnectionFactory lettuceConnectionFactory()
{
final SocketOptions socketOptions = SocketOptions.builder().connectTimeout(Duration.ofSeconds(10)).build();
ClientOptions clientOptions = ClientOptions.builder()
.socketOptions(socketOptions)
.autoReconnect(true)
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
.build();
LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
.commandTimeout(Duration.ofSeconds(10))
.clientOptions(clientOptions).build();
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(this.host, this.port);
return new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);
}
All the core Spring Framework Cache abstraction annotations (e.g. #Cacheable) along with the JSR-107 JCache annotations supported by the core SF delegate to the underlying CacheManager under-the-hood, and for Redis, that is the RedisCacheManager.
You would configure the RedisCacheManager in Spring XML configuration meta-data similar to here.
One approach would be to write an AOP Proxy for the (Redis)CacheManager that uses the RedisConnection (indirectly from the RedisTemplate) to ascertain the state of the connection on each (Redis)CacheManger operation.
If the connection has failed, or is closed, for standard cache ops, the (Redis)CacheManager could return an instance of RedisCache for getCache(String name) that always returns null (indicating a Cache miss on an entry), thus passing through to the underlying data store.
There maybe better ways to handle this as I am not an expert on all things Redis (or SDR), but this should work and perhaps give you a few ides of your own.
Cheers.
You can use CacheErrorHandler. But you should make sure to make
RedisCacheManager transactionAware to false in your Redis Cache Config(to make sure the transaction is committed early when executing the caching part and the error is caught by CacheErrorHandler and don't wait until the end of the execution which skips CacheErrorHandler part). The function to set transactionAware to false looks like this:
#Bean
public RedisCacheManager redisCacheManager(LettuceConnectionFactory lettuceConnectionFactory) {
JdkSerializationRedisSerializer redisSerializer = new JdkSerializationRedisSerializer(getClass().getClassLoader());
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(redisDataTTL))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer));
redisCacheConfiguration.usePrefix();
RedisCacheManager redisCacheManager = RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(lettuceConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.build();
redisCacheManager.setTransactionAware(false);
return redisCacheManager;
}

Resources