Thursday, August 22, 2013

ERROR 1558 (HY000)...: Column count of mysql.proc is wrong.

I had MySQL Stored Procedure to run from shell scrip on Red Hat 5.7. I got this error message:

ERROR 1558 (HY000) at line 1: Column count of mysql.proc is wrong. Expected 20, found 16. Created with MySQL 50077, now running 50168. Please use mysql_upgrade to fix this error.

The script ran without a problem on my other Red Hat instance. I compared Mysql versions on both. The version of MySQL where I did not get an error was 14.12 build 5.0.77. The version of MySQL where I got an error was 14.14 build 5.1.68. I run suggested command:

mysql_upgrade

... and restarted the Server. It solved my problem.

Wednesday, March 6, 2013

Java: Determine what OS are you running

Today I stumble into a problem in my code... I run the code from different OS types, and depending on the OS, I need to create/read files in/from different locations. Of course I thought of Google! I found this code example, that I just wanted to save and share (Big thanks to '', http://www.mkyong.com/java/how-to-detect-os-in-java-systemgetpropertyosname/)


public class OSValidator {

private static String OS = System.getProperty("os.name").toLowerCase();
private static String USER_HOME = System.getProperty("user.home");

public static void main(String[] args) {

System.out.println(OS);
getUserHome();

if (isWindows()) {
System.out.println("This is Windows");
} else if (isMac()) {
System.out.println("This is Mac");
} else if (isUnix()) {
System.out.println("This is Unix or Linux");
} else if (isSolaris()) {
System.out.println("This is Solaris");
} else {
System.out.println("Your OS is not support!!");
}
}

public static boolean isWindows() {
return (OS.indexOf("win") >= 0);
}

public static boolean isMac() {
return (OS.indexOf("mac") >= 0);
}

public static boolean isUnix() {
return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 );
}

public static boolean isSolaris() {
return (OS.indexOf("sunos") >= 0);
}
public static String getUserHome() {
return (USER_HOME+"/");
}

}

Monday, March 14, 2011

Show hidden files in MAC Finder

I was looking on how to show the hidden files in MAC Finder, and I found someone already had a post on this Mac OS X – Show / Hide Hidden Files in Finder .


Here is what I had to do. Kill all my opened Finders. Open the Terminal and type the command:

$ defaults write com.apple.finder AppleShowAllFiles TRUE

Friday, March 11, 2011

Regex, Pattern and Matcher

Need to know about Regex specifics.

Metacharacter

Meaning


Iteration


?The ? (question mark) matches the preceding character 0 or 1 times only, for example, colou?r will find both color (0 times) and colour (1 time).
*The * (asterisk or star) matches the preceding character 0 or more times, for example, tre* will find tree (2 times) and tread (1 time) and trough (0 times).
+The + (plus) matches the previous character 1 or more times, for example, tre+ will find tree (2 times) and tread (1 time) but not trough (0 times).
{n}Matches the preceding character, or character range, n times exactly, for example, to find a local phone number we could use [0-9]{3}-[0-9]{4} which would find any number of the form 123-4567.
Note: The - (dash) in this case, because it is outside the square brackets, is a literal. Value is enclosed in braces (curly brackets).
{n,m}Matches the preceding character at least n times but not more than m times, for example, 'ba{2,3}b' will find 'baab' and 'baaab' but NOT 'bab' or 'baaaab'. Values are enclosed in braces (curly brackets).
Brackets, Ranges and Negation
[ ] Match anything inside the square brackets for ONE character position once and only once, for example, [12] means match the target to 1 and if that does not match then match the target to 2 while [0123456789] means match to any character in the range 0 to 9.
- The - (dash) inside square brackets is the 'range separator' and allows us to define a range, in our example above of [0123456789] we could rewrite it as [0-9].
You can define more than one range inside a list, for example, [0-9A-C] means check for 0 to 9 and A to C (but not a to c).
NOTE: To test for - inside brackets (as a literal) it must come first or last, that is, [-0-9] will test for - and 0 to 9.
^ The ^ (circumflex or caret) inside square brackets negates the expression (we will see an alternate use for the circumflex/caret outside square brackets later), for example, [^Ff] means anything except upper or lower case F and [^a-z] means everything except lower case a to z.
NOTE: Spaces, or in this case the lack of them, between ranges are very important.
            
