SAP Business Objects 4.2 Integration - java-8

I need help on how to migrate our java codes with regards to connecting to business objects. It was recently migrated from version 3 to 4.2. We are using java 8 running on WAS 9. I have tried updating the jars based from the forums that I have read but I am encountering this error.
org.apache.axis2.AxisFault: login The exception is of a known origin. (Error: FWB 00008)
at com.businessobjects.dsws.Consumer.dswsExceptionDocToAxisFault(Unknown Source)
at com.businessobjects.dsws.session.Session.login(Unknown Source)
at com.bms.reacts.bobj.BOWSClient.getInstance(BOWSClient.java:138)
at com.bms.reacts.ui.reports.action.GetDynaReportPromptsAction.getBoWsClient(GetDynaReportPromptsAction.java:674)
at com.bms.reacts.ui.reports.action.GetDynaReportPromptsAction.execute(GetDynaReportPromptsAction.java:153)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1234)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:778)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:477)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:143)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:96)
at com.bms.sidetrack.DebugFilter.doFilter(DebugFilter.java:103)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:197)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:90)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:969)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1109)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:82)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:961)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:294)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:465)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:532)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:318)
at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892)
Please see below codes:
public static synchronized BOWSClient getInstance()
throws AxisFault, NamingException, MalformedURLException {
BOWSClient bowsclient = null;
if (bowsclient == null) {
bowsclient = new BOWSClient();
}
try {
// create connection
Connection boConnection;
boConnection = new Connection(getBoConURL());
int bobjServerTimout = Integer.parseInt(System.getProperty("BOBJ_SRVR_TOUT")) *60*1000;
boConnection.setTimeOut(bobjServerTimout);
// provide authentication credentials
EnterpriseCredential boCredential = EnterpriseCredential.Factory.newInstance();
//username, pwd and urls are loaded from database table appl_parm during login
boCredential.setLogin(System.getProperty("BOBJ_UNAME"));
boCredential.setPassword(ReactsUtil.doROT13Convert(System.getProperty("BOBJ_PWD")));
boCredential.setAuthType("secEnterprise");
if (bowsclient.bowsSession == null) {
// create session
bowsclient.bowsSession = new Session(boConnection);
SessionInfo boSI = bowsclient.bowsSession.login(boCredential);
bowsclient.bowsSession.resetSessionTimeOut();
if (log.isDebugEnabled())
log.debug("BOWS Conn established successfully.");
}
} catch (AxisFault e) {
log.error("Exception message is " + e.getMessage(), e);
throw e;
} catch (NamingException e) {
log.error("Exception message is " + e.getMessage(), e);
throw e;
} catch (MalformedURLException e) {
log.error("Exception message is " + e.getMessage(), e);
throw e;
}
return bowsclient;
}
I am not sure if this is an error on Java or BO. Please let me know the steps on how to integrate it properly.

Related

okhttp 2.7.5 fixing without going to okhttp3

