Angularjs, JavaEE and http request with inherited objects? - javascript

I work on webapp and can't find solution or example of my problem.
I use AngularJS, RestServis and JavaEE . My problem is how to send inherited object with superObject
In java I have two classes:
public class User{
protected String userName;
protected String userSurename;
..
..
}
Second class is a subclass
public class Worker extends User{
protected int idWorker;
protected String position;
..
..
}
in Angular controller I have
$scope.user = {
userName : "jon" ,
userSurename :"dep" }
$scope.worker= {
idWorker: 88 ,
position: "seller" }
and I use http protocol to send data on server side like this
this.saveWorker = function(worker) {
return $http({
method:'post',
url:this.apiBasicUrl,
contentType: "application/json",
data: worker
});
};
How in Angular in data to put one object and on Java side get worker object with user data also ? Can I , object like in java , make in angular with inherited ?

On Angular side, I suggest using $resource for communication with REST API:
var Worker = $resource('/worker/:workerId', {workerId:'#id'});
//get
var worker = Worker.get({workerId:123}, function() {
worker.abc = true;
//save
worker.$save();
});
On server side you should have a REST endpoint that is supposed to pick up these objects:
#Path("/worker")
public class WorkerService {
#GET
#Path("{workerId}")
public Worker getWorker(#PathParm("workerId") Integer workerId) {
//implement
}
#POST
public void saveWorker(Worker worker) {
//implement
}
}
This might not work out of the box. You will most likely need Jackson provider to enable REST to "translate" JSON into Java objects.
See this example: http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/

Related

Spring Websocket integration with Kafka

I'm trying to send consumed Kafka data to frontend (JavaScript) via Spring-Websockets in a Spring MVC project.
To establish the communication between the server and client, I have the following.
Client (app.js)
function connect() {
var socket = new SockJS('/kafka-data-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.send("/app/fetchData");
stompClient.subscribe('/data/records', function (message) {
console.log(JSON.parse(message.body).content);
});
});
}
Server (KafkaController.java)
#Controller
public class KafkaController {
#MessageMapping("/fetchData")
#SendTo("/data/records")
public String fetchMetrics() {
//...
}
}
To consume data from a specific Kafka topic I'm using #KafkaListener annotation as follows:
public class KafkaReceiver {
#KafkaListener(topics = "mytopic")
public void receive(ConsumerRecord<?, ?> record) {
MyRecord m = new MyRecord(new Long(record.offset()), record.key().toString(), record.value().toString());
//...
}
}
And I have a proper KafkaConfig class with all the necessary beans (like explained here).
How can I send data from receive method to KafkaController's fetchMetrics (and consequently to the websocket) on each incoming/consumed message?
You should inject SimpMessagingTemplate into the KafkaReceiver and use it from the receive() method:
this.template.convertAndSend("/data/records", m);
See more info in the Spring Framework Reference Manual.

SingalR didn't invoke server side method and broadcast data back to client side

