Wednesday, December 14, 2011

CKEditor plugin + grails submitTorRemote == fail

so people in my office talked to me now a couple of times that they like to have a formating option for text in the comment field.

So my first thought was to use the mighty ckeditor and there is a grail plugin already around. SO we should be done with this in 5 minutes...

Wrong it took a bit longer, since my form kept refusing to save my content and always reported the original content instead.

After quite a bit of googleling and the mandatory
I'm pissed about grails beer, this time it was a nice Aventinius

I found a solution to make it work.

Basically if you want to use CKEditor with JQuery you need to update it fields before (the plugin should really handle this! Do you hear me? I mean I fixed to many plugins by now...)




<g:form name="createNewComment" id="createNewComment" controller="comment">


<ckeditor:editor height="300px" width="80%" name="text ">

test
</ckeditor:editor>

<g:hiddenField name="id" value="${id}"/>
<g:hiddenField name="type" value="${type}"/>
<g:hiddenField name="destination" value="${destination}"/>


<g:javascript>
function CKupdate() {
for (instance in CKEDITOR.instances)
CKEDITOR.instances[instance].updateElement();
return true;
}
</g:javascript>

<g:submitToRemote before="CKupdate();" class="save" action="saveAjax" update="${destination}" value="save comment"/>


</g:form>




And this is all, now before we press the button, we always call the method to update the editor and everybody is happy...

Friday, December 9, 2011

jQuery + grails and my missing buttons...

currently I'm switching miniX over to use jQueryUi style buttons, since this makes life so much easier to maintain them.

Except during my event processing my buttons keep disappearing, which is rater annoying, to say at least.

Couple of hours later I finally found a crude but working solution. I just create a simple event handler, which re renders all by buttons...


$(document).ajaxComplete(function() {
$("input:submit, a.button, input:button, div.qq-upload-button").button()
});

$(document).ready(function() {
$("input:submit, a.button, input:button, div.qq-upload-button").button()
});

Wednesday, November 30, 2011

scala and instanceOf -

I'm for some reason a fan of instanceOf in java and just love to be able to check at runtime of what kind a class is and do some action depending on this outcome.

But sometimes it's a bit tedios. For example



Object a = new String("tada");
Object result = null;

if(a instanceOf Number){
result = "its a number";
}
else if(a instanceOf String){
result = "its a string";
}


System.out.println(result);



ok it's a silly example, now the pretty scala approach using match



var a:Any = "tada..."

val result = a match {
case n:Number => "it's a number"
case s:String => "it's a string"
}
println(result)



oh so pretty and easy to read.

Monday, November 28, 2011

casting and scala

since a couple of month's I work more and more with scala and really start to like this language. But some of the concepts are really confusing and make me wounder if this really is necceasary.

A prime example would be the whole casting of variables.

In java you simple do:


String value = (String)object;


now in scala


val value:String = object.asInstanceOf[String]


now I admit it looks very clean, but sure took a while to find this one little details.

Otherwise it's always better to use matchers.

Friday, November 4, 2011

rocks linux - virtual hosts with apache

currently I have a cluster setup in the office with about 5 nodes and a bit over 50 cpus, so this morning I decided to rebuild some of the nodes, since I needed to make some changes to the cluster.

20 minutes into this procedure, I keep getting odd error messages, like file 'update.img' not found and so.

So while backtracking the latest changes I did to the server. I realized that I setup 20 virtual hosts in the apache configuration, which ended up screwing with the kickstart configuration. It turns out that the order of the virtual host seems to quite important and that the kickstart configuration always needs to be first, and than you have to define the other virtual hosts.

Example of a virtual host configuration, which allows the kickstart configuration to work,


vim /etc/httpd/conf.d/rocks.conf


actual file:


<IfModule mod_mime.c>
AddHandler cgi-script .cgi
</IfModule>

UseCanonicalName Off


DirectoryIndex index.cgi

