Parsing application.yml in angularjs - angularjs

I have a application.yml file in my application
spring:
profiles:
active: default,dev
app:
properties:
lucene:
indexInfoFile: ${spring.jpa.properties.hibernate.search.default.indexBase}/index.properties
reindex: false
storage:
home: ${user.home}/xxx
basePath: ${app.properties.storage.home}/uploads/
staticFilesPrefix: /files/
appUrl: /app/
spring:
profiles: dev
http:
multipart:
max-file-size: 3MB
max-request-Size: 3MB
Now in my controller, I am trying to get the data from yml file and the code for the same is
$http.get('/resources/application.yml').then(function (response) {
console.log('entire data is ', response.data);
console.log('basePath is ', response.data.basePath);
});
Entire Data is printing perfectly ( the whole yml file is getting printed) but when ever I am trying to print a particular property like basePath, max-file-size etc I am getting "undefined error".
My question is how to get a particular property to be printed on the console.

I would not recommend to access the yml file directly in Angular.
The format is difficult to parse (hence your question) and you sooner or later you may not want to expose all your confguration details.
Instead create a rest controller in spring mapped to something like /config
Let spring inject all the configuration values you need using #Value and return a Map or a simple PoJo with exactly the attributes you need.
Spring will convert this to JSON which you can easily be consumed in Angular.

Related

Config variable not being fetched as expected from application.yml

