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

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);

Related

How do I make authenticated HTTP GET request with Spring schedule service

In ruby I can make a GET request with username and password by doing:
uri = URI('http://192.00.00.00')
req = Net::HTTP::Get.new(uri)
req.basic_auth 'username', 'password'
res = Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(req)
}
Right now I am trying to make a GET request to my server that requires an username and password using Java and Spring. How does the above code translates to Java?
Also, if I want to make the request every 5 seconds, should I simply have the java code inside the block below?
#Scheduled(fixedRate = 5000)
public void httpRequest() {
//java code here
}

server for fetching a url and passing the results back

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

Error While Generating Access Token For Shopify App

I have built an app for Shopify Shops and it was working fine until yesterday. Link to the documentation followed to create a Shopify app: https://docs.shopify.com/api/authentication/oauth
But now there seems to be an error while generating an access token. I have been getting the error in response:
{"error":"795: unexpected token at 'code=<my-code>\u0026client_secret=<my-secret>\u0026client_id=<my-client-id>'"}
Here is the gist of code written in Google App Script.
function doPost(e)
{
try
{
var client_id = e.parameter['client_id'];
var client_secret = e.parameter['client_secret'];
var code = e.parameter['code'];
var shopUrl = e.parameter['shopUrl'];
var headers = {
"Accept":"application/json",
"Content-Type":"application/json"
};
var payload = {
"client_id" : client_id,
"client_secret" : client_secret,
"code": code
};
var options =
{
"method" : "POST",
"payload" : payload,
"headers" : headers,
"muteHttpExceptions":true
};
var response = UrlFetchApp.fetch(shopUrl, options);
var data = response.getContentText().split('"')[3];
//response variable gives the following response
// {"error":"795: unexpected token at 'code=<my-code>\u0026client_secret=<my-client-secret>\u0026client_id=<my-client-id>'"}
return ContentService.createTextOutput(data).setMimeType(ContentService.MimeType.TEXT);
}//try
catch(e)
{
//log the exception
}//catch
}//doPost
Did anybody encounter the same error? Please help
Make sure that you requested to right URL, it just likes as
"https://[YOUR_SHOP_DOMAIN]/admin/oauth/access_token".
Make sure that you gave right ID&secret.
Check my PHP-code here for getting Shopify access-token:
ShopifyClient.php (scroll to the function "getAccessToken")

Getting Request parameters from Ajax Response

I am making ajax call to a java method for every 30 seconds.
I am setting few request parameters in the java method.
How can I get them from ajax response.
<script LANGUAGE="JavaScript1.2">
var tId = window.setTimeout(function () {
location.reload(true);
alert('<s:property value="#disableReload" />');
if('<s:property value="#disableReload" />' == "true"){
alert("clearing");
}else{
var url = 'moveETHAction_fetchExecutorData.action';
var form = document.getElementById('moveForm');
var params = Form.serialize(form) + '&ms=' + new Date().getTime();
form.action = "fetchExecutorData";
var myAjax = new Ajax.Request(url, {method: 'post', parameters: params, onComplete: showResponseAction} );
}
}, 30 * 1000);
function showResponseAction(originalRequest){
alert(originalRequest.responseText);
alert('<s:property value="#request[\'DISABLE_FLOW'\]" />');
document.getElementById('actionChange').innerHTML = originalRequest.responseText;
}
</script>
In Java method I am setting this parameter
request.setAttribute(GenericConstants.DISABLE_FLOW, false);
But I am not getting the updated value from the ajax
Any changes to the HttpServletRequest on the server side will not be visible on the client side. Moreover setAttribute method will not affect the incoming HTTP request string. It's additional store within HttpServletRequest to pass-around information on the server-side.
You need to add the information to the existing response, in a structured away (JSON is preferable for your client to convert into a javascript object right away and access the individual values within response). Hope this helps.

How do I get all values in a JIRA multi-checkbox customfield with SOAP?

I'm developing a web application that uses SOAP to communicate with JIRA. I have a custom field that contains several checkboxes, and I can get this field through SOAP, but I can't get to the actual checkboxes it contains. Is there a way to do this?
Since nobody has answered this so far, here is an old copy of some JavaScript I did for JIRA, reading customfields.
var unitlist_val = $("#unitList_0").val();
var errorlist_val = $("#errorList_0").val();
var larmlist_val = $("#larmList_0").val();
var URL= ""+jira+"/sr/jira.issueviews:searchrequest-xml/temp/SearchRequest.xml jqlQuery=project+%3D+"+problem+
"+AND+%22Symptom+1+-+Component%22+~+%22+"+unitlist_val+"%22+AND+%22Symptom+2+-+State%22+~+%22"+errorlist_val+
"%22+AND+%22Symptom+3+-+alarm%22+~+%22"+larmlist_val+
"%22&tempMax=1000&field=title&field=link&field=customfield_10422&field=customfield_10423&field=customfield_10424&field=customfield_10420&field=resolution&field=customfield_10440";
$.ajax({
type: "GET",
url: URL,
dataType: "xml",
cache: false,
beforeSend: function(request) {
request.setRequestHeader("Accept", "text/xml; charset=utf-8");
},
success: function(data){
$(data).find("item").each(function(){
// Make sure swedish chars, are handled properly. Append to page first, then get value.
var unitList = $("<div/>").html($(this).find("#customfield_10422 customfieldvalue").text()).text().split(",");
var errorList = $("<div/>").html($(this).find("#customfield_10423 customfieldvalue").text()).text().split(",");
var alarmList = $("<div/>").html($(this).find("#customfield_10424 customfieldvalue").text()).text().split(",");
var knownerror = $("<div/>").html($(this).find("#customfield_10420 customfieldvalue").text()).text() || "None";
var resolution = $("<div/>").html($(this).find("resolution").text()).text() || "None";
}
});
You can probably do something similar in Java and use a simple GET request. I cut out quite a lot of code, so some parts might be syntax error on.

Categories

Resources