Invoke Bluemix Workflow with Node.js app - node.js

I am able to invoke my workflow with the DevOps IDE, but not with Node.js app. My Node.js app code is:
var buffer = new Buffer(workflowConfig.credentials.user + ":" + workflowConfig.credentials.password,"ascii");
var base64Auth = buffer.toString('base64');
var baseURL = workflowConfig.credentials.url.substr(0, workflowConfig.credentials.url.lastIndexOf('/'));
var scriptFilepath = 'helloworld';
var wfTarget = 'echo';
var APIUrl = urljoin(baseURL, 'myworkflow', scriptFilepath, '_', wfTarget);
var requestOptions = {
headers : {
"Authorization" : base64Auth
}
}
console.log("APIUrl: " + APIUrl);
console.log("requestOptions: " + JSON.stringify(requestOptions));
request.get(APIUrl, requestOptions, function(error, response, body){
if (error) {
console.log(error);
res.status(500).send(error)
}else{
console.log(body);
res.json(body);
}
});
I tried running it on Bluemix and on my local env (with hard-coded VCAP_SERVICES). The response body is an HTML page with a title: "Redirect To OP"
Kindly please help

Related

Getting User Level Permissions on List in sharepoint online using Javascript and Rest API

I have implemented sharepoint hosted app for getting user level permissions on a list using javascript and rest api.
Here is my code,
'use strict';
var hostweburl;
var appweburl;
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
hostweburl = _spPageContextInfo.siteAbsoluteUrl;
appweburl = _spPageContextInfo.siteServerRelativeUrl;
alert(hostweburl);
alert(appweburl);
getListUserEffectivePermissions();
});
function getListUserEffectivePermissions() {
var listTitle = 'MyList_Deepa';
//var account = 'i%3A0%23.f%7Cmembership%7Cuser%40abhishek#sarasamerica.com&#target=';
var endpointUrl = "'" + appweburl + "'/_api/SP.AppContextSite(#target)/web/lists/getbytitle('" + listTitle + "')/getusereffectivepermissions(#user)?#user='i%3A0%23.f%7Cmembership%7Cuser%40abhishek#sarasamerica.com&#target='" + hostweburl + "'";
//var endpointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + MyList_Deepa + "')/getusereffectivepermissions(#u)?#u='" + encodeURIComponent(account) + "'";;
return $.ajax({
url: endpointUrl,
dataType: 'json',
headers: {
"accep": "application/json;odata=verbose",
"X-RequestDigest": $("#_REQUESTDIGEST").val()
}
});
}
function parseBasePermissions(value) {
var permissions = new SP.BasePermissions();
permissions.initPropertiesFromJson(value);
var permLevels = [];
for (var permLevelName in SP.PermissionKind.prototype) {
if (SP.PermissionKind.hasOwnProperty(permLevelName)) {
var permLevel = SP.PermissionKind.parse(permLevelName);
if (permissions.has(permLevel)) {
permLevels.push(permLevelName);
}
}
}
return permLevels;
}
getListUserEffectivePermissions().done(function (data) {
var roles = parseBasePermissions(data.d.GetUserEffectivePermissions);
console.log(roles);
});
Error: Failed to load resource: the server responded with a status of 404 (Not Found).
Please anybody can give solution to resolve the problem.

using node jsrequest for the flickr API

I'm using the node js request function to access the following URL for the flickr API
https://www.flickr.com/services/oauth/access_token?oauth_token=X&oauth_verifier=X&oauth_consumer_key=X&oauth_nonce=X&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1468959629921&oauth_version=1.0&oauth_signature=X
For some reason, I'm getting a response timeout. What would you recommend that I do to fix this?
Here's the code
request(url, function (e, r, body) {
if (!e && r.statusCode === 200) {
var tokens = qs.parse(body);
console.log('test1');
var key = self.PLATFORM_TYPE + '_' + tokens.user_nsid;
var user = {
tokens: tokens,
key: key,
platform: self.PLATFORM_TYPE
};
deferred.resolve(user);
} else {
deferred.reject(body);
}
});

Put data and attachment to Cloudant DB IBM bluemix

