I am a newbie to Pentaho and try to make an alert(some_msg_from_datasource) in the index.jsp of Pentaho. But I cannot figure out how to access the Pentaho variables from here. This is what I have
<head> ... <script type="text/javascript">
var Home = null;
pen.require(["home/home",
"common-ui/util/ContextProvider"], function(pentahoHome, ContextProvider) {
Home = pentahoHome;
// Define properties for loading context
var contextConfig = [{
path: "properties/config",
post: function(context, loadedMap) {
context.config = loadedMap;
}
}, {
path: "properties/messages",
post: function(context, loadedMap) {
context.i18n = loadedMap;
}
}];
// Define permissions
ContextProvider.addProperty("canCreateContent", <%=canCreateContent%>);
ContextProvider.addProperty("hasAnalyzerPlugin", <%=pluginIds.contains("analyzer")%>);
ContextProvider.addProperty("hasDataAccess", false); // default
// BISERVER-8631 - Manage datasources only available to roles/users with appropriate permissions
var serviceUrl = Home.getUrlBase() + "plugin/data-access/api/permissions/hasDataAccess";
Home.getContent(serviceUrl, function(result) {
ContextProvider.addProperty("hasDataAccess", result);
ContextProvider.get(Home.init, contextConfig); // initialize
}, function(error) {
console.log(error);
ContextProvider.get(Home.init, contextConfig); // log error and initialize anyway
});
});
</script> </head>
And for the body:
<body data-spy="scroll" data-target=".sidebar" onload="onBodyLoad()">
<script>
function onBodyLoad(){
alert("MOTD: " + the_motd_from_a_pentaho_var);
}
</script>
I assume I need the webcontext but I don't understand the head-scripts and how I can make it run. Tbh I don't even fully understand the syntax in the head. Please help :(
Related
I have a blog that I want to make shareable via LinkedIn. The docs LinkedIn presents, while simply stated don't have enough detail for me to understand my use case. My use case requires me to dynamically put the picture and description in each blog post, which isn't being populated right now. This is an Angular project.
My current code:
post.html
<script>
delete IN;
$.getScript("https://platform.linkedin.com/in.js");
</script>
<script type="IN/Share" data-url={{webAddress}} data-counter="right"></script>
post.js
//I have all of my data in $scope variables in this area, which includes
// the picture and description I'd like to attach to the post.
Here is what the LinkedIn docs show as the right way to do this:
post.html
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: YOUR_API_KEY_HERE
authorize: true
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to share content on LinkedIn
function shareContent() {
// Build the JSON payload containing the content to be shared
var payload = {
"comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG",
"visibility": {
"code": "anyone"
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
</script>
As I understand it, I need to populate the payload object with the right data/links. I have no clue how to do this based on what's in the docs.
Here are a few things I've tried/thought about along with where I'm currently stuck:
1) Get the data from post.js and put it in the payload object between the script tags in post.html. After doing some research, it is not possible to do this. Though I welcome being corrected if I'm wrong.
2) Bring the IN object into angular and populate the payload in post.js. This sounds really great but LinkedIn provides no html with which to call a function in post.js with Angular. Plus the LinkedIn code as presented takes care of formatting for the button and what comes after you click it.
3) Make an http call inside the script tags with JQuery. I rarely if ever use JQuery and have never used http for JQuery before. If this is even a feasible way to think of this problem, this is what I came up with:
<script type="IN/Share" data-url={{webAddress}} data-counter="right">
$.get( "https://public-api.wordpress.com/rest/v1.1/sites/myPost", function( response ) {
var post = _.first(_.filter(response.posts, function(n){return n.title.replace(/ /g,"-").replace(/[:]/g, "").toLowerCase() === $stateParams.id}));
var post1 = _.assign(post, {category: _.first(_.keys(post.categories)), pic: _.first(_.values(post.attachments)).URL, credit: _.first(_.values(post.attachments)).caption, linkCredit: _.first(_.values(post.attachments)).alt, fullStory: post.content.replace(/<(?!\s*\/?\s*p\b)[^>]*>/gi,'')});
**var image = post1.pic;**
**var title = post1.title;**
**var webAddress = window.location.href;**
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
function shareContent(title, image, webAddress) {
var payload = {
"content": {
"title": title,
"submitted-image-url": image,
"submitted-url": webAddress
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
});
</script>
This solution did not result in a solution either. Where to go from here, I have no ideas. I'm sure this simple but idiosyncratic enough that I need a little hand holding.
Unfortunately, I have not worked with linkedin API.
Perhaps not all will be right in my example. But I've got to use a variable IN in angular and write about the call API wrapper.
An example of the use of plugins, see page LinkedIn Plugins.
Live example on jsfiddle.
//CallBackHell
function LinkedInServiceFunc(callback) {
callback && IN.Event.onDOMReady(callback);
}
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope, LinkedInService, ShareLinkedINService) {
console.log('ExampleController IN', IN);
console.log('ExampleController LinkedInService', LinkedInService);
LinkedInService.promise.then(function(LIN) {
console.log('Complete loading script for LinkedIn in ExampleController', LIN.Objects)
});
//Then you can interact with IN object as angular service. Like this
$scope.shareContent = function() { // Use the API call wrapper to share content on LinkedIn
// Build the JSON payload containing the content to be shared
var payload = {
"comment": $scope.comment,
"visibility": {
"code": 'anyone'
}
};
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
console.log('shareContent', payload);
LinkedInService.promise.then(function(LIN) {
LIN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
});
}
$scope.shareContentService = function() {
//It's better way, i think
ShareLinkedINService.shareContent($scope.comment, 'anyone').then(function(data) {
console.log('success', data);
}).catch(function(data) {
console.err('error', data);
});
}
})
.service('LinkedInService', function($q) {
var defer = $q.defer();
LinkedInServiceFunc(function() {
defer.resolve(IN);
});
return {
promise: defer.promise
};
})
//You can create wrapper on IN API
.service('ShareLinkedINService', function(LinkedInService, $q) {
return {
shareContent: function(comment, visible) {
var defer = $q.defer();
var payload = {
"comment": comment,
"visibility": {
"code": visible
}
};
LinkedInService.promise.then(function(LIN) {
LIN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(defer.resolve)
.error(defer.reject);
});
return defer.promise;
}
}
})
.directive('linkedInShareButton', function(LinkedInService) {
return {
restrict: "E",
replace: false,
scope: {
shareUrl: "#",
counter:"#"
},
link: function(scope, elem, attr) {
var script = document.createElement('script');
script.setAttribute('type', 'IN/Share');
script.setAttribute('data-url', scope.shareUrl);
script.setAttribute('data-counter', scope.counter);
elem.append(script);
},
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
authorize: false
onLoad: LinkedInServiceFunc
//I don't have api_key, because i delete it
// api_key: YOUR_API_KEY_HERE
// authorize: true
// onLoad: onLinkedInLoad
</script>
<body ng-app="ExampleApp">
<div>
<div ng-controller="ExampleController">
<input ng-model="comment">
<button ng-click="shareContent()">
shareContent
</button>
<button ng-click="shareContentService()">
shareContentService
</button>
<script type="IN/Share" data-url="www.mail.ru" data-counter="top"></script>
<linked-in-share-button share-url="www.mail.ru" counter="top"></linked-in-share-button>
</div>
</div>
</body>
Background:
I am trying to encrypt a pouchdb database by using crypto-pouch library.
I had a look at the example shown at https://github.com/calvinmetcalf/crypto-pouch
But it doesn't seem to do anything for me.
My code:
<!DOCTYPE html>
<html ng-app="pouchdbApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="pouchdbDemo.js"></script>
<script src="http://cdn.jsdelivr.net/pouchdb/5.2.1/pouchdb.min.js"></script>
<!-- <script src="crypto-pouch-master/bundle.js"></script> -->
<script src="http://wzrd.in/standalone/crypto-pouch"></script>
<script>
var db = new PouchDB('kittens2');
var password = "mypassword";
db.crypto(password).then(function (publicKey) {
console.log("publicKey");
console.log(publicKey);
});
/* db.removeCrypto(); */
var doc = {
"_id": "mittens",
"name": "Mittens",
"occupation": "kitten",
"age": 3,
"hobbies": [
"playing with balls of yarn",
"chasing laser pointers",
"lookin' hella cute"
]
};
db.put(doc);
db.get('mittens').then(function (doc) {
console.log(doc);
});
</script>
</head>
<body>
</body>
</html>
But my code doesn't see to do any encryption of the data entered, or i couldn't see any public key generated.
Any clue how i should be using the crypto-pouch library with pouchdb.
Edit: this answer originally refereed to version 1.x of crypto pouch, but is not correct for the current version (3.x), in the current version db.crypto(password) does not return a promise so the code examples updated are
db.crypto(password)
// <-- encryption set up
and
db.crypto(password);
db.put({_id: 'foo', bar: 'baz'}).then(function () {
return db.get('foo');
}).then(function (doc) {
console.log('decrypted', doc);
return db.removeCrypto();
}).then(function () {
return db.get('foo');
}).then(function (doc) {
console.log('encrypted', doc);
})
Original answer (still valid for v1.x) follows:
so the documentation is a bit confusing (which I just cleaned up) but when you call db.crypto it wraps the database so that documents are transparently encrypted and decrypted
db.crypto(password).then(function () {
// <-- encryption set up
})
and it will transparently encrypt documents you create and decrypt ones you read until you call
db.removeCrypto();
so if you want to test do something like
db.crypto(password).then(function () {
return db.put({_id: 'foo', bar: 'baz'});
}).then(function () {
return db.get('foo');
}).then(function (doc) {
console.log('decrypted', doc);
return db.removeCrypto();
}).then(function () {
return db.get('foo');
}).then(function (doc) {
console.log('encrypted', doc);
})
I tried combDB and its the only one that seems to work as of now with the new nodeJS
const PouchDB = require('pouchdb')
PouchDB.plugin(require('comdb'))
const password = 'extremely secure value'
const db = new PouchDB(POUCH_PATH)
db.setPassword(password)
db.post({
_id: 'gay-agenda',
type: 'queerspiracy',
agenda: ['be gay', 'do crimes']
}).then(() => {
// now replicate to a couchdb instance
return db.replicate.to(`${COUCH_URL}/FALGSC`)
})
or with Angular (Typescript)
import PouchDB from 'pouchdb-browser';
...
this.db = new PouchDB('myProjectDB');
this.db.setPassword(environment.dbPassword);
I have got to know toaster.js from this site and trying to implement it in my web app. I have done it according to the example but it doesn't work.
Here is my service where I Implemented:
function () {
angular
.module('FoursquareApp')
.factory('DataService', DataService);
DataService.$inject = ['$http','toaster'];
function DataService($http, toaster) {
.id,
venueName: venue.name,var serviceBase = '/api/places/';
var placesDataFactory = {};
var userInContext = null;
var _getUserInCtx = function () {
return userInContext;
};
var _setUserInCtx = function (userInCtx) {
userInContext = userInCtx;
};
var _savePlace = function (venue) {
//process venue to take needed properties
var minVenue = {
userName: userInContext,
venueID: venue
address: venue.location.address,
category: venue.categories[0].shortName,
rating: venue.rating
};
return $http.post(serviceBase, minVenue).then(
function (results) {
toaster.pop('success', "Bookmarked Successfully", "Place saved to your bookmark!");
},
function (results) {
if (results.status == 304) {
toaster.pop('note', "Faield to Bookmark", "Something went wrong while saving :-(");
}
else {
toaster.pop('error', "Failed to Bookmark", "Something went wrong while saving :-(");
}
return results;
});
};
I have called the library scripts in index.html and also the css files.
Any ideas of what I might be doing wrong?
Are you sure that you use toaster.js library? The popular one is toastr.js
Try to modify your code to
DataService.$inject = ['$http','toastr'];
function DataService($http, toastr) {
...
Also ensure, that you link this js file in you index.html and also refer this package in main app module definition as a second (dependency) parameter
I want to provide users a facility to sign in with google. However, I want to use my image(only image, no css) as "sign in with google" button. I am using the following code:
<div id="mySignin"><img src="images/google.png" alt="google"/></div>
I am also using gapi.signin.render function as mentioned on google developer console. The code is:
<script src="https://apis.google.com/js/client:platform.js" type="text/javascript"></script>
<script>
function render(){
gapi.signin.render("mySignIn", {
// 'callback': 'signinCallback',
'clientid': 'xxxx.apps.googleusercontent.com',
'cookiepolicy': 'single_host_origin',
'requestvisibleactions': 'http://schema.org/AddAction',
'scope': 'profile'
});
}
The problem is that google signin popup is not opening and I cannot figure out how to solve it. Please suggest. Thanks in advance.
<script type="text/JavaScript">
/**
* Handler for the signin callback triggered after the user selects an account.
*/
function onSignInCallback(resp) {
gapi.client.load('plus', 'v1', apiClientLoaded);
}
/**
* Sets up an API call after the Google API client loads.
*/
function apiClientLoaded() {
gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);
}
/**
* Response callback for when the API client receives a response.
*
* #param resp The API response object with the user email and profile information.
*/
function handleEmailResponse(resp) {
var primaryEmail;
var jsonobj=JSON.stringify(resp);alert(jsonobj);
var uid= jsonobj.id;
var user_name1= jsonobj.name;
for (var i=0; i < resp.emails.length; i++) {
if (resp.emails[i].type === 'account') primaryEmail = resp.emails[i].value;
}
/* document.getElementById('response').innerHTML = 'Primary email: ' +
primaryEmail + '<br/>id is: ' + uid; */
}
To use an image as your "Google Sign-in" button, you can use the GoogleAuth.attachClickHandler() function from the Google javascript SDK to attach a click handler to your image. Replace <YOUR-CLIENT-ID> with your app client id from your Google Developers Console.
HTML example:
<html>
<head>
<meta name="google-signin-client_id" content="<YOUR-CLIENT-ID>.apps.googleusercontent.com.apps.googleusercontent.com">
</head>
<body>
<image id="googleSignIn" src="img/your-icon.png"></image>
<script src="https://apis.google.com/js/platform.js?onload=onLoadGoogleCallback" async defer></script>
</body>
</html>
Javascript example:
function onLoadGoogleCallback(){
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: '<YOUR-CLIENT-ID>.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
scope: 'profile'
});
auth2.attachClickHandler(element, {},
function(googleUser) {
console.log('Signed in: ' + googleUser.getBasicProfile().getName());
}, function(error) {
console.log('Sign-in error', error);
}
);
});
element = document.getElementById('googleSignIn');
}
For those who come to here trying to get the button work out: The code below should do the trick.
It looks like the 'callback' method doesn't seem to work not sure if this is something to do with Vue as I am building it on Vue, or Google changed it as this was posted 5 years ago. Anyways, use the example below.
window.onload =() =>{
var GoogleUser = {}
gapi.load('auth2',() =>{
var auth2 = gapi.auth2.init({
client_id: '<client-unique>.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
scope: 'profile'
});
auth2.attachClickHandler(document.getElementById('googleSignup'), {},
(googleUser) =>{
console.log('Signed in: ' + googleUser.getBasicProfile().getName());
},(error) =>{
console.log('Sign-in error', error);
}
);
});
}
Change 'client_id' to your client id, and element id to your customized button id.
I hope this saves time for anyone!
Plus: I ended up using the code below, which is clearer:
window.onload = () => {
gapi.load('auth2', () => {
let auth2 = gapi.auth2.init({
client_id: '<client_id>.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
scope: 'profile email'
});
document.getElementById('googleSignup').addEventListener('click',() => {
auth2.signIn().then(() => {
let profile = auth2.currentUser.get().getBasicProfile();
... profile functions ...
}).catch((error) => {
console.error('Google Sign Up or Login Error: ', error)
});
});;
});
}
I am trying to introduce pagination using the backbone.js paginator plugin's requestPager.
Problem: After setting up the collection which extends Backbone.Paginator.requestPager, I refreshed the webpage and the javascript console threw the error:
Uncaught TypeError: Object function (a){return new m(a)} has no method 'result' backbone.paginator.js:678
I am very new to backbone and is not sure what went wrong. Is it because I used fetch(), which showed up in the screenshot of the error below? I also noticed that no GET requests were sent to the backend. What happened, and how should I fix this? Thanks!
JS code
// Collection
window.ListingCollection = Backbone.Paginator.requestPager.extend({
model: Listing,
paginator_core: {
type: 'GET',
dataType: 'jsonp',
url: 'api/listings'
},
paginator_ui: {
firstPage: 0,
currentPage: 0,
perPage: 10,
totalPages: 10
},
server_api: {
'$filter': '',
'$per_page': function() { return this.perPage; },
'$current_row': function() { return this.currentPage * this.perPage; },
'$order_by': 'listing_id'
},
parse: function(response){
this.totalPages = Math.floor(response.total_rows / this.perPage);
}
});
JS Code
// Router
var AppRouter = Backbone.Router.extend({
routes: {
'': 'listings',
'listings': 'listings'
},
listings: function() {
var self = this;
// Load initial search results
this.listingList = new ListingCollection();
this.listingList.fetch({
success: function() {
self.listingListView = new ListingListView({ model: self.listingList });
$('#listing_list table').append(self.listingListView.render().el);
}
});
this.listingFilterView = new ListingFilterView();
}
});
Screenshot of Error in Javascript Console
JS Includes
<!-- JavaScript -->
<script src="assets/js/lib/jquery-1.7.1.min.js"></script>
<script src="assets/js/lib/underscore-min.js"></script>
<script src="assets/js/lib/backbone-min.js"></script>
<script src="assets/js/lib/backbone.paginator.js"></script>
<script src="assets/js/lib/bootstrap.js"></script>
<script src="assets/js/lib/bootstrap-datepicker.js"></script>
<script src="assets/js/app.js"></script>
You are probably using older version of Underscore. I use 1.3.1 and it does not have result() method. Download their new production version 1.3.3 - it has result().