RSS
 

Cloud Foundry + Grails = lightning fast deployment

07 Jan

The purpose of this article is to show how quickly and easily deploy Grails application to Cloud Foundry platform.

What is Cloud Foundry?

From cloudfoundry.com:

Cloud Foundry is an open platform as a service, providing a choice of clouds, developer frameworks and application services. Initiated by VMware, with broad industry support, Cloud Foundry makes it faster and easier to build, test, deploy and scale applications. It is an open source project and is available through a variety of private cloud distributions and public cloud instances, including CloudFoundry.com.

Prerequisites

To make a use of this article you’ll need to have Grails framework installed.

To check if Grails is properly installed, use

grails -version

You should see something like

Grails version: 2.0.0

If you haven’t, just follow the Grails Getting Started Guide.

Let’s the fun begin

The whole process is extraordinary simple! Just do the following steps.

  1. Create Grails app

    grails create-app cloud_foundry_example
    
  2. Change your working directory to a new application directory

    cd cloud_foundry_example
    
  3. Install Cloud Foundry plug-in

    grails install-plugin cloud-foundry
    
  4. Configure your Cloud Foundry credentials

    You can configure it in both grails-app/conf/Config.groovy and in ~/.grails/settings.groovy. Since the file will contain sensitive, it’s not recommended to put it in source control. That’s why the second option is considered the best practice.

    So, configure your credentials using

    grails.plugin.cloudfoundry.username = "<your_username>"
    grails.plugin.cloudfoundry.password = "<pass>"
    
  5. Test your config

    grails cf-info
    

    The output should look like

    VMware's Cloud Application Platform
    For support visit http://support.cloudfoundry.com
    Target:   http://api.cloudfoundry.com (v0.999)
    
    User:     <your_username>
    Usage:    Memory   (0B of 2.0G total)
              Services (0 of 16 total)
              Apps     (0 of 20 total)
    
  6. Deploy your app!

    grails prod cf-push
    

    You’ll be asked about the application URL, and also about some persistence services (in the time of writing: MySQL and PostgreSQL). I advise to accept default address and chose one of these services.

    If you want to re-deploy after some changes, just do

    grails prod cf-update
    

That’s it!

The app is deployed and ready to work. A proof? PartyPlanner app.

In next part I’ll describe how to configure different services in Cloud Foundry.

 
2 Comments

Posted in Grails

 

Mastering Git by Matthew McCullough and Tim Berglund

05 Mar

Mastering Git by Matthew McCullough and Tim Berglund Video cover

On the beginning, I just want to say one thing – McCullough and Berglund on Mastering Git is a perfect way to learn Git! The only requirement is an ability to learn in a classroom-type environment. An impression of class or conference is maximized by the fact that “students” are asking questions. If you’re able to learn from a lecture, keep reading!

This video provide you with step-by-step instructions on how to efficiently use Git in a production environment. You’ll begin from the very beginning: installing and configuring Git on different platforms.

Then you’ll go to basics like managing repositories, three-stage approach, committing, creating local branches and tracking the remote ones and so on.

What I especially like about this training is the fact that it also covers more sophisticated topics. You’ll learn what DAG is and how this structure influences a whole Git. You’ll become a best friend of tags (both light- and heavyweight) and know how to use rebasing, amend, stashing and others. I’ve to mention that it’s quite easy to get lost during these topics discussion, but you can always rewind the video and repeat a complex part.

A few words about technical details. The whole training is recorded in high-resolution, so it was a pleasure to watch it. The sound was also very high-quality. The only things missing are subtitles. It’d be a great help for foreigners and the disabled.

The verdict is simple. I would recommend this video to a friend.

O’Reilly Product Page: Mastering Git by Matthew McCullough and Tim Berglund

 

2010 summary and 2011 resolutions

31 Dec

