I am new to React, Spring and WebSocket and I'm trying to make a WebSocket using Spring to connect to the React app.
It works on Firefox but not on Chrome or Edge.
I can't modify the React app and the app connects with HTTP.
The configuration class
#Configuration
#EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new SocketHandler(), "/");
}
}
The SocketHandler class
#Component
public class SocketHandler implements WebSocketHandler {
#Override
public void handleTextMessage(WebSocketSession session, WebSocketMessage<?> message)
throws Exception {
System.out.println("I received");
session.sendMessage(new TextMessage("Hi how may we help you?"));
}
}
I've tried to use certificates or org.springframework.security but none of it works.
Related
I am trying to use apache camel with Quarkus. Previously I was using the spring-boot framework to develop camel integration. So there are lots of questions that I am still trying to figure out w.r.t. Quarkus framework.
Regarding: Bean
In spring-boot I could do something like this
#Configuration
public class JABXContextConfig {
#Bean
Unmarshaller jaxbUnmarshaller() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(MyPOJO.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return jaxbUnmarshaller;
}
}
and then I could inject it into the class using DI
#Component
public class MyRestServiceRoute extends RouteBuilder {
private final JaxbDataFormat jaxb;
#Autowired
public MyRestServiceRoute(JaxbDataFormat jaxb) throws Exception{
this.jaxb = jaxb;
}
....
}
QUESTION:
How can I do the same in the Quarkus framework?
P.S> I tried replacing #Configuration with #ApplicationScoped and #Bean with #Dependent but it's not working.
Thanks,
I recommend taking a read through the Quarkus CDI documentation:
https://quarkus.io/guides/cdi
https://quarkus.io/guides/cdi-reference
There's also a basic overview of using CDI to configure Camel:
https://camel.apache.org/camel-quarkus/latest/user-guide/bootstrap.html#_cdi
https://camel.apache.org/camel-quarkus/latest/user-guide/cdi.html
In your examples, #Bean could be replaced by a producer method like:
public class JaxbDataFormatProducer {
#ApplicationScoped
JaxbDataFormat jaxbDataFormat() {
return new JaxbDataFormat();
}
}
And the #Autowired constructor argument might look like this (If there’s only one constructor then there's actually no need for #Inject):
#ApplicationScoped
public class MyRestServiceRoute extends BaseRouteBuilder {
private final JaxbDataFormat jaxb;
#Inject
public MyRestServiceRoute(JaxbDataFormat jaxb) throws Exception{
super(properties);
this.jaxb = jaxb;
}
}
I'm trying to create webSocket on springBoot application.
this is config class:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/sub");
config.setApplicationDestinationPrefixes("/send");
}
#Override
public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
}
#Override
public void configureClientInboundChannel(ChannelRegistration registration) {
}
#Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
}
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
}
#Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
}
#Override
public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
return true;
}
}
Now from AngularJS I'm trying to connect to websocket using SockJS and Stomp
var socket = new SockJS('/api/ws');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function (frames) {
stompClient.subscribe('/subs/hello', function (data) {
console.log(data);
});
});
When I open console I get this message:
admin-components.js:112173 WebSocket connection to 'wss://proxy.beta.corp.payment21.com/api/ws/135/hwq2yv3q/websocket' failed: Error during WebSocket handshake: Unexpected response code: 502
After 30 seconds I get this:
VM333 sockjs.min.js:2 Uncaught Error: Incompatibile SockJS! Main site uses: "1.4.0", the iframe: "1.0.0".
at s (VM333 sockjs.min.js:2)
And after 30 more seconds:
And it is working...
When I go to network to see details in the frames it says
(Opcode -1)
What is the problem here? Is it the spring configuration or SockJS?
Based on the Spring documentation the supported client SockJS version is 1.0.x
On the browser side, applications can use the sockjs-client (version 1.0.x). It emulates the W3C WebSocket API and communicates with the server to select the best transport option, depending on the browser in which it runs.
Am using Spring Boot and I have just added camel to it.
I have a simple camel route setup :
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
#Component
public class MyRoute extends RouteBuilder {
#Override
public void configure() throws Exception {
from("file://in").to("file://out");
}
}
When I try to create simple test for this route with :
#RunWith(CamelSpringBootRunner.class)
#SpringBootTest
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class MyRouteTest extends CamelTestSupport {
#Autowired
private CamelContext camelContext;
#Produce(uri = "file://in")
private ProducerTemplate producerTemplate;
#EndpointInject(uri = "mock:file://out")
private MockEndpoint mockEndpoint;
#Test
public void routeTest() throws Exception {
mockEndpoint.expectedMessageCount(1);
producerTemplate.sendBody("Test");
mockEndpoint.assertIsSatisfied();
}
}
It fails with
mock://file://out Received message count. Expected: <1> but was: <0>
Not sure what could be a problem here. I have producer template that has uri as my route from point and am mocking to endpoint with EndpointInject and the the mock uri?
Fixed but not 100%
If I change route from real one
from("file://in").to("file://out");
to
from("file://in").to("mock:out");
And in my test override
#Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new MyRoute();
}
to create specific route
and strangest of all ! Had to remove :
#SpringBootTest
and after that
private CamelContext camelContext;
And then it started working !
But unfortunately not what I need, still there are things that need to be fixed, I would like to use my real prod route !
from("file://in").to("file://out");
And if possible not use advise on route , but just mock it , tried with
mock:file://out in test, but it didnt work :(
and also , it does not work with #SpringBootTest ??? very strange ?!
You need to add
#Override
public String isMockEndpoints() {
return "*";
}
This should mock all the enpoints and then you can use mock:file:out for example
If I am not misstaken you are mocking your output endpoint yet your endpoint endpoint is a file endpoint. When you send a message you need to drop a message to whereever the file endpoint is polling. Otherwise you need to mock that as well.
The environment CXF2.2.6 and Spring 2.5. On Startup JBOSS I need to read CXF properties and change End point details. From basic reading it gives me the idea that CXF Service Info class (org.apache.cxf.service.model.ServiceInfo) handle bindings,endpoints,messages,schemas and so on.
I can Extend CXFServlet and create my own custom servlet. Please advise me the way I can give my own details to Endpoint in startup and override what is given in Spring.xml
The below Spring bean should do what you wanted. Why do you want to override ServiceInfo class ? Any particular reason ?
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ServletContextAware;
public class CXFConfig implements InitializingBean{
#Autowired
Bus cxfBus;
#Override
public void afterPropertiesSet() throws Exception {
EndpointImpl endpoint = new EndpointImpl(cxfBus, new GdsAutomationServiceProviderImpl());
endpoint.setAddress("/public/api/service/v1");//WSDL URL
endpoint.setPublishedEndpointUrl(getEndPointAddress());
endpoint.publish();
}
public Bus getCxfBus() {
return cxfBus;
}
public void setCxfBus(Bus cxfBus) {
this.cxfBus = cxfBus;
}
public String getEndPointAddress() {
// Soap address location you need to define here
return "address"
}
#Override
public void setServletContext(ServletContext context) {
context.getServerInfo();
}
}
my problem is very "simple". I don't know how to setup my OAUTH2 auth server to accept username/password and returns me token.
If I use:
curl curl:password#localhost:8081/oauth/token\?grant_type=client_credentials
it returns me the token but the problem is that it registers user "curl" in the DB so... not so good...
If I use:
http://www.example.com:8081/oauth/authorize?client_id=web&response_type=token
it prompts username and password dialog, I enter them and then it asks me I "Do you authorize 'web' to access your protected resources?
scope.read: Approve Deny"
Can I combine those two and just create simple request which will return me the token? I want to use it for angularjs frontend using RESTful WS in Spring Boot and Jersey.
Should I use this scheme
https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql
use this config -> clients.jdbc(dataSource);
How to setup one user for that scheme? just basic login with username and password.
OauthConfiguration
#Configuration
#EnableAuthorizationServer
public class OAuthConfiguration extends AuthorizationServerConfigurerAdapter
{
#Autowired
private DataSource dataSource;
#Bean
public TokenStore tokenStore()
{
return new JdbcTokenStore(dataSource);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception
{
endpoints.tokenStore(tokenStore());
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
{
// #formatter:off
clients.inMemory()
.withClient("curl")
.authorities("USER")
.resourceIds("reee")
.scopes("read", "write")
.authorizedGrantTypes("client_credentials")
.secret("password")
.and()
.withClient("web")
.redirectUris("http://github.com/techdev-solutions/")
.resourceIds("reee")
.scopes("read")
.authorizedGrantTypes("implicit");
// #formatter:on
}
}
SecurityConfiguration
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
#Autowired
private DataSource dataSource;
#Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests().antMatchers("/**").authenticated()
.and().httpBasic().realmName("OAuth Server");
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
PasswordEncoder encoder = new BCryptPasswordEncoder();
auth.userDetailsService(userDetailsService()).passwordEncoder(encoder);
auth.jdbcAuthentication().dataSource(dataSource);
}
#Bean
public UserDetailsService userDetailsService()
{
return new CustomUserDetailsService(dataSource);
}
}
i think we have similar issues as i have opened a q & a what are the java* configuration for oauth2 to return token after authentication
you can avoid the username and password box by adding username and password in the header of the request http://localhost:8081/oauth/authorize?client_id=web&response_type=token and in your client configuration for web add clients.inMemory().autoApprove(true) however server will respond with the redirect url. My problem is that I don't want it to redirect I just want the token in the response..