<Directory "/var/www/html">
Options FollowSymLinks Indexes ExecCGI
AllowOverride None
Order allow,deny
Allow from all
</Directory>

<Directory "/var/www/html/proc">
Options FollowSymLinks Indexes ExecCGI
AllowOverride None
Order deny,allow
Allow from 10.1.0.0/255.255.0.0
Allow from 127.0.0.1
Deny from all
</Directory>

<Directory "/var/www/html/pxelinux">
Options FollowSymLinks Indexes ExecCGI
AllowOverride None
Order deny,allow
Allow from 10.1.0.0/255.255.0.0
Allow from 127.0.0.1
Deny from all
</Directory>

<VirtualHost *:80>
ServerName kickstart.host.com
DocumentRoot "/var/www/html"
</VirtualHost>

<VirtualHost *:80>
ServerName virtual.host.com
DocumentRoot "/var/www/cts/html"
</VirtualHost>

Wednesday, November 2, 2011

grails quartz plugin - don't repeat jobs

well it might be obvious, but sometimes you just want to execute a simple job once during the startup and than let them be.

For an example I needed this to synchronize a database and run statistics over it. So the simples trigger I could come up with, was


static triggers = {
simple name: 'synchronize', startDelay: 60000, repeatCount: 0
}


An alternative way could had been todo schedule the job during the startup phase


SynchronizeExperimentJob.triggerNow([experimentId: id, database: database])


this line should be put into your bootstrapping file.

Personally I feel the trigger is more elegant.

Tuesday, November 1, 2011

kinesis avantage pro - day one

so the keyboard got finally delivered and now Im in the progress of learning typing again and to say i'm inefficient is quite and understatement. I mean the layout is so weird and my hands feel way to big for this keyboard and i'm constantly hunting for the letters.

most frustrating things so far:

- only one space button instead of two
- i'm using muscles in my hand I never used before, I'm actually getting sore from typing after just a minute or two
- the enter button is in the most awkward spot ever, why cant the keyboard be a bit wider, so that there can be a dedicated enter button to be hit with my right pinky and a dedicated backspace button for the left pinky
- the right side of the keyboard if way more confusing than the left side
- the buttons are just a touch to large
- no dedicated number block, only a funky food pedal to switch some buttons around

Thursday, October 27, 2011

rocks 5.4 cluster - installing subversion

sometimes the most trivial things turn out to be rather interessting.

For example my latest drama with rocks was that I just needed subversion, to convert one of my BinBase images to a development image for BinBase.

Little did I know, that in the rocks 5.4 version, the installer fails to provide you with the base repository. Quality control anyone?

Anyway, to get your yum to work, as exspected. Just open your


/etc/yum.conf


file and add the following section



