Java 8 on Raspberry Pi

 Development, general, Java  Comments Off on Java 8 on Raspberry Pi
May 192013
 

This is more of a reminder to myself. But others may find it useful.

Make sure ssh is enabled on your raspberry pi and set the memory split down to 16 for the gui.

ssh into the raspberry pi


cd /tmp
wget http://download.java.net/JavaFXarm/jdk-8-ea-b36e-linux-arm-hflt-29_nov_2012.tar.gz
tar zxf jdk-8-ea-b36e-linux-arm-hflt-29_nov_2012.tar.gz
rm jdk-8-ea-b36e-linux-arm-hflt-29_nov_2012.tar.gz
sudo mv ./jdk1.8.0/ /opt/
sudo chown root:root -R /opt/jdk1.8.0/
sudo ln -s /opt/jdk1.8.0/ /opt/jdk8

Then just add it to your path.


PATH="$PATH":/opt/jdk8/bin
JAVA_HOME=/opt/jdk8

and your done. I went on and install jetty 9

 

I’ve been writing a lot of javascript lately. Lots of nodejs and also sencha touch and jquerymobile.

I ran across a very frustrating error in jquerymobile the other day when injecting a list into the dom.

From jquerymobile docs it says you should call $(‘#mylist’).listview(‘refresh’);
However when I did this I got the error jquerymobile cannot call methods on listview prior to initialization. This is a very annoying error and it seems that jquerymobile has overlooked injecting content into the dom and restyling it, as from my google searches, it appears to be a common problem.

Here is my solution:

after injecting call:

 $('#mylist').listview(); 
 $('#mylist').listview('refresh');
  

Seems simple but I thought I would share this info as it caused quite a lot of pain before discovering the solution.

Running Multiple Apps on Same port Nodejs

 Development, general, node.js  Comments Off on Running Multiple Apps on Same port Nodejs
Jan 072012
 

This is actually surprisingly simple due to great work done by nodejitsu and also by the connect team. And I have largely copied the content from the links at the bottom of the page:

So with http proxy you can use it as follows:


npm install http-proxy

-- app.js ---

var http = require('http'),
httpProxy = require('http-proxy');
//
// Create your proxy server
//
var options = {
hostnameOnly: true,
router: {
'foo.com': '127.0.0.1:8001',
'bar.com': '127.0.0.1:8002'
}
}
httpProxy.createServer(options).listen(80);

in terminal run
nohup nodemon app.js & //will keep it running

-- foo.js --

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied 8001!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(8001);

in terminal run nodemon foo.js
-- bar.js --

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied 8001!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(8002);

in terminal run nodemon bar.js

finally edit your /private/etc/hosts file and add:

127.0.0.1 foo.com
127.0.0.1 bar.com

browse to bar.com and foo.com to see that both apps are running.

more info here
nodejitsu http proxy

The vhosts from connect is also really nice:
you can see a really good example of this in action here:

vhosts example

Models and Decorators adjusting data the right way

 Development, general  Comments Off on Models and Decorators adjusting data the right way
Nov 102011
 

Carrying on from my previous article about heavy lifting models Heavy lifting models I thought I would write a little about decorators and models.

What is a decorator
Briefly a decorator is an class whose purpose it is to decorate another object adding functionality or adjusting the current functionality. This can sometimes be a good alternative to subclassing.

A quick example

abstract class PricingDecorator implements Pricing {

Pricing price;

public PricingDecorator(Pricing price) {
this.price = price;
}
}

public class DiscountPricingDecorator extends PricingDecorator {

Discount discount;

public DiscountPricingDecorator(Pricing price, Discount discount) {
super(price);
this.discount = discount;
}

@Override
public Float getPrice() {
if (discount.getType() == Discount.DISCOUNT_TYPE_PERCENTAGE) {
return price.getPrice() - (discount.getValue() / 100) * price.getPrice();
} else if (discount.getType() == Discount.DISCOUNT_TYPE_PRICE) {
return discount.getValue();
}
return price.getPrice();
}
}

public class DiscountImp implements Discount {

public int type;
public Float value;

public DiscountImp(int type, Float value) throws InvalidDiscountType {
this.checkType(type);
this.type = type;
this.value = value;
}

@Override
public int getType() {
return type;
}

private void checkType(int type) throws InvalidDiscountType {
if (type == Discount.DISCOUNT_TYPE_PERCENTAGE || type == Discount.DISCOUNT_TYPE_PRICE) {
return;
} else {
throw new InvalidDiscountType("invalid discount type");
}
}

@Override
public void setType(int type) throws InvalidDiscountType {
this.checkType(type);
this.type = type;
}

@Override
public Float getValue() {
return value;
}

@Override
public void setValue(Float value) {
this.value = value;
}

}

So some of the above code is contrived and compacted to save too much code. The above would be used to decorate a Pricing Object with a various Discounts. As shown below:


try{
Discount discount = new DiscountImp(Discount.DISCOUNT_TYPE_PERCENTAGE, new Float(10));
Pricing price = new DiscountPricingDecorator(new ProductPricing(new Float(30)), discount);
System.out.print("discounted price" + price.getPrice());
}catch(InvalidDiscountType e){
e.printStackTrace();
}

It may be tempting to subclass your Pricing Object maybe into a DiscountedPricing:
and this is also an ok solution but in scenarios as seen above, I believe a Decorator is a better way of achieving this solution as I think it is clearer what is happening but because we have stuck to interface driven design we can reuse the decorator with other Pricing implementations and Discount implementations. It also maintains the simplicity of your Pricing Model class.

 

So recently I was asked for my thoughts on model view controller MVC and where business logic should be done. While I hope I answered the question well enough, I wanted to expand on my thoughts and maybe see what others thought.

What should a model know?
Often you see models represented as bare bean or container classes filled only with properties and setters and getters. Normally these properties relate to fields in some form of database. So the model only knows about the data it contains. This is a good thing. However it is also a very powerful piece of information. In my opinion the model should have many helper methods on top of the normal setters and getters to formulate the data as cleanly as possible for a nice skinny view and controller and also allowing improved decoupling of the code. The model should never contain any html, but an example of a helper method in a java bean model might be something like:

class Person{
private String firstName;
private String secondName;

/..Setter and Getters../

//helpers
public String getFullName(){
return firstName+" "+secondName;
}
}

Another example of a helper method but with a bit more meat to it:

class Customer implements CustomerModel {
private List<ProductModel> customerProducts;

//normally would be a Hibernate hasMany mapping
public List<ProductModel> getCustomerProducts(){
if(customerProducts == null){
Mapper mapper = new ProductMapper();
customerProducts = mapper.findById(this.customerId);
}
return customerProducts;
}

public Integer productCount(){
return getCustomerProducts().size();
}

Public Integer getCustomersTotalSpend(){
List<Products> prods = getCustomerProducts();
Integer total = 0;
if(prods.isEmpty()){
return total;
}
for(ProductModel prod : prods){
total+= prod.getValue();
}
return total;
}

}

These kind of methods are clearly tightly associated with the models data and so should never be done in the controller and even less so in the view. While the examples are a little simple and contrived, I think they highlight how you should think about your models. Having the model do as much as it can, but without stepping beyond the mark of what a model should know, provides you with the opportunity to have “Skinny controllers and Views with Fat Models”. In the above example, as long as you observe programming to an interface, you can easily swap in out models if needed without needing to change the controllers or the views and although I have written this example with Java in mind it transposes languages and is just as relevant in PHP or any other kind of language.

 

If you have’t heard Mozilla identity labs has introduced a new way to login into sites called browserid. We have all become familiar with the “sign in with twitter” and “connect with Facebook” buttons on sites that enable us to have a centralised login to many of our favourite web services.

These centralised logins are very useful, but are ultimately controlled by a company. So into the breach steps Mozilla offering an openid type login service. Browserid is open source and you can choose to use mozilla as an authentication service or you can set up your own. I’m going to show you how to setup this service as a login and using Mozilla as the authenticator.

So assuming you have a login image with an Id attribute of “login” the following code should work in most modern browsers. I’m using jquery as the javascript framework.



$('document').ready(function (){

$('img.login').click(function(){
navigator.id.getVerifiedEmail(gotVerifiedEmail);
});

});
//this function is called in the above function
function gotVerifiedEmail(assertionObj){
If(assertionObj){
//Ajax to a login controller
$.ajax({
url:"/yourcontroller/youraction",
data:{assertion:assertionObj},
dataType:"json",
type:"post",
success:function(data,textStatus,jqXHR){
// do your thing
},
error:function(){
// something went wrong with ajax call
}
});
}else{
// something went wrong
}
}

So that’s the JavaScript part however we still need to verify the assertion with Mozilla. You can do this with JavaScript too. In the above code you would replace the call to your controller with
The following URL:
“https://browserid.org/verify?assertion=”+window.encodeURIComponent(assertionObj)+”&audience=”+window.encodeURIComponent(window.location.host);

In my controller class I do the following in a grails app:

def browserIdLogin ={

If(params.assertion){
def url = new URL(
"https://browserid.org/verify?assertion=${URLEncoder.encode(params.assertion)}&audience=
${URLEncoder.encode(request.getHeader('HOST'))}");

def jsonResponse= JSON.parse(url.text)

Println jsonResponse
}

}

// this will output something like [audience:localhost:8080, issuer:browserid.org:443, email:[email protected], status:okay, valid-until:1310908947530]

So you now you are dealing with an authentic user with authenic email address. Now you can do as you please. if this user already has an account you can load up their account details and set the session parameters etc or if they have no account you can send them to complete an account creation (if you need more details than the email address). After they complete this they can then sign in without needing to remember a password etc.

In php you could use the CURL library or open a socket etc or you could even just use


email;
?>

Anyway hope this is helpful. There is plenty of info on browserid and they also have example code.

© 2012 Craig Brookes Suffusion theme by Sayontan Sinha