I have config variable(in application.yml) as:
xyz:
exception.emails: ['abc#gmail.com']
While fetching this in local works fine but after deploying war I am getting config variable as:
xyz: [
exception: [
emails[
0
]: abc#gmail.com
]
]
I am pulling this as:
def email = Holders.config.grails.xyz.exception.emails
I'm actually surprised this work at all, because I don't think that is proper yml syntax looking at the default application.yml they specify a list of userAgents like this:
grails:
mime:
disable:
accept:
header:
userAgents:
- Gecko
- WebKit
- Presto
- Trident
Personally I like to use an application.groovy and use groovy syntax like this:
grails {
mime {
disable {
accept {
header {
userAgents:
['Gecko', 'WebKit', 'Presto', 'Trident']
}
}
}
It maybe a little out of date but here is an example of a application.yml converted to application.groovy:
https://github.com/virtualdogbert/Grails3Tutorial/blob/step_01_settings_yml_to_groovy/grails-app/conf/application.groovy
Also note in the past you could run code from application.groovy, however if you have any imports they won't work,because application.yml/groovy, is meant for the cli(pre runtime), so as a workaround you can also specify a runtime.groovy, where you can have imports. If you ever go the extra mile and write a plugin, you can specify a plugin.groovy, to set defaults.

Configure the sw-precache WebPack plugin to load a server rendered page as the navigateFallback route

consider the following scenario:
My express server dynamically generates HTML for the "/" route of my single page application.
I would like to re-serve this same generated HTML as the service worker navigateFallback when the user is offline.
I'm using https://www.npmjs.com/package/sw-precache-webpack-plugin in my webpack configuration.
If I generate an index.html via html-webpack-plugin, say, and set index.html as my navigateFallback file, that generated file gets served correctly by the service worker.
However, I can see no way to cause the on-the-fly rendered index html (what the live server returns for the "/" path) to be cached and used as the offline html.
Use dynamicUrlToDependencies option of Service Worker Precache to cache your route url and its dependencies. Then set navigateFallback to '/' and navigateFallbackWhitelist to a regex matching your sublinks logic.
Take this configuration : (Add const glob = require('glob') atop of your webpack config)
new SWPrecacheWebpackPlugin({
cacheId: 'my-project',
filename: 'offline.js',
maximumFileSizeToCacheInBytes: 4194304,
dynamicUrlToDependencies: {
'/': [
...glob.sync(`[name].js`),
...glob.sync(`[name].css`)
]
},
navigateFallback: '/',
navigateFallbackWhitelist: [/^\/page\//],
staticFileGlobsIgnorePatterns: [/\.map$/],
minify: false, //set to "true" when going on production
runtimeCaching: [{
urlPattern: /^http:\/\/localhost:2000\/api/,
// Use network first and cache as a fallback
handler: 'networkFirst'
}],
})
That use case should be supported. I have an example of something similar using the underlying sw-precache library, and I believe the syntax should be equivalent when using the Webpack wrapper.
In this case, /shell is the URL used for dynamically generated content from the server, constituting the App Shell, but it sounds like your use case is similar, with / instead of /shell.
{
// Define the dependencies for the server-rendered /shell URL,
// so that it's kept up to date.
dynamicUrlToDependencies: {
'/shell': [
...glob.sync(`${BUILD_DIR}/rev/js/**/*.js`),
...glob.sync(`${BUILD_DIR}/rev/styles/all*.css`),
`${SRC_DIR}/views/index.handlebars`
]
},
// Brute force server worker routing:
// Tell the service worker to use /shell for all navigations.
// E.g. A request for /guides/12345 will be fulfilled with /shell
navigateFallback: '/shell',
// Other config goes here...
}

Not able to retrieve data from mobile data using bluemix

I am trying to retrieve data from mobile data services using bluemix.
The code that I am using is:
jQuery.ajax({
type: 'GET',//POST
url: 'https://mobile.ng.bluemix.net:443/data/rest/v1/apps/c3b20173-b6a4-42d0-b543-93da13c1953e/objects?classname=Report&start=0&num=0',
headers: {"IBM-Application-Secret": "2fc3aa67db1ab71a80f4f38aa1770ff802120848"},
data: data,
dataType: 'json',
crossDomain: true,
success : getData,
error : throwError
})
function getData(data)
{
console.log('GOT REPORT' + JSON.stringify(data));
}
function throwError(data)
{
/*var query = Bluemixdata.Query.ofType("Report");
query.find({Severity: "SEV 4"});
console.log('Pallavi'+ JSON.stringify(query));*/
console.log('GOT REPORTError' + JSON.stringify(data));
}
but on executing the control is moving to throwError method somehow may be its not hitting the URL.
Please suggest if I am doing anything wrong. Want to acknowledge that I am getting data through bluemix console and via postman but not able to retrieve using code.
Even tried to retrieve data using Bluemixdata.Query.ofType("Report"); but getting IBMBluemix not defined error message that should be thrown as <script type="text/javascript" src="js/Bluemix/IBMBluemix.js"></script> is already defined in index.html above all the below given js
LogCat Console Output:
08-13 14:36:21.993: E/AndroidProtocolHandler(21658): Unable to open asset URL: file:///android_asset/www/default/js/Bluemix/cordova_plugins.js
08-13 14:36:22.343: I/chromium(21658): [INFO:CONSOLE(10)] "calling bluemix initialize with values----------------", source: file:///android_asset/www/default/js/Services.js (10)
08-13 14:36:22.423: I/chromium(21658): [INFO:CONSOLE(13)] "---- IBM Bluemix Initializing ------", source: file:///android_asset/www/default/js/Services.js (13)
08-13 14:36:22.433: I/chromium(21658): [INFO:CONSOLE(16)] "HiPal", source: file:///android_asset/www/default/js/Services.js (16)
08-13 14:36:22.433: I/chromium(21658): [INFO:CONSOLE(17)] "GOT A PERSON ----[object Object]", source: file:///android_asset/www/default/js/Services.js (17)
08-13 14:36:22.453: I/chromium(21658): [INFO:CONSOLE(36)] "GOT REPORTError{"statusText":"Not Found","status":404,"response":"","responseType":"","responseXML":null,"responseText":"","upload":{"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null},"withCredentials":false,"readyState":4,"timeout":0,"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null}", source: file:///android_asset/www/default/js/BarChart.js (36)
Is there a reason you are using jQuery.ajax to formulate your REST request? I suspect there is something wrong with the way you are configuring the request.
If you are going to use our hybrid SDK, you can use the APIs we provide, located here to accomplish the same thing.
I also notice that the Bluemix Cordova plugin is having some problems. Try removing your android platform from your cordova project and re-add it. You can try the same with the plugins.
Also, I recommend checking out the sample bluemixcordovadata for more detailed usages and general help.
Warning: Please avoid pasting your app secret since this is a public forum.

How do you escape a . (full stop) or / so it doesn't change URL's meaning?

I have a Web API 2.0 service which defines a particular route:
/api/someEntityGroup/{entityName}
I'm calling this enpoint using Angular $resource service.
The problem is when user wants to provide an entity name with characters that have a specific meaning in URL:
404 Not found - . (full stop), /, +
400 Bad request - ?, :, &, %, *, <, >
And these are the ones I've encountered. There may be others that may be problematic as well and I'm not even aware of them (yet).
If I use window.escape() function these still don't work, but I mainly get 404 back (the only exception being * which still returns 400 Bad request).
My code
Angular resource creation:
.factory("entityResource", ["$resource", function() {
return $resource("/api/entities/:id", null, {
search: {
method: "GET",
url: "/api/entities/:name",
isArray: true
}
});
}]);
How I call it in my code:
entityResource.search({ query: scope.name }, function(data) {
...
});
My Api controller action:
[RoutePrefix("/api/entities")]
public class EntitiesController: ApiController
{
[Route("{searchQuery}")]
public IEnumerable<Interest> Get(string searchQuery)
{
return this.interestService.Search(searchQuery);
}
...
}
I can shed some light on your 404 Not found issue when using ., /, + characters.
The issue isn't with Angular but rather with Web API and the way it resolves routes. Urls that Web API interprets as being managed resources (e.g. static content, pages etc.) it will try to resolve independently.
Set the following in your web.config to disable this behavior and force WebAPI to run all requests through your modules:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
Just a warning - If your Web API is hosted together with something like MVC or a static website, the above is not recommended as it will force all managed resources (pages, MVC routes, content[css,js,images]) through your API modules and there will be a performance impact. However, if all the API is doing is serving resource routes I would recommend enabling the above.

How to understand chats.html v.s ('/getchats', ChatsRequestHandler)]

I try to understand the different between:
The class ChatsRequestHandler generate a template with the name chats.html
template = self.generate('chats.html', template_values)
In the application view its is named getchats:
application = webapp.WSGIApplication(
[('/', MainRequestHandler),
('/getchats', ChatsRequestHandler)],
The same occurs to me at edit_user.html v.s ('/edituser', EditUserProfileHandler)
How is it that the application knows that the getchats is connected to the chats.html aldo they have not the same name? I would expect that it should be the same name chats.html and ('/chats', ChatsRequestHandler).
The flow of your request goes something like this.
App Engine looks up your app.yaml file. It should contain an entry that says /getchats should be handled by application in somefile.py.
It then goes to this "application view" and matches it to a Webapp Route. In this case, that route is ('/getchats', ChatsRequestHandler).
Then it calls get or post on ChatRequestHandler, passing it the request and response objects.
The output of that is sent back to the user's browser.
You are free to implement ChatRequestHandler as you'd like. In this case you're doing so by reading in a template named chats.html, populating it with some values, and then outputting it.
So the application knows that getchats is connected to ChatRequestHandler. The name of chats.html is pretty arbitrary - the ChatReqeustHandler has to know it, but that is all. You could rename it.
Thanks for helping me:
The example a came up with comes from codenvy.com as a examples app.
1 App Engine looks up your app.yaml file. It should contain an entry that says /getchats should be handled by application in somefile.py.
Here is the app.yaml file of this application
application: 3kus-apps
version: 1
runtime: python
api_version: 1
handlers:
- url: /css
static_dir: css
- url: /js
static_dir: js
- url: /.*
script: devchat.py
So as you can see it contain's no entry that says /getchats should be handled by application in somefile.py.
What i found there is a util.js file witch has a function updateChat(). function updateChat() {downloadUrl(getRandomUrl("/getchats"), "GET", null, onChatsReturned);}.
However, I would like to know - under (1) how this should be handled by a somefile.py.

Resources