CoralCode Web programming snippets


Java – Convert string to enum

To convert a string to an enum value in Java you can simply use the valueOf method on your enum as the following example demonstrates:

public enum Fruit {

Fruit myFriut = Fruit.valueOf("APPLE");

However this solution is case sensitive. To solve this problem we need to add an extra method to our enum that will returns with the correct value in a case insensitive way.

public enum Fruit {
	public static Fruit getValue(String str) {
		if ( {
			return APPLE;
		} else if ( {
			return BANANA;
		} else if ({
			return ORANGE;
		return null;

Java – Compare strings

For a beginner java programmer it can lead for strange errors using the == operator for comparing strings. This is because Strings are objects and the == operator tests only the reference of the objects but not their content. To make it a bit more complicated as the compiler makes some optimization sometimes the == operator gives the expected result. For example the following is true:

"mystring" == "mystring"

However the correct way to compare strings in java is using the equals() method as you can see in the following example:

String fruit = "orange";
if (fruit.equals("orange")) {
    // Put your code here

Besides this there are some other comparison methods so you can use the followings for string comparison:


Prevent SQL injection in PHP

Using PDO (PHP Data Object) and prepared statements it is quite simple to prevent any SQL injection in your PHP code. A simple code is:

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

$stmt->bindParam(':userName', "myUserName", PDO::PARAM_STR);


Java – jvm default values like Xmx, MaxPermSize

In general you can check Java jvm options on the following oracle site: Java HotSpot VM Options

However if you want to check your actual installation settings you can use the following command:

java -XX:+PrintFlagsFinal -version

This command will list a huge amount of options so it is easier to filter the output. For example to get the actual value of the MaxPermSize use the following command on Windows:

java -XX:+PrintFlagsFinal -version | find "MaxPermSize"

The result will be something similar:

    uintx MaxPermSize                               = 85983232        {pd product}
java version "1.7.0_15"
Java(TM) SE Runtime Environment (build 1.7.0_15-b03)
Java HotSpot(TM) 64-Bit Server VM (build 23.7-b01, mixed mode)

If a default value was already modified then in the output you will find a := instead of = as you can see in the following example:

    uintx MaxHeapSize                              := 4148166656      {product}

Java – OutOfMemoryError: PermGen space

In case of web application development in Java after every 4-5 re-deployments a PermGen space error occurs.

java.lang.OutOfMemoryError: PermGen space

This is because during hotcode re-deployment a new instance of a class will be placed in the permanent generation heap (This holds the byte code of a class) and so a multiple instances of a class will be present in the permgen heap.

To solve this problem you should increase the PermGen space with the following jvm argument:


By default the MaxPermSize is 64m on a 32bit system and 82m on a 64bit system in Java 7

In general if you increase the max heap size you should also increase max perm size as well.


How to detect request type with PHP

You can simply detect the request type using the built in superglobal $_SERVER array as you can see in the following example:

Tagged as: No Comments

Check if a string contains a specific word using PHP

Simply use the strpos function. But don't forget to use the right operator !== and not !=
Here is a simple example:

if (strpos($str,'car') !== false) {
    return true;
Tagged as: No Comments

Iterate over a HashMap in Java

If you want to iterate over a Java HashMap simply use one of the following code:

	public static void hashMapIteration() {
HashMap myMap = new HashMap();
// Iterate over keys and values as pairs
Iterator it = myMap.entrySet().iterator();
   while (it.hasNext()) {
       Map.Entry pairs = (Map.Entry);
       System.out.println("Key: " + pairs.getKey() + "  ---  Value: " + pairs.getValue());
   //Iterate over only values
   Iterator it2 = myMap.values().iterator();
   while (it2.hasNext()) {
       System.out.println("Value: " +;

   //Iterate over only keys
   Iterator it3 = myMap.keySet().iterator();
   while (it3.hasNext()) {
       System.out.println("Key: " +;
Tagged as: , No Comments

Boolean to NSString

If you want to convert the value of an objective c BOOL variable into a nice, human readable format you can do this using the ternary operator as shown here:

BOOL myBooleanVar = YES;
NSLog(@"The value is: %@", myBooleanVar ? @"YES" : @"NO");

That's all.

Filed under: Objective C No Comments

Java – Convert InputStream to String

Depending on the jre you are using you can convert an InputStream to string in different ways.

Using Java 1.4 you can make the conversion as this:

	public static String convertStreamToString(InputStream is, int bufferSize, String encoding) throws IOException {
		Reader reader = new BufferedReader(new InputStreamReader(is, encoding));
		StringBuffer content = new StringBuffer();
		char[] buffer = new char[bufferSize];
		int n;
		while ( ( n = != -1 ) {
		return content.toString();

With Java 1.5 and above you can make the conversion with much less code.

The shortest way is using the Scanner class.

	public static String convertStreamToString(InputStream is) {
	    Scanner s = new Scanner(is).useDelimiter("\\A");
	    return s.hasNext() ? : "";

However this solution can be a bit hard to understand.

You can also use a third party library like Apache IOUtils and do the conversion with it as shown here:

	public static String convertStreamToString(InputStream is, String encoding) throws IOException {
		StringWriter writer = new StringWriter();
		IOUtils.copy(is, writer, encoding);
		return writer.toString();
Filed under: Java No Comments

MySQL backup with cron

To backup a mysql database on your server you can simply setup a cron job to do this. Simply use the official mysqldump utilities and compress the result with gzip. However you should check if mysqldump and gzip is accessible on your server.

The syntax is the following:

15 2 * * * root mysqldump -u root -pPASSWORD --all-databases | gzip > /mnt/disk2/database_`data '+%m-%d-%Y'`.sql.gz

Later you can email this file with a PHP script.


PHP file copy

You can simply copy files in PHP using the built in copy function. You need to provide the source and destination file and that's it.
The copy syntax is quite simple:

boolean $result = copy(src_file, dst_file);

The function returns with a boolean value that indicates whether the copy was success or not.

Here is a complete php file copy example:

   $srcFile = "/home/demo/test/myFile.txt";
   $dstFile = "/home/other/newFile.txt";

   if (copy($srcFile, $dstFile)) {
      echo "File copy was success!";
   } else {
      echo "File copy failed";

PHP – Remove multiple spaces

To remove multiple spaces in a string and replace it with a single space character simply use the following code:

$text = preg_replace('/\s+/', ' ', $text);
Filed under: PHP No Comments

PHP – Convert string to array

To convert any string into an array you need 2 inputs. You need the text/string itself and a separator character. If you have them you can simply use the explode function to make the conversion.

$text = 'This is a demo text to demonstrate explode function';
$delimiter = ' '; // This is a simple space character
$myArray = explode($delimiter, $text);
echo var_dump($myArray);
Filed under: PHP No Comments

JavaScript – Character count

If you want to inform the user how many characters he/she was written in a textarea then you can simply add a function to the onkeyup event of the input field. The function simply reads the text from the textarea and get its length. Later you can display the result in any location you want.

The core function looks like this:

function getCharacterCount(element){
   var counter = element.value.length();
Filed under: JavaScript No Comments

PHP – suppress errors and warnings

In some cases you want to be sure that no error or warning messages will be printed out to the visitors browser window. If you can't edit php.ini settings or want to overwrite the general settings for some special cases then you can use the @ operator before the relevant function call. For example you can try top open a file in this way:

$myFile = @fopen($fileName);
Filed under: PHP No Comments

PHP – Redirect page

If you want to redirect page in your php script you can simply use the header function with the new location. However don't forget that after redirection the original script runs to the end, so if you want to stop it you need to do it manually. Here is an example how to use it:

Filed under: PHP No Comments

MySQL – List values without duplication

If you want to list all unique values from a table where the field has no unique constraint then you can use the DISTINCT keyword to remove duplications.
Use the following syntax:

Filed under: MySQL 4 Comments

MySQL – Change auto increment value

Sometimes you may want to change the auto increment value in your table. You can do this by simply altering the table and set the auto_increment value as here:

Filed under: MySQL 4 Comments

MySQL – Concatenate fields and strings

If you want to concatenate some of the table fields in MySQL you can easily do it using the concat() function. You can give as many parameter as you want, they can be field names and also strings. For example create a full address from the zip_code, city, street, house_nr as follows:

SELECT CONCAT(zip_code, ' ' , city, ', ' street, ' ', house_nr) FROM address;
Filed under: MySQL 1 Comment