I have a regular running job which is registered into an OWIN host app, I took the project of stock ticker broadcasting app as a reference, and I want to make that job like the stock ticker class which is being able to broadcast data to a JavaScript client.
however, after i followed the example, and set everything right, some weird problem happened and I couldn't figure out why.
(1) the traffic will automatically downgrade to long polling, instead of using server send event like the stock ticker did.
(2) I have called a dynamic method at server side, and defined that method at client side, but it never got called
this is my server side hub definition
[HubName("healthCheckHub")]
public class HealthCheckHub : Hub
{
private readonly PublicVendorCloudHealthJob _healthCheckjob;
public HealthCheckHub()
{
this._healthCheckjob = PublicVendorCloudHealthJob.Instance;
}
public IEnumerable<HealthCheckItemResponse> GetAllHealthCheckResponses()
{
return this._healthCheckjob.GetAllHealthCheckResponses();
}
}
this is my Job class implementation
public class PublicVendorCloudHealthJob : SkyJobGrain, IPublicVendorCloudHealthJob
{
private readonly ConcurrentBag<HealthCheckItemResponse> _response;
private static IConfiguration _configuration;
private static IDeploymentElevator _deploymentElevator;
private static IItineraryElevator _itineraryElevator;
private static IResourceElevator _resourceElevator;
public PublicVendorCloudHealthJob(IConfiguration configuration, IDeploymentElevator deploymentElevator, IItineraryElevator itineraryElevator, IResourceElevator resourceElevator)
: base(configuration, deploymentElevator, itineraryElevator, resourceElevator)
{
this.Clients = GlobalHost.ConnectionManager.GetHubContext<HealthCheckHub>().Clients;
_configuration = configuration;
_deploymentElevator = deploymentElevator;
_itineraryElevator = itineraryElevator;
_resourceElevator = resourceElevator;
this._response = new ConcurrentBag<HealthCheckItemResponse>
{
new HealthCheckItemResponse
{
Description = "Larissa test"
}
};
}
public override Task Execute(object obj)
{
this.Clients.All.publishHealthChecks("Larissa" + DateTime.UtcNow);
return TaskDone.Done;
}
public static PublicVendorCloudHealthJob Instance => (PublicVendorCloudHealthJob)Activator.CreateInstance(typeof(PublicVendorCloudHealthJob), _configuration, _deploymentElevator, _itineraryElevator, _resourceElevator);
public IEnumerable<HealthCheckItemResponse> GetAllHealthCheckResponses()
{
return this._response;
}
private IHubConnectionContext<dynamic> Clients { get; }
}
I also configure the hub in Owin startup.cs file like this
app.UseCors(CorsOptions.AllowAll);
GlobalHost.Configuration.KeepAlive = null;
GlobalHost.Configuration.TransportConnectTimeout = TimeSpan.FromSeconds(5);
app.MapSignalR();
for the JS client side, after I get the generated proxy, i did sth like this
signalrService.signalr().then((value) => {
if (value === "success"){
const healthCheckHub = $.connection.healthCheckHub;
const healthCheckHub2 = $.connection.hub.proxies.healthcheckhub;
healthCheckHub.client.publishHealthChecks = (data) => {
console.log(data);
};
healthCheckHub2.client.publishHealthChecks = (data) => {
console.log(data);
};
$.connection.hub.logging = true;
$.connection.hub.start().done(() => {
const defaultData = healthCheckHub.server.getAllHealthCheckResponses();
console.log(defaultData);
});
}
});
really need some help, It's been taking me for about one week to figure this out, thanks in advanced
P.S.
the things i m using is listed below
(1) Chrome v.51
(2) SingalR.core v.2.2.0
(3) Owin

Notify registered clients using Websockets with AngularJS (angular-websocket-service) and Spring Boot

I am new in AngularJS as well as FullStack development. The architecture of my current app is already set up and should not change preferably (for security reasons). So far, I can emit messages to the server using angular-websocket-service. Here is the code snippet of the service from the front-end:
proxiMiamApp.service('WebSocketService', function ($websocket) {
var wsEndpoint = {};
this.openWsEndpoint = function () {
wsEndpoint = $websocket.connect("ws://localhost:9000/proximiamHandler");
console.log(wsEndpoint);
return wsEndpoint;
}
this.sendMessage = function(){
if($.isEmptyObject(this.wsEndpoint)){
this.openWsEndpoint();
}
eventUser = {
idEvent : '1',
idUser : '49'
};
wsEndpoint.register('/eventUser', function(){
console.log('Register OK!');
});
console.log('Ready!');
wsEndpoint.emit('/eventUser',eventUser);
}});
As for the back-end, I am using an implementation of the WebSocketHandler interface:
#Controller
public class ProximiamHandler implements WebSocketHandler {
#Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
System.out.println("afterConntectionEstablished called");
}
#Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
System.out.println("handleMessage called");
// My code here...
}
#Override
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
System.out.println("handleTransportError called");
}
#Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
System.out.println("afterConnectionClosed called");
}
#Override
public boolean supportsPartialMessages() {
return true;
}}
The Implementation of the WebSocketHandler is called via Spring WebSocketConfigurer
#Configuration
#EnableWebSocket
#Controller
public class WebSocketConfig implements WebSocketConfigurer {
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/proximiamHandler").setAllowedOrigins("*");
}
#Bean
public WebSocketHandler myHandler() {
return new ProximiamHandler();
}}
My questions are:
Can I notify subscribed clients using this architecture?
If yes, how can I do it?
Is there a way to return something to subscribed clients from the server? (an Object or a String for instance)
Thanks in advance for your help
Can I notify subscribed clients using this architecture?
=> Yes.
If yes, how can I do it?
=> Based on the Spring web socket APIs, you have to retain the ' WebSocketSession' passed to you via "afterConnectionEstablished" callback.
Use the sendMessage() API of Web socket session to send notifications to client.
Is there a way to return something to subscribed clients from the server? (an Object or a String for instance)
=> You can format your data in either JSON or XML & wrap it using "WebSocketMessage" and pass it to client.
I never worked on spring, however, I am answering this based on my knowledge on web socket. See if it helps.

How to call a C# function from JavaScript?

