server for fetching a url and passing the results back - java

I want to build a server that when invoked, it simply fetches the url that you pass it and sends the result back
I'm pretty sure there are many of these projects on guthub but I don't know what to search. I tried 'proxy server' but the results are not what im looking for
eg : myserver.com?/fetch?url=reddit.com fetches reddit.com and returns the result

Easy do it with express and request package
var app = require('express')(),
request = require('request');
function addHttp(url) {
if (!/^(?:f|ht)tps?\:\/\//.test(url))
return "http://" + url;
return url;
}
app.get('/fetch', function (req, res) {
console.log(req.query.url);
request.get(addHttp(req.query.url)).pipe(res)
});
app.listen(3000, function (err) {
if (err) console.log(err);
else console.log('magic start at port 3000')
})
Then try
localhost.com:3000/fetch?url=reddit.com

Related

Extracting the #Field parameter from retrofit with Node.js Express

I am trying to make an app in Android and have some problem. I have searched the web but I haven't found an obvious solution.
In my Android app I send a Post request for a login task using Retrofit.
#FormUrlEncoded
#POST("/login")
Call<Boolean> loginUser(#Field("username") String userName, #Field("password") String password);
My server is in Node.js with express and I don't know how to extract the username and password parameters.
my app.js file looks like this:
var http = require('http');
var express = require('express');
var bodyparser = require('body-parser');
var connection = require('./dbConnection');
var app = express();
require('./models')(app);
require('./controllers')(app);
require('./routes')(app);
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json());
connection.init();
var server = app.listen(3000, function() {
console.log('Server listening on port ' + server.address().port);
});
And my routes file for login looks like this:
var loginM = require('../models/login');
var loginC = require('../controllers/login');
module.exports = function(app) {
app.post('/login/', function(req, res, next) {
loginM.attemptLogin(req.body, res);
});
}
req.body does not seem to give me the #Field variables, I have tried req.headers and req.params as well with no success. Can someone explain how to extract them?
Much appreciated
On NodeJs side, or better: expressjs app side, you need to use a body-parser middleware, such as https://github.com/expressjs/body-parser
npm install body-parser --save
Since body-parser supports JSON as well as URL encoded input (which retrofit #Field generates) you need to add appropriate middleware functions to app:
var bodyParser = require('body-parser');
// parse JSON inputs
app.use(bodyParser.json());
// Also, parse URL encoded inputs
app.use(bodyParser.urlencoded());
// handle requests
app.post('/login/', function(req, res, next) {
loginM.attemptLogin(req.body, res);
});
Also, remember that you add body-parser middleware Before adding routes/controllers to the app. Because parser middleware should be executed before so that input is parsed by the time request handling logic is executed.
var app = express();
// first
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json());
// after
require('./models')(app);
require('./controllers')(app);
require('./routes')(app);

java spring boot pass array of strings as parameters inside json for ajax call

In my application I need to pass an array of parameters form client side to server side. I tried the following code but its not working.I need to get data from checkbox list and pass it to server side.
My code for the client side
$(".add").click(function(){
monitoring.length=0;
nonMonitoring.length=0;
$('.modal-body input:checked').each(function() {
monitoring.push($(this).val());
});
$('.addkeywords input:checked').each(function() {
nonMonitoring.push($(this).val());
});
// alert(monitoring[2]+ " " + nonMonitoring[2]);
var monitoringLength=monitoring.length;
var nonMonitoringLength=nonMonitoring.length;
$.ajax({
type : "GET",
url : '/rest/my/rest/mysql/controller',
data : {
monitoringLength: monitoringLength,
nonMonitoringLength: nonMonitoringLength,
monitoring : monitoring,
nonMonitoring: nonMonitoring,
},
success : function(data) {
// var keywordsList=data
//console.log(keywordsList);
// htm = "" ;
if(data=='success'){
// loadChannels();
location.reload();
}else{
alert("failed to upload");
}
}
});
})
My code for the server side.
#RequestMapping("/rest/my/rest/mysql/controller")
public void monitorKeywords(#RequestParam(value="monitoringLength",required=true)int monitoringLength,#RequestParam(value="nonMonitoringLength",required=true)int nonMonitoringLength,#RequestParam(value="monitoring",required=true)List<String> monitoring,#RequestParam(value="nonMonitoring",required=true)List<String> nonMonitoring){
System.out.println("MonitoringLength =>" +monitoringLength);
System.out.println("NonMonitoringLength=>" +nonMonitoringLength);
System.out.println("Monitoring=>" +monitoring);
System.out.println("Monitoring=>" +nonMonitoring);
Somehow this is not working.What is the error in this? Please help
In Request parameter change List to array
i.e.
#RequestParam(value="monitoring",required=true) String[] monitoring, #RequestParam(value="nonMonitoring",required=true) String[] nonMonitoring

AngularJS and Servlet integration

I'm trying to call a function that returns me a json object from a servlet through a link.
My HTML link, call fTest function:
<td>ver</td>
My controller:
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {$scope.descargas = response.descargas;});
$window.alert(JSON.stringify($scope.descargas));
};
});
when I press for the first time the link appears "undefined" in the alert
but when I press a second time if I can see the json object that returns in the alert
What may be happening when I press first the link? please help
thanks
The problem here is your are alerting $scope.descargas outside of the success callback therefore it truly is not defined yet try modifying it like this.
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
$window.alert(JSON.stringify($scope.descargas));
});
};
});
Since every server side request using $http in Angular is an AJAX i.e. an asynchronous call to server, you are assuming that your alert method will be called after the success response execution complete. But this is wrong.
This is where the concept of promises comes in Angular.
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga) {
console.log("1");
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
console.log("2");
});
console.log("3");
$window.alert(JSON.stringify($scope.descargas));
};
});
So when you execute this code with a delay at server side, you will see the order of console log as: 1, 3 and 2.
So, your success function is executed when the response received from the server. So for the first time, the value in descargas variable is null but get's stored using first server response and next time, value from previous call is being displayed.

