Angular 2/4 file download from web api

Your Component

this.commonService.getMultipart()
  .subscribe(blob => {
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="any name + extension";
    link.click();
  })

Service 

setMultipartHeader(headers:Headers){
headers.append('method', 'GET');
//any headers you want to set
}

getMultipart(){
var headers = new Headers();
this.setMultipartHeader(headers);
let requestOptions = new RequestOptions({
headers: headers,
responseType:ResponseContentType.Blob,//dont forget to import the enum
//In case you get Module not found: Error: Can't resolve '@angular/http/src/enums', just use 3 instead ex "responseType:3"
});

return this.http.get("url",requestOptions)
.map(res => {
return new Blob( [res.blob()], { type: "application/octet-stream"} );
})
}

Web Api Sample (can use this as reference for spring/grails. I am using grails)

File file = new File("path")
if(file.exists()){
    response.setContentType("application/octet-stream")
    response.setContentLength((int) file.length())
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"")
    response.outputStream << file.bytes
    response.outputStream.flush()
}

 

AngularJs directive for google’s place autocomplete

Please don’t be harsh if you find something wrong or not done the right way . I am really new to angular and mostly learning by implementation and not from books

Controller

var app = angular.module('appName', ['appDirective']);
app.controller('public', ['$scope', function ($scope) {
    $scope.address = {location: null, state: null, city: null, latitude: null, longitude: null};

}]);

Directive

var appdirective = angular.module('appDirective', []);

appdirective.directive('googleMaps', function () {
    return {
        restrict: 'A',
        scope: {
            model: '=model',
            city: '=city',
            state: '=state',
            latitude: '=latitude',
            longitude: '=longitude'
        },
        link: function (scope, element, attrs) {
            var options = {componentRestrictions: {country: 'in'}};
//any options you want to set
            var autocomplete  = new google.maps.places.Autocomplete(element[0], options);
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
                var components = place.address_components;
                scope.$apply(function () {
                    for (var i in components) {
                        if (components[i].types[0] == 'locality') {
                            scope.city = components[i].long_name;
                        }
                        else if (components[i].types[0] =='administrative_area_level_1') {
                            scope.state = components[i].long_name;
                        }
                    }
                    scope.latitude = place.geometry.location.lat();
                    scope.longitude = place.geometry.location.lng();

                });
                //
                //
            })
        }
    }
})

html

<input google-maps model="address.location" city="address.city"
state="address.state" latitude="address.latitude"
 longitude="address.longitude" name="area" class="form-control"/>

Know whether the image being posted is horizontal or vertical

Suppose you have a CommonsMultipartFile object  and you want to know whether image posted is vertical or horizontal (example in case of cover photo like facebook’s, you might want user to post only horizontal snap) , then it can be done in the following way

CommonsMultipartFile image

BufferedImage src = ImageIO.read(new ByteArrayInputStream(image.bytes))
if (src.getHeight() > src.getWidth()) {
print(“====================is vertical”)
} else
print(“====================is horizontal”)
}

Getting fresh currency exchange rates from yahoo

Yahoo provides YQL(Yahoo Query Language) platform that enables you to query , filter and combine data . These queries syntax is just like SQL queries.

So the query used to get fresh exchange rate from yahoo is

select * from yahoo.finance.xchange where pair in ("USDINR") 

This query would return usd to inr exchange rate along with the date and time this instance of exchange rate was created and other useless information which can be avoided.

And if you want to get multiple exchange rates at once , then you can manipulate the query like:-

select * from yahoo.finance.xchange where pair in ("USDINR","USDEUR","USDNGN","USDCAD")  

Just like that you can implement it for all combinations you want.

So now you would be like ” OK I have the query , so how do i get the damn exchange rates”, well you could do that by making http request using get method, if you don’t know how to do that well then you cal follow the following blog for doing that in java , groovy . For others please try to find that out yourself.


https://hprog99.wordpress.com/2014/11/03/send-http-postget-request-in-java/
 

So the complete url that you would sending request to is


https://query.yahooapis.com/v1/public/yql?q=
select * from yahoo.finance.xchange where pair in ('USDINR','USDEUR','USDNGN','USDCAD')&format=json&env=store://datatables.org/alltableswithkeys&callback=

Again you could manipulate the query depending upon which currency pairs are you interested in .
Also before making http request , you would need to encode the url with UTF-8, so after encoding the url with UTF-8 it should look something like


https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%27USDINR%27%2C%27USDEUR%27%2C%27USDNGN%27%2C%27USDCAD%27)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=

And you would get the following json as reponse


