facebook graph api call to post image using servlet - java

I am trying to post image to user wall using javascript FB.api. Image is generated from a java servlet dynamically, but due to asynchronous behavior before the image is generated it passes control below the block to post image to Facebook part.
I want either
how can I make fb.api post to Facebook call from servlet?
how to deal with this behavior so that control will not passes below before image generation?
note servlet is working file and generating image .
var imgURL="http://xxx.xxx.xxx.xxx:8084/myapps/app1?monthly="+monthly+"&recent="+recent+"&likes="+likes;
//var imgURL="http://xxx.2xx.xx6.1x8:8084/WebApplication6/image";
alert('image');
//var imgURL="https://graph.facebook.com/100000329585395/picture";
var img = document.createElement('img');
img.src =imgURL;
document.body.appendChild(img);
FB.api('/me/photos', 'post', {
message:'image',
url:imgURL
}, function(response){
alert('here');
if (!response || response.error) {
alert('Error occured'+response.error);
} else {
var postId = response.id;
alert(postId);}
});

Check RESTFB Api which is a Java API. You can use this instead of Javascript API.

Related

Server-side processing of DataTables in Java

I have a spring boot app with Rest api and Oracle database and react front. It works well, but now I want to try datatables with server side processing. I have quite a lot of entities and controllers. I would like to clarify something. Every example I used to learn used jpa. Is it possible to use JDBC? (I have JDBC set up and I don't want to redo all in jpa). When I tried to change examples to jdbc they usually respond with null pointer exception. Also, how about the controller? I saw examples using both get and post. Usually I use get to get the data. But from what I tried to replicate and use with my database, post seems to be recognized, and Get throws the null. Do I need to specify the draw and other paramenters in body or where? Also, is there maybe only one controller which can somehow prepare the response from others or i should change every single controller? Sorry, it's my first time with datatables server-side.
This is what I use, is it enough?
componentDidMount() {
var index = null;
var table = $(this.refs.main).DataTable({
dom: '<"data-table-wrapper"t>',
data: this.props.data,
"processing": true,
"serverSide": true,
"pageLength": 1,
"ajax": $.fn.dataTable.pipeline( {
"url": "/api/calculations",
"type": "POS"
"data": function (data) {
return data = JSON.stringify(data);
}}),
'pagingType': 'simple',
'order': [[0,'asc']],
'pageLength': 100,
"columns": this.props.columns
});
$(this.refs.main).on('click', 'tr', () => {
var index = table.row(this).index();
var item = table.row(this).data();
this.updateIndex(index);
console.log(index);
console.log(item);
});
}
So, my frontend, after authenticating and authorizating, goes to that component, where I perform (there was pagination in api, i just decided to try without it now)
fetchItems = async (page, elements) => {
try {
const response = await CalculationsApiService.fetchAll()
this.setState({ items: response.data })
} catch (e) {
this.setState({
e,
isError: true,
items: null,
})
}
}
And later in render I Call my child component with my universal table and pass the columns and items as props (the first portion of code in this post) Maybe the error is that I call for data first in parent and then ajax in child? What about the controllers in general? Can I use normal rest controllers somehow and just send something special from my react? When not modified by the tutorial above i have a normal rest api with responseentity

ajax calling the wrong servlet

weird problem here I can't seem to solve.
I'm working in Eclipse Java EE, I have a servlet called Process (mapped to /process)
There is a link to process
Checkout
Within process is a doGet method, verifying there is a user logged in, which redirects to a checkout page. (this works) The checkout page contains items, each with an individual input, and I have a seperate doPost method which updates the DB.. obtaining the input to update as follows
<input id='ID created in servlet' value='decided in servlet'>
followed by
<button id="update">Button</button>
I have the following JS
var json = [];
$('#update').click(function(){
$('.items').find('input').each(function(){
var tmp = "{id:" + $(this).attr('id') + ",quantity:" + $(this).val() + "}";
json.push(tmp);
});
$.ajax( {
url : 'process',
type : 'POST',
data : json,
dataType : 'json',
success: function(data) {
alert("success");
}
});
});
So, two questions I guess.
First, this is sending a request to a different servlet, in a different project. However when accessed using a doGet, it works. (I have different code for a doPost) Is there any reason it's not recognizing the doPost method within my Process.java file? What could cause it to search for another servlet?
Second, I know what to do once I get the data in the servlet, but I don't know how to actually access the data. It's passed through jquery in 'data:', then how would I access it in the servlet?
First Question:
If i have understood right, Your problem is that "when you try to send a post request using AJAX (inside a jquery function), you are not hitting the desired servlet".
Solution: You need to append the name of your project to the url.
So lets say your servlet is placed in project named "SomeProject" and the servlet is mapped to url named "servletProcess".
So your jQuery should look something like this:
var json = [];
$('#update').click(function(){
$('.items').find('input').each(function(){
var tmp = "{id:" + $(this).attr('id') + ",quantity:" + $(this).val() + "}";
json.push(tmp);
});
$.ajax( {
url : '/SomeProject/servletProcess',
type : 'POST',
data : json,
dataType : 'json',
success: function(data) {
alert("success");
}
});
});
This should fix the problem :)
Second Question: try this Similar Query