[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os



at the end of the file and than you can install subversion like always using:



yum -y install subversion

Wednesday, October 26, 2011

google is weird...

ok I love the autocomplete function in google, but sometimes it just results in to odd of search recommendations...

example:


The fun part is that robin and I were actually researching for smurf costumes (it's bring your smurf to school day on monday...), but that the first suggestion on 'do sm...'

do smurfs have tails

I really did not see that comming

Friday, October 21, 2011

grouping dates in postgres using date_trunc

well recently I started to write some statistics functions for my miniX application and so I was woundering, how can you easily execute queries like:

give me the count of object for the last 24h grouped by hour

which should be rather simple, if you know about the functions 'date_trunc' in postgres.

So 5 minutes later some sql appeared...


"select max(object_count) as object,date_trunc('hour',created_at) as date from bbstatistic_snapshot where object_name = ? and created_at between ? and ? group by date_trunc('hour',created_at) order by date_trunc('hour',created_at)"


which works rather well and get's the job done, but the speed is a touch slow.

Results should look like:


object | date
--------+---------------------
1742 | 2011-10-13 15:00:00
1742 | 2011-10-13 16:00:00
1742 | 2011-10-13 17:00:00
1742 | 2011-10-13 18:00:00
2102 | 2011-10-13 19:00:00
2102 | 2011-10-13 20:00:00
2057 | 2011-10-13 21:00:00
1899 | 2011-10-13 22:00:00
1803 | 2011-10-13 23:00:00
1742 | 2011-10-14 00:00:00
1742 | 2011-10-14 01:00:00
1742 | 2011-10-14 02:00:00
1742 | 2011-10-14 03:00:00
1742 | 2011-10-14 04:00:00
1742 | 2011-10-14 05:00:00
1742 | 2011-10-14 06:00:00

Wednesday, October 19, 2011

reinstalling a compute node in rocks

this is actually a no brainer, but since I barely ever have todo it, here is the procedure:


  1. log onto compute node
  2. execute 
    /boot/kickstart/cluster-kickstart-pxe
  3. wait for the install to finish
that's it

Tuesday, October 11, 2011

cron - useful triggers

just a nice list of commonly used cron triggers I keep forgetting.

Cron Expression to fire the trigger every five minutes:
0 0/5 * * * ?
(e.g. 3:00:00, 3:05:00, 3:10:00

Cron Expression to fire the trigger every hour:
0 0 * * * ?

Cron Expression to fire the trigger every two Hours:
0 0 0/2 * * ?

Cron expression to fire the trigger every Four Hours:
0 0 0/4 * * ?

Cron Expression to fire the trigger every 10 Minutes 20 Seconds:
20 0/10 * * * ?
(e.g. 10:00:20, 10:10:20, 10:20:20)

Every half an hour between 1 AM to 7 AM on 20th of Every Month
0 0/30 1-7 5, 20 * ?
(e.g. 2010-07-20 1:00:00, 2010-07-20 1:30:00m 2010-07-20 2:00:00)

Cron Expression to fire the trigger on the 25th Minute from 1 AM to 5 PM on every Monday and Wednesday
0 25 1-5 ? * MON,WED

Cron Expression to fire the trigger at Noon every day
0 0 12 * * ?

Cron Expression to fire the trigger at Noon every day only in 2010
0 0 12 * * 2010

Cron Expression to fire the trigger Every 10 minutes between 9 AM to 5 PM (until 5:50) Every Day
0 0/10 9, 17 * * ?

Cron Expression to fire the trigger at 2:30 PM on the last Saturday of every month.
0 30 14 ? * 7L

Cron Expression to fire the trigger at 7:10 AM every Monday, Tuesday, Wednesday, Thursday and Friday
0 10 7 ? * MON-FRI

Cron Expression to fire the trigger at 2:10 PM and at 2:40 PM every Sunday in the month of July.
0 10,40 14 ? 7 SUN


source: cron-expression-to-fire-the-trigger-every-hour

Wednesday, August 10, 2011

groovy - a quick way to copy a list of files to the local directory

don't we love these tasks? We get a list of files to look at and they are in a directory with thousands of other files and now we need to copy them one, by one, by one and there is no clear patter, which could ease the pain of doing so.

But like always there is a simple groovy way todo this in a quicker fashion.


def values = [
1333020,
1332872,
1332428,
1332280,
1331984,
1331836,
1331688,
1331540
]

values.each{def value ->
new File("${value}.xml") << new File("/Users/****/Documents/metadata/${value}.xml").text
}


this does simplify your life once in a while to copy a quick list of text files to a different folder.

Tuesday, August 9, 2011

remote ssh forwarding

for some reason I always forget the syntax to forward a port on my server to my local system to work remotely from home on some of my webapps.

Now to not forget it again, I shall write it down on my blog, so I can just look at it...


ssh -L port:remoteServer:port remoteServer


now this let's me access the 'port' on my 'remoteServer' on my local system and work on the webapp. Now I just have to rewrite all the absolute paths to relative paths, so that I can find my css stylesheets too...

Monday, August 8, 2011

grails + jquery + checkboxes

sometimes forms based on checkboxes can be rather annoying. An example would be that this is the return of a standard html checkbox,

html defined checkboxes:

<g:checkBox name="compare" id="1"/>
<g:checkBox name="compare" id="2"/>
<g:checkBox name="compare" id="3"/>


result of the send parameters to the server:



def compareBins = {
println params
}

out:

compare:[on, on, on]


now this is rather useless, we rather would see the id of the checkbox in the result. So let's call jQuery to the rescue and see how it can save out day!



jQuery(document).ready(function() {
$('input:checkbox').each(
function() {
$(this).click(function() {

if (this.checked) {
var value = $(this).attr('id');
$(this).val(value);
}
});
}
);
});



and promptly we have the following result if all 3 boxes are selected


compare:[1,2,3]


or if 1 and 3 are selected


compare:[1,3]


so we can actually tell, which elements where checked instead of getting just 'on'

Thursday, August 4, 2011

Arduino + Ethernet Shield + Temperature 2

After monitoring the thermometer for a couple of hours, it turned out the temperature sensor is a bit off. About 2.5 degrees.
At least compared to me being cold and a good old HG thermometer.

Now this meant we need some improvement in our little thermometer or better, let's find a way to calibrate it.

So looking around in the tool box I quickly discovered a potentiometer and some more cables and thought, we can wire this to another pin and scale it to +/- 5 degree celsius and apply this correction.

This is how it roughly looks now:


And the new code to apply the correction settings is here


#include <SPI.h>
#include <Ethernet.h>


byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1, 2 };

Server server(80);

float coreVoltage = 5.0;
float correctionScale = 10; //in degree celsius +/- half scale

void setup()
{
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
}

void loop()
{
// listen for incoming clients
Client client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: application/json");
client.println();

// output the value of each analog input pin


//read twice to improve precission
float voltageSensor = analogRead(0);
voltageSensor = analogRead(0) * coreVoltage;

//get temperature of the potentio meter
float voltagePotentioMeter = analogRead(1);
voltagePotentioMeter = analogRead(1)*coreVoltage/1000;

float debugVotlage = voltagePotentioMeter;

//scale it to +/- 1/2 coreVoltage
voltagePotentioMeter = voltagePotentioMeter - (coreVoltage/2);

//calculate the correction value in celsius, based on our scale
float correctionValue = voltagePotentioMeter * correctionScale / coreVoltage ;

voltageSensor /= 1024.0;

//temperature calculation
float temperatureC = (voltageSensor - 0.5) * 100 + correctionValue; //converting from 10 mv per degree wit 500 mV offset
float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;


client.print("sensor {");

client.print("temperature_voltage:");
client.print(voltageSensor);
client.print(",");


client.print("temperature_celsius:");


client.print(temperatureC);
client.print(",");

client.print("temperature_fahrenheit:");

client.print(temperatureF);
client.print(",");

client.print("temperature_correction:");

client.print(correctionValue);
client.print(",");

client.print("voltage_potentiometer:");
client.print(debugVotlage);
client.print("}");

break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}



Also since we want to keep track of the correction values, we updated the expected json string a bit to reflect the changes in our implementation.


sensor {temperature_voltage:0.75,temperature_celsius:21.98,temperature_fahrenheit:71.56,temperature_correction:-3.22,voltage_potentiometer:0.89}


I have to say, I'm really start to enjoy playing with this little thing. The next step should be have the transmission of several sensors done wirelessly over XBees and to send them to one central location...

Ardunio + Ethernet shield

After I received the ethernet shield, my first task was it to figure out how to monitor the temperature in my office over the network and possible in a way, which allows me to store this result in a database.

So this got me thinking, JSON is the way togo.

  • easy to create
  • easy to read
  • possible to be understood without an interpreter
  • very lightweight
  • everybody uses it
So let's see how the code would look for the arduino


#include <spi.h>
#include <ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1, 2 };

Server server(80);

void setup()
{
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
}

void loop()
{
// listen for incoming clients
Client client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: application/json");
client.println();

// output the value of each analog input pin


//read twice to improve precission
float voltage = analogRead(0) * 5.0;
voltage = analogRead(0) * 5.0;

voltage /= 1024.0;

float temperatureC = (voltage - 0.5) * 100 ; //converting from 10 mv per degree wit 500 mV offset
float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;

client.print("sensor {");

client.print("temperature_voltage:");
client.print(voltage);
client.print(",");


client.print("temperature_celsius:");


client.print(temperatureC);
client.print(",");

client.print("temperature_fahrenheit:");

client.print(temperatureF);
client.print("}");


break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}


now this was rather simple and results in the following json string on port 80 of the arduino address


sensor {temperature_voltage:0.74,temperature_celsius:24.22,temperature_fahrenheit:75.59}


Now back to my actual project, trying to monitor the PH value and ammonia value with an arduino and adjust the ph, if needed...

Tuesday, August 2, 2011

MedPlan

Over the last couple of days I was thinking about creating a small grails to show the speed of development with grails. The goal was to create an application in less than 24h, which is able to track your medications and at the same time has some important features.

The original idea came from spending the last 5 days with my wife's sick sister and see how difficult and confusing it was to track all her different medications. Specially since there were 3 people involved doing this and nobody really know, which medications did she already receive.

What does the user want:

  • easily enter a new prescription
  • see which medications have been taken
  • show when to take a medication
  • show the medication's in form of a calendar

What did I want as a developer:
  • easy to use
  • multi user access
  • ajax driven/jquery
  • calendar interface
  • auto complete
  • multi platform support (ipad/windows/linux/osx)
  • able to run without a tomcat installation
  • don't look like a standard grails scaffolding application
  • use as few mouse clicks as possible
how does it look after 16h of work?

weekly overview

prescription overview

adding a prescription

What is missing?

I think at this point in time the application does what it's supposed todo, but some nice features would be:

  • iPad support as a native application
  • internationalization
  • share your prescription plan with another user
  • send out an email, 30 minutes before a medication has to be used
  • soap/rest based access 
Where can I get it?

You can download the application here

Monday, July 25, 2011

grails - export plugin, at dynamically more attributes

What is this about?

currently I'm writing on a little tech study application, called times. Which can be accessed here

This application is a very simplistic timetracker, but allows me to play with some api's I normally don't use or to simply test some grails functions.

Right now I had a simple idea.

I want to export all my data, using the grails export plugin, without cluttering my database model with dozens of attributes, which will never be queried. I also did not want to create pojo's, just for the export. Instead I decided to play a bit with the EMC MetaClass again and see if, we can do this on the fly.

Example:



def exports = []

def fields = ["name","organization","project","beginDate","endDate","timeSpend"]
def labels = ["name":"Name","organization":"Organization","project":"Project","beginDate":"Start","endDate":"Finished","timeSpend":"Durations (s)"]
Task.list().each {Task t ->
if (t.endDate != null) {
t.metaClass.timeSpend = (t.endDate.time - t.beginDate.time)/1000

exports.add(t)
}
}
exportService.export(params.format, response.outputStream, exports,fields,labels, [:], [:])


this registers the attribute 'timeSpend' to the lifespan of the Task instance 't'. Which is only be required during the export.

The important line is



t.metaClass.timeSpend = (t.endDate.time - t.beginDate.time)/1000



Short, it can simplify your life a bit and reduces the need of introducing a pojo, just to export data or to permanently add this object to your database. Specially since it's a calculated value and can be regenerated on the fly.

Monday, July 18, 2011

openCl - not recognizing GPU, during remote logins

in the last couple of days I had some issues with my Ubuntu/Ati GPU based calculation units. They refused to execute any calculations, whenever I tried to use SSH to run them.

So a bit of googleling later I found the following informations in a hidden pdf:



a. Add the following lines at the end of /etc/gdm/Init/Default,
before the exit 0, to modify the security settings, allowing remote
sessions to access the X server and ensuring that remote sessions have
access to the necessary device files when communicating with the GPU:
xhost +
chmod uog+rw /dev/ati/card*
b. If you normally use bash, add the following line to the end of
/etc/bashrc file to ensure remote sessions know which X server to
access.
case $DISPLAY in ’’) export DISPLAY=:0;; *) ;; esac
NOTE: ’ ’ are two single quotes, not a single double-quot



