angular + ngStomp + spring websocket controller not executed - angularjs

I have searched through all the tutorials and did exactly as explained there, but I can't reach my controller.
Here is my websocket xml config:
<websocket:handlers>
<websocket:mapping path="/updateHandler" handler="updateHandler"/>
<websocket:sockjs/>
</websocket:handlers>
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/update">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
I don't actually know do I need the handler, but without it stomp connection fails with "whoops! Lost connection to undefined".
Any suggestion in this direction is also welcome.
Here is my empty handler:
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
public class UpdateHandler extends TextWebSocketHandler {
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
}
}
And my controller
#RestController
public class WebSocketController {
#MessageMapping("/update")
#SendTo("/topic/messages")
public OutputMessage sendmMessage(Message message) {
return new OutputMessage(message, new Date());
}
}
I am using ngStomp from angular as suggested:
var message = {message: 'message body', id: 1};
$scope.testWebSocket = function () {
$stomp.setDebug(function (args) {
console.log(args + '\n');
});
$stomp.connect('/myAppContext/update', {})
.then(function (frame) {
var connected = true;
var subscription = $stomp.subscribe('/topic/messages', function (payload, headers, res) {
$scope.payload = payload;
}, {});
$stomp.send('/myAppContext/app/update', message);
subscription.unsubscribe();
$stomp.disconnect(function () {
console.error('disconnected');
});
}, function(error){
console.error(error);
});
};
My Message Class:
public class Message {
private String message;
private int id;
public Message() {
}
public Message(int id, String text) {
this.id = id;
this.message = text;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
My OutputMessage class:
public class OutputMessage extends Message {
private Date time;
public OutputMessage(Message original, Date time) {
super(original.getId(), original.getMessage());
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
when I execute the testWebSocket() I get following output:
Opening Web Socket...
Web Socket Opened...
>>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000
<<< CONNECTED
version:1.1
heart-beat:0,0
user-name:user#domain.com
connected to server undefined
>>> SUBSCRIBE
id:sub-0
destination:/topic/messages
>>> SEND
destination:/myAppContext/app/update
content-length:33
{"message":"message body","id":1}
Why connected to server undefined?
And why my controller never gets executed after sending a message?
I am using spring-4.1.4 with security-core-3.2.5 and Tomcat server 8.0.18

As a non-pretty workaround, I moved websocket configuration to the Java config and it works.
Config below:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/update")
.withSockJS();
}
I actually don't know why.

Related

spring cloud gcp pub/sub Jackson messageConverter deserialize fail

I'm trying to receive and process messages through GCP Pub/Sub.
I tried to convert and receive the payload part of the message through JacksonPubSubMessageConverter, but it failed.
It seems that I am not handling byte[] properly inside JacksonPubSubMessageConverter. Do I need to change ObjectMapper settings or override JacksonPubSubMessageConverter?
Below is a code example.
#Slf4j
#Configuration
public class PubSubConfig {
#Bean
public PubSubMessageConverter pubSubMessageConverter(ObjectMapper objectMapper) {
return new JacksonPubSubMessageConverter(objectMapper);
}
}
// ...
#Getter
#Setter
#ToString
#NoArgsConstructor(access = AccessLevel.PROTECTED)
public class MessageDTO {
private PubSubAction action;
#JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate startedAt;
private Boolean dryRun;
}
// ...
public enum PubSubAction {
MY_ACTION("my action"),
ETC("etc action");
private final String description;
PubSubAction(String description) {
this.description = description;
}
#JsonCreator
public static PubSubAction create(String name) {
return Stream.of(PubSubAction.values())
.filter(pubSubAction -> pubSubAction.name().equals(name))
.findAny()
.orElse(null);
}
}
// ...
class MyConsumer() {
private final String subscriptionName;
private final PubSubTemplate pubSubTemplate;
public MyConsumer(
String subscriptionName,
PubSubTemplate pubSubTemplate
) {
this.subscriptionName = subscriptionName;
this.pubSubTemplate = pubSubTemplate;
}
private void consume(
ConvertedBasicAcknowledgeablePubsubMessage<MessageDTO> convertedMessage) {
try {
MessageDTO payload = convertedMessage.getPayload();
log.debug("payload {}", payload);
// payload MessageDTO(action=MY_ACTION, startedAt=null, dryRun=null)
convertedMessage.ack();
} catch (Exception e) {
log.error("Unknown Exception {} {}", e.getMessage(), this.subscriptionName, e);
}
}
private Consumer<ConvertedBasicAcknowledgeablePubsubMessage<MessageDTO>> convertConsumer() {
return this::consume;
}
public void subscribe() {
log.info("Subscribing to {}", subscriptionName);
pubSubTemplate.subscribeAndConvert(subscriptionName, this.convertConsumer(),
MessageDTO.class);
}
}

websocket communication with authorization using react socket io and spring

So I have an API using spring boot, and I try to implement a WebSocket endpoint where users get subscribed when they log in, and where they listen to notifications of different entities creation. Supposedly my WebSocket is working on the backend, here is my code.
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/points_notification")
.setAllowedOrigins("localhost:3000")
.withSockJS();
}
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
#Controller
public class NotificationsController {
#Autowired private NotificationDispatcher dispatcher;
#MessageMapping("/start")
public void start(StompHeaderAccessor stompHeaderAccessor) {
dispatcher.add(stompHeaderAccessor.getSessionId());
System.out.println("GOT a session! " + stompHeaderAccessor.getSessionId());
}
#MessageMapping("/stop")
public void stop(StompHeaderAccessor stompHeaderAccessor) {
dispatcher.remove(stompHeaderAccessor.getSessionId());
}
}
#Service
public class NotificationDispatcher {
#Autowired
private SimpMessagingTemplate template;
private final Set<String> listeners = new HashSet<>();
public <T extends Serializable> void dispatch(T addedObj) {
for (String listener : listeners) {
LOG.info("Sending notification to " + listener);
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setSessionId(listener);
headerAccessor.setLeaveMutable(true);
template.convertAndSendToUser(
listener,
"/topic/item",
new ObjWithMsgResponse<T>("Point added by: " + listener, addedObj),
headerAccessor.getMessageHeaders());
}
}
//getters and event listeners
}
of course the dispatch() are injected and called when the creation of entities.
In the front I'm using react and trying to handle the socket connection with socket.io-client, I'm a little new with this, so I don't really understand how the emit and on methods work, because in the documentation they show that you call and eventName, but in spring the endpoints are using the URL, I can not find anywhere how to ping a URL and not an eventName.
I also tried to use SockJS that works like a charm but the endpoint needs Authentication and with this, I can not add that header to the socket request, which soocket.io permits me.
here is my solution, which only connects but doesn't receive or emit any request.
class SocketManager {
socketRef: Socket | undefined = undefined;
startListening(authToken: String) {
this.socketRef = io('http://localhost:11000/weblab4/', {
path: "/weblab4" + '/points_notification',
transports: ['websocket'],
extraHeaders: {
Authorization: "Bearer " + authToken
}
});
this.socketRef.emit('/app/start', {});
this.socketRef.on('/user/topic/item', (data: INewPointNotification) => {
console.log("received data from socket: " + data);
toast.success('🦄 ' + data.msg + data.point, {/*toast props*/});
});
console.log("socket connected", this.socketRef);
}
stopListening() {
if (this.socketRef !== undefined)
this.socketRef.disconnect();
console.log("socket disconnected", this.socketRef);
}
}

Codename One: 405 Method Not Allowed error

I had been developing and testing on the Codename One simulator and everything worked fine.
However, when I tested it on a real Android device, I get a 405 Method Not Allowed error. This happened on both a POST and GET request.
I suspect it is the #Consume and #Produces which are causing the problem. How do I fix this?
Here are my server side code:
#GET
#Path("/all/{language}")
#Produces("application/json")
public final Response getAllCelebrities(#PathParam("language") String language) {
String celebritiesJSONString = CelebrityActions.getAllCelebritiesNamesJSONString(language);
return Response.ok(celebritiesJSONString).build();
}
#POST
#Path("/login")
#Consumes("application/x-www-form-urlencoded")
#Produces("text/plain")
public final Response login(
#FormParam("loginid") String loginid,
#FormParam("password") String password
) {
System.out.println("login 0 started");
Long fanID;
try {
fanID = AccountsActions.login(loginid, password);
} catch (Exception e) {
return Response.serverError().entity(e.getMessage()).build();
}
if (fanID == null) {
return responseFanIDNotFoundError();
}
System.out.println("This is printed out!!!");
System.out.println("login 100 ended");
return Response.ok().build();
}
And here's my log upon execution of the login() method:
login 0 started
This is printed out!!!
login 100 ended
which means the server side method was ready to return a 200 response.
What is causing the Android client to show a 405 Method Not Allow error?
EDIT: I'm adding my cient-side code here:
(note that this one handles a cookie from a server)
public class Login extends PostConnection {
private final String LoginEndpoint = "account/login";
private String loginIDString;
private String loginPasswordString;
// Tested and works on simulator!
public Login(String loginIDString, String loginPasswordString) {
super();
endpoint = LoginEndpoint;
this.loginIDString = loginIDString;
this.loginPasswordString = loginPasswordString;
}
#Override
protected void prepareParametersMap() {
parametersMap = new HashMap<>();
parametersMap.put("loginid", loginIDString);
parametersMap.put("password", loginPasswordString);
}
}
public abstract class PostConnection extends PostPutConnection {
public PostConnection() {
super();
}
public boolean connect() throws IOException {
connectionRequest.setHttpMethod("POST");
return super.connect();
}
}
public abstract class PostPutConnection extends Connection {
protected HashMap<String, String> parametersMap;
public PostPutConnection() {
super();
}
protected static final void setPostParameters(ConnectionRequest connectionRequest, HashMap<String, String> parametersMap) {
Set<String> paramateterKeys = parametersMap.keySet();
Iterator<String> parameterKeysIterator = paramateterKeys.iterator();
while (parameterKeysIterator.hasNext()) {
String key = parameterKeysIterator.next();
String value = parametersMap.get(key);
connectionRequest.addArgument(key, value);
}
}
protected abstract void prepareParametersMap();
public boolean connect() throws IOException {
prepareParametersMap();
setPost();
setPostParameters();
return super.connect();
}
private void setPostParameters() {
setPostParameters(connectionRequest, parametersMap);
}
private final void setPost() {
connectionRequest.setPost(true);
}
}
public abstract class Connection {
private final static String protocol = "http";
private final static String domain = "192.168.0.109:20000";
protected ConnectionRequest connectionRequest;
protected String endpoint;
public Connection() {
super();
init();
}
protected void init() {
connectionRequest = new ConnectionRequest();
connectionRequest.setCookiesEnabled(true);
ConnectionRequest.setUseNativeCookieStore(true);
}
public boolean connect() throws IOException {
connectionRequest.setUrl(protocol + "://" + domain + "/" + endpoint);
NetworkManager.getInstance().addToQueueAndWait(connectionRequest);
int responseCode = getResponseCode();
return responseCode == 200 ? true : false;
}
private int getResponseCode() {
int responseCode = connectionRequest.getResponseCode();
return responseCode;
}
}
And another method below:
(note that this one does not handle cookies)
public class GetAllCelebrities extends GetConnection {
private final String GetCelebritiesEndpoint = "celebrity/all";
public GetAllCelebrities(String language) {
super();
endpoint = GetCelebritiesEndpoint + "/" + language;
}
}
public abstract class GetConnection extends Connection {
private Map<String, Object> responseData;
public GetConnection() {
super();
}
public boolean connect() throws IOException {
connectionRequest.setHttpMethod("GET");
boolean connectResult = super.connect();
if (!connectResult) {
return false;
}
responseData = getResponseResult();
return true;
}
private Map<String, Object> getResponseResult() throws IOException {
byte[] responseData = connectionRequest.getResponseData();
ByteArrayInputStream responseDataBAIS = new ByteArrayInputStream(responseData);
InputStreamReader responseDataISR = new InputStreamReader(responseDataBAIS, "UTF-8");
JSONParser responseDateJSONParser = new JSONParser();
Map<String, Object> responseResult = responseDateJSONParser.parseJSON(responseDataISR);
return responseResult;
}
public Map<String, Object> getResponseData() {
return responseData;
}
}
And it is called like:
private Map<String, Object> fetchCelebrities() throws IOException {
GetAllCelebrities getAllCelebrities = new GetAllCelebrities("en");
getAllCelebrities.connect();
return getAllCelebrities.getResponseData();
}
private boolean performLogin() throws IOException {
String loginIDString = loginID.getText();
String loginPasswordString = loginPassword.getText();
Login login = new Login(loginIDString, loginPasswordString);
boolean loginResult = login.connect();
return loginResult;
}
It's a bit hard to read all of this code but I'll venture a guess based on the server message. You've set the method to "PUT" along the way in the post put class and that isn't supported by the server yet.
The best way to debug these things is with the network monitor in the Simulator. Its shows the traffic and would have made these things mostly clear

Handling failed claim in Nancy

I am using the RequiresClaims mechanism in Nancy like this:
public class HomeModule : NancyModule
{
public HomeModule()
{
Get["/"] = ctx => "Go here";
Get["/admin"] = ctx =>
{
this.RequiresClaims(new[] { "boss" }); // this
return "Hello!";
};
Get["/login"] = ctx => "<form action=\"/login\" method=\"post\">" +
"<button type=\"submit\">login</button>" +
"</form>";
Post["/login"] = ctx =>
{
return this.Login(Guid.Parse("332651DD-A046-4489-B31F-B6FA1FB290F0"));
};
}
}
The problem is if the user is not allowed to enter /admin because the user doesn't have claim boss, Nancy just responds with http status 403 and blank body.
This is exactly what I need for the web service part of my application, but there are also parts of my application where nancy should construct page for user. How can I show something more informative to the user?
This is the user mapper that I use:
public class MyUserMapper : IUserMapper
{
public class MyUserIdentity : Nancy.Security.IUserIdentity
{
public IEnumerable<string> Claims { get; set; }
public string UserName { get; set; }
}
public Nancy.Security.IUserIdentity GetUserFromIdentifier(Guid identifier, Nancy.NancyContext context)
{
return new MyUserIdentity { UserName = "joe", Claims = new[] { "peon" } };
}
}
And this is the bootstrapper that I use:
public class MyNancyBootstrapper : DefaultNancyBootstrapper
{
protected override void RequestStartup(
Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context)
{
base.RequestStartup(container, pipelines, context);
var formAuthConfig = new Nancy.Authentication.Forms.FormsAuthenticationConfiguration
{
RedirectUrl = "~/login",
UserMapper = container.Resolve<Nancy.Authentication.Forms.IUserMapper>()
};
Nancy.Authentication.Forms.FormsAuthentication.Enable(pipelines, formAuthConfig);
}
}
You need to handle the 403 status code as part of the pipeline and then return an html response to the user. Take a look at http://paulstovell.com/blog/consistent-error-handling-with-nancy

Google GWT RPC Vector

I use Google GWT and RPC. On the Client side is the class SplitDatenhalter. This works OK:
Vector <SplitDatenhalter> vec = new Vector<SplitDatenhalter>();
vec.add(new SplitDatenhalter("a", "b", "c","D"));
vec.add(new SplitDatenhalter("ab", "bc", "dc","Dee"));
How can I send this to the server side?
Update
I have on the client side the class SplitDatenhalter. See below,
public class SplitDatenhalter implements Serializable{
private static final long serialVersionUID = 1L;
String name ;
String vorname;
String nachname;
String email;
public SplitDatenhalter(String name, String vorname, String Nname, String Email) {
this.name = name;
this.vorname = vorname;
this.nachname = Nname;
this.email = Email;
}
public String getName() {
return name;
}
//others setter and getter Function
The client side has MyService:
public interface MyService extends RemoteService
{
public void myVector(Vector<SplitDatenhalter> vec);
}
The other interface:
public interface MyServiceAsync {
public void myVector(Vector < SplitDatenhalter > vec,
AsyncCallback < Void > callback);
}
This is the server side:
public void myVector(Vector < SplitDatenhalter > vec)
{
// TODO Auto-generated method stub
System.out.println("vector");
for (int i = 0; i < vec.size(); i++) {
this.name = vec.get(i).getName();
this.name = vec.get(i).getVorname();
this.name = vec.get(i).getNachname();
this.name = vec.get(i).getEmail();
}
}
This code part is from client side:
Vector<SplitDatenhalter> vect = new Vector<SplitDatenhalter>(); // TODO Auto-generated method stub
MyServiceAsync svc = (MyServiceAsync) GWT.create(MyService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) svc;
// endpoint.setServiceEntryPoint("/myService");
// define a handler for what to do when the service returns a result
#SuppressWarnings("rawtypes")
AsyncCallback callback = new AsyncCallback()
{
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
System.out.println("Fehler");
}
//#Override
public void onSuccess(Object result) {
// TODO Auto-generated method stub
System.out.println(result.toString());
}
};
this.vect.add(new SplitDatenhalter(this.name, Vname, Nname, Email)); //this a part from Function
I need this code part
public static MyServiceAsync getService()
{
MyServiceAsync svc = (MyServiceAsync) GWT.create(MyService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) svc;
endpoint.setServiceEntryPoint("/myService");
return svc;
}
The last part:
# SuppressWarnings("unchecked")
public void vectorExe()
{
System.out.println("vectorExe befor");
getService().myVector(this.vect, callback);
}
After this function executes, I get an error from onFailure(Throwable caught). Where did I go wrong?
you can use vector in client and pass it fto server side (see reference)
Maybe your SplitDatenhalter class is not Serializable. What's the problem?

Resources