I am new to angular, can anyone tell me how to retrieve spring returned map value inside angular's controller?
Here is my code snippet:
app.js
// Service -----------------------------------------------------------------
myApp.service('FolderService', function ($log, $resource, $http) {
return {
onlineView: function(docId) {
var viwerResource = $resource('processOnlineView', {}, {
get: {method: 'POST', params: {'docId' : docId}}
});
return viwerResource.get();
}
}
})
// Controller -----------------------------------------------------------------
.controller('FolderController', function ($scope, $log, FolderService) {
//click online view
$scope.view = function(doc) {
var rtnMap = FolderService.onlineView(doc.cmObjectId);
console.log('rtnMap: ' + rtnMap );
// it shows rtnMap: [object Object]
var key = 'response';
var value = rtnMap[key];
console.log('value: ' + value );
// I want to get map value, but it shows undefined
// I except get "d:/tomcat/bin/hello.swf" here
$scope.rtnFileName = rtnMap;
}
});
my spring controller java code
#RequestMapping(value = "/processOnlineView", method = RequestMethod.POST)
public #ResponseBody Map<String, String> processOnlineView(#RequestParam(value = "docId") String docId) {
String resultDocName = "";
try {
// get File by docId
File file = queryFile(docId);
// set resultDocName value
resultDocName = file.getAbsolutePath(); // real file path, like: d:/tomcat/bin/hello.swf
} catch (Exception e) {
e.printStackTrace();
}
return Collections.singletonMap("response", resultDocName);
}
chrome log:
I can get expect value in html by using this:
rtnFileName: {{rtnFileName.response}}
html shows:
rtnFileName: d:/tomcat/bin/hello.swf
But how to get map value in angular controller directly?
Any suggestion would be appreciated.
Problem solved.
First, use $http post instead of $resource:
onlineView: function(docId) {
$http({
method: 'POST',
url: urlBase + '/processOnlineView',
params: {
docId: docId
}
})
.success(function(data, status, headers, config) {
console.log('success data: ' + data); // result: success data: [object Object]
for (key in data){
console.log('>> data key: ' + key );
console.log('>> data value: ' + data[key] );
}
var resultDocName = data['response'];
console.log('resultDocName: ' + resultDocName);
runFlexpaper(resultDocName);
})
.error(function(data, status, headers, config) {
});
}
Second, retrieve returned map inside 'success' block, because $http post is asynchronous call.
Use a service. For example:
var app = angular.module('myApp', [])
app.service('sharedProperties', function () {
var mapCoord= 'Test';
return {
getProperty: function () {
return mapCoord;
},
setProperty: function(value) {
mapCoord= value;
}
};
});
Inside your Main controller
app.controller('Main', function($scope, sharedProperties) {
$scope.mapCoord= sharedProperties.setProperty("Main");
});
Inside your Map controller
app.controller('Map', function($scope, sharedProperties) {
$scope.mapCoord= sharedProperties.getProperty();
});
When I use the following method :
public String getProjectList() {
projNames = new ArrayList<>();
projNames.add("Project1");
projNames.add("Project2");
projNames.add("Project3");
return new Gson().toJson(projNames);
in the following code :
$(document).ready(function() {
$.getJSON('DBDropDown', function(resp) { // on sucess
var $select = $('#someselect');
$select.find('option').remove();
$select.prepend("<option value='Select Project'></option>").val('');
$.each(resp, function(key, value) { // Iterate over the JSON object.
$('<option>').val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
});
}).fail(function() { // on failure
alert("Request failed.");
});
});
and my JSP call is :
response.getWriter().write(MusicDatabase
.getInstance()
.getProjectList()
I am able to get the dropdown menu. But when I use this method in place of getProjectList I dont get a response when I check chrome developer tools and debug.
public String Names() throws URISyntaxException{
names = new ArrayList<>();
URI uri = new URI("https://jira.xxxxx.com");
JiraRestClientFactory jrcf = new AsynchronousJiraRestClientFactory();
JiraRestClient jrc = jrcf.createWithBasicHttpAuthentication(uri, "xxx", "xxxx");
Iterable<BasicProject> allproject = jrc.getProjectClient().getAllProjects().claim();
for(BasicProject project : allproject){
names.add(project.getName());
}
return new Gson().toJson(names);
}
I am not getting any response and console throws ClassDefNotFound Exception when I already have all the classes needed. Help me if you have gone through this type of issue.
Thanks
Hi I'm new to JSON and I've been trying to get my List into a JSONArray, so that I can use it later with JQuery and include it on a website, but it keeps returning an empty array. I'm using Java EE and wrote a named query, I'm not too sure that the named query is the thief behind it. Here's most probably the appropiate code I hope.
The named query in Review.class:
#NamedQueries ({
#NamedQuery(name="Review.findByTitleOrName", query = "SELECT r FROM Review r WHERE r.artist.artistNr = (SELECT a.artistNr FROM Artist a WHERE a.artistName Like :A) OR r.track.trackID = (SELECT t.trackID FROM Track t WHERE t.trackTitle LIKE :A)")
})
Method in the EAO for reviews that should work:
public List<Review> getReviewsByTitleOrName(String searchParameter) {
TypedQuery<Review> tq = em.createNamedQuery("Review.findByTitleOrName", Review.class);
tq.setParameter("A", searchParameter);
List<Review> reviewList = tq.getResultList();
return reviewList;
}
Servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json; charset=utf-8");
JsonArrayBuilder arrayOfJsonReviews = Json.createArrayBuilder();
String searchParameter = request.getParameter("ajax_searchParameter");
List<Review> reviews = facade.getReviewsByTitleOrName(searchParameter);
for(Review r : reviews){
JsonObjectBuilder review = Json.createObjectBuilder();
review.add("date", r.getDate());
review.add("comment", r.getComments());
review.add("rating", r.getRating());
review.add("user", r.getUserName());
arrayOfJsonReviews.add(review);
}
response.getWriter().write(arrayOfJsonReviews.build().toString());
}
And last but not least the JQuery:
$(document).ready(function() {
$(".SearchBtn").click(function() {
console.log("Clicked button");
$.getJSON("http://localhost:8080/DynamicDolphinProject/DolphinServlet", function(data){
console.log(data);
//placeReviewDat(data);
console.log("Should have data");
});
});
//function placeReviewData(reviews){
//}
})
I am using jquery Ajax to send my parameters to backend in java and return value is of JSON type. My application has different categories which uses the same jsp. If i open a single category in one tab everything is working fine. But when i open different categories in different tabs, the last opened tab/category only sends parameters to the back end, the first opened tabs triggers the ajax call, but the parameters passed are not available in the back end. PFB the code snippet of the AJAX call made,
function addThings(things) {
$(document).ready(function() {
var parameters = {
_method : 'put'
};
for ( var i = 0; i < things.length; i++) {
if (parameters[things[i][0]] != null) {
parameters[things[i][0]] = parseInt(parameters[things[i][0]])
+ parseInt(things[i][1]);
} else {
parameters[things[i][0]] = things[i][1];
}
}
$.ajax({
type : "POST",
url : "addThings.do",
async : false,
data : parameters,
datType : "json",
failure : function(data) {
ShowFatalError();
},
success : function(response) {
var resp =$.getJSON(response);
if (resp == null) {
ShowFatalError();
} else {
if (response.exceptionsOccured) {
ShowFatalError();
}
CurrentJSON = response;
CountDisplay(CurrentJSON);
return (CurrentJSON);
}
}
});
});
return CurrentJSON;
}
The above function is triggered on a button click.
Please help me out in this.
i already found out how to post something to a wall with the graph api on behalf of the facebook user. But now i want to post something in the name of my application.
Here is how i'm trying to do this:
protected void btn_submit_Click(object sender, EventArgs e)
{
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("message", "Testing");
// i'll add more data later here (picture, link, ...)
data.Add("access_token", FbGraphApi.getAppToken());
FbGraphApi.postOnWall(ConfigSettings.getFbPageId(), data);
}
FbGraphApi.getAppToken()
// ...
private static string graphUrl = "https://graph.facebook.com";
//...
public static string getAppToken() {
MyWebRequest req = new MyWebRequest(graphUrl + "/" + "oauth/access_token?type=client_cred&client_id=" + ConfigSettings.getAppID() + "&client_secret=" + ConfigSettings.getAppSecret(), "GET");
return req.GetResponse().Split('=')[1];
}
FbGraphApi.postOnWall()
public static void postOnWall(string id, Dictionary<string,string> args)
{
call(id, "feed", args);
}
FbGraphApi.call()
private static void call(string id, string method, Dictionary<string,string> args )
{
string data = "";
foreach (KeyValuePair<string, string> arg in args)
{
data += arg.Key + "=" + arg.Value + "&";
}
MyWebRequest req = new MyWebRequest(graphUrl +"/" + id + "/" + method, "POST", data.Substring(0, data.Length - 1));
req.GetResponse(); // here i get: "The remote server returned an error: (403) Forbidden."
}
Does anyone see where this i going wrong? I'm really stuck on this.
Thanks!
You need to obtain the Auth Token for your application to post as that application.
The Auth_Token defines the security context you are posting as.
You would need to request the following Graph API URL, for the current user, to find the access token for your application.
https://graph.facebook.com/me/accounts?access_token=XXXXXXXX
This should give you an output similar to the following:
{
"data": [
{
"name": "My App",
"category": "Application",
"id": "10258853",
"access_token": "xxxxxxxxxxxxxxxx"
}
]
}
Be sure you have the manage_pages permission before calling that API or your will not get the access token back.
Once you have the Access Token you publish to the wall like you would any other user. Note that the ID used in the URL matches the ID of the application. This will post to the Application's wall as the Application.
https://graph.facebook.com/10258853/feed?access_token=XXXXXXX
Be sure you have the publish_stream permission as well before posting to the wall.
Recently I had worked With FB api's.
I had Done every thing in javascript.
Here is what i used to post to a users wall.
I hope this helps you.
Include the javascript library provided by FB and add your app id to it.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
For login , i used a button with "fb_login" as id and then i used jquery as follows:
$("#fb_login").click(function(){
FB.login(function(response) {
if (response.session)
{
if (response.perms)
{
// alert("Logged in and permission granted for posting");
}
else
{
// alert("Logged in but permission not granted for posting");
}
}
else
{
//alert("Not Logged In");
}
}, {perms:'publish_stream'});
Note that You have to add {perms:'publish_stream'} as done above which will obtain you the rights to post to the users wall.
A button with id="stream_publish" and then the following jquery:
$("#stream_publish").click(function(){
FB.getLoginStatus(function(response){
if(response.session)
{
publishPost(response.session);
}
});
});
function publishPost(session)
{
var publish = {
method: 'stream.publish',
message: 'Your Message',
picture : 'Image to be displayed',
link : 'The link that will be the part of the post, which can point to either your app page or your personal page or any other page',
name: 'Name or title of the post',
caption: 'Caption of the Post',
description: 'It is fun to write Facebook App!',
actions : { name : 'Start Learning', link : 'link to the app'}
};
FB.api('/me/feed', 'POST', publish, function(response) {
document.getElementById('confirmMsg').innerHTML =
'A post had just been published into the stream on your wall.';
});
};
private class FbWebViewClient extends WebViewClient {
boolean started=false;
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("Facebook-WebView", "Redirect URL: " + url);
if (url.startsWith(Facebook.REDIRECT_URI)) {
Bundle values = Util.parseUrl(url);
String error = values.getString("error");
if (error == null) {
error = values.getString("error_type");
}
if (error == null) {
mListener.onComplete(values);
} else if (error.equals("access_denied")
|| error.equals("OAuthAccessDeniedException")) {
mListener.onCancel();
} else {
mListener.onFacebookError(new FacebookError(error));
}
FbDialog.this.dismiss();
return true;
} else if (url.startsWith(Facebook.CANCEL_URI)) {
mListener.onCancel();
FbDialog.this.dismiss();
return true;
} else if (url.contains(DISPLAY_STRING)) {
return false;
}
// launch non-dialog URLs in a full browser
getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(new DialogError(description, errorCode,
failingUrl));
FbDialog.this.dismiss();
}
public Map<String, String> getUrlParameters(String url)
throws UnsupportedEncodingException {
Map<String, String> params = new HashMap<String, String>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String pair[] = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
params.put(key, value);
}
}
return params;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d("Facebook-WebView", "Webview loading URL: " + url);
String newUrl="http://www.facebook.com/dialog/feed?_path=feed&app_id=";
if (url.contains("touch") && started==false) {
started=true;
ChildTabBibleLessonActivity.fbMaterial=ChildTabBibleLessonActivity.fbMaterial.replace(" ", "+");
url=url+"&picture=http://www.minibiblecollege.org/mbclandingpage/images/icmlogo-small.jpg&description="+ChildTabBibleLessonActivity.fbMaterial;
/* Map<String,String> param;
try {
param = getUrlParameters(url);
newUrl=newUrl+param.get("app_id")+"&redirect_uri="+"https://deep-rain-6015.herokuapp.com"+"&display=page&picture=http://www.minibiblecollege.org/mbclandingpage/images/icmlogo-small.jpg"+"&name=MiniBible&description=heregoesMyMessage";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
view.loadUrl(url);
//super.onPageStarted(view, url, favicon);
}
else
{
super.onPageStarted(view, url, favicon);
}
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mSpinner.dismiss();
/*
* Once webview is fully loaded, set the mContent background to be
* transparent and make visible the 'x' image.
*/
mContent.setBackgroundColor(Color.TRANSPARENT);
mWebView.setVisibility(View.VISIBLE);
mCrossImage.setVisibility(View.VISIBLE);
}
}