Taken from:

http://developer.amd.com/sdks/AMDAPPSDK/assets/App_Note-Running_AMD_APP_Apps_Remotely.pdf

Now everything works fine and all is dandy again.

Sunday, July 10, 2011

Groovy HTTP Builder- fetching JSON data over post and supply parameters

Right now I'm playing around with the MtGox api to issue online transactions to buy and sell bitcoins. Yes I'm still obsessed with these and don't think this is going to change anytime soon, since It's starting to actually generate money.

But the big pain right now is that you have togo to so many different websites todo a simple transaction and I really want to have this all combined in one single tool.

So the api exspects from you to be queried over post arguments and the first thing which came to my mind was to use the fantastic HttpBuilder in groovy.

so let's define a simple method to simplify life a bit for us


private executeQuery(Map parameter, String path) {

def http = new HTTPBuilder("https://mtgox.com/")

def result = ""
http.post(body: parameter, path: path, requestContentType: URLENC) { resp, json ->

if (resp.statusLine.statusCode == 200) {
result = json
}
else {
result = false
}

}

return result


and a second method to actually call this


def getCurrentBalance() {

if (MtGoxAccessHandler.isConfigured()) {
def values = executeQuery([

name: MtGoxAccessHandler.getUserName(),
pass: MtGoxAccessHandler.getPassword()],
"/code/getFunds.php")

return [usd: values.usds, coins: values.btcs]
}
else {
return false
}
}



The class MtGoxAccessHandler is just a little helper, which stores the username and password and allows me to simplify the code a bit and easy testing.

This post is also related to the google code project DeepBitView

Monday, July 4, 2011

JSON and SSL in groovy, how to ignore certificates

In the last couple of days I became more and more interested in bitmining and the first thing I noticed was the utter lack of integrated tools and hence statistics I would like to associated with my miners.

This resulted in me creating a tiny grails application to synchronzie my deepbit statistics with the current market data from mtgox to calculate at which point it becomes pointless to mine these thing. I basically hope that this pays for the 700$ for my 2x6950 radeons and associated cooling the 100+F heat we have here in California.

Now originally you could assume that this is rather straightforward. After all you got json data, which just need to be parsed.


Map jsonArray = JSON.parse(new InputStreamReader(new URL("https://mtgox.com/code/data/ticker.php").openStream()))

println jsonArray



but sadly the java ssl security manager does not agree here with us and tosses a fit..



javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1649)