I’ve never done summary of the past year before. As well as I’ve never make huge resolutions for the upcoming year. But, come on, this year was so great it deserve this! We often forget about our past successes so I think that just thinking about them is a great way to start the New Year with good attitude. On the other hand, the next year resolutions list can be a guide for what to do in every single day to get closer to our aims. And, after all, I’ve never got a blog to post the summary ;)

So, first things first. This year was good, very good. What I’ve done?

  1. I’ve graduated from Polish-Japanese Institue of Information Technology with honours degree in Computer Science.
  2. I’ve found a new, great job that I really enjoy. It helps in my skills development and, what is the most important, I do what I love to do!
  3. I’ve learned quite many new technologies and programming languages:
    • Android SDK. The result is visible in Android Market and it’s called AutoResponder ;)
    • Python / Django
    • Objective C / iOS SDK
    • Groovy / Grails
  4. I’ve been on my first Java conference, GeeCON in Poznan.

What do I plan to do in 2011?

  1. First of all, as usual I want to improve my development/programming skills, especially in iOS, Android and Python. I also want to polish my “soft” development abilities. How to do that? More books, conferences, and, first of all, practice – both in work and in open-source projects.
  2. I want to learn Scala and Lift framework.
  3. There are other languages than programming ones, aren’t there? ;) I want to polish my English skills. This blog is one of the steps toward it. Moreover, I plan to start the new course on the beginning of the year.
  4. There is also one huge project I plan to start in 2011, but for now I can’t say much more.

That’s all for now. One year is quite a lot of time so I will probably add more items to the above list, if I only have enough time.

Happy New Year, Everone! :)

 
1 Comment

Posted in Personal

 

How to create UIPickerView with toolbar above it in iOS

06 Dec

A few days ago, I had to implement a UIPickerView based select list with toolbar above it. The toolbar had to have a button to close the picker. The whole solution had to be very similar to the one used in a mobile version of Safari browser. How to do that?

The clue of the problem is contained in just two properties of UIResponder class: inputView and inputAccessoryView. The first one contains a view which will be displayed if its owner will become a first responder. For example, for UITextFields it’s a keyboard by default. The second one in turn, represents a view which will be displayed before (ie. above) the view pointed by inputView property.

So now it should be quite easy:

UIResponder *firstResponder; // use your future first responder

UIPickerView *pickerView = [[UIPickerView alloc] init];
pickerView.showsSelectionIndicator = YES;

firstResponder.inputView = pickerView;
[pickerView release];

UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
toolbar.barStyle = UIBarStyleBlackTranslucent;

firstResponder.inputAccessoryView = toolbar;
[toolbar release];

Unfortunately, it isn’t. Both inputView and inputAccessoryView are readonly properties, so we’ve to redeclare them in a subclass:

@property (readwrite, retain) UIView *inputView;
@property (readwrite, retain) UIView *inputAccessoryView;

What is the best, we aren’t limited to use this feature on UITextFields only. Because of fact that UIView inherits from UIResponder, we can attach this behaviour to all views, for example to a button or a table cell. To do that we have to override canBecomeFirstResponder method in our subclass. For example, the UIButton subclass implementation can look like this:

@implementation CustomButton //it's UIButton subclass

@synthesize inputView, inputAccessoryView;

- (BOOL) canBecomeFirstResponder {
    return YES;
}

- (void)dealloc {
	[inputView release];
	[inputAccessoryView release];
	[super dealloc];
}

@end
 

Scaling Django

06 Dec

Just quick info: very interesting presentation by Mike Malone about scalability of Django-based web applications.

 

Django and Rails and Grails comparison

08 Nov

I’ve recently found a link to an interesting presentation at zenzire.com. Its author, Jaime Buelta, speaks about differences between Django, Rails and Grails frameworks.

I know Django and Grails. Personally, I like both of them. I can’t only disagree with one argument about Grails – it’s rather poorly documented. But still, it deserves to give it a shot.

Just take a look at it.