{"query":{"count":4,"created":"2015-06-11T05:43:15Z","lang":"en-US","results":{"rate":[{"id":"USDINR","Name":"USD/INR","Rate":"63.8550","Date":"6/11/2015","Time":"6:43am","Ask":"63.8600","Bid":"63.8550"},{"id":"USDEUR","Name":"USD/EUR","Rate":"0.8846","Date":"6/11/2015","Time":"6:43am","Ask":"0.8847","Bid":"0.8846"},{"id":"USDNGN","Name":"USD/NGN","Rate":"198.9500","Date":"6/11/2015","Time":"6:43am","Ask":"199.0000","Bid":"198.9500"},{"id":"USDCAD","Name":"USD/CAD","Rate":"1.2277","Date":"6/11/2015","Time":"6:43am","Ask":"1.2278","Bid":"1.2277"}]}}}

If you have any doubts or suggestions then please post them in comments.

Install wordpress alongside another application with Nginx

So I ran into a problem in which I was supposed to install wordpress blog on ubuntu server with another app deployed on tomcat.

Many of you would think , just configuring subdomain to redirect to wordpress would do the trick , but I was not supposed to use subdomain but instead I was supposed redirect all hits on http://www.myapp.com/wordpress to it.

I am going to list all the steps that I followed to make it work for me.

1) Hoping you have nginx installed on your server , if you have not please follow this link 

https://hprog99.wordpress.com/2015/04/05/how-to-install-nginx-on-ubuntu/

2) Setup wordpress

a) To setup wordpress , you would need mysql . If you do not have mysql installed then please do so by using these commands

 sudo apt-get install mysql-server
 sudo apt-get install mysql-client

Enter password for user root when prompted
b) Create a separate database for wordpress like yourAppName_wp or any of your choice
c) Download wordpress using the following command

wget http://wordpress.org/latest.tar.gz

d) Extract tar.gz using

tar -zxvf latest.tar.gz

-this command would extract the contents under wordpress directory.

e) Copy the extracted wordpress directory to /var/www. So final structure would be like /var/www/wordpress.

f) Configure wordpress

cd /var/www/wordpress

– create a copy of sample configuration file and name it wp-config.php

sudo cp wp-config-sample.php wp-config.php

– Now edit the configuration file using

sudo vim wp-config.php

– You will need to find and enter the configuration settings for DB_NAME (your database name), DB_USER(database user), DB_PASSWORD(database password)

3) Configure php

a)Make sure php-fpm is running

ps -eaf | grep -y php

– If you can find any php processes running , reinstall php using or install fresh if you haven’t already using second statement only.

sudo apt-get remove php5 php5-cgi php5-fpm php5-mysql
sudo apt-get install php5 php5-cgi php5-fpm php5-mysql

b) Next get php-fpm to listen on the correct host/port

cd /etc/php5/fpm/pool.d
sudo vim www.conf

– Change the listen value from /var/run/php5-fpm.sock to 127.0.0.1:9000

c) Restart php-fpm using

sudo service php5-fpm restart

4) Final step is to configure nginx

a) Explore or edit nginx server blocks

cd /etc/nginx/sites-available/

– You can edit the default config or create your own

– I am going to use my config file for explanation


server {
listen 80;
server_name appname.com www.appname.com;

#root used for setting root directory would contain the location of your primary application 
#which should be served upon entering above domain

root /var/lib/tomcat7/webapps;
location / {

proxy_set_header X-Forwarded-Host $host;

proxy_set_header X-Forwarded-Server $host;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_pass http://127.0.0.1:8080/;

}

#use location directive to redirect the user to wordpress if he enters appname.com/wordpress(
#in my case).Do make sure that the name of the wordpress folder matches the location provided #in location directive that is /wordpress

location /wordpress{

root /var/www;
#root would contain the location of the folder in which wordpress folder is present, 
#if the name of folder doesn't match the uri postfix /wordpress then use alias instead of root.
# for example for location /blog ,use alias /var/www/wordpress instead of root
index index.php index.html index.htm;

#index directive tests for the existence of index files according to its parameters

try_files $uri $uri/ /index.php;

#try_files tell ngingx to look for a file with the exact name given first
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
# same listen value that you set /etc/php5/fpm/pool.d/www.conf

fastcgi_index index.php;
include fastcgi_params;
}
}
}

5) Restart nginx using
-sudo service nginx restart

6) Test by enterting domain name as yourapp.com/wordpress or any other name you followed throughout

Getting latitude and longitude using Google Place AutoComplete

What exactly is google place autocomplete?

It is a web service by Google which returns place predictions


How to use it to get latitude and longitude? 

1) Add reference to google maps api on your web page

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>

2) Create an input field with id of your choice

 <input id="location" type="text" placeholder="Google AutoComplete Search" /> 

3)Define the following function to attach google’s autocomplete event handler to your input field

</pre>
<script>
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var input = document.getElementById('location');
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
})

}
</script>

4) getPlace() method would return value with many details

You can view the value returned by using stringify so that you can manipulate it easily according to your need

JSON.stringify() method converts a JavaScript value to a JSON string

example JSON.stringify(place)

5) To fetch latitude and longitude, just call following methods

var latitude=place.geometry.location.lat()

var longitude=place.geometry.location.lng()