How to save the response data return by Facebook in Java class using Spring MVC

I am trying to save the user data which is return by the Facebook response.
I am using Facebook Javascript.Response is in JSon format and I want to parse it first and then save it in to my database using java.
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
/* var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
console.log("User id is" + uid);
console.log(accessToken); */
document.getElementById('accesstoken').value=response.authResponse.accessToken;
console.log(response.authResponse.accessToken);
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxxxxxx',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
// window.location="http://localhost:8080/SpringMvcHibernateJavaBased/list";
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
console.log(response);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
document.getElementById('usernamefb').value=response.name;
document.getElementById('userId').value=response.id;
document.getElementById('emailfb').value=response.email;
});
}
function checkLogoutState(){
FB.logout(function(response) {
FB.Auth.setAuthResponse(null, 'unknown');
});
};
function checkData()
{
return $.ajax({
})
}
</script>
I am using Spring MVC approach fully JAVA based not using any xml files.
I have searched lot but didn't get any solution
In "if (response.status === 'connected') {}" block you need to call another API of Facebook to fetch the user's details by passing user id and token and after receiving the data you can call your own controller through Ajax and save into DB if required.
Another solution can be, you may use "http://projects.spring.io/spring-social/" on server side itself.
Krish

How do I access POST variables in my controller?

I am making the following AJAX request:
$.post('/route', {
arg1 : 'foo',
arg2 : 'bar'
});
Through the route:
POST /route controllers.Test.readPost()
How do I access these POST variables in the method of my controller?
public static Result readPost() {
return TODO; // read post variables
}
I cannot find a simple way of doing this in the documentation. It only states how to get values from JSON requests.
Use DynamicForm
public static Result getValues(){
DynamicForm requestData = form().bindFromRequest();
String name = requestData.get("name");
String desg = requestData.get("desg");
// etc
return ok("You sent: " + name + ", " + desg);
}
There is also other possibility to construct AJAX query and pass arguments via javascriptRoutes: https://stackoverflow.com/a/11133586/1066240
Of course it will pass the params via URL so it's not suitable for every value, but in many places it will be goot enough for sending POST requests with AJAX. Of course javascriptRoutes create the request with type set in routes file.
BTW: it was better if you wrote which version you are using.
you can use GET with an ajaxRequest. more information can be found here http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml
var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
if (mygetrequest.readyState==4){
if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mygetrequest.responseText
}
else{
alert("An error has occured making the request")
}
}
}
var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
mygetrequest.send(null)

Categories

Resources