Positioning
^ The ^ (circumflex or caret) outside square brackets means look only at the beginning of the target string, for example, ^Win will not find Windows in STRING1 but ^Moz will find Mozilla.
$ The $ (dollar) means look only at the end of the target string, for example, fox$ will find a match in 'silver fox' since it appears at the end of the string but not in 'the fox jumped over the moon'.
. The . (period) means any character(s) in this position, for example, ton. will find tons, tone and tonneau but not wanton because it has no following character.

More...


() The ( (open parenthesis) and ) (close parenthesis) may be used to group (or bind) parts of our search expression together.
| The | (vertical bar or pipe) is called alternation in techspeak and means find the left hand OR right values, for example, gr(a|e)y will find 'gray' or 'grey'.

Characters
x The character x
\\ The backslash character
\0n The character with octal value 0n (0 <= n <= 7)
\0nn The character with octal value 0nn (0 <= n <= 7)
\0mnn The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)
\xhh The character with hexadecimal value 0xhh
\uhhhh The character with hexadecimal value 0xhhhh
\t The tab character ('\u0009')
\n The newline (line feed) character ('\u000A')
\r The carriage-return character ('\u000D')
\f The form-feed character ('\u000C')
\a The alert (bell) character ('\u0007')
\e The escape character ('\u001B')
\cx The control character corresponding to x

Predefined Character Classes
. Any character (may or may not match line terminators)
\d A digit: [0-9]
\D A non-digit: [^0-9]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]


I used this site as a reference http://www.zytrax.com/tech/web/regex.htm. They have cool Regular Expresion tester: http://www.zytrax.com/tech/web/regex.htm#parenthesis

Java Code to use Pattern and Matcher.

.....
import java.util.regex.Matcher;
import java.util.regex.Pattern;
....
                String value ="mysortofString23%%%";
                Pattern p = Pattern.compile("[a-zA-Z]+"); //matches if contains characters
                Matcher m = p.matcher(value);
                boolean result = m.find();
                //the result is TRUE

Examples for Regex patterns.

      ^[0-9]+    Matches number only
     ......
(I will add more as I use them more.)












Thursday, March 3, 2011

Spring JNDI configuration with Tomcat

I was really curious about how to configure data source  using Spring JNDI lookup and Tomcat.

I am using Spring 3.0.5, Tomcat 6.0.14 and MySql. Here is what I did:


1) In my Spring config xml file, application-config.xml , I used Spring JNDI lookup tag to create dataSource bean


<jee:jndi-lookup id="myDataSource" jndi-name="jdbc/testDatasource"/>

2) In Tomcat's server.xml I  added <resource> tag to <GlobalNamingResources> tag:

<GlobalNamingResources>
..............
     <Resource
      name="jdbc/testDatasource"
      type="javax.sql.DataSource"
      maxActive="4"
      maxIdle="2"
      username="yourDbUser"
      maxWait="5000"
      validationQuery="select 1"
      driverClassName="com.mysql.jdbc.Driver"
      password="yourpPassword"
      url="jdbc:mysql://yourDatabase.com/yourDBname"/>
   </GlobalNamingResources>

3) In tomcat's LIB folder I added mysql-connector-java-5.1.14.jar (you add an appropriate JDBC driver jar)

4) Now, I was trying to start up my Tomcat from Eclipse and it didn't work at first. I added this code to my web.xml

<resource-ref>
        <description>My Datasource</description>
        <res-ref-name>jdbc/testDatasource</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

and I was able to start the Server from Eclipse Server configuration.

To run JUnit tests, I don't think there is a way to use JNDI if you don't run them from the Tomcat's container. Although I wish thare is a way to do it. I tried to run JUnit tests with my configuration in Eclipse. As far as I got is that I had to have jndi.properties file in my classpath.  Without it I get the following Exception:

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

When I added jndi.properties and I also created jndi.xml, I got  this Error:

Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.StackOverflowError

Friday, October 8, 2010

Mockito Sample

I am one of those Developers who "steals" the code from the web. But in this case I write my own example, because I have been told so...

Mockito is a mock object framework for Java. You can find it here.  The following example shows how to mock up the dependencies for your system under JUnit test. In this particular example, I'm testing an InventoryService class and it has a dependency to a BookDao interface.  Using interface-based programming makes it easy to swap in different implementations of a supertype.  First we have object Book - simple POJO:

package example1.model;

public class Book {
  