I am trying to PUT my data within its attachment. I am doing it with NodeJS
Here is my code:
var date = new Date();
var data = {
name : obj.name,
serving : obj.serving,
cuisine : obj.cuisine,
uploadDate : date,
ingredients : obj.ing,
directions: obj.direction
} //Assume that I read this from html form and it is OK
db.insert(data, function(err, body){
if(!err){
console.log(body);
var id = body.id
var rev = body.rev
var headers = {
'Content-Type': req.files.image.type
};
var dataString = '#' + req.files.image.path;
var options = {
url: 'https://username:password#username.bluemix.cloudant.com/db_name/' + id + '/' + req.files.image.name +'?' + 'rev=' + rev,
method: 'PUT',
headers : headers,
body : dataString
}
console.log(options)
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
}
});
I am getting a 201 response after an image attachment has been sent. But in the cloudant dashboard I see "length": 38 of uploaded image which is impossible.
If I try to access uploaded image it gives:
{"error":"not_found","reason":"Document is missing attachment"}.
How I can fix this problem?
It looks like you are uploading the path to the image and not the contents of the image itself:
var dataString = '#' + req.files.image.path;
This will just upload the string '#xyz' where xyz is the path of the file. You need to upload the contents of the image. See the following for more information:
https://wiki.apache.org/couchdb/HTTP_Document_API#Attachments
I am not sure how to get the contents of the uploaded file from req.files. I believe req.files no longer works in Express 4, so I use multer:
https://github.com/expressjs/multer
This is how I upload a file to Cloudant that was uploaded to my app:
Client
<form action="/processform" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" value="Submit">
</form>
Node.js Routing
var multer = require('multer');
...
var app = express();
...
var uploadStorage = multer.memoryStorage();
var upload = multer({storage: uploadStorage})
app.post('/processform', upload.single('myfile'), processForm);
Note: 'myfile' is the name of the file input type in the form.
Node.js Upload to Cloudant
function processForm() {
// insert the document first...
var url = cloudantService.config.url;
url += "/mydatabase/" + doc.id;
url += "/" + encodeURIComponent(req.file.originalname);
url += "?rev=" + doc.rev;
var headers = {
'Content-Type': req.file.mimetype,
'Content-Length': req.file.size
};
var requestOptions = {
url: url,
headers: headers,
body: req.file.buffer
};
request.put(requestOptions, function(err, response, body) {
if (err) {
// handle error
}
else {
// success
}
});
...
}

node.js - page keeps loading - no errors to investigate

this is 1.js
let's run it
node 1.js
and then on the web
execute: domain.tld/-2
it all works perfect.
i see it loaded 2.js and then
used a function to do the mysql query
and displays all the results. perfect.
now on the web let's try to
go to : domain.tld/-3
1.js tries to load 3.js
because the urlpath name is '/-3'
but there is no '3.js'
i am expecting it to say
"page not found'
node 1.js is not crashing.
and web browser is still.. 'loading.."
here is the 1.js :
var http = require('http');
var url = require('url');
var mysql = require('mysql');
var Memcached = require('memcached');
var memcached = new Memcached('localhost:11211');
var connection = mysql.createConnection({
host : '--------------',
user : '2',
password : '-------------',
database : '1'
});
connection.connect();
var server=http.createServer(function(req,res){
res.writeHead(200,{'Content-Type': 'text/html; charset=utf-8'});
var pathname=url.parse(req.url).pathname;
if (pathname.match(/\/-\d{1,2}/)) {
pathname = pathname.replace('-', '')
try{
var o = require('/' + pathname + '.js')
} catch (err){
var o = '0'
}
if (o == '0'){
o = 'page not found'
}else{
o.makeQuery(connection, function(err, result){
if(err) return res.end(err);
o = result;
res.end(o)
});
}
} else if (pathname.match(/^\/$/)) {
res.end('welcome to index page');
} else {
pathname = pathname.replace('/', 'o');
res.end('welcome to user profile page');
}
}).listen(80);
although it may not matter..
here is the 2.js
exports.makeQuery = function(connection, callback) {
var queryString = 'SELECT * FROM 1_accounts order by ac_nu asc limit 5';
connection.query(queryString, function(err,res,fields){
if (err) {return callback(err)};
bb = JSON.stringify(res);
callback(null, bb);
});
}
before i added the following segment to
1.js it was working fine via web.
if (pathname.match(/\/-\d{1,2}/)) {
} else if (pathname.match(/^\/$/)) {
} else {
}
in other words it must have something to do
with those perhaps.
before i added those lines..
it would smoothly display:
"page not found"
You have set o='page not found' but there is no response.write(o) or res.end(o) for it as it is in the else part hence it will never be displayed

I am unable to convert http.get image into base 64

app.getImage = function() {
var image = Meteor.http.get("https://turtlerock-discourse.global.ssl.fastly.net/user_avatar/talk.turtlerockstudios.com/takran/45/879.png", {
});
var prefix = "data:image/png;base64,";
var imagebase64 = new Buffer(image.content, 'binary').toString('base64');
imagebase64 = prefix + imagebase64;
console.log(imagebase64);
return imagebase64;
}
but I am not seeing results,
any help?
This is a dummy text for the error.
a pure Meteor solutions:
var response = HTTP.call('GET', url,{npmRequestOptions: { encoding: null }})
var data = "data:" + response.headers["content-type"] + ";base64," + new Buffer(response.content).toString('base64');
This is how I fixed this issue.
app.getImage = function(){
var myrequest = request.defaults({ encoding: null });
var fut = new Future();
var options = {
"url" : "https://any.domain.com/any.png"
}
myrequest.get(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = "data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64');
fut.return(data);
}
else
fut.return(null);
});
return fut.wait();
}
I was assuming this solution should have come with meteor code itself,
but it doesn't,
I had to use nodejs way to do it.
I will still be waiting for someone to post an answer based on pure meteor way.

Resources