Can I invoke a servlet URLwithout using AJAX

Can I invoke a URL,
directly from javascript without using AJAX,on click of a play button, i am calling the playAlbumFromMediaUrl().
function playAlbumFromMediaUrl() {
var trackMasterList = document.audioDetails.trackMasterIdList.value;
var stringUrl = trackMasterList.split('::');
for (var i = 0; i < stringUrl.length - 1; i++) {
playlist[i] = {
file: stringUrl[i],
provider: "/teams/web/jwplayer/AkamaiAdvancedJWStreamProvider.swf"
}
}
setTimeout(function () {
jwplayerSetupForPlayAlbum();
}, 1000);
}
function jwplayerSetupForPlayAlbum() {
jwplayer('html5AudioPlayer').setup({
playlist: [{
file: "http://localhost:8080/servlet/MediaLibraryAccessServlet?trackMasterId=898035&isProtocol=rtmpe&assetFormat=MP448Full",
provider: "/teams/web/jwplayer/AkamaiAdvancedJWStreamProvider.swf"
}],
width: 550,
height: 30
}).play();
}
Once the url is invoked,it calls the MediaLibraryAccess servlet class that returns a mp4 url, that can be played by the jwplayer.
I need to invoke the servlet url,without using AJAX.
For simplicity, i am not looping the playlist,instead i hard coded the servlet URL call in the jwplayer file attribute.
Can anyone help with this.
As far as i know there are 4 basic ways to call a URL.
Direct POST/GET (normal clicking of a link)
Using frames
Using Ajax
Opening a pop-up window that will call the URL with one of the above methods.
Eliminating option 2-3 you are left with only option 1 witch I doubt that it will fill your needs. I think you should spend some times and make it work using options 2 or 3
UPDATE:
To use option 1 or 4 using javascript see Window.location.href and Window.open () methods in JavaScript
In short for Option 1 you can use:
window.location.href = 'http://www.google.com'; //Will take you to Google using GET.

How to pass javascript variable in jsp page to another java file?

Good Evening, I try to do a checkbox which embedded in a JSP page. I use document.getElementByID("checkbox") in the JSP javascript function. How to pass the variables in the javascript function to another java file without passing it through url for security concern?
This is Checkbox Function:
var checkbox = document.getElementById("chbx");
function foo(){
if(checkbox.checked=true){
//passThisVariableToAnotherJavaFile-isChecked
}
else {
//passThisVariableToAnotherJavaFile-isNotChecked
}
};
This is Java File:
public class CheckBoxEvent{
if(isChecked) {
//then whatever
} else if (isNotChecked) {
//then no whatever
}
}
I am a newbie is this jsp stuff, I used to be doing this in PHP but everything mixed-up in my mind when there is a HashMap appear in the java file. Well, need some hints and help.
Thank You
How to pass the variables in the javascript function to another java file without passing it through url for security concern?
You have two options here and in both the cases you need to send the value to the server for processing :
An AJAX POST or GET request. This looks more appropriate to your requirement. You can get an example here.
Submit the form using POST.
Read here When do you use POST and when do you use GET?
In both the cases , there will be a Servlet/JSP/Controller handling the request in the server. You can call the methods in your Custom Java class with the request parameters.
when you do var checkbox = document.getElementById("chbx"); you are doing it at client side. Now if you want to propagate this value to server side i.e to some java class(most of the cases it will be servlets) then you have two options:-
1)Make an AJAX call. (You can also use jquery here to make AJAX call).Here is
the small example, you can find ample on google
$.ajax({
type: 'GET',
dataType: 'json',
url: servlerURL,
success: function(reply) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
or
2)Submit the form

Can you capture end user's Java version when they run an applet?

An applet developed outside our company just started failing for some users this week. Apparently it was because of the latest version of java (1.6u24) that auto updated. Is there a way to capture what version of java the user opened the applet with?
You can use System.getProperty("java.version") to get that information. This is an example applet that uses it and the About page has the source.
You can use System.getProperty, specifically :
System.getProperty("java.version")
For a list of possible key value, see : getProperties()
http://pscode.org/prop/?prop=java.version%2Cjava.vm.version
Using the answers from another question, I ended up writing the code below. When the page loads, I get the user's java version then use an ajax call to save it where ever I need to. The part I used was the reference to the deployJava.js from Sun.
$(document).ready(function() {
var jVersion = "";
for (var i = 0; i < deployJava.getJREs().length; ++i) {
jVersion += deployJava.getJREs()[i];
}
var url = 'saveJavaVersionAction.jsp';
var params = 'version=' + jVersion;
$.ajax({
url: url,
data: params,
success: function(html) {
$("#results").append(html);
}
});
});

Categories

Resources