Deploying Grails Application on Tomcat With External Config File

By default, Grails application will use DataSource.groovy config file to store database connection configurations for all environments. Deploying to Tomcat by using grails war command will use the “production” configuration section on that file.

This is not a problem if you use a fixed database connection informations as specified on the DataSource.groovy. But this is rarely the case. In the real situation we will need a separate config file (external) from the Grails application file structure so that we can easily modify it to suit the existing production environment.

To do this, create a new file on the grails-app/conf/ folder, for example myapp-config.properties. The file content is any configuration entry that you want to customize in the production environment, like:

dataSource.url=jdbc:mysql://localhost/mydatabase
dataSource.username=root
dataSource.password=1234

Then, add an entry in the main conf/Config.groovy file that will include the external config file above:

grails.config.locations = [
 "classpath:${appName}-config.properties",
]

That entry says that Grails will include myapp-config.properties and replace any matching configuration already defined on the DataSource.groovy. Once all set, then generate the WAR file:

grails war

This will generate myapp.war file on the target folder. Copy the WAR file to Tomcat’s webapp folder.

The external config file will reside in the classes folder of the deployed application:

webapp/myapp/WEB-INF/classes/myapp-config.properties

To modify the configuration, just edit the file, and then reload the application from Tomcat application manager web interface.

You can watch the log from Tomcat’s log file logs/catalina.out to see if there’s something goes wrong.

 

 

Posted in grails, groovy, Java | Tagged , , | Leave a comment

Groovy – Iterate All Map/List Elements

If we have a map variable like this:

def map = [
 'iPhone':'iWebOS',
 'Android':'2.3.3',
 'Nokia':'Symbian',
 'Windows':'WM8'
 ]

and wish to iterate all elements, we can use “each” closure like this:

map.each{ k, v -> println "${k}:${v}" }

to print:

'iPhone':'iWebOS',
'Android':'2.3.3',
'Nokia':'Symbian',
'Windows':'WM8'

 

Alternatively, we can use a “for” loop:

for ( e in map ) {
   println "${e.key} : ${e.value}"
}

to do the same thing.

Note that when using “for” loop, the value of e is a Map.Entry element, meaning that you can get the key from e.key and the value from e.value.

One benefit of using a “for” loop as opposed to an “each” closure is easier debugging, as you cannot hit a break point inside an each closure.

 

Posted in grails, groovy, Java | Tagged , , | Leave a comment

Grails – How to Check If Element Exists in List/Maps

Method .contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue().

For example, if we have a lists named numbers.

numbers = [234,23,456,778,23]

To check whether 23 is in the list, simply call this:

numbers.contains(23)

It will return true because 23 is in the list, otherwise it will return false.

Next, if we have a maps called phones.

phones = ["ahmad": "9940", "bani":"2344", "charlie":"5489"]

To check whether “ahmad” is a key in the maps, call:

phones.containsKey("ahmad")

And to check whether “2344″ is in the maps as someone’s phone number (the value), call:

phones.containsValue("2344")

 

 

Posted in grails, groovy, Java | Tagged , , | Leave a comment

Grails – Groovy Lists and Maps

Lists

Lists are used to store ordered collections of data. It’s like arrays in other language. For example, let’s have a list called numbers:

numbers = [100,200,300,400,500,1000]

We can access a list element using square bracket notation, where indexes start at 0, for example:

println numbers[0]

will result:

100

We can get the length of the list with the “size” method:

println myList.size()

Should print out:

6

To iterate all list elements we can use “each” method.

Maps

A map is used to store “associative arrays” or “dictionaries”. It’s an unordered collections of heterogeneous, named data. For example, let’s store phone books for some employee:

phones = ["Ahmad":"0829999000", "Zaki": 10930020, "Betty": "990020020"]

Note that each of the values stored in the map is of a different type. Ahmad is a string, Zaki is an integer, and Betty is a string again.

We can access the values in a map in two main ways:

println phones["Ahmad"]
println phones.Ahmad

Both will produce the output:

0829999000
0829999000

To add data to a map, the syntax is similar to adding values to an list. For example:

phones["Charlie"] = "820930293"

Also as an aside, you can create an empty map or an empty list with the following:

emptyMap = [:]
emptyList = []

To make sure the lists are empty, you can run the following lines:

println emptyMap.size()
println emptyList.size()

Should print a size of 0 for the List and the Map.

 

Posted in grails, groovy, Java | Tagged , , | Leave a comment

Grails – Set Default Value for a Field

Setting default value for a Grails Domain Class can be done by using defaultValue on the static mapping of the domain.

Example, setting up active field to true whenever the record is created:

class Batch {
   Boolean active
   static mapping = {
      version false
      active defaultValue: true
   }
}
Posted in Java | Tagged | Leave a comment