     private int id;
     private String name;
     private String author;
     private int year;
    
     public int getId() {
      return id;
     }
     public void setId(int id) {
      this.id = id;
     }
     public String getName() {
      return name;
     }
     public void setName(String name) {
      this.name = name;
     }
    
     public String getAuthor() {
      return author;
     }
     public void setAuthor(String author) {
      this.author = author;
     }
         
     public void setYear(int year) {
      this.year = year;
     }
    
     public int getYear() {
          return year;
         }
}

Second, the interface types for BookInventoryService 

package example1.service;

import java.util.List;

import example1.dao.BookDao;
import example1.model.Book;

public interface BookInventoryService {
   
    public void setDataAccess(BookDao bookDao);
    public List<Book> getInventory();
    public Book getInventoryById(int id) throws Exception;
    public void updateInventory(List<Book> books);
    public void deleteInventory(List<Book> books);
   
}

and BookDao:

package example1.dao;

import java.util.List;

import example1.model.Book;

public interface BookDao {
    public Book getBookById(int id);
    public List <Book> getBooks();
    public void updateBook(Book book);
    public void deleteBook(Book book);
}

Next up is the implementation of BookInventory - MysteryBookInventory class, which will be tested.
The MysteryBookInventory collaborates with a BookDao type, but it does not take on the responsibility of creating the BookDao implementation.  That responsibility lies elsewhere in the application.  In this scenario, the unit test will provide the implementation (a mock implementation using Mockito) and inject that instance into the MysteryBookInventory instance.

package example1.service;

import java.util.List;

import example1.dao.BookDao;
import example1.model.Book;

public class MysteryBookInventoryService implements BookInventoryService{
   
    BookDao bookDao;
   
    @Override
    public void setDataAccess(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    @Override
    public List<Book> getInventory() {
        return bookDao.getBooks();
    }

    @Override
    public Book getInventoryById(int id) throws Exception {
        Book book = bookDao.getBookById(id);
        if (book == null) {
            throw new Exception("Book not found.");
        }
        return book;
    }
   
    @Override
    public void updateInventory(List<Book> books) {
        for (Book book : books) {
            bookDao.updateBook(book);
        }
    }

    @Override
    public void deleteInventory(List<Book> books) {
        for (Object book : books) {
            bookDao.deleteBook((Book)book);
        }
    }

}

Finally the unit tests.  Mockito is used to create mock instances of the BookDao type, suitable for testing the BookInventoryService implementation. I am using @Mock Annotation. You can import it through RunWith JUnit statement or you will have to import it as a package at the beginning. I have 3 tests set up: 1) verification of a state and of a method call; 2) verifying the Exception thrown and 3) is consecutive stubbing:

import static org.junit.Assert.*;
import static org.mockito.Mockito.when;

import java.util.*;

import example1.dao.BookDao;
import example1.model.Book;
import example1.service.BookInventoryService;
import example1.service.MysteryBookInventoryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class InventoryServiceTest {
   
    BookInventoryService service;
   
    @Mock
    private BookDao bookDao;
   
    @Mock
    private List <Book> mockedBooks;
   
    @Mock
    private Book mockedBook1;
   
    @Mock
    private Book mockedBook2;
   
    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this); //Important! Mocks need to be initialized.
        service = new MysteryBookInventoryService();
        service.setDataAccess(bookDao);
    }
   
    //verifying state and behavior
    @Test
    public void testGetInventory() {
        when(bookDao.getBooks()).thenReturn(mockedBooks);
        List <Book> resultList = service.getInventory();
        //verify state
        assertNotNull("Inventory should not be null", resultList);
        //verify behavior
        verify(bookDao).getBooks();
    }
   
    //verifying Exception
    @Test(expected = Exception.class)
    public void testGetInventoryById() throws Exception {
        when(bookDao.getBookById(1)).thenReturn(null);
        @SuppressWarnings("unused")
        Book book = service.getInventoryById(1);
    }
   
    //Consecutive stubbing
    @Test
    public void testGetInventoryByIdManyTimes() throws Exception{
        when(bookDao.getBookById(1)).thenReturn(mockedBook1, mockedBook2);
        Book result = service.getInventoryById(1);
        //verify 1 state
        assertEquals(result,mockedBook1);
       
        result = service.getInventoryById(1);
        //verify 2 state
        assertEquals(result,mockedBook2);
    }
}