Django and Rails and Grails, Oh my! (Jaime Buelta) from whykay on Vimeo.

 

Virtualenv + pip

02 Oct

In the Java world there was always a problem with dependencies. All the jars we had to mange by hand – quite awful. Thankfully there is a Maven project which helps us in requirements management. But what about Python? Is there any way to handle necessary libraries? Of course, there is! It is a tandem of virtualenv and pip.

Virtualenv is a tool to create isolated Python environments. I’m sure you can imagine a situation when one project needs a library in version x, while another one needs the same library but in version y. Then, you can’t install both libraries to your default site-packages directory. Another example: let’s assume that new version of Django has been released and you want to test your application with this version. It’d perfect to create independent environment for the new release, wouldn’t it? So, this is a place for virtualenv.

Pip is simply the Python packages installer. It can be called easy_install successor. Here, you can read pip and easy_install compare. From our point of view, pip has one extremely useful feature. It can save all requirements information to the text file and use it later to download necessary libraries. The example file is listed below.

Django==1.2.1
Fabric==0.9.1
PIL==1.1.7
South==0.7.2
...

OK, but how can we use it together? Here comes how. Let’s assume, we’ve virtualenv installed. Then, just do the following steps.

  1. virtualenv --no-site-packages environment_name – this command creates new environment with given name. The no-site-packages option ensures that this environment won’t inherit any libraries previously installed in your system.
  2. cd environment_name – virtualenv has created a new directory, so we’ve to go to it
  3. Now, we’ve to install all requirements into a new environment. As a bonus, virtualenv contains pip package and puts it into each environment. So, all you’ve to do is bin/pip install package_name. We need to repeat this command for each library our project depends on.
  4. It’d be useful to export all the dependencies into to the file to use it in the future. To do that just run bin/pip freeze > requirements_file.txt
  5. You can use this file to build your environment later, perhaps on another machine. It’s simple: bin/pip install -r requirements_file.txt
  6. It’s almost done. The last thing is to activate our new virtual environment. We need this to run all subsequent commands within its context. Use source bin/activate and notice that your command prompt got a prefix – an environment name. To deactivate the environment, simply write deactivate.

Of course, the possibilities of virtualenv and pip are a lot more sophisticated. For example, you can create your own bootstrap script with virtualenv to setup a whole web application. On the other hand, you can use pip to download dependencies from version control systems directly or even create your own libraries bundle to use it when you’re offline. The use case I’ve described above is just an introduction. But I hope, it is a useful one.

 

Productivity tips for programmers

05 Sep

I’ve recently started reading The Productive Programmer book. In a few first chapters, I’ve found some interesting tips for programmers. Some of them can be useful for non-programmers too.

Prefer typing than using mouse

It is quite obvious that moving hands from keyboard to mouse consumes a lot of time. How to minimize this effort?

  • Use launchers. That applications can be started by a simple keystroke. They display an input where you can enter a name of a program or document. I use Gnome-Do on my Ubuntu and it behaves extremely well. On a Windows platform you can use Launchy or Enso as well.
  • A lot of typing can be time-consuming too. Why not to simplify the process with some automation tool? For example: to start my development server in Django application, I’ve to change my directory (cd ~/django/project/webapp) and than activate the virtual environment with necessary requirements (source ~/virtual_envs/project/bin/activate). With automation tool like Autokey (Linux) or AutoHotkey (Windows) I was able to create an abbreviation like aproject to get the same result.

Clean up your desktop

How much time do you spend in your everyday work to switch through all the windows on your desktop? Have you ever look for an appropriate terminal window because you had so much of them? I had so I really appreciate the following tips.

  • Use virtual desktops. Currently, I use three of them: Main for my IDE, Manage for database and development server terminals and Docs for all documents like APIs or framework documentation. No more switching between windows, you’ve got all of them together.
  • It is important not to spend a time on searching a relevant windows. It’s especially hard to manage terminal windows because they are very similar and you’ve to read their content sequentially before you get the correct one. One way to beat that problem is to use different sets of colors for every terminal window. For example, I use green font and black background in a terminal with my development server and light yellow background in a terminal with my database client. Moreover, I try to put that windows in the same position every time I use them. Using this tips together makes finding the correct window a lot easier.

