Wednesday, August 14, 2013

Java: Converting String to Enum


Sometimes is necessary to convert a String value to an Enum, perhaps because we have the value as a String in the database, but we want to manipulate it as an Enumerator in the Java code.

The follow code shows hot to obtain the Enum value from a String. Basically, a static method is added to the Enum to return the specif Enum value. This is accomplished by iterating all the Enum values and making a comparison with the String value passed as a parameter. If the String does not match with any of the values, then an illegal argument exception is thrown.


public enum Volcano {

 IRAZU("Irazu"), POAS("Poas"), ARENAL("Arenal"), RINCON_DE_LA_VIEJA("Rincon de la vieja");

 private String name;

 private Volcano(String name) {
  this.name = name;
 }

 public static Volcano fromString(String name) {
  if (name == null) {
   throw new IllegalArgumentException();
  }
  for (Volcano volcano : values()) {
   if (name.equalsIgnoreCase(volcano.getName())) {
    return volcano;
   }
  }
  // Passed string value does not correspond to a valid enum value.
  throw new IllegalArgumentException();
 }

 public String getName() {
  return this.name;
 }

 public static void main(String[] args) {
  Volcano volcano1 = Volcano.fromString("Poas");
  System.out.println(volcano1);

  Volcano volcano2 = Volcano.fromString("rincon de la vieja");
  System.out.println(volcano2);

  Volcano volcano3 = Volcano.fromString("Fuji");
 }
}

Output:


POAS
RINCON_DE_LA_VIEJA
java.lang.IllegalArgumentException
 at com.bodybuilding.common.enums.Volcano.fromString(Volcano.java:22)
 at com.bodybuilding.common.enums.Volcano.main(Volcano.java:36)

Tuesday, August 13, 2013

Oracle: Search text in name of tables and columns

Just a couple of handy Oracle SQL sentences to search for a specific string contained in the name of tables and columns. I found them useful when working in maintenance for legacy systems, or big projects where you didn't start from the beginning.

To search inside name of tables, indexes, etc:

SELECT * 
FROM dba_objects 
WHERE object_name LIKE '%STRING%';

To search inside name of columns:

SELECT owner, table_name, column_name 
FROM all_tab_columns 
WHERE column_name LIKE '%COL_STRING%';

Friday, August 9, 2013

Calculate days lived since birth date

Just a small piece of code showing how to calculate total days lived since birth date (to current date):
import java.util.Calendar;
import java.util.GregorianCalendar;
 
public class TotalLifeTimeDays {
  
 public int getLifeTimeDays(int birthYear, int birthMonth, int birthDay) {
   
  Calendar birthDayCal = new GregorianCalendar();
     Calendar currentDayCal = Calendar.getInstance();
 
  birthDayCal.set(birthYear, birthMonth, birthDay);    
  return (int)((currentDayCal.getTime().getTime() - birthDayCal.getTime().getTime())
     / (1000 * 60 * 60 * 24));  
 }
  
 public static void main(String[] args) {
  TotalLifeTimeDays totalLifeTimeDays = new TotalLifeTimeDays();
  int totalDays = totalLifeTimeDays.getLifeTimeDays(1982, 11, 20);
  System.out.println("Total days lived: " + totalDays);
 }
}

Monday, August 5, 2013

Oracle: ORA-12519, TNS: no appropriate service handler found

This error can have various root causes, but in my particular case it was bothering me while trying to open new connections because apparently I had exceeded the maximum amount of processes and/or allowed sessions.

Fortunately, this value can be modified by running a simple SQL sentence (Oracle needs to be restarted after):


alter system set processes=150 scope=spfile;

SQL*Plus: Release 10.2.0.1.0 - Production on Thu Jun 27 14:46:58 2013

Copyright (c) 1982, 2005, Oracle.  All rights reserved.


Connected to:
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production

SQL> select * from v$resource_limit where resource_name in ('processes','sessions');

RESOURCE_NAME                  CURRENT_UTILIZATION MAX_UTILIZATION
------------------------------ ------------------- ---------------
INITIAL_ALLOCATION
----------------------------------------
LIMIT_VALUE
----------------------------------------
processes                                       38              40
        40
        40

sessions                                        42              49
        49
        49

RESOURCE_NAME                  CURRENT_UTILIZATION MAX_UTILIZATION
------------------------------ ------------------- ---------------
INITIAL_ALLOCATION
----------------------------------------
LIMIT_VALUE
----------------------------------------


SQL> alter system set processes=150 scope=spfile;

System altered.

SQL> exit
Disconnected from Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production
gabo@gabo-Precision-M6600:/usr/lib/oracle/xe/app/oracle/product/10.2.0/server$ sudo /etc/init.d/oracle-xe restart
Shutting down Oracle Database 10g Express Edition Instance.
Stopping Oracle Net Listener.

Starting Oracle Net Listener.
Starting Oracle Database 10g Express Edition Instance.

Monday, July 22, 2013

Flyway Validate: Cannot determine latest applied migration. Was the metadata table manually modified?

In our project we use Flyway to control modifications to the database. Recently I started seeing this error on my local environment, which doesn't give too many clues on why it could be failing:


Flyway Validate: Cannot determine latest applied migration. Was the metadata table manually modified?

Given that Flyway is an Open Source project, it wasn't very hard to find the code and search for the error string. We can see what the code does is to look for the column "CURRENT_VERSION":
   /**
     * @return The latest migration applied on the schema. {@code null} if no migration has been applied so far.
     */
    public MetaDataTableRow latestAppliedMigration() {
        if (!hasRows()) {
            return null;
        }

        String query = getSelectStatement() + " where current_version=" + dbSupport.getBooleanTrue();
        @SuppressWarnings({"unchecked"})
        final List metaDataTableRows = jdbcTemplate.query(query, new MetaDataTableRowMapper());

        if (metaDataTableRows.isEmpty()) {
            if (hasRows()) {
                throw new FlywayException("Cannot determine latest applied migration. Was the metadata table manually modified?");
            }
            return null;
        }

        return metaDataTableRows.get(0);
    }

    ...

    /**
     * @return The select statement for reading the metadata table.
     */
    private String getSelectStatement() {
        return "select VERSION, DESCRIPTION, TYPE, SCRIPT, CHECKSUM, INSTALLED_ON, EXECUTION_TIME, STATE from " + schema + "." + table;
    }

So I just identified the last applied migration and manually set the column "CURRENT_VERSION" in 1. Problem solved!