Now java is kinda smart, if want's to force you install a security certificate from the server you access and authorize yourself. But sometimes you don't want this. In this case it's overkill, since we are having a readonly transaction.

So what has to be done?

you need to create your own security manager implementation. Which basically is a 3 step procedure


  1. implement an interface


    class TrustManager implements X509TrustManager {

    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    return null;
    }

    public void checkClientTrusted(
    java.security.cert.X509Certificate[] certs, String authType) {
    }

    public void checkServerTrusted(
    java.security.cert.X509Certificate[] certs, String authType) {
    }

    }




  2. register the interface and update the context configuration

    TrustManager[] trustAllCerts = new TrustManager[1]

    trustAllCerts[0] = new TrustManager()
    try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }

  3. and continue like always with your json script

    Map jsonArray = JSON.parse(new InputStreamReader(new URL("https://mtgox.com/code/data/ticker.php").openStream()))


and the result should be now the current ticker for the USD to BitCoin exchange rate.


    {"ticker":{"high":15.4989,"low":13.31415,"avg":14.726503862,"vol":42862,"last":13.31415,"buy":13.331,"sell":13.35999}}



    Wednesday, June 22, 2011

    groovy - parsing reading builder content from an external file

    we all know that groovy builders are great and fun and can make your life so much easier.

    For example if you want to create a simple xml file in your groovy script you can just do the following


    def writer = new StringWriter()
    def xml = new MarkupBuilder(writer)
    xml.records() {
    car(name:'HSV Maloo', make:'Holden', year:2006) {
    country('Australia')
    record(type:'speed', 'Production Pickup Truck with speed of 271kph')
    }
    car(name:'P50', make:'Peel', year:1962) {
    country('Isle of Man')
    record(type:'size', 'Smallest Street-Legal Car at 99cm wide and 59 kg in weight')
    }
    car(name:'Royale', make:'Bugatti', year:1931) {
    country('France')
    record(type:'price', 'Most Valuable Car at $15 million')
    }
    }



    looks easy and is easy. But now you come to the point where you think. Mhm it would be nice, if I could just read the builder code from an external file and generate the xml on the fly using this. For example you have to generate an xml configuration file and rather simplify this process using groovy and this has to be done more than once...

    After a couple of hours googleing the best solution I came up with, was to provide your own binding to the builder, which simplified things quite a bit.



    class XmlBinding extends Binding{
    def builder


    Object getVariable(String name) {
    return { Object... args -> builder.invokeMethod(name,args) }
    }
    }


    let's assume we like to read the following builder code, defined in a file named 'test.groovy'



    config{
    bin{
    allow(minimumClassSize:1)
    }
    }



    which all you need to do, now you could for example have a main method somewhere containing this:


    def groovyScriptContent = new File("test.groovy").text
    def writer = new StringWriter()
    def xml = new MarkupBuilder(writer)
    def binding = new XmlBinding()
    binding.builder = xml

    def dslScript = new GroovyShell().parse(groovyScriptContent)
    dslScript.binding = binding
    dslScript.run()

    println writer.toString()


    and as a result it generates the following xml document


    <config>
    <bin>
    <allow minimumClassSize='1' />
    </bin>
    </config>

    Thursday, March 17, 2011

    vmware fusion - changing nat address range on the host

    recently I was installing a lot of vmware virtual machines on 3 different macs to test some binbase issues and it turns out the vmware fusion assigns a random iprange on every box.

    Rather annoying if you virtual machine needs a fixed IP, thank you rocks guys for this...

    Anyway to change the vmnet8 interface configuration you need to modify the following files:





    sudo vim /Library/Application\ Support/VMware\ Fusion/vmnet8/nat.conf
    sudo vim /Library/Application\ Support/VMware\ Fusion/vnetworking
    sudo vim /Library/Application\ Support/VMware\ Fusion/vmnet8/dhcpd.conf



    and update the default range with you wished range.

    afterwards execute:


    ./boot.sh --restart


    in the directory:


    /Library/Application\ Support/VMware\ Fusion/


    and you should be good togo!

    More about this can be found at http://blog.mclaughlinsoftware.com/2010/03/01/vmware-fusion-nat/

    Thursday, February 10, 2011

    locking an application to a space in OSX Snowleopard

    since i have several monitors connected to my max I like to have some apps always in one window on the same screen and not have to keep searching for it.

    Most importantly I always want to keep my browser and terminal on the right screen and on the left screen I have several different IDE's.

    Like...

    • eclipse in space 1
    • intellij in space 2
    • etc
    solution?
    1. Go to your System Preferences and enable Spaces.
    2. Now, in the box in the middle of the Spaces settings that says Application Assignments, add an application using the + button.
    3. Just navigate to the chosen program in your Applications folder.
    4. Now the trick here is in the Space column to choose Every Space from the picklist.
    5. rinse and repeat for all applications