#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
#GetMapping("/printJson")
public String getJson(#RequestParam(name="reports", required=false, defaultValue="None") RestTemplate restTemplate, Model model) throws Exception {
List<DailyReport> reports = restTemplate.getForObject("http://localhost:8080/pwa/services/dailyReport/all",
(Class<List<DailyReport>>) ((Class)List.class));
model.addAttribute("reports", reports);
return "printJson";
}
Hi, I am trying to consume my own webservice with restTemplate. On my webservice I have stored data with JSON and I want to print it or use it with a web application
This is what my json file looks like :
{
"serial_number": 202102,
"report_date":"2019-11-23T23:00:00.000+0000",
"status": "en service",
"automate_information":{
"state": "ok",
"temperature": 20,
"payment_state":{
"coins": "normal",
"smart_card": "normal",
"card": "normal"
}
},
"errors":[
{"type": "ax23", "description": "azerty"},
{"type": "cx400", "description": "qzerty"}
],
"articles":[
{"name": "cafe", "quantity": 20},
{"name": "chocolat", "quantity": 30},
{"name": "oasis", "quantity": 10}
],
"income": 300
}
I have made a matching structure with the same names and all, but when I launch my application and I go on the corresponding view :
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>JSON</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<tr th:each="report: ${reports}">
<td th:text="${report.id}" />
<td th:text="${report.serial_number}" />
</tr>
<form th:action="#{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>
Nothing at all is printed. When I tried to call the .size() on the variable reports, I had the error : Cannot call .size() function on null.
I have searched everywhere, and looked back at my structure to see if the names were exactly alike and didn't find anything.
Is there something wrong I am doing with resttemplate ?
Thank you a lot for your help, I might have done a lot of mistakes I am new to spring.
Related
I'trying to send a Multipart form data, through Flutter but the response api can't get the image file. I created a Backend just to debug my call and I got this:
My code:
Map<String, String> fields = {
"label":'-Ll7XfpsPLd_w5kz-D0m'
};
MultipartRequest request = MultipartRequest(
'POST',
Uri.parse(url),
);
request.fields.addAll(fields);
request.files.add(
MultipartFile.fromBytes(
'image',
imagem.readAsBytesSync(),
contentType: MediaType('image', 'jpeg'),
)
);
return request.send();
The server answer:
received fields:
{ label: [ '-Ll7XfpsPLd_w5kz-D0m' ],
image:
[ '\M-o\M ... A LOT OF DATA]}
Then a made a HTML page just to test:
<form method="POST" enctype="multipart/form-data" action="http://172.20.10.2:5002/upload" >
<input type="text" name="zava" value="Zava" /> <br />
<input type="file" name="image" /> <br />
<input type="submit" /> <br />
</form>
And received de server answer:
received fields:
{ zava: [ 'Zava' ] }
received files:
{ image:
[ { fieldName: 'image',
originalFilename: 'Grifo.png',
path: '/tmp/0wvX_w8W5Mw_7flqIdK0b1xX.png',
headers: [Object],
size: 114862 } ] }
What's wrong with my code? Why de Multipart does not send the file as a file?
I discovered that if you pass the optional param filename of the MultipartFile the request works correctly.
Just have to do something like this:
MultipartFile.fromBytes(
'image',
imagem.readAsBytesSync(),
contentType: MediaType('image', 'jpeg'),
filename: 'dummy.jpg'
)
I had opened a bug on flutter about the request without filename (if must be repaired or the documentation changed)...
What: I am creating a Chrome Extension.
Setup:
When I click the extension icon, it loads popup.html as a window. I am trying to load a JSON table of data using this code http://bootstrap-table.wenzhixin.net.cn/examples/ into a pretty HTML table.
Problem: The table loads fine. The javascript appears to be working fine but the stylesheet does not appear to be working. I linked to the local stylesheet in the head of popup.html which loads when I click the extensions's icon in Chrome like so...
<link rel="stylesheet" type="text/css" href="bootstrap-table.css">
Question: Do I need to add it to the manifest somewhere? I just need the stylesheet for the popup html. I dont need to inject it into the web page. I am just trying to display a pretty html table.
manifest.json
{
"manifest_version": 2,
"name": "Chrome Extension",
"description": "Analyze page.",
"version": "0.1",
"icons": { "32": "icon32.png",
"72": "icon72.png",
"114": "icon114.png",
"144": "icon144.png" },
"browser_action": {
"default_icon": "icon32.png",
"default_popup": "popup.html"
},
"web_accessible_resources": [
"bootstrap-table.css",
],
"permissions": [
"activeTab",
]
}
// see http://bootstrap-table.wenzhixin.net.cn/documentation/
// see http://issues.wenzhixin.net.cn/bootstrap-table/#methods/getSelections.html
var data = [
{
"name": "bootstrap-table",
"stargazers_count": "526",
"forks_count": "122",
"description": "An extended Bootstrap table with radio, checkbox, sort, pagination, and other added features. (supports twitter bootstrap v2 and v3) "
},
{
"name": "multiple-select",
"stargazers_count": "288",
"forks_count": "150",
"description": "A jQuery plugin to select multiple elements with checkboxes :)"
},
{
"name": "bootstrap-show-password",
"stargazers_count": "32",
"forks_count": "11",
"description": "Show/hide password plugin for twitter bootstrap."
},
{
"name": "blog",
"stargazers_count": "13",
"forks_count": "4",
"description": "my blog"
},
{
"name": "scutech-redmine",
"stargazers_count": "6",
"forks_count": "3",
"description": "Redmine notification tools for chrome extension."
}
];
function renderStatus(statusText) {
document.getElementById('status').textContent = statusText;
}
// MAIN CODE: on click of extension icon
document.addEventListener('DOMContentLoaded', function() {
//renderStatus('Test1');
//$('#status').append('Test2');
$(function () {
$('#table').bootstrapTable({
data: data
});
var $table = $('#table');
$('#select-button').click(function () {
var msg = 'getSelections: ' + JSON.stringify($table.bootstrapTable('getSelections'));
renderStatus(msg);
});
});
});
<!doctype html>
<html>
<head>
<title>Chrome Extension</title>
<link rel="stylesheet" type="text/css" href="bootstrap-table.css">
<style>
body{
width:820px;
height:400px;
}
#table{
width:100%;
}
</style>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="bootstrap-table.js"></script>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div id="status"></div>
<div class="toolbar">
<button id="select-button" class="btn btn-default">Selected Rows</button>
<button type="button" class="btn btn-default">
<i class="glyphicon glyphicon-plus"></i>
</button>
<button type="button" class="btn btn-default">
<i class="glyphicon glyphicon-heart"></i>
</button>
<button type="button" class="btn btn-default">
<i class="glyphicon glyphicon-trash"></i>
</button>
</div>
<table
data-show-columns="true"
data-toolbar="#toolbar"
data-search="true"
data-show-refresh="true"
data-height="460"
id="table">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="name"
data-switchable="false"
data-sortable="true">
Name
</th>
<th data-field="stargazers_count"
data-sortable="true">
Stars
</th>
<th data-field="forks_count"
data-sortable="true">
Forks
</th>
<th data-field="description"
data-visible="false"
data-sortable="true">
Description
</th>
</tr>
</thead>
</table>
</body>
</html>
In my experience, referencing CSS files included in the extension from the popup does work without adding anything CSS specific to the manifest.
After modifying the manifest so it loads, your sample above does work for me, producing a well formatted table. The manifest I used:
{
"manifest_version": 2,
"name": "Chrome Extension",
"description": "Analyze page.",
"version": "0.1",
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
Is there a way to define a custom Handlebars helper with Mandrill? Say that I've got an object and the currency is in cents.
"products": [
{
"sku": "hdrPhotos",
"price": 19000,
"title": "Unlimited HDR Photography"
},
{
"sku": "panos",
"price": 2500,
"title": "Panoramas / Virtuals"
},
{
"sku": "fullVideo",
"price": 43000,
"title": "Full Video"
},
{
"sku": "aerialDaytimePhotos",
"price": 17500,
"title": "Aerial Daytime Photography"
},
]
I've got this template:
<!-- BEGIN PRODUCT LOOP // -->
{{#each products}}
<tr class="item">
<td valign="top" class="textContent">
<h4 class="itemName">{{title}}</h4>
<span class="contentSecondary">${{toCurrency price}}</span>
<br/>
<span class="contentSecondary sku"><em>{{sku}}</em></span>
<br/>
</td>
</tr>
{{/each}}
I want to take price, which is in cents, and write a custom helper toCurrency that simply divides it by 100.
Custom helpers are easy enough to do in standard Handlebars, but is it possible with Mandrill's utilization of it?
According to the documentation this isn't possible :
"Use Handlebars regardless of whether you're using templates in Mandrill. We'll cover the basics of Handlebars, helpers implemented specifically for Mandrill, and some deviations from and additions to standard Handlebars."
Reference: https://mandrill.zendesk.com/hc/en-us/articles/205582537-Using-Handlebars-for-Dynamic-Content#using-helpers
There are not even all helpers from handlebar.
I have the following query:
[{
"type": "/tv/tv_series_episode",
"series": "The Simpsons",
"/tv/tv_series_episode/guest_stars": [{
"actor": null
}],
}]
I want to print out a list of guest stars, how do I do such a thing? I tried:
<acre:script>
var query = acre.require("simpsons").query;
var result = acre.freebase.MqlRead(query).result;
</acre:script>
<ul>
<li acre:for="someResult in result">$someResult.actor.name</li>
</ul>
but that's obviously wrong.
I fixed your code: working example.
Your query is nested, but your display code wasn't.
Note how I used console.log(obj) with "View with Console" to examine the query result.
<html>
<head>
<acre:script>
var query = [{
"type": "/tv/tv_series_episode",
"series": "The Simpsons",
"guest_stars": [{
"actor": {
"name":null
}
}],
}];
var result = acre.freebase.mqlread(query).result;
console.log(result);
</acre:script>
</head>
<body>
<ul>
<li acre:for="episode in result">
<div acre:for="star in episode.guest_stars">$star.actor.name</div>
</li>
</ul>
</body>
</html>
I am using Knockout and the Knockout Mapping plugin.
My MVC3 Action returns a View and not JSON directly as such I convert my Model into JSON.
This is a data entry form and due to the nature of the system validation is all done in the Service Layer, with warnings returned in a Response object within the ViewModel.
The initial bindings and updates work correctly its the "post-update" behavior that is causing me a problem.
My problem is after calling the AJAX POST and and receiving my JSON response knockout is not updating all of my bindings... as if the observable/mappings have dropped off
If I include an additional ko.applyBindings(viewModel); in the success things do work... however issues then arise with multiple bindings and am certain this is not the correct solution.
This is the HTML/Template/Bindings
<!-- Start Form -->
<form action="#Url.Action("Edit")" data-bind="submit: save">
<div id="editListing" data-bind="template: 'editListingTemplate'"></div>
<div id="saveListing" class="end-actions">
<button type="submit">Save Listings</button>
</div>
</form>
<!-- End Form -->
<!-- Templates -->
<script type="text/html" id="editListingTemplate">
<div class="warning message error" data-bind="visible: Response.HasWarning">
<span>Correct the Following to Save</span>
<ul>
{{each(i, warning) Response.BusinessWarnings}}
<li data-bind="text: Message"></li>
{{/each}}
</ul>
</div>
<fieldset>
<legend>Key Information</legend>
<div class="editor-label">
<label>Project Name</label>
</div>
<div class="editor-field">
<input data-bind="value: Project_Name" class="title" />
</div>
</fieldset>
</script>
<!-- End templates -->
And this is the Knockout/Script
<script type="text/javascript">
#{ var jsonData = new HtmlString(new JavaScriptSerializer().Serialize(Model)); }
var initialData = #jsonData;
var viewModel = ko.mapping.fromJS(initialData);
viewModel.save = function ()
{
this.Response = null;
var data = ko.toJSON(this);
$.ajax({
url: '#Url.Action("Edit")',
contentType: 'application/json',
type: "POST",
data: data,
dataType: 'json',
success: function (result) {
ko.mapping.updateFromJS(viewModel, result);
}
});
}
$(function() {
ko.applyBindings(viewModel);
});
</script>
And this is the response JSON returned from the successful request including validation messages.
{
"Id": 440,
"Project_Name": "",
"Response": {
"HasWarning": true,
"BusinessWarnings": [
{
"ExceptionType": 2,
"Message": "Project is invalid."
}, {
"ExceptionType": 1,
"Message": "Project_Name may not be null"
}
]
}
}
UPDATE
Fiddler Demo Is a trimmed live example of what I am experiencing. I have the Project_Name updating with the returned JSON but the viewModel.Response object and properties are not being updated through their data bindings. Specifically Response.HasWarning().
I've changed back to ko.mapping.updateFromJS because in my controller I am specifically returning Json(viewModel).
Cleaned up my initial code/question to match the demo.
I guess Response is reserved, when I change "Response" to "resp", everything went fine. See http://jsfiddle.net/BBzVm/
Should't you use ko.mapping.updateFromJSON on your success event? Chapter Working with JSON strings on Knockout Mapping site says:
If your Ajax call returns a JSON string (and does not deserialize it into a JavaScript object), then you can use the functions ko.mapping.fromJSON and ko.mapping.updateFromJSON to create and update your view model instead.