I’m curious about your programmers productivity tips. Please, share them in comments.

 

Python 3. Kompletne wprowadzenie do programowania – opinia

01 Sep

Pozycja Python 3. Kompletne wprowadzenie do programowania (oryg. Programming in Python 3: A Complete Introduction to the Python Language) ukazała się w Polsce nakładem wydawnictwa Helion. Niniejszy tekst stanowi próbę oceny tej książki.

“Python 3. Kompletne wprowadzenie do programowania” można podzielić na dwie główne części. Pierwsza stanowi wprowadzenie do podstawowych elementów języka, bez znajomości których ciężko byłoby stworzyć sensowny program w Pythonie. Druga natomiast to omówienie bardziej zaawansowanych technik wykorzystania biblioteki standardowej w sytuacjach uznanych przez autora za istotne.

Już we wstępie Mark Summerfield zaznacza, że książka stanowi cenne źródło wiedzy zarówno dla nowicjuszy, jak i specjalistów, w tym naukowców, związanych z programowaniem. Jak przekłada się wybór tak szerokiego spektrum odbiorców na ostateczny kształt tej pozycji? Cóż, moim zdaniem, nie do końca korzystnie. Z jednej strony autor stosuje skróty myślowe i zakłada pewną świadomość czytelnika, z drugiej z kolei opisuje przykłady w sposób dość rozwlekły. To niestety nie wpływa korzystnie na poziom pierwszej części. Zdarzało się wielokrotnie, że tekst tylko zaciemniał znaczenie omawianego kodu. Być może jest to jednak kwestia tłumaczenia, które to zasłużyło na własny akapit. Osobiście nie polecałbym również tej książki do nauki programowania jako takiego, w oderwaniu od konkretnej technologii czy języka. W pamięci utkwił mi zwłaszcza fragment rozdziału dotyczącego programowania zorientowanego obiektowo, w którym autor tworzy klasę Punkt, po czym jako jej podklasę wskazuje klasę Okrąg. Toż to jawne naruszenie koncepcji specjalizacji!

Na szczęście dalej jest już tylko lepiej. W części drugiej opisy faktycznie pomagają przyswoić materiał, a odwoływanie się do wiedzy czytelnika jest bardziej na miejscu. Na szczególną uwagę zasługuje w moim odczuciu rozdział dotyczący zaawansowanych możliwości Pythona. Naprawdę da się tu poczuć naturę tego języka. Pozytywnie odebrałem również część, w której opisano metody utrwalania danych. Odrębną kwestię stanowią ćwiczenia dołączone na końcu każdego rozdziału. Osoba chcąca poznać język w praktyce, a pozbawiona możliwości codziennej z nim pracy, może śmiało skorzystać ze wspomnianych zadań.

Niestety średnią ocenę całości zaniża tłumaczenie i korekta książki. Sporo w niej literówek i dziwnych, czasem wręcz wprowadzających w błąd sformułowań. Niepotrzebne tłumaczenia tekstów typowo technicznych, czy nawet kodu źródłowego to standard. Niech za przykład posłuży rozdział dotyczący programowania GUI. W kodzie programu definiowane są skróty klawiaturowe w postaci zwyczajowego Alt+wybrana litera opisu akcji powoduje jej uruchomienie. Nie byłoby w tym niczego złego, gdyby nie fakt, że tłumaczenia wspomnianego opisu burzy relację, czego tłumacz nie uwzględnia. Mam po prostu wrażenie, że osoba ta nie miała wiele wspólnego z procesem programowania.

