CoralCode Web programming snippets

2Aug/130

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 {
    APPLE, BANANA, ORANGE
}

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 {
	APPLE, BANANA, ORANGE;
	
	public static Fruit getValue(String str) {
		if (APPLE.name().equalsIgnoreCase(str)) {
			return APPLE;
		} else if (BANANA.name().equalsIgnoreCase(str)) {
			return BANANA;
		} else if (ORANGE.name().equalsIgnoreCase(str)){
			return ORANGE;
		}
		return null;
	}
}
9Jul/130

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:

equals()
equalsIgnoreCase()
compareTo()
compareToIgnoreCase()
24Jun/130

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);

$stmt->execute();
12Jun/130

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}
15May/130

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:

-XX:MaxPermSize=128m

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.

19Apr/130

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:

$method = $_SERVER['REQUEST_METHOD'];
Tagged as: No Comments
7Mar/130

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
18Jan/130

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();
myMap.put("1","A");
myMap.put("2","B");
myMap.put("3","C");
myMap.put("4","D");
// Iterate over keys and values as pairs
Iterator it = myMap.entrySet().iterator();
   while (it.hasNext()) {
       Map.Entry pairs = (Map.Entry)it.next();
       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: " + it2.next());
   }	

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

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
15Jan/120

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 = reader.read(buffer)) != -1 ) {
		    content.append(buffer,0,n);
		}
		
		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() ? s.next() : "";
	}

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
17Feb/110

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.

10Jan/110

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:

<?php
   $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";
   }
?>
30Nov/100

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
25Nov/100

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
17Nov/100

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
9Nov/100

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
27Oct/100

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:

header('Location:http://www.coralcode.com');
die();
Filed under: PHP No Comments
16Oct/104

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:

SELECT DISTINCT lastname FROM user;
Filed under: MySQL 4 Comments
8Oct/104

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:

ALTER TABLE tablename AUTO_INCREMENT = 1;
Filed under: MySQL 4 Comments
4Oct/101

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