Got this vulnerability,
okhttp-2.7.5.jar | Reference: CVE-2021-0341 | CVSS Score: 7.5 | Category: CWE-295 | In verifyHostName of OkHostnameVerifier.java, there is a possible way to accept a certificate for the wrong domain due to improperly used crypto. This could lead to remote information disclosure with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android-8.1 Android-9 Android-10 Android-11Android ID: A-171980069
Can this be fix without going to okhttp3?
My code would be changed with all the okhttp library, all ok except this com.squareup.okhttp.MultipartBuilder to okhttp3.MultipartBody.Builder. Which is going to give me error with,
java.lang.NullPointerException: trustManager.acceptedIssuers must not be null
at okhttp3.internal.platform.Platform.buildTrustRootIndex(Platform.kt:163)
at okhttp3.internal.platform.Platform.buildCertificateChainCleaner(Platform.kt:160)
at okhttp3.OkHttpClient$Builder.sslSocketFactory(OkHttpClient.kt:754)
org.apache.camel.support.processor.DelegateSyncProcessor.process(DelegateSyncProcessor.java:65)
at org.apache.camel.processor.errorhandler.RedeliveryErrorHandler$SimpleTask.run(RedeliveryErrorHandler.java:471)
at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:193)
at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:64)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:184)
at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:398)
at org.apache.camel.component.jetty.CamelContinuationServlet.doService(CamelContinuationServlet.java:245)
at org.apache.camel.http.common.CamelServlet.service(CamelServlet.java:130)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:750)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:799)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:550)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:233)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1440)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:188)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:501)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:186)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1355)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
at org.eclipse.jetty.server.Server.handle(Server.java:516)
at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:487)
at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:732)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:479)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:277)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:105)
at org.eclipse.jetty.io.ChannelEndPoint$1.run(ChannelEndPoint.java:104)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:338)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:315)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:173)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:131)
at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:409)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:883)
at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:1034)
at java.lang.Thread.run(Thread.java:748)
Also I'm limited to java 8.
Thanks.
It's a pretty bogus CVE in that you need to use the HostnameVerifier API directly with untrusted input to exploit. You're probably not doing that; that interface is designed for end users to plug in a custom implementation and will rarely be used by end users directly. (OkHttp sanitizes input before passing it to this API.)
If you confirm you're not using HostnameVerifier directly your vulnerability is mitigated.
But you should upgrade anyway cause OkHttp 2.x is very obsolete.
Vulnerability got fixed with this and I'm using okhttp3,
TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
private X509TrustManager standardTrustManager = null;
#Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
#Override
public void checkServerTrusted(X509Certificate[] certificates, String authType)
throws CertificateException {
if ((certificates != null) && (certificates.length == 1)) {
certificates[0].checkValidity();
} else {
standardTrustManager.checkServerTrusted(certificates, authType);
}
}
#Override
public void checkClientTrusted(X509Certificate[] certificates, String authType)
throws CertificateException {
standardTrustManager.checkClientTrusted(certificates, authType);
}
} };
But got new error,
com.example.HTTPS$HTTPSError: javax.net.ssl.SSLException: java.lang.NullPointerException
at org.apache.camel.support.processor.DelegateSyncProcessor.process(DelegateSyncProcessor.java:65)
at org.apache.camel.processor.errorhandler.RedeliveryErrorHandler$SimpleTask.run(RedeliveryErrorHandler.java:471)
at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:193)
at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:64)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:184)
at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:398)
at org.apache.camel.component.jetty.CamelContinuationServlet.doService(CamelContinuationServlet.java:245)
at org.apache.camel.http.common.CamelServlet.service(CamelServlet.java:130)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:750)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:799)
Caused by: javax.net.ssl.SSLException: java.lang.NullPointerException
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1903)
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1886)
Caused by: java.lang.NullPointerException
at sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(SSLContextImpl.java:1091)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1621)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223)

Spring Boot Runs on Tomcat 8.5.x but not 8.0.37 java.lang.NoClassDefFoundError: org/apache/coyote/UpgradeProtocol