Dla kogo jest zatem ta książka? Moim zdaniem dla przynajmniej średnio doświadczonego programisty, który chce poznać kolejną technologię, a któremu nie straszne jest przedzieranie się przez miejscami zawiły tok rozumowania autora. Jeśli spełniasz te warunki, na pewno wyniesiesz wiele dobrego z lektury tej pozycji.

 

Generic relationships in Django

24 Aug

Last week I’ve completed an interesting task within our project: building internal link-shortening system based on persisted objects, not on constant URLs. The main requirement was to get as loosely-coupled design as possible. In the perfect world the “shortenable” classes should know absolutely nothing about link-shortening mechanism. How to get such a flexibility in Django? I’ve used the ContentTypes framework with generic relations and it works pretty well!

First of all, we need to prepare the model class which will keep references to every “shortanable” object and its shortening key which will be used in URLs. The key-related part is quite easy, but what about the former requirement? How it is possible to keep a relation to an object of type we don’t even know? The answer is: ContentTypes framework. It gives us an ability to get an identifier of every class within Django-based application. So, we’ve got all we need now. Just take a look into a small code snippet to see this feature in action:

class ShorteningKey(models.Model):
    """ Contains a key for a generic object used in short link resolving """
    key = models.SlugField(unique=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

Quite neat, isn’t it? Now it is possible to get a shortening key for a given object. We’ll do that with help of the following method.

    @classmethod
    def get_shortening_key_for_instance(cls, instance):
        """ Return ShorteningKey object associated with given model object.
            May throw DoesNotExist exception """
        type = ContentType.objects.get_for_model(instance)
        return ShorteningKey.objects.get(content_type__pk=type.id, object_id=instance.id)

The last thing to do is to generate a unique key for every object. As I’ve mentioned, it was extremely important to keep “shortenable” classes as clean as possible, so hard-coding shortening key generating method within the scope of each relevant class wasn’t a good idea. Instead of this, I’ve used Signals. Now, we have to write key-generation method and associate it with post_save signal. Why do we use the post_save? Because we need persisted instance to use it within ContentTypes framework. The described function is listed below while process of attaching it to the signal will be shown later.

def generate_shortening_key(sender, **kwargs):
    """ Generates shortening key for given object """
    instance = kwargs['instance']
    new_instance_created = kwargs['created']

    if new_instance_created:
        attempt = 0
        while attempt < 100:
            try:
                shortening_key = ShorteningKey(content_object=instance, key=generate_key())
                shortening_key.save()
                break
            except DatabaseError:
                attempt += 1
        else:
            logging.warning("Cannot create link shortening for " + str(instance))

We'll also need a function which will delete unnecessary key after object deletion. It's quite simple and similar so I won't put its code here.

The whole thing is almost ready, we just need to provide a function which is responsible for retrieving shortened URL.

def get_shortened_url(instance):
    """ Returns shortened url to given instance. If there is no shortened url,
        it tries to return full url to object. If there is no one, it returns empty string.
        This function is dynamically attached to any class with link shortening enabled """
    try:
        shortening_key = ShorteningKey.get_shortening_key_for_instance(instance)
        return shortening_key.get_shortened_url()
    except ShorteningKey.DoesNotExist:
        try:
            return instance.get_absolute_url()
        except (TypeError, AttributeError):
            return ''

It will be perfect if the function would be a member of each "shortenable" class, won't it? We will attach it dynamically to each of them in the same loop which is responsible for signals attaching.

LINK_SHORTENING_ENABLED_CLASSES = (Class1,Class2,...)
for cls in LINK_SHORTENING_ENABLED_CLASSES:
    post_save.connect(generate_shortening_key, sender=cls)
    post_delete.connect(delete_shortening_key, sender=cls)
    cls.get_shortened_url = get_shortened_url

That's all! We've got fully featured link-shortening system with loosely-coupled classes. You can easily adjust this example and make it appropriate for your particular needs. For example, you can build a comment system, just like Django team did :)