I want to call CsharpFunction, a C# function in code-behind, from JavaScript. I tried the code below but whether the JavaScript condition is True or False, CsharpFunction was called regardless!
JavaScript code:
if (Javascriptcondition > 0) {
<%CsharpFunction();%>
}
C# code behind:
protected void CsharpFunction()
{
// Notification.show();
}
How do I call a C# function from JavaScript?
You can use a Web Method and Ajax:
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
.CS File
namespace Csharp
{
public void CsharpFunction()
{
//Code;
}
}
JS code:
function JSFunction() {
<%#ProjectName.Csharp.CsharpFunction()%> ;
}
Note :in JS Function when call your CS page function.... first name of project then name of name space of CS page then function name
A modern approach is to use ASP.NET Web API 2 (server-side) with jQuery Ajax (client-side).
Like page methods and ASMX web methods, Web API allows you to write C# code in ASP.NET which can be called from a browser or from anywhere, really!
Here is an example Web API controller, which exposes API methods allowing clients to retrieve details about 1 or all products (in the real world, products would likely be loaded from a database):
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
[Route("api/products")]
[HttpGet]
public IEnumerable<Product> GetAllProducts()
{
return products;
}
[Route("api/product/{id}")]
[HttpGet]
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
The controller uses this example model class:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Example jQuery Ajax call to get and iterate over a list of products:
$(document).ready(function () {
// Send an AJAX request
$.getJSON("/api/products")
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
});
Not only does this allow you to easily create a modern Web API, you can if you need to get really professional and document it too, using ASP.NET Web API Help Pages and/or Swashbuckle.
Web API can be retro-fitted (added) to an existing ASP.NET Web Forms project. In that case you will need to add routing instructions into the Application_Start method in the file Global.asax:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
Documentation
Tutorial: Getting Started with ASP.NET Web API 2 (C#)
Tutorial for those with legacy sites: Using Web API with ASP.NET Web Forms
MSDN: ASP.NET Web API 2
Use Blazor
http://learn-blazor.com/architecture/interop/
Here's the C#:
namespace BlazorDemo.Client
{
public static class MyCSharpFunctions
{
public static void CsharpFunction()
{
// Notification.show();
}
}
}
Then the Javascript:
const CsharpFunction = Blazor.platform.findMethod(
"BlazorDemo.Client",
"BlazorDemo.Client",
"MyCSharpFunctions",
"CsharpFunction"
);
if (Javascriptcondition > 0) {
Blazor.platform.callMethod(CsharpFunction, null)
}
Server-side functions are on the server-side, client-side functions reside on the client.
What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load handler you can access value of variable and call the server method.
More info can be found here
and here
If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.
You can't. Javascript runs client side, C# runs server side.
In fact, your server will run all the C# code, generating Javascript. The Javascript then, is run in the browser. As said in the comments, the compiler doesn't know Javascript.
To call the functionality on your server, you'll have to use techniques such as AJAX, as said in the other answers.

ASP.net MVC put complex data (array) to controller method

I'm porting an ASP.net Web Forms application to MVC.
The application uses AJAX, by means of Ajax-enabled WCF Web service and asp:ScriptManager. I send an array of objects for service, it handles it just great. Code example,
<script type="text/javascript">
$().ready(function () {
var ser = new Services.TasksService();
$('#tasks').tasksgrid(
'newTaskName',
'createTask',
'submitData',
loadData,
submitData,
deleteData
);
function loadData(callback) {
return ser.GetAllTasks(callback, null, null);
}
function submitData(data, callback) {
return ser.Submit(data, callback, null, null);
}
function deleteData(data, callback) {
return ser.Delete(data, callback, null, null);
}
}
);
</script>
WCF service side code:
[ServiceContract(Namespace = "Services")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TasksService
{
[OperationContract]
public IList<Task> GetAllTasks()
{
//Code..
}
[OperationContract]
public void Submit(IList<Task> tasks)
{
//Code..
}
[OperationContract]
public void Delete(IList<Task> tasks)
{
//Code..
}
}
The Submit/Delete method, recieves Array of Tasks objects. I create those array dynamically in client side script and just put it to corresponding Services.TasksService (no $.toJSON or JSON.stringly call, nothing like that). WCF infrastucture handles it greacefully and I always get a correct object on server.
Now, I'm getting rid of WCF service and try to do the same with Controller class. GetAllTasks were fine.. but I totally missed with 'recieving' data methods.
In controller I have,
[HttpPost]
public JsonResult Submit(IList<Task> tasks)
{
On client,
function submitData(data, callback) {
$.post('/Tasks/Submit', JSON.stringify(data), callback, 'json');
}
But anything I tried, I always recieve null as tasks object (so, data is not binded).
I've seen Phil Haack post on that, but would like to avoid using of any additional assemblies, if possible.
MVC needs to be told what variable on the server side to bind the data to. In your example you could do the following:
function submitData(data, callback) {
$.post('/Tasks/Submit', { tasks: data }, callback, 'json');
}
Look here http://theycallmemrjames.blogspot.com/2010/05/aspnet-mvc-and-jquery-part-4-advanced.html

Categories

Resources