relatively new to Spring so I am guessing I am not doing something correctly. I have been converting an older java soap service to spring. I am able to run it locally on tomcat 8.5 and up, but when I run it on tomcat 8.0.37 (which is what the server I will deploy it to is on) I get the error below. I came across this error in another project, but realized in the other project I was unnecessarily creating a servlet, so once I ripped out the servlet code I was good to go. In this instance I need to create a servlet. The error is looking for "org/apache/coyote/UpgradeProtocol" which is not in Tomcat 8.0.37. Not sure what in my code is trying to use it. Any suggestions are appreciated, thanks.
Tomcat dependencies in pom...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
error...
2019-01-17 16:05:12,539 SEVERE Class= org.apache.catalina.core.ContainerBase Method= addChildInternal Message= ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/exampleServices]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:940)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1816)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'containerFactory' defined in class path resource [com/removed/exampleServices/exampleServicesConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory]: Factory method 'containerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/coyote/UpgradeProtocol
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:591)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1246)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:548)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:157)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:137)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:91)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:172)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
config class below, I assume the issue is with how I am creating my TomcatServletWebServerFactory or my ServletRegistrationBean
#ComponentScan({"com.example.exampleservices", "com.example.examplesoapservices"})
#Configuration
#EnableAWSF
public class exampleservicesConfiguration {
static {
// Statically initialize SystemImpl so it doesn't slow down first
// request
try {
SystemImpl.getInstance();
} catch (exampleException e) {
throw new RuntimeException(e);
}
}
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new WSSpringServlet(), "/exampleservicesSOAP/*", "/exampleservicesSOAPV3/*");
//ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new WSSpringServlet(), "/exampleservicesPort/*", "/exampleservicesPortV3/*");
servletRegistrationBean.setEnabled(true);
servletRegistrationBean.setLoadOnStartup(0);
return servletRegistrationBean;
}
#Bean
#SneakyThrows
public SpringBinding springBinding(exampleservicesSOAPImpl exampleservicesSOAPImpl, AWSFHandlers awsfHandlers) throws Exception {
SpringBinding springBinding = new SpringBinding();
springBinding.setUrl("/exampleservicesSOAP");
SpringService springService = new SpringService();
springService.setBean(exampleservicesSOAPImpl);
springService.setHandlers(awsfHandlers.getAwsfHandlers());
springBinding.setService(springService.getObject());
return springBinding;
}
#Bean
#SneakyThrows
public SpringBinding springBindingV3(exampleservicesSOAPV3Impl exampleservicesSOAPV3Impl, AWSFHandlers awsfHandlers) throws Exception {
SpringBinding springBinding = new SpringBinding();
springBinding.setUrl("/exampleservicesSOAPV3");
SpringService springService = new SpringService();
springService.setBean(exampleservicesSOAPV3Impl);
springService.setHandlers(awsfHandlers.getAwsfHandlers());
springBinding.setService(springService.getObject());
return springBinding;
}
#Bean
public Executor threadPoolTaskExecutor(){
return new ThreadPoolTaskExecutor();
}
#Bean
public TomcatServletWebServerFactory containerFactory() {
return new TomcatServletWebServerFactory () {
protected void customizeConnector(Connector connector) {
super.customizeConnector(connector);
}
};
}
#Bean
public Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setContextPath(exJAXBContext.JAXB_CONTEXT_PATH);
return jaxb2Marshaller;
}
#Bean
private static JAXBContext initContext() {
try {
return JAXBContext.newInstance(BasicServiceComponents.eesvcof.getClass().getPackage().getName() + ":" + BasicServiceComponents.eesvcofV3.getClass().getPackage().getName());
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
private static final JAXBContext context = initContext();
#Bean
public Marshaller marshaller() {
Marshaller marshaller = null;
try {
marshaller = this.context.createMarshaller();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//any setters
return marshaller;
}
#Bean
public Unmarshaller unmarshaller() {
Unmarshaller unmarshaller = null;
try {
unmarshaller = this.context.createUnmarshaller();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//any setters
return unmarshaller;
}
}
Well , most probably it is because Spring Boot 2.0 series requires Tomcat 8.5 which is mentioned in the release note. That UpgradeProtocol is something related to HTTP2 which does not exist in Tomcat 8.0 , so your best bet is try to disable HTTP2 in the application.properties :
server.http2.enabled=false
So the code that was breaking is
#Bean
public TomcatServletWebServerFactory containerFactory() {
return new TomcatServletWebServerFactory () {
protected void customizeConnector(Connector connector) {
super.customizeConnector(connector);
}
};
}
When I was testing before I was commenting this out and when I would run locally I would get a different error. Someone I work with suggested removing this bean (I guess it is not needed with spring 2) and also removing my pom code that specifies the tomcat version. This worked. So locally spring is managing my Tomcat version. I believe spring sets Tomcat to 8.5.35 for the spring 2.0.7 release. When I deploy my code it now runs fine on Tomcat 8.0.35. So you do not need that bean, and when running locally just let spring set your own Tomcat version. I am not sure why that bean works on Tomcat 8.5.35 but I don't need it anyways.

#Controller Kafka Listener exception not catched by Exception handler #ControllerAdvice

I have a Kafka Listener marked with #Controller:
#KafkaListener(topics = "${binlookup.kafka.topic.insert}")
public BinInfoJsonDTO listenAndInsert(String binInfoJson, Acknowledgment ack) {
log.debug("Kafka server: {}", bootstrapServers);
log.info("Kafka inserting: {}", binInfoJson);
ObjectMapper mapper = new ObjectMapper();
BinInfoJsonDTO dto;
BinLookupError error;
String responseError;
try {
dto = mapper.readValue(binInfoJson, BinInfoJsonDTO.class); // <--- exception happens here
log.debug("The converted DTO: {}", dto);
ResponseEntity<BinInfoJsonDTO> response = controller.insertBIN(Utilities.jsonDtoToEntity(dto));
log.debug("BIN inserted by Kafka. {}", response);
if (response.getStatusCodeValue() == HttpStatus.OK.value() ||
response.getStatusCodeValue() == HttpStatus.CREATED.value()) {
ack.acknowledge(); // manual acknowledge.
log.debug("Acknowledged.");
} else {
responseError = "Unexpected response status code: " + response.getStatusCodeValue();
log.error(responseError);
error = new BinLookupError(responseError);
error.setErrorType(ErrorTypeEnum.UNEXPECTED_STATUS_CODE);
throw new BinLookupException(error);
}
} catch (JsonProcessingException e) {
log.error("Cannot parse Kafka incoming JSON. ", e);
error = new BinLookupError(e.getMessage());
error.setErrorType(ErrorTypeEnum.KAFKA_JSON_FAILURE);
throw new BinLookupException(error);
} catch (IOException e1) {
log.error("I/O exception in Kafka. ", e1);
error = new BinLookupError(e1.getMessage());
error.setErrorType(ErrorTypeEnum.IO_EXCEPTION);
throw new BinLookupException(error);
}
return dto;
}
And, I have an exception handler marked with #ControllerAdvice:
#Slf4j
#ControllerAdvice
public class BinLookupExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(value = {BinLookupException.class})
protected ResponseEntity<BinLookupError> handleBinLookupException(BinLookupException ex) {
BinLookupError error = ex.getError();
log.error("Exception handler: {}", error.getOriginalMsg());
...
}
Now, when I run the application and enter wrongly formatted JSON into the producer, the exception will occur but not catched by the exception handler. The exception is com.fasterxml.jackson.core.JsonParseException.
[NODE=Shenmue3] [ENV=dev] [SRC=UNDEFINED] [TRACE=] [SPAN=] [2018-09-13T09:38:21.035Z] [INFO] [MSG=[org.springframework.kafka.KafkaListenerEndpointContainer#1-0-C-1] c.p.binlookup.kafka.BinInfoConsumer - Kafka inserting: {{{{{ ]
[NODE=Shenmue3] [ENV=dev] [SRC=UNDEFINED] [TRACE=] [SPAN=] [2018-09-13T09:38:21.119Z] [ERROR] [MSG=[org.springframework.kafka.KafkaListenerEndpointContainer#1-0-C-1] c.p.binlookup.kafka.BinInfoConsumer - Cannot parse Kafka incoming JSON. com.fasterxml.jackson.core.JsonParseException: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
at [Source: (String)"{{{{{"; line: 1, column: 3]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:663)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:561)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddName(ReaderBasedJsonParser.java:1757)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:682)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2992)
at com.xxx.binlookup.kafka.BinInfoConsumer.listenAndInsert(BinInfoConsumer.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:181)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:114)
at org.springframework.kafka.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:48)
at org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:248)
at org.springframework.kafka.listener.adapter.RecordMessagingMessageListenerAdapter.onMessage(RecordMessagingMessageListenerAdapter.java:80)
at org.springframework.kafka.listener.adapter.RecordMessagingMessageListenerAdapter.onMessage(RecordMessagingMessageListenerAdapter.java:51)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeRecordListener(KafkaMessageListenerContainer.java:1071)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeWithRecords(KafkaMessageListenerContainer.java:1051)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeRecordListener(KafkaMessageListenerContainer.java:998)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:866)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:724)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
]
[NODE=Shenmue3] [ENV=dev] [SRC=UNDEFINED] [TRACE=] [SPAN=] [2018-09-13T09:38:21.122Z] [ERROR] [MSG=[org.springframework.kafka.KafkaListenerEndpointContainer#1-0-C-1] o.s.k.listener.LoggingErrorHandler - Error while processing: ConsumerRecord(topic = insert, partition = 0, offset = 0, CreateTime = 1536831499778, serialized key size = -1, serialized value size = 5, headers = RecordHeaders(headers = [], isReadOnly = false), key = null, value = {{{{{) org.springframework.kafka.listener.ListenerExecutionFailedException: Listener method 'public com.xxx.binlookup.dto.BinInfoJsonDTO com.xxx.binlookup.kafka.BinInfoConsumer.listenAndInsert(java.lang.String,org.springframework.kafka.support.Acknowledgment)' threw exception; nested exception is BinLookupException [error=BinLookupError(originalMsg=Unexpected character ('{' (code 123)): was expecting double-quote to start field name
at [Source: (String)"{{{{{"; line: 1, column: 3], fields=[], errorType=Cannot parse Kafka incoming JSON)]
at org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:267)
at org.springframework.kafka.listener.adapter.RecordMessagingMessageListenerAdapter.onMessage(RecordMessagingMessageListenerAdapter.java:80)
at org.springframework.kafka.listener.adapter.RecordMessagingMessageListenerAdapter.onMessage(RecordMessagingMessageListenerAdapter.java:51)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeRecordListener(KafkaMessageListenerContainer.java:1071)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeWithRecords(KafkaMessageListenerContainer.java:1051)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeRecordListener(KafkaMessageListenerContainer.java:998)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:866)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:724)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.xxx.binlookup.exception.BinLookupException: Original message is: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
at [Source: (String)"{{{{{"; line: 1, column: 3]
at com.xxx.binlookup.kafka.BinInfoConsumer.listenAndInsert(BinInfoConsumer.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:181)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:114)
at org.springframework.kafka.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:48)
at org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:248)
... 10 common frames omitted
]
"Exception handler: {}", as part of the log in the handler, is not there.
What more should I do to make it aware of my exception thrown? Thanks.

Getting BadCredentialsException in password change openldap spring

I have openldap running on my localhost, i am trying to change user account password from my spring application but i am getting below Exception.
Please help.
org.springframework.security.authentication.BadCredentialsException: Authentication for password change failed.
at org.springframework.security.ldap.userdetails.LdapUserDetailsManager$3.executeWithContext(LdapUserDetailsManager.java:204) ~[spring-security-ldap-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.ldap.core.LdapTemplate.executeWithContext(LdapTemplate.java:817) ~[spring-ldap-core-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.ldap.core.LdapTemplate.executeReadWrite(LdapTemplate.java:812) ~[spring-ldap-core-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.security.ldap.userdetails.LdapUserDetailsManager.changePassword(LdapUserDetailsManager.java:191) ~[spring-security-ldap-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at com.atulsia.controller.UserController.getTemplate(UserController.java:417) ~[classes/:na]
at com.atulsia.controller.UserController.getAllUsers(UserController.java:437) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171]
Code:
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl("ldap://localhost:389");
contextSource.setUserDn("cn=Anil Pawar,cn=mts,ou=mm,dc=example,dc=com");
contextSource.setPassword("123456");
try {
contextSource.afterPropertiesSet();
} catch (Exception ex) {
ex.printStackTrace();
}
LdapTemplate template = new LdapTemplate();
template.setContextSource(contextSource);
LdapUserDetailsManager ldapUserDetailsManager = new LdapUserDetailsManager(template.getContextSource());
ldapUserDetailsManager.changePassword("123456", "111111");

Custom Liquibase Change error when integrating with Spring: Unknown Liquibase extension. Are you missing a jar from your classpath?

As part of the database upgrade for an existing application, a custom Liquibase change which extends AbstractChange has been created:
#DatabaseChange(name = "springBeanChange", description = "Runs a spring bean custom change", priority = ChangeMetaData.PRIORITY_DEFAULT)
public class SpringBeanChange extends AbstractChange {
private String beanName;
private String changeClass;
#DatabaseChangeProperty(description = "Spring bean name (optional)")
public String getBeanName() {
return this.beanName;
}
public void setBeanName(final String beanName) {
this.beanName = beanName;
}
#DatabaseChangeProperty(description = "Spring bean class")
public String getChangeClass() {
return this.changeClass;
}
public void setChangeClass(final String changeClass) {
this.changeClass = changeClass;
}
private CustomTaskChange bean;
#Override
public boolean generateStatementsVolatile(final Database database) {
return true;
}
#Override
public String getConfirmationMessage() {
return findBean().getConfirmationMessage();
}
#Override
public SqlStatement[] generateStatements(final Database database) {
try {
findBean().execute(database);
} catch (CustomChangeException e) {
throw new UnexpectedLiquibaseException(e);
}
return new SqlStatement[0];
}
#SuppressWarnings("unchecked")
private CustomTaskChange findBean() {
Class<CustomTaskChange> requiredType = CustomTaskChange.class;
if (this.changeClass != null) {
try {
Class<?> requestedType = Class.forName(this.changeClass);
if (CustomTaskChange.class.isAssignableFrom(requestedType)) {
requiredType = (Class<CustomTaskChange>) requestedType;
} else {
throw new UnexpectedLiquibaseException(
"Specified changeClass " + this.changeClass
+ " was not an instance of "
+ CustomTaskChange.class);
}
} catch (ClassNotFoundException e) {
throw new UnexpectedLiquibaseException(
"Could not create change class", e);
}
}
if (this.bean == null) {
if (getBeanName() == null) {
this.bean = SpringContextHolder.getInstance().getContext()
.getBean(requiredType);
} else {
this.bean = SpringContextHolder.getInstance().getContext()
.getBean(getBeanName(), requiredType);
}
}
return this.bean;
}
#Override
public ValidationErrors validate(final Database database) {
try {
return findBean().validate(database);
} catch (NullPointerException p_exception) {
return new ValidationErrors()
.addError("Exception thrown calling validate():"
+ p_exception.getMessage());
} catch (UnexpectedLiquibaseException p_exception) {
return new ValidationErrors()
.addError("Exception thrown calling validate():"
+ p_exception.getMessage());
} catch (NoSuchBeanDefinitionException p_exception) {
return new ValidationErrors()
.addError("Exception thrown calling validate():"
+ p_exception.getMessage());
} catch (BeanNotOfRequiredTypeException p_exception) {
return new ValidationErrors()
.addError("Exception thrown calling validate():"
+ p_exception.getMessage());
} catch (BeansException p_exception) {
return new ValidationErrors()
.addError("Exception thrown calling validate():"
+ p_exception.getMessage());
}
}
}
This is then configured in the database change log XML file as follows:
<changeSet id="15" author="theauthor">
<XXX:springBeanChange
changeClass="XXX.XXX.XXX.upgrade.tasks.TaskUpgrade" />
</changeSet>
Where TaskUpgrade implements CustomTaskChange and is the class that is returned get the call to getBean in SpringBeanChange.
The database change log file also contains many 'normal' liquibase commands such as addColumn.
A custom Java class has then been written which actually performs the upgrade (the following lines show the important lines of code which actually do the upgrade). This Java program is manually executed after the application has been deployed onto the server:
Liquibase liquibase =
new Liquibase(getChangeLogFile(), new ClassLoaderResourceAccessor(), new JdbcConnection(conn));
if ("update".equalsIgnoreCase(command)) {
liquibase.update(contexts);
} else {
throw new IllegalArgumentException("Unknown command " + command);
}
This works fine and executes the database upgrade.
I'm looking to avoid the need to use the custom Java program to perform the upgrade and actually do it when the application starts up. The app already uses Spring so it makes sense to to the upgrade when the Spring context is initialising.
To do this, I've added the following to the applicationContext file:
<bean id="myLiquibase" class="liquibase.integration.spring.SpringLiquibase">
<property name="dataSource" ref="dataSource" />
<property name="changeLog" value="classpath:databaseChangeLog.xml" />
<property name="contexts" value="test, production" />
</bean>
However, when the application starts up, I get the following exception:
2014-03-25 13:02:16,097 [main] ERROR context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myLiquibase' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is liquibase.exception.ChangeLogParseException: Invalid Migration File: Unknown Liquibase extension: springBeanChange. Are you missing a jar from your classpath?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1488)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:549)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:136)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at XXX.XXX.XXX.demo.YYYDemo.main(YYYDemo.java:47)
Caused by: liquibase.exception.ChangeLogParseException: Invalid Migration File: Unknown Liquibase extension: springBeanChange. Are you missing a jar from your classpath?
at liquibase.parser.core.xml.XMLChangeLogSAXParser.parse(XMLChangeLogSAXParser.java:133)
at liquibase.Liquibase.update(Liquibase.java:129)
at liquibase.integration.spring.SpringLiquibase.performUpdate(SpringLiquibase.java:291)
at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:258)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1485)
... 22 more
Caused by: org.xml.sax.SAXException: Unknown Liquibase extension: springBeanChange. Are you missing a jar from your classpath?
at liquibase.parser.core.xml.XMLChangeLogSAXHandler.startElement(XMLChangeLogSAXHandler.java:495)
at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
at org.apache.xerces.parsers.AbstractXMLDocumentParser.emptyElement(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaValidator.emptyElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at liquibase.parser.core.xml.XMLChangeLogSAXParser.parse(XMLChangeLogSAXParser.java:99)
... 27 more
Caused by: org.xml.sax.SAXException: Unknown Liquibase extension: springBeanChange. Are you missing a jar from your classpath?
at liquibase.parser.core.xml.XMLChangeLogSAXHandler.startElement(XMLChangeLogSAXHandler.java:359)
... 39 more
I can't find anything on the Liquibase site or anywhere else which provides any help as to what JAR I'm missing (if indeed I am missing one) or if anything else is missing/not defined.
Does anyone have any ideas?
Thanks in advance.
The jar that contains the custom extension is what is missing from your classpath. I don't use Spring, so I don't know how it sets up the classpath, but you probably need to either put the jar in a standard location so Spring can find it or else configure the Spring classpath.

Resources