Script to Add All New Files to SVN

Create a new script file, example svn-add-all.sh as follows:

#!/bin/sh
svn st|grep ?|cut -d? -f2|xargs svn add

Change mode to 755 and put it into $PATH, eq /usr/local/bin

To use it, change to your project folder which is already imported into SVN repository.

Run svn-add-all.sh, all your newly created files on that directory will be added into the SVN. Then, just commit to send it to the repository.

 

Posted in SVN | Leave a comment

Basic Accounting Software Source Code

Now Available: Full PHP Source Code for Basic Accounting Software. Suitable for learning purpose, modification for further enhancement, etc.

Download the Screenshot here

Functional Features

  • Input Journal Transaction
  • Input Cash and Bank Transaction
  • General Ledger
  • Balance Sheet Report
  • Profit and Loss Report
  • COA Transaction Report
  • Print out to PDF
  • Management User
  • Management Group
  • Management Module Menu
  • Workflow Document (approval)

Technical Features

  • Yii MVC Framework PHP
  • MySQL
  • jQuery/ AJAX

 

Order Now

Contact Email : info@vitraining.com
or visit www.vitraining.com

 

Posted in Delphi | Leave a comment

Ayo Membuat MP3 Player Sederhana di Android

Ini cuma aplikasi sederhana cara memainkan MP3 di SDCARD, dengan menampilkan daftar lagu MP3 pada sebuah ListView.

Buat proyek baru dengan nama MP3Player di Eclipse. Activity utama kita bernama Mp3PlayerActivity.

Layout

Pertama-tama definisikan layout untuk menampilkan daftar lagu. Pakai saja ListView untuk menyederhanakan program. Nanti kalau sudah mahir boleh pakai list yang lebih cantik tampilannya. Jadi bikin dulu layout baru namanya daftarlagu.xml.

<?xml version=“1.0″ encoding=“utf-8″?>

<LinearLayout

xmlns:android=“http://schemas.android.com/apk/res/android”

android:orientation=“vertical”

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<ListView android:id=“@id/android:list”

android:layout_width=“fill_parent”

android:layout_height=“fill_parent”

android:layout_weight=“1″

android:drawSelectorOnTop=“false”

/>

<TextView android:id=“@id/android:empty”

android:layout_width=“fill_parent”

android:layout_height=“fill_parent”

android:text=“tidak ada lagu SD Card”

/>

</LinearLayout>

ListView yang cukup simple, yang akan menampilkan text “tidak ada lagi di SD card” ketika tidak ada items ditemukan di ListView.

Lalu bikin lagi file XML untuk menampilkan setiap file MP3 yang akan dimunculkan di ListView, kasi nama misalnya viewlagu.xml.

<?xml version=“1.0″ encoding=“utf-8″?>

<?xml version=“1.0″ encoding=“utf-8″?>

<TextView android:id=“@+id/text1″ xmlns:android=“http://schemas.android.com/apk/res/android”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”/>

Activity

Kemudian buka file MP3PlayerActivity.java yang sudah otomatis dibuat pada saat create project sebelumnya. Edit file tersebut sehingga lengkap seperti sebagai berikut:

package com.vitraining;

import java.io.File;

import java.io.FilenameFilter;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import android.app.ListActivity;

import android.media.MediaPlayer;

import android.media.MediaPlayer.OnCompletionListener;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.ArrayAdapter;

import android.widget.ListView;

public class Mp3PlayerActivity extends ListActivity {

private static final String MEDIA_PATH = new String(“/sdcard/”);

private List<String> songs = new ArrayList<String>();

private MediaPlayer mp = new MediaPlayer();

private int currentPosition = 0;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.daftarlagu);

updateDaftarLagu();

}

public void updateDaftarLagu() {

File home = new File(MEDIA_PATH);

if (home.listFiles(new Mp3Filter()).length > 0) {

for (File file : home.listFiles(new Mp3Filter())) {

songs.add(file.getName());

}

ArrayAdapter<String> songList = new ArrayAdapter<String>(this, R.layout.viewlagu, songs);

setListAdapter(songList);

}

}

@Override

protected void onListItemClick(ListView l, View v, int position, long id) {

currentPosition = position;

playSong(MEDIA_PATH + songs.get(position));

}

private void playSong(String songPath) {

try {

mp.reset();

mp.setDataSource(songPath);

mp.prepare();

mp.start();

// Setup listener so next song starts automatically

mp.setOnCompletionListener(new OnCompletionListener() {

public void onCompletion(MediaPlayer arg0) {

nextSong();

}

});

} catch (IOException e) {

Log.v(getString(R.string.app_name), e.getMessage());

}

}

private void nextSong() {

if (++currentPosition >= songs.size()) {

// Last song, just reset currentPosition

currentPosition = 0;

} else {

// Play next song

playSong(MEDIA_PATH + songs.get(currentPosition));

}

}

}

class Mp3Filter implements FilenameFilter {

public boolean accept(File dir, String name) {

return (name.endsWith(“.mp3″));

}

}

Import package-package yang diperlukan. Di Eclipse, arahkan ke class yang dibilang error, lalu pilih import <nama package>.

Lakukan proses build (Project à Build Project) agar layout dikenali disini.

Function onCreate() gunanya untuk menampilkan view daftarlagu yang sudah kita buat sebelumnya. Kemudian memanggil function updateDaftarLagu().

Function updateDaftarLagu()  gunanya untuk membaca semua file yang ada di SD Card sesuai filter yang telah didefinisikan sebelumnya (yaitu class MP3Filter). Setiap file lagu yang ditemukan, nama filenya disimpan di variable songs. Kemudian dibentuk ListAdapter yang datanya berasal dari variable songs dan layoutnya dari viewlagu yang sudah didefinisikan di atas.

Ketika item di ListView di-click maka program menjalankan function playSong().

Function playSong()  gunanya untuk memainkan file MP3. Terlebih dahulu object variable mp di reset(), kemudian di-set file data nya dengan setDataSource(), di prepare(), dan di start(). Ketika selesai memainkan suatu lagu, program menjalankan function nextSong(). Ini dilakukan pada function setOnCompleteListener().

Function nextSong()  gunanya untuk  memajukan index variable songs dan memainkan lagu pada index tersebut.

Class Mp3Filter gunanya untuk meng-accept() file hanya jika ber-extension MP3.

Membuat emulasi SD Card

Agar bias jalan seperti di device, kita perlu bikin SD Card di emulator. Masuk ke folder android-sdk/tools, dan jalankan.

./mksdcard 128M /tmp/sd.img

Selanjutnya masuk ke menu Eclipse Run à Run Configurations… Pilih nama project yaitu MP3Player.

Di Tab Target, tambahkan di bagian Additional Emulator Command Line Options: “–sdcard /tmp/sd.img”

Lalu klik Run disitu untuk menjalankan emulator.

Awalnya program menampilkan pesan “tidak ada lagu di SC Card”. Gimana cara mengisi SD Card dengan file MP3?

Masuk ke android-sdk/platform-tools, dan jalankan

Adb push <sumber> /mnt/sdcard

Misalnya

adb push /Users/akhmaddanielsembiring/Documents/etc/lagu/Gigi\ -\ 11\ Januari.mp3 /mnt/sdcard

Jalankan ulang program di emulator, hasilnya kira-kira seperti ini.

Pingin tau lebih detail tentang pemrograman Android? Koneksi ke server, web services, JSON, GPS, Mapping Google maps? Ikuti training Android di VITRAINING.

Posted in Delphi | 2 Comments

How to Import Existing Project Directory Into SVN Repository

You can import an existing project directory (with contents) into an SVn repository, and use the current location as your version controlled working copy.

Here is how to do it:

Suppose that your non-versioned project sources are in /home/user/aproject, and your repository is ready at http://server/repos.

First, create an empty directory somewhere outside of your project tree, say, /tmp/empty. Import that empty directory in your subversion repository.

cd /tmp/empty
svn import . http://server/repos/aproject

Then, go into your existing non-versioned project directory. Now checkout the repository location you created in step 1.

cd /home/user/aproject
svn checkout http://server/repos/aproject .

Do not forget the trailing dot at the previous command. This will add the .svn files to your existing project directory, but it will not do anything else, so your existing files are safe.

Next, add the directory with your files to the repository

svn add *
svn commit -m 'initial commit'

Done.

Posted in SVN | 3 Comments

Guide to installing 3rd party JARs in Maven

Often times you will have 3rd party JARs that you need to put in your local repository for use in your builds. The JARs must be placed in the local repository in the correct place in order for it to be correctly picked up by Maven. To make this easier, and less error prone, we have provide a goal in the install plug-in which should make this relatively painless.

To install a JAR in the local repository use the following command:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \ -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

 

For example, to install jbilling_api.jar (API for connecting to JBilling application), use the following command:

mvn install:install-file -Dfile=/opt/jbilling_api.jar -DgroupId=jbilling \ -DartifactId=jbilling -Dversion=2.0 -Dpackaging=jar

Then, on the project’s POM file, add the following external dependency, so that Maven will include this jar while compiling:

<dependencies>

   <dependency>
           <groupId>jbilling</groupId>
           <artifactId>jbilling</artifactId>
           <version>2.0</version>
    </dependency>

</dependencies>

Posted in Funambol, Java, jbilling | Tagged , , , | 1 Comment