Spring-Boot BeanCreatingException - spring

My project was running but after 5 minutes there is no change and i recompile my project there is an error just enter code here like this.
2018-11-12 14:04:27.508 INFO 7904 --- [ main] c.i.IwbEmuhasebeAdapterApplication : Starting IwbEmuhasebeAdapterApplication on PRMS-ALC with PID 7904 (D:\eclipse-workspace\iwb-emuhasebe-adapter\target\classes started by Alican in D:\eclipse-workspace\iwb-emuhasebe-adapter)
2018-11-12 14:04:27.516 INFO 7904 --- [ main] c.i.IwbEmuhasebeAdapterApplication : No active profile set, falling back to default profiles: default
2018-11-12 14:04:27.626 INFO 7904 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#5a45133e: startup date [Mon Nov 12 14:04:27 EET 2018]; root of context hierarchy
2018-11-12 14:04:30.873 INFO 7904 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8083 (http)
2018-11-12 14:04:30.940 INFO 7904 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-11-12 14:04:30.940 INFO 7904 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.34
2018-11-12 14:04:30.969 INFO 7904 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_171\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files\Java\jdk1.8.0_171\jre\bin;C:/Program Files/Java/jre1.8.0_191/bin/server;C:/Program Files/Java/jre1.8.0_191/bin;C:/Program Files/Java/jre1.8.0_191/lib/amd64;C:\oracle\product\11.2.0\dbhome_1\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Java\jdk1.8.0_171;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\MongoDB\Server\3.6\bin;C:\Program Files\PuTTY\;C:\Program Files\Java\jdk1.8.0_171\bin\;C:\Program Files\Java\jre1.8.0_191\bin;C:\Users\Alican\AppData\Local\Microsoft\WindowsApps;;C:\Program Files (x86)\Microsoft VS Code\bin;C:\Users\Alican\AppData\Roaming\npm;C:\eclipse;;.]
2018-11-12 14:04:31.212 INFO 7904 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-11-12 14:04:31.213 INFO 7904 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3599 ms
2018-11-12 14:04:31.354 INFO 7904 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-11-12 14:04:31.359 INFO 7904 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-11-12 14:04:31.360 INFO 7904 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-11-12 14:04:31.360 INFO 7904 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-11-12 14:04:31.360 INFO 7904 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-11-12 14:04:31.800 WARN 7904 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appServlet': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.iworkbetter.controller.AppServlet] from ClassLoader [sun.misc.Launcher$AppClassLoader#18b4aac2]
2018-11-12 14:04:31.804 INFO 7904 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
Here is the my appServlet.java
#RestController
public class AppServlet {
#Autowired
private AdapterEngine engine;
public AppServlet(AdapterEngine engine) {
this.engine = engine;
}
#RequestMapping("/EFaturaSender")
public void hndEFaturaSender(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
response.setContentType("text/html; charset=UTF-8");
engine.eFaturaSender(customizationId, AdapterUtil.uInt(requestParams.get("efatura_id")));
}
/*
* #RequestMapping("/EFaturaReceiverGelen") public void
* hndEFaturaReceiverGelen(HttpServletRequest request, HttpServletResponse
* response) throws IOException { Map<String, String> requestParams =
* AdapterUtil.getParameterMap(request); int customizationId = 0;
*
* if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) { try {
* customizationId = AdapterUtil.uInt(requestParams.get("customizationId")); }
* catch (Exception e) { e.printStackTrace(); } } int insertedInvoice = 0;
* response.setContentType("text/html; charset=UTF-8"); insertedInvoice =
* engine.eFaturaGelenAra(customizationId,
* AdapterUtil.uDate(requestParams.get("start_dt")),
* AdapterUtil.uDate(requestParams.get("end_dt")));
* response.getWriter().write("{'success':true,'insertedInvoice':" +
* insertedInvoice + "}");
*
* }
*/
#RequestMapping("/EFaturaReceiverGiden") // TODO Şimdilik gerek yok
public void hndEFaturaReceiverGiden(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
int insertedInvoice = 0;
response.setContentType("text/html; charset=UTF-8");
try {
insertedInvoice = engine.eFaturaAlGiden(customizationId, requestParams);
response.getWriter().write("{'success':true,'insertedInvoice':" + insertedInvoice + "}");
} catch (Exception e) {
response.getWriter().write("{'success':false}");
e.printStackTrace();
} finally {
response.getWriter().close();
}
}
#RequestMapping("/EFaturaMukellefGuncelle") // TODO
public void hndEFaturaMukellefGuncelle(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
int insertedMukellef = 0;
response.setContentType("text/html; charset=UTF-8");
try {
insertedMukellef = engine.eFaturaMukellefGuncelle(customizationId);
response.getWriter().write("{'success':true,'insertedMukellef':" + insertedMukellef + "}");
} catch (IOException e) {
response.getWriter().write("{'success':false}");
e.printStackTrace();
} finally {
response.getWriter().close();
}
}
#RequestMapping("/EFaturaGelenFaturaDurum")
public void hndGelenEFaturaDurumGuncelle(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
response.setContentType("text/html; charset=UTF-8");
try {
engine.eFaturaGelenDurumSorgula(customizationId, AdapterUtil.uInt(requestParams.get("efatura_id")));
response.getWriter().write("{'success':true}");
} catch (Exception e) {
response.getWriter().write("{'success':false}");
e.printStackTrace();
} finally {
response.getWriter().close();
}
}
#RequestMapping("/EFaturaGidenFaturaDurum")
public void hndGidenEFaturaDurumGuncelle(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
response.setContentType("text/html; charset=UTF-8");
try {
engine.eFaturaGidenFaturaDurumSorgula(customizationId, AdapterUtil.uInt(requestParams.get("efatura_id")));
response.getWriter().write("{'success':true}");
} catch (Exception e) {
response.getWriter().write("{'success':false}");
e.printStackTrace();
} finally {
response.getWriter().close();
}
}
#RequestMapping("/EFaturaYanıtla")
public void hndEFaturaYanitla(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
response.setContentType("text/html; charset=UTF-8");
try {
engine.eFaturaYanitla(customizationId, requestParams);
response.getWriter().write("{'success':true}");
} catch (Exception e) {
response.getWriter().write("{'success':false}");
e.printStackTrace();
} finally {
response.getWriter().close();
}
}
// #Scheduled(fixedRate = 200000) // gelen fatura icin scheduled
public void scheduled4ReceiverInvoice() {
int customizationId = 0;// TODO
Date end_date = new Date();
GregorianCalendar start_date = new GregorianCalendar();
start_date.setTime(end_date);
start_date.add(Calendar.DATE, -6);// bugunle 6 gun oncesi
engine.eFaturaGelenAra(customizationId, start_date.getTime(), end_date);
}
// #Scheduled(fixedRate = 200000)
public void scheduled4MukellefUpdate() {
int customizationId = 0;
engine.eFaturaMukellefGuncelle(customizationId);
}
#RequestMapping("EFaturaReceiverGelen")
public void deserializeTest(HttpServletRequest request, HttpServletResponse response)
throws JAXBException, IOException {
Map<String, String> requestParams = AdapterUtil.getParameterMap(request);
int customizationId = 0;
if (!AdapterUtil.isEmpty(requestParams.get("customizationId"))) {
try {
customizationId = AdapterUtil.uInt(requestParams.get("customizationId"));
} catch (Exception e) {
e.printStackTrace();
}
}
int insertedInvoice = 0;
response.setContentType("text/html; charset=UTF-8");
insertedInvoice = engine.deserializeTest(customizationId, AdapterUtil.uDate(requestParams.get("start_dt")),
AdapterUtil.uDate(requestParams.get("end_dt")));
response.getWriter().write("{'success':true,'insertedInvoice':" + insertedInvoice + "}");
}
#RequestMapping("ShowInvoice")
public void showInvoiceOnBrowser(HttpServletRequest request, HttpServletResponse response) throws IOException {
byte[] pdfBytes = engine.showInvoice();
JSONObject j = new JSONObject();
try {
j.put("data1", pdfBytes);
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// response.setContentType("application/json");
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(j);
out.flush();
try {
response.getWriter().write("{'success':true,'data':" + "}");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* response.setHeader("Content-Type", "text/plain");
* response.setHeader("success", "yes"); PrintWriter writer =
* response.getWriter(); writer.write(pdfBytes.toString()); writer.close();
*/
}
}
and this is the warning message:
2018-11-12 14:54:13.580 WARN 7784 --- [ main]
ConfigServletWebServerApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'appServlet': Lookup method resolution failed;
nested exception is java.lang.IllegalStateException: Failed to
introspect Class [com.iworkbetter.controller.AppServlet] from
ClassLoader [sun.misc.Launcher$AppClassLoader#18b4aac2]

I had the same problem. I've fixed 2 things and the problem is resolved:
I found that I made a typo at pom.xml.
I was using Java 8 to run, but compiled with Java 11.

Related

ResponseEntityExceptionHandler not called

I'm working with Spring Boot 2.7.1 and trying to implement Exception handling. Somehow it's not working. Here're the details:
Controller Advice
#ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
#ExceptionHandler(RoomNotFoundException.class)
#ResponseBody
public final ResponseEntity<ErrorMessage> handleRoomNotFoundException(RoomNotFoundException e, WebRequest request) {
ErrorMessage errorMessage=new ErrorMessage(HttpStatus.NOT_FOUND,e.getMessage());
System.out.println("RestResponseEntityExceptionHandler.RoomNotFoundException()");
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorMessage);
}
}
RestController Implementation:
#RestController
#RequestMapping("/api")
public class WebServiceController {
#Autowired
private final ReservationService reservationService;
#Autowired
private RoomRepository roomRepository;
#Override
public String toString() {
return "WebServiceController []";
}
public WebServiceController(ReservationService reservationService) {
super();
this.reservationService = reservationService;
}
#RequestMapping(path = "/jpa/getroomId/{id}", method = RequestMethod.GET)
public Room getRooms(#PathVariable String id) throws RoomNotFoundException {
Optional<Room> optionalRoom;
try {
optionalRoom = reservationService.getRoomDetail(Integer.parseInt(id));
if (!optionalRoom.isPresent()) {
throw new RoomNotFoundException("Room Id is incorrect:" + id);
}
return optionalRoom.get();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
ErrorMessage Bean class:
public class ErrorMessage {
private HttpStatus status;
private String message;
public ErrorMessage(HttpStatus status, String message) {
super();
this.status = status;
this.message = message;
}
public ErrorMessage() {
}
public HttpStatus getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
On Postman when I hit:
I get no return and the Response status code is 200.
On Eclipse server, I get the below output:
022-07-28 20:55:41.571 INFO 6893 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8000 (http) with context path ''
2022-07-28 20:55:41.575 INFO 6893 --- [ restartedMain] c.k.j.l.LearningSpringApplication : Started LearningSpringApplication in 0.891 seconds (JVM running for 1266.472)
2022-07-28 20:55:41.576 INFO 6893 --- [ restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged
2022-07-28 20:55:49.292 INFO 6893 --- [nio-8000-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-07-28 20:55:49.292 INFO 6893 --- [nio-8000-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-07-28 20:55:49.294 INFO 6893 --- [nio-8000-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
Hibernate: select room0_.room_id as room_id1_2_0_, room0_.bed_info as bed_info2_2_0_, room0_.name as name3_2_0_, room0_.room_number as room_num4_2_0_ from room room0_ where room0_.room_id=?
com.khushboo.java.learningspring.exceptions.RoomNotFoundException: Room Id is incorrect:500
at com.khushboo.java.learningspring.webservice.WebServiceController.getRooms(WebServiceController.java:56)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
Thanks for taking the time and sharing any helpful insights on why the ExceptionHandler code is not getting invoked.
ResponseEntityExceptionHandler is not get called because here:
}catch (Exception e) {
e.printStackTrace();
}
return null;
you are swallowing all exceptions, including RoomNotFoundException

Spring Boot - Getting the hostname in application.properties for Spring-Kafka client Id

I am working on a project with Spring-Kafka and Boot and am wanting to get the hostname in the application.properties for the property spring.kafka.consumer.client-Id so that each of my consumers can be distinguished in the server side logs should there be an issue.
Is there a way i could do that? I check on the spring boot reference guide and java.lang.System class but could not find fruitful pointers.
Here's one way - add an EnvironmentAware bean to your config...
#SpringBootApplication
public class So43191948Application implements EnvironmentAware {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(So43191948Application.class, args);
#SuppressWarnings("unchecked")
KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
template.send("so43191948", "foo");
Thread.sleep(10000);
context.close();
}
#KafkaListener(topics = "so43191948")
public void foo(String in) {
System.out.println(in);
}
#Override
public void setEnvironment(Environment environment) {
Properties props = new Properties();
try {
props.setProperty("spring.kafka.consumer.client-id", InetAddress.getLocalHost().getHostName() + ".client");
PropertiesPropertySource propertySource = new PropertiesPropertySource("myProps", props);
if (environment instanceof StandardEnvironment) {
((StandardEnvironment) environment).getPropertySources().addFirst(propertySource);
}
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
In this case, I did it in the boot app itself but it can be done in any bean.
2017-04-03 16:12:32.646 INFO 64879 --- [ main] o.a.k.clients.consumer.ConsumerConfig
: ConsumerConfig values:
auto.commit.interval.ms = 5000
auto.offset.reset = earliest
bootstrap.servers = [localhost:9092]
check.crcs = true
client.id = myhost.client
...
application.properties:
spring.kafka.consumer.client-id=foo
spring.kafka.consumer.group-id=myGroup
spring.kafka.consumer.auto-offset-reset=earliest
As you can see, the client-id is overridden.
import java.net.InetAddress;
import java.net.UnknownHostException;
private String getHostAddress() {
String hostaddress = "";
try {
hostaddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.error("Error while fetching hostaddress:", e);
}
return hostaddress;}

How and where to invoke HeaderValueRouter and HeaderEnricher for jms or activemq with spring-integration

In my project ,we use spring-integration to implement the queue. The configuration for Header-Value-Router is in the xml as below:
<header-value-router input-channel="jmsUVMasterMessageChannel"
header-name="METADATA_TYPE" default-output-channel="nullChannel"
resolution-required="false">
<mapping value="ASSEMBLY" channel="downloadImageToS3Channel" />
<mapping value="THIRDPARTY" channel="invokeUVMasterAPIChannel" />
</header-value-router>
<header-enricher input-channel="JuiceVendorMessageChannel"
output-channel="JuiceHeaderEnricherChannel">
<header name="sourceName" value="JUICE" />
</header-enricher>
And here is the gateway config:
I wanna know how to implement this config in java code? I searched google and found following code:
#Bean
public HeaderValueRouter headerRouter(String gatewayPrefix) {
HeaderValueRouter router = new HeaderValueRouter("METADATA_TYPE");
router.setChannelMapping("ASSEMBLY", "downloadImageToS3Channel");
router.setChannelMapping("THIRDPARTY", "invokeUVMasterAPIChannel");
router.setDefaultOutputChannel(new NullChannel());
router.setResolutionRequired(false);
return router;
}
#Bean
#Transformer(inputChannel="sdiVenderMessageChannel", outputChannel="sdiHeaderEnricherChannel")
public HeaderEnricher enrichHeaders() {
Map<String, HeaderValueMessageProcessor<?>> headersToAdd = new HashMap<String, HeaderValueMessageProcessor<?>>();
// TODO
//headersToAdd.put("sourceName",new StaticHeaderValueMessageProcessor<String>("SDI"));
headersToAdd.put("sourceName", null);
HeaderEnricher enricher = new HeaderEnricher(headersToAdd);
if(logger.isDebugEnabled()){
logger.debug("HeaderEnricher bean initial!");
}
return enricher;
}
But here are my questions:
1) how to config the 'input-channel' in java config?
2) Where should I invoke this function? When I start the application , the code doesn't run into this function. I know the headerValueRouter is used to dispatcher the message from input-channel to the output-channel, but what's the exact place that I can invoke this router? In the ConnectionFactory or ListenerContainer?
And here is the gateway I defined:
public void registerDynamicInboundGateway(DefaultListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
BeanDefinitionBuilder builder = BeanDefinitionBuilder
.genericBeanDefinition("org.springframework.integration.jms.JmsMessageDrivenEndpoint");
String jndiFactoryName = this.registerJndiObjectFactoryBean(gatewayPrefix, jmsQueueValue);
this.destination = jndiFactoryName;
String containerBeanName = this.registerMessageListenerContainer();
String listenerBeanName = this.registerMessageListener();
builder.addConstructorArgReference(containerBeanName);
builder.addConstructorArgReference(listenerBeanName);
setValueIfAttributeDefined(builder, autoStartup, "auto-startup");
String beanName = null;
if(gatewayPrefix.equals(HCC_GATEWAY_PREFIX)){
beanName = gatewayPrefix + DynamicInboundGateway.HCC_GATEWAY_SUFIX;
} else if (gatewayPrefix.equals(UVMASTER_GATEWAY_PREFIX)) {
beanName = gatewayPrefix + DynamicInboundGateway.UVMASTER_GATEWAY_PREFIX;
} else {
beanName = gatewayPrefix + DynamicInboundGateway.GATEWAY_SUFIX;
}
this.beanFactory.registerBeanDefinition(
beanName, builder.getBeanDefinition());
}
I felt confused and didn't found any sample code for this.
Thanks a lot!
When I define the HeaderEnricher according to the sample code in the spring-integration website like below:
#Bean
#Transformer(inputChannel="sdiVenderMessageChannel", outputChannel="sdiHeaderEnricherChannel")
public HeaderEnricher enrichHeaders() {
Map<String, HeaderValueMessageProcessor<?>> headersToAdd = new HashMap<String, HeaderValueMessageProcessor<?>>();
// TODO
headersToAdd.put("sourceName",new StaticHeaderValueMessageProcessor<String>("SDI"));
//headersToAdd.put("sourceName", null);
HeaderEnricher enricher = new HeaderEnricher(headersToAdd);
if(logger.isDebugEnabled()){
logger.debug("HeaderEnricher bean initial!");
}
return enricher;
}
And this occured some error:
StaticHeaderValueMessageProcessor cannot be resolved to a type
But I've import all the required packages with maven. I can not figure out why.
Hopefully, this simple Spring Boot app will make things clear...
#SpringBootApplication
public class So40585409Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(So40585409Application.class, args);
JmsTemplate template = context.getBean(JmsTemplate.class);
template.convertAndSend("foo", "message1", m -> {
m.setStringProperty("foo", "bar");
return m;
});
template.convertAndSend("foo", "message2", m -> {
m.setStringProperty("foo", "baz");
return m;
});
Thread.sleep(5000);
context.close();
}
#Bean
public JmsMessageDrivenEndpoint inbound(ConnectionFactory jmsConnectionFactory) {
return new JmsMessageDrivenEndpoint(container(jmsConnectionFactory), listener());
}
#Bean
public DefaultMessageListenerContainer container(ConnectionFactory jmsConnectionFactory) {
DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
container.setConnectionFactory(jmsConnectionFactory);
container.setDestinationName("foo");
return container;
}
#Bean
public ChannelPublishingJmsMessageListener listener() {
ChannelPublishingJmsMessageListener listener = new ChannelPublishingJmsMessageListener();
listener.setRequestChannelName("toRouter");
return listener;
}
#Bean
#Router(inputChannel="toRouter")
public HeaderValueRouter router() {
HeaderValueRouter router = new HeaderValueRouter("foo");
router.setChannelMapping("bar", "barChannel");
router.setChannelMapping("baz", "bazChannel");
return router;
}
#ServiceActivator(inputChannel = "barChannel")
public void bar(String in) {
System.out.println("Received via barChannel: " + in);
}
#ServiceActivator(inputChannel = "bazChannel")
public void baz(String in) {
System.out.println("Received via bazChannel: " + in);
}
}
Result:
2016-11-14 09:17:56.798 INFO 65082 --- [ main] com.example.So40585409Application : Started So40585409Application in 8.842 seconds (JVM running for 10.819)
Received via barChannel: message1
Received via bazChannel: message2
2016-11-14 09:18:02.038 INFO 65082 --- [ main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#2b546384: startup date [Mon Nov 14 09:17:49 EST 2016]; root of context hierarchy
EDIT - Header Enricher
I just added your bean with no problems...
#ServiceActivator(inputChannel = "barChannel2")
public void bar(String in, #Header("sourceName") String sourceName) {
System.out.println("Received via barChannel: " + in + " " + sourceName);
}
#ServiceActivator(inputChannel = "bazChannel")
public void baz(String in) {
System.out.println("Received via bazChannel: " + in);
}
#Bean
#Transformer(inputChannel = "barChannel", outputChannel = "barChannel2")
public HeaderEnricher enrichHeaders() {
Map<String, HeaderValueMessageProcessor<?>> headersToAdd = new HashMap<String, HeaderValueMessageProcessor<?>>();
headersToAdd.put("sourceName", new StaticHeaderValueMessageProcessor<String>("SDI"));
HeaderEnricher enricher = new HeaderEnricher(headersToAdd);
return enricher;
}
Result:
2016-11-15 09:00:48.383 INFO 50137 --- [ main] com.example.So40585409Application : Started So40585409Application in 1.814 seconds (JVM running for 2.528)
Received via barChannel: message1 SDI
Received via bazChannel: message2
2016-11-15 09:00:53.424 INFO 50137 --- [ main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#2c34f934: startup date [Tue Nov 15 09:00:46 EST 2016]; root of context hierarchy

Spring Boot JettyServerCustomizer | HTTPS port not opened | A ServletContext is required to configure default servlet handling

I am trying to use Spring Boot with embedded. I want the embedded Jetty to open a HTTPS port at 443.
After referring the answer posted here, I came up with this configuration:-
import java.io.FileNotFoundException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ssl.SslSocketConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.jetty.JettyServerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.util.ResourceUtils;
import com.samsoft.expunto.service.UserService;
/**
* #author Kumar Sambhav Jain
*
*/
#Configuration
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/", "/resources/**")
.permitAll().anyRequest().authenticated().and().formLogin()
.loginPage("/").defaultSuccessUrl("/home", false).and()
.requiresChannel().anyRequest().requiresSecure().and().logout()
.invalidateHttpSession(true).logoutUrl("/logout")
.logoutSuccessUrl("/").and().userDetailsService(userService);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
}
#Bean
public JettyServerCustomizer jettyCutomizer() {
return new JettyServerCustomizer() {
#Override
public void customize(Server server) {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePassword("jetty6");
try {
sslContextFactory.setKeyStorePath(ResourceUtils.getFile(
"classpath:jetty-ssl.keystore").getAbsolutePath());
} catch (FileNotFoundException ex) {
throw new IllegalStateException("Could not load keystore",
ex);
}
SslSocketConnector sslConnector = new SslSocketConnector(
sslContextFactory);
sslConnector.setPort(443);
sslConnector.setMaxIdleTime(60000);
server.addConnector(sslConnector);
}
};
}
}
Trying to run the application using spring-boot:run, I can see in logs that port 80 is opened but no HTTPS port:-
2014-06-10 23:41:56.932 INFO 196 --- [lication.main()] /
: Initializing Spring FrameworkServlet 'dispatcherServlet' 2014-06-10
23:41:56.932 INFO 196 --- [lication.main()]
o.s.web.servlet.DispatcherServlet : FrameworkServlet
'dispatcherServlet': initialization started 2014-06-10 23:41:56.960
INFO 196 --- [lication.main()] o.s.web.servlet.DispatcherServlet
: FrameworkServlet 'dispatcherServlet': initialization completed in 26
ms 2014-06-10 23:41:57.037 INFO 196 --- [lication.main()]
o.e.jetty.server.AbstractConnector : Started
SelectChannelConnector#0.0.0.0:80 2014-06-10 23:41:57.043 INFO 196
--- [lication.main()] .s.b.c.e.j.JettyEmbeddedServletContainer : Jetty started on port: 80 2014-06-10 23:41:57.045 INFO 196 ---
[lication.main()] c.s.expunto.web.config.Application : Started
Application in 7.628 seconds (JVM running for 16.509)
UPDATE
Using this configuration:-
#Configuration
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
implements EmbeddedServletContainerCustomizer {
#Autowired
private UserService userService;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/", "/resources/**")
.permitAll().anyRequest().authenticated().and().formLogin()
.loginPage("/").defaultSuccessUrl("/home", false).and()
.requiresChannel().anyRequest().requiresSecure().and().logout()
.invalidateHttpSession(true).logoutUrl("/logout")
.logoutSuccessUrl("/").and().userDetailsService(userService);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
}
public JettyServerCustomizer jettyServerCustomizer() {
return new JettyServerCustomizer() {
#Override
public void customize(Server server) {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePassword("jetty6");
try {
sslContextFactory.setKeyStorePath(ResourceUtils.getFile(
"classpath:jetty-ssl.keystore").getAbsolutePath());
} catch (FileNotFoundException ex) {
throw new IllegalStateException("Could not load keystore",
ex);
}
SslSocketConnector sslConnector = new SslSocketConnector(
sslContextFactory);
sslConnector.setPort(443);
sslConnector.setMaxIdleTime(60000);
server.addConnector(sslConnector);
}
};
}
public void customizeJetty(
JettyEmbeddedServletContainerFactory containerFactory) {
containerFactory.addServerCustomizers(jettyServerCustomizer());
}
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (container instanceof JettyEmbeddedServletContainerFactory) {
customizeJetty((JettyEmbeddedServletContainerFactory) container);
}
container.setContextPath("");
}
}
I get this error:-
: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:54)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:346)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$d7014349.CGLIB$defaultServletHandlerMapping$24(<generated>)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$d7014349$$FastClassBySpringCGLIB$$ec8be680.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$d7014349.defaultServletHandlerMapping(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
As per M. Deinum advice, moving the customizers to class annotated with #EnableAutoConfiguration did the trick.
This is what worked for me:-
#Configuration
#EnableAutoConfiguration
public class Application implements EmbeddedServletContainerCustomizer {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
#Bean
public JettyServerCustomizer jettyServerCustomizer() {
return new JettyServerCustomizer() {
#Override
public void customize(Server server) {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePassword("jetty6");
try {
sslContextFactory.setKeyStorePath(ResourceUtils.getFile(
"classpath:jetty-ssl.keystore").getAbsolutePath());
} catch (FileNotFoundException ex) {
throw new IllegalStateException("Could not load keystore",
ex);
}
SslSocketConnector sslConnector = new SslSocketConnector(
sslContextFactory);
sslConnector.setPort(443);
sslConnector.setMaxIdleTime(60000);
server.addConnector(sslConnector);
}
};
}
public void customizeJetty(
JettyEmbeddedServletContainerFactory containerFactory) {
containerFactory.addServerCustomizers(jettyServerCustomizer());
}
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (container instanceof JettyEmbeddedServletContainerFactory) {
customizeJetty((JettyEmbeddedServletContainerFactory) container);
}
}
}

Is it possible to list the avaiable JNDI datasources?

Is it possible to list the avaiable JNDI datasources for the current application? If yes, how can I do this.
Here is some sample code to try in a Servlet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
try {
InitialContext ictx = new InitialContext();
Context ctx = (Context) ictx.lookup("java:");
out.println("java: = " + ctx.getClass().getName());
printContext(out, ctx, 1);
} catch (Exception exc) {
throw new ServletException(exc);
}
}
private void printContext(PrintWriter out, Context ctx, int indent) throws ServletException, IOException, NamingException {
NamingEnumeration en = ctx.listBindings("");
while (en.hasMore()) {
Binding b = (Binding) en.next();
char[] tabs = new char[indent];
Arrays.fill(tabs, '\t');
out.println(new String(tabs) + b.getName() + " = " + b.getClassName());
try {
if (b.getObject() instanceof Context) {
printContext(out, (Context) b.getObject(), indent + 1);
}
} catch (Exception exc) {
throw new ServletException(exc);
}
}
}
Try it out and let me know if it works

Resources