I configured Angularjs ui-grid options, to be specific, columnDefs, from Java but because the grid loads before it gets the columnDefs configuration from Java, filtering doesn't show because it loads before and doesn't see any columns.
I used the $http.get('url') function(gridOps) to get the columnDefs.
How could I load config data from Java before ui-grid loads?
Thank you!
Found the solution:
var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.selection', 'ui.grid.exporter', 'ui.grid.importer', 'ui.grid.autoResize']);
fetchData().then(bootstrapApplication);
}
function fetchData() {
var initInjector = angular.injector(["ng"]);
var $http = initInjector.get("$http");
return $http.get("url").then(function(response) {
app.constant("config", response.data);
}, function(errorResponse) {
// Handle error case
});
}
app.controller('MainCtrl', ['$scope','uiGridConstants', '$http','config', function ($scope, uiGridConstants, $http, config) {
Related
There are four query values which I want to put in google chart value1 to value4. The problem is passing values from java to html. Under below I posted relevant codes.
Those
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['value1', **3**],
['value2', **2**],
['value3', **2**],
['value4', **2**]
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
And this is java class.
public ResponseEntity<Map<String,Object>> status() {
Map<String,Object> map = new HashMap<String,Object>();
long countByXmlSuccessResult = statusRepository.countByXmlSuccessResult();
long countByXmlErrorResult = statusRepository.countByXmlErrorResult();
long countByJsonSuccessResult = statusRepository.countByJsonSuccessResult();
long countByJsonErrorResult = statusRepository.countByJsonErrorResult();
map.put("xml success:", **countByXmlSuccessResult**);
map.put("xml error:", **countByXmlErrorResult**);
map.put("json success:", **countByJsonSuccessResult**);
map.put("json error:", **countByJsonErrorResult**);
return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
}
plus, html file path is under src/main/java folder and java file path is under src/main/resources folder.
You can expose that Java functionality as a service, and then make an ajax call to that service using jquery and finally grab the result and use it in your google chart code.
Ex:
Spring Boot:
#RestController
public class myHomeController{
...
#RequestMapping("/getValues")
public someDomainClass getMyValues(){
...
//someDomainClass is just a reg. pojo to store your values.
someDominClass class1 = new someDomainClass(value1, value2, value3
, value4);
return class1;
}
}
Your HTML file:
...
<script>
$.ajax({
url: "/getValues",
type: "GET",
success: function(result){
//result is a json object containing your values 1..4.
},
failure: functtion(err){...}
});
</script>
Best of luck :)
I am developing a platform based on the micro services architecture (JAX-RS) and a nodeJS API.
I have a problem adding an object to the database, because it always marks null by spring boot.
*Here is my REST controller code (JAX-RS):
#RequestMapping(value="/Add")
public Actifs AjouterActifs( #RequestBody Actifs act){
return Actif.saveT(act);
}
*Here the code node API to add the object "Actifs":
app.post("/act/add",function (req,res) {
var addActif = JSON.stringify(req.body);
console.log("params: "+addActif);
try {
http.get(url+"/Add",+addActif, function (response) { //problem is here "addActif is null"
var dataJson ='';
response.on('data',function(data){
dataJson += data;
});
response.on('end',function(){
try
{
var addAct = JSON.parse(dataJson);
}
catch(err) {
console.log('erreur de retourner l\'actif -->', +err);
}
res.json(addAct);
});
});
}
catch(e) {
console.log("erreur d'ajouter les info d'actif -->", +e);
}
});
*Postman:
I get this error:
org.springframework.http.converter.HttpMessageNotReadableException:
Required request body is missing:
How to avoid a null object passing from node JS to the JAX-RS service ?
thank you for helping me,
You are sending the actif to be added as a query parameter
http.get(url+"/Add?act="+addActif, function (response) {
...
}
But your SpringMVC Endpoint expects to find the Actif object in the request body
#RequestMapping(value="/Add")
public Actifs AjouterActifs( #RequestBody(required=false) Actifs act) {
...
}
Option 1: Use #RequestParameter("act") Actifs act and register an editor to parse the object from the query parameter string (see this question).
Option 2: Actually send the Actif json as the request body, e.g. by performing a POST request to url + "/Add" instead of a GET. You will have to use http.request to implement that.
Furthermore I would suggest to use #RequestBody (without required=false). That ensures that the parameter must be non-null and lets the application fail fast if that is not the case.
I solved the problem by changing the code like this
app.post("/act/add",function (req,res) {
var addActif = JSON.parse(req.body); //parse object
console.log("params: "+addActif);
try {
http.get(url+"/Add",addActif, function (response) { // delete '+'
var dataJson ='';
response.on('data',function(data){
dataJson += data;
});
response.on('end',function(){
try
{
var addAct = JSON.parse(dataJson);
}
catch(err) {
console.log('erreur de retourner l\'actif -->', +err);
}
res.json(addAct);
});
});
}
catch(e) {
console.log("erreur d'ajouter les info d'actif -->", +e);
}
});
I'm trying to call a JavaEE 6 rest service from an Angular factory and I am running into issues.
The java rest service was created by someone else and I'm trying to work off of it and I'm not super-well versed in JavaEE yet, so if you need more info, I'll chip in where I can.
#Path("bills")
public class BillResource {
#EJB
#Resource
private BillableEventBean billableEventBean;
private final BillableEventMapper billableEventMapper = new BillableEventMapper();
BillService implementation not working
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("query")
public List<BillableEventDuplicate> listBillableEvents(BillableEventQueryFilter queryFilter) {
List<BillableEvent> ejbRet = billableEventBean.listBillableEvents(queryFilter.getUserID(),
queryFilter.getBillingTeamID(), queryFilter.getBillStatus(), null);
List<BillableEventDuplicate> ret = billableEventMapper.toBillableEventDuplicateList(ejbRet);
return ret;
}
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("{billableEventI}")
public BillableEventDuplicate getBillableEvent(#PathParam("billableEventI") String id) {
BillableEvent ejbRet = billableEventBean.getBillableEvent(id);
BillableEventDuplicate ret = billableEventMapper.toBillableEventDuplicate(ejbRet);
return ret;
}
}
My angular factory for the service looks like this:
'use strict';
var aumBills = angular.module('appBills', ['ngResource']);
appBills.factory('Bills', ['$resource',
function($resource)
{
return $resource('/ua_appcore/api/v1/bills/:billNumber',
{
billNumber:'#billNumber'
},
{
getList: {method: 'POST', params: {'userID':'ABC123'}, url: '/ua_appcore/api/v1/bills/query/'}
});
}]);
The factory in invoked from the controller thusly:
'use strict';
angular.module('app.bills', ['ngRoute','appBills'])
.config(['$routeProvider', function($routeProvider)
{
$routeProvider.
when('/bills',
{
templateUrl: 'bills/bill-list.html',
controller: 'BillListCtrl'
}).
when('/bills/:billId',
{
templateUrl: 'bills/bill-detail.html',
controller: 'BillDetailCtrl'
}).
when('/billsearch',
{
templateUrl: 'bills/bill-search.html',
controller: 'BillSearchCtrl'
});
}])
.controller('BillListCtrl', ['$scope', '$http', '$routeParams', 'Bills',
function($scope, $http, $routeParams, Bills)
{
Bills.getList({},{}).$promise.then(function(billList)
{
$scope.billList = billList;
});
}])
.controller('BillDetailCtrl', ['$scope', '$http', '$routeParams', 'Bills',
function($scope, $http, $routeParams, Bills)
{
Bills.get({},{billNumber: $routeParams.billNumber }).$promise.then(function(bill)
{
$scope.bill = bill;
});
}]);
In my understanding, I needed to create a custom action in the factory to make use of the URL option since there is a POST to get a list of bills back using the same root call. The problem I'm having is that I can't seem to be able to feed any parameters into the queryFilter object even with the Consumes annotation. Am I doing something fundamentally wrong?
First of all you can use chrome plugin Postman to check if your rest service is working correctly if true there is problem with your angular $resource. In my opinion there is missing header "Content-Type=application/json" in your request. I've never use angular in that way you can try to create service like that (this tutorial should be also helpful)
app.service("billsService", function ($resource) {
var bills = $resource("/ua_appcore/api/v1/bills/query");
this.getBills = function () {
var billsResource = new bills();
billsResource.sampleVar = 'value'; // here you can place your vars
return billsResource.$save();
}
});
So, it turns out that it was an infrastructure issue the entire time. We had been deploying to a Websphere Liberty server, and it does not contain the entire WebProfile that JavaEE 6 needs to recognize the rest services. Their may be some work-arounds for it, but the quickest short-term solution is to run a full Websphere server for deployments.
Thanks for the help!
i would like to add a compiler to my jsp pages where the user can enter his code and compile it. Any idea whats the method to add a compiler to jsp pages?
Heh. I tried to put in where I got this approach from, but the spam filter prevented it. I can't vouch for whether the urls below are open for anyone to use, but this is one way to do it:
function submitForm(){
jQuery.support.cors = true;
$('#wait').show();
if ($.browser.webkit || $.browser.mozilla) {
var url = "http://www.compileonline.com/compile_new.php";
}else{
var url = "col_proxy.php";
}
$.ajax({
type: "POST",
cache: false,
crossDomain: true,
url: url,
target: "view",
data: $("#ff").serialize(),
success:function(data)
{
$('#view').contents().find("html").html(data);
$('#wait').hide();
return false;
},
error:function (data, status, error) {
alert(error);
return false;
}
});
return false; // avoid to execute the actual submit of the form.
}
I am fiddling around with JBOSS's Web Services, and I have created the following:
http://127.0.0.1:8080/IM/TestService?wsdl
Now I need to access Web Methods from that Web Service from JavaScript.
Say I have a web method named foo in TestService, how do I make an ajax call to it?
I tried accessing the method via http://127.0.0.1:8080/IM/TestService/foo, but I'm getting an HTTP Status 404.
I wrote the following JavaScript that will allow me to call the Web Methods from the JBoss Web Service.
Dependencies
jQuery
XML Objectifier
jQuery Soap Client (depends on jQuery and XML Objectifier)
var WS = function (url, ns, nsName) {
return function (method, parameters, callback) {
var i, j, para, soapBody = new SOAPObject(method), sr, response;
soapBody.ns = {
name: nsName,
uri: ns
};
if (typeof parameters === "function") {
callback = parameters;
} else if (parameters && parameters.length) {
for (i = 0, j = parameters.length; i < j; ++i) {
para = parameters[i];
soapBody.appendChild(new SOAPObject(para.name)).val(para.value);
}
}
sr = new SOAPRequest(method, soapBody);
SOAPClient.Proxy = url;
SOAPClient.SendRequest(sr, function (r) {
response = r.Body[0][method + "Response"][0]["return"][0]["Text"];
if (callback) {
callback.call(sr, response);
}
});
}
};
Usage
var ws = WS("http://127.0.0.1:8080/IM/TestService", "http://wservices/", "ns2");
ws("foo", [{name: "name", value:"dreas"}], function (r) {
console.log(r);
});
Disclaimer: This is still very much untested, so it can still blow up your computer