Pages

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, January 14, 2013

A Serverless, Zero-Configuration Database Solution : SQLite




Most software need saving data. Sometimes that data is predicted to be small and hundreds or thousands of transactions on it will not be needed at the same time. But you will need some SQL-like operations on that data, because some modifications can be difficult and time consuming with regular file operations. At that time, SQLite becomes a very practical solution to this situation.

It started as a C/C++ library (on http://www.sqlite.org/) but it also has Xerial jdbc project for Java (on http://www.xerial.org/trac/Xerial/wiki/SQLiteJDBC and https://bitbucket.org/xerial/sqlite-jdbc lastly). We will tell some details of Java JDBC project here. Some critical properties are:

  • You need only one jar file and adding it to the classpath.
Download latest jar (from here: https://bitbucket.org/xerial/sqlite-jdbc/downloads) and add to the classpath. 
  • Needs one line of code to start using.
Class.forName("org.sqlite.JDBC"); line is enough for activating driver.
  • It creates one database file per schema at the place which you will determine.
Connection con = DriverManager.getConnection("jdbc:sqlite:mydb.db"); line creates "mydb.db" file as database file on the root of your project and creates a connection for DB operations.
  • Supports a general formed JDBC SQL syntax with a useful JDBC API.
Some code examples are shown below (connection opening/closing statements are not included each time for simplifying statements):

  1. // opening connection
  2. Connection con = DriverManager.getConnection("jdbc:sqlite:person.db");
  3. Statement stat = con.createStatement();

  4. // closing connection
  5. con.close();
  6.  
  7. // creating table
  8. stat.executeUpdate("create table person(id INT, name varchar(30));");
  9. // dropping table
  10. stat.executeUpdate("drop table if exists person");
  11. // inserting data
  12. PreparedStatement prep = con.prepareStatement("insert into person values(?,?);");
  13. prep.setInt(1, 1);
  14. prep.setString(2, "andy brown");
  15. prep.execute();
  16. // selecting data
  17. ResultSet res = stat.executeQuery("select * from person");
  18. while (res.next()) {
  19.      System.out.println(res.getString("id") + " " + res.getString("name"));
  20. }
  21. // updating data
  22. PreparedStatement prep = con.prepareStatement("update person set name = ? where id = ?;");
  23. prep.setString(1, "andy black");
  24. prep.setInt(2, 1);
  25. prep.execute();

For more detailed examples about SQL syntax, please take a look at:
http://docs.oracle.com/javase/tutorial/jdbc/index.html

Friday, November 30, 2012

Software Unit Testing and Best Practices





Software Unit Testing is about testing of individual units of source code. Those units are generally methods and they are grouped by class names (called as Test Case). 


For example, if you have an XYZUtility class which having methodA, methodB, methodC methods, you will potentially have an XYZUtilityTestCase class having methodATest, methodBTest and methodCTest tests.

Unit tests must cover as much code as they can while running, but it is not the primary purpose. Code coverage is prefferred to be high as a result but the main purpose of the unit tests are:
  • Testing output of a function with specific inputs. Those inputs must include boundary (min/max) values and potential exceptional values (divide by 0 etc.). And the inputs are also preffered to be chosen for covering all condition cases of the method.
  • Documenting the software. One of the self-documenting code development techniques is unit testing. It shows usage of the code section.
  • Increasing modularity, flexibility and extensibility of the code along with concerning the developer with the interface before implementation, in Test Driven Development (TDD) approach.
There are also 5 important properties for unit tests that must be obeyed according to Andy Hunt's Pragmatic Unit Testing book.

  • Automatic
Unit test results (pass/fail) must be controlled automatically with tools. And generally more than one tests are need to be run together. A test should not have a manual step which stops execution of all tests.
  • Repeatable
A unit test must be repeatable. In other words, if it passes on a certain version of code, it must always pass with that code or if it fails on a certain version of code, it must always fail with that code. Database changes or other external services or files etc. should not change the result of the unit test.
  • Independent
Unit test results must be independent of other unit tests. If a unit test result changes after changing the running order or other environment change (database data etc.), it can not be called as a unit test.
  • Thorough
A unit test must control every condition as it can (all possibilities, exceptions, boundaries ...). Its code coverage must be as much as it can and controlled conditions are preferred to be logical and functional.
  • Professional
Unit test code must obey coding standards of the project which it belongs to, because it also is  a professional code. Furthermore, it was stated before that unit test is another way of self-documenting code. Clean and understandable unit test code will bring better documentation.

As a last word, for providing repeatable and independent unit tests, using mock objects is a good practice. Mock objects replaces the external sources (database, services, etc.) and returns predefined results. A good object oriented design having required amount of interfaces will  simplfy the creation of mock objects. You can also use some API's like EasyMock or Mockito. 


Thursday, October 18, 2012

Best Must-Read Books for Software Engineers





Here are the CodeBuild selection of must-read software engineering books. Books are grouped according to their content with some description.

  • Reference Books
These Robert C. Martin and Gang of Four books are very fundamental OOP resources for every software engineer.

    
  • Coding Perfection
These Steve McConnell, Robert C. Martin and Joshua Bloch books are very helpful with increasing your coding skills.

      

  • Refactoring and Patterns
Refactoring and patterns are very important issues of OOP, which brings quality and maintainability. These Martin Fowler and Joshua Kerievsky books are maybe the best references about this issue.

          

  • Pragmatic Programming
Andrew Hunt's and David Thomas's "pragmatic" approach to programming brings very important viewpoints to software engineering.

     

  • Project Management
There are many project management books in the market but  Frederick P. Brooks Jr. and Tom DeMarco presents very impressive important viewpoints to project management.


     

Monday, October 15, 2012

Start Android Development in 5 Minutes





Android OS is the most popular mobile OS nowadays (leading market with %46.9 above iOS's %18.8). Besides, globally over %20 of computers are mobile devices. So, over %10 of people in the world uses Android OS and softwares related with it. For this reason, Android application development is a very important issue for developers and software engineers. 

This post will describe a fast (5 minutes, excluding tool download periods) and simple startup of an android project on Eclipse IDE, for developers who deal with the matter.

1. JDK and Eclipse IDE:

Download and install appropriate JDK for your computer and OS (JDK 6 or 7 are preferred)

Download latest Eclipse distribution, unzip it to your computer.

2. Android SDK:

Download and install android SDK:

Run Android SDK and install some API (e.g. 8, 14, 16, ...). Android distributions have various APIs and your application API must be compatible with your device. This step may also be performed using Eclipse ADT plug-in Android toolbar buttons. For each API, "SDK Platform" is required. "SDK Tools" and "SDK Platform Tools" under "Tools" menu and "Android Support Library" under "Extras" menu should be installed for general usage.



Don't forget to set your Android SDK directory on Eclipse Window --> Preferences:



3. Eclipse ADT Plugin:

Start Eclipse. Click Help --> Install New Software, paste adress below and click OK:



Select "Android Development Tools" from "Developer Tools", click "Next" various times and finish installation.

You will see Android SDK (which performs installing different APIs as told in step 2) and Android emulator buttons on the top panel. You can also start Android projects from now on.


4. Android Emulator:

Android SDK includes a useful emulator for testing. After installing ADT plug-in, you can start emulator by "Android Virtual Device Manageer" button from toolbar. After that you may add one or more android devices with different API and system configurations.



You can have detailed info about emulator usage and command line parameters here:

5. Creating Project:

Select File --> New --> Project --> Android Application Project. You can also start an Android Sample Project for exercising. 



You must select "Build SDK" and "Minimum Required SDK" while creating project. 



After that right click your project and select "Run". Your project will run on selected emulator.

After this short and simple start, you may want to look at these:



Monday, June 25, 2012

20 Subjects Every Software Engineer Should Know





Here are the most important subjects for software engineering, with brief explanations:

1.Object oriented analysis & design: For better maintainability, reusability and faster development,  the most well accepted approach, shortly OOAD and its SOLID principals are very important for software engineering.

2.Software quality factors: Software engineering depends on some very important quality factors. Understanding and applying them is crucial.

3.Data structures & algorithms: Basic data structures like array, list, stack, tree, map, set etc. and useful algorithms are vital for software development. Their logical structure should be known.

4. Big-O notation: Big-O notation indicates the performance of an algorithm/code section. Understanding it is very important for comparing performances. 

5.UML notation: UML is the universal and complete language for software design & analysis. If there is lack of UML in a development process, it feels there is no engineering.

6.Software processes and metrics: Software enginnering is not a random process. It requires a high level of systematic and some numbers to monitor those techniques. So, processes and metrics are essential.

7.Design patterns: Design patterns are standard and most effective solutions for specific problems. If you don't want to reinvent the wheel, you should learn them.

8.Operating systems basics: Learning OS basics is very important because all applications runs on it. By learning it, we can have better vision, viewpoints and performance for our applications.

9.Computer organization basics: All applications including OS requires a hardware for physical interaction. So, learning computer organization basics is vital again for better vision, viewpoints and performance.

10.Network basics: Network is related with computer organization, OS and the whole information transfer process. In any case we will face it while software development. So, it is important to learn network basics.

11.Requirement analysis: Requirement analysis is the starting point and one of the most important parts of software engineering. Performing it correctly and practically needs experience but it is very essential.

12.Software testing: Testing is another important part of software engineering. Unit testing, its best practices and techniques like black box, white box, mocking, TDD, integration testing etc. are subjects which must be known.

13.Dependency management: Library (JAR, DLL etc.) management, and widely known tools (Maven, Ant,  Ivy etc.) are essential for large projects. Otherwise, antipatterns like Jar Hell are inevitable.

14.Continuous integration: Continuous integration brings easiness and automaticity for testing large modules, components and also performs auto-versioning. Its aim and tools (like Hudson etc.) should be known.

15.ORM (Object relational mapping): ORM and its widely known implementation Hibernate framework is an important technique for mapping objects into database tables. It reduces code length and maintenance time.

16.DI (Dependency Injection): DI or IoC (Inversion of Control) and its widely known implementation Spring framework makes life easy for object creation and lifetime management on big enterprise applications.

17.Version controlling systems: VCS tools (SVN, TFS, CVS etc.) are very important by saving so much time for collaborative works and versioning. Their logical viewpoint and standard cammands should be known. 

18.Internationalization (i18n): i18n by extracting strings into external files is the best way of supporting multiple languages in our applications. Its practices on different IDEs and technologies must be known.

19.Architectural patterns: Understanding architectural design patterns (like MVC, MVP, MVVM etc.) is essential for producing a maintainable, clean, extendable and testable source code.

20.Writing clean code: Working code is not enough, it must be readable and maintainable also. So, code formatting and readable code development techniques are needed to be known and applied.

Thursday, April 19, 2012

A Generic Text Comparison Tool Implementation with LCS Approach





Detecting and showing differences of two texts (especially having hundreds or thousands of lines) is a common problem. Using pure java.lang.String class methods may be a solution, but the most important issue for that kind of operations, "performance" will not be satisfactory. We want an efficient solution which may have a view as below: 

Text Difference Tool Example
The problem contains two parts: 
  • Detecting differences of two texts: For detecting differences, an efficient dynamic algorithm of LCS (Longest Common Subsequence) used in this solution. This solution has O(text1WordCount * text2WordCount) complexity and coded as "longestCommonSubsequence" method below.
  • Visualizing the differences: For visualizing, an HTML tag based approach is used, which marks new words of text2 with green color and old words of text1 with red color. This solution has O(changedWordsCount * (text1WordCount+text2WordCount)) complexity and coded as "markTextDifferences" method below.
Note1: For simplicity, "normalizeText" method is used for removing \n, \t and multiple space characters. 
Note2: This class was created as a Vaadin component. But "longestCommonSubsequence" is pure generic and "markTextDifferences" method is generic on HTML based visual components, so they can also be used with different frameworks.


  1. import java.util.ArrayList;
  2. import com.vaadin.ui.CustomComponent;
  3. import com.vaadin.ui.Label;
  4. import com.vaadin.ui.Layout;
  5. import com.vaadin.ui.VerticalLayout;
  6. /**
  7.  * Text comparison component which marks differences of two texts with colors.
  8.  *
  9.  * @author cb
  10.  */
  11. public class TextCompareComponent extends CustomComponent {
  12.     private Layout mainLayout = new VerticalLayout();
  13.     private ArrayList<String> longestCommonSubsequenceList;
  14.     private static final String INSERT_COLOR = "#99FFCC";
  15.     private static final String DELETE_COLOR = "#CB6D6D";
  16.     public TextCompareComponent(String text1, String text2) {
  17.        
  18.         text1 = normalizeText(text1);
  19.         text2 = normalizeText(text2);
  20.         this.longestCommonSubsequenceList = longestCommonSubsequence(text1, text2);
  21.         String result = markTextDifferences(text1, text2,
  22.             longestCommonSubsequenceList, INSERT_COLOR, DELETE_COLOR);
  23.        
  24.         Label label = new Label(result, Label.CONTENT_XHTML);
  25.         mainLayout.addComponent(label);
  26.         setCompositionRoot(mainLayout);
  27.     }
  28.     /**
  29.      * Finds a list of longest common subsequences (lcs) of given two texts.
  30.      *
  31.      * @param text1
  32.      * @param text2
  33.      * @return - longest common subsequence list
  34.      */
  35.     private ArrayList<String> longestCommonSubsequence(String text1, String text2) {
  36.         String[] text1Words = text1.split(" ");
  37.         String[] text2Words = text2.split(" ");
  38.         int text1WordCount = text1Words.length;
  39.         int text2WordCount = text2Words.length;
  40.        
  41.         int[][] solutionMatrix = new int[text1WordCount + 1][text2WordCount + 1];
  42.        
  43.         for (int i = text1WordCount - 1; i >= 0; i--) {
  44.             for (int j = text2WordCount - 1; j >= 0; j--) {
  45.                 if (text1Words[i].equals(text2Words[j])) {
  46.                     solutionMatrix[i][j] = solutionMatrix[i + 1][j + 1] + 1;
  47.                 }
  48.                 else {
  49.                     solutionMatrix[i][j] = Math.max(solutionMatrix[i + 1][j],
  50.                         solutionMatrix[i][j + 1]);
  51.                 }
  52.             }
  53.         }
  54.        
  55.         int i = 0, j = 0;
  56.         ArrayList<String> lcsResultList = new ArrayList<String>();
  57.         while (i < text1WordCount && j < text2WordCount) {
  58.             if (text1Words[i].equals(text2Words[j])) {
  59.                 lcsResultList.add(text2Words[j]);
  60.                 i++;
  61.                 j++;
  62.             }
  63.             else if (solutionMatrix[i + 1][j] >= solutionMatrix[i][j + 1]) {
  64.                 i++;
  65.             }
  66.             else {
  67.                 j++;
  68.             }
  69.         }
  70.         return lcsResultList;
  71.     }
  72.    
  73.     /**
  74.      * Normalizes given string by deleting \n, \t and extra spaces.
  75.      *
  76.      * @param text - initial string
  77.      * @return - normalized string
  78.      */
  79.     private String normalizeText(String text) {
  80.        
  81.         text = text.trim();
  82.         text = text.replace("\n", " ");
  83.         text = text.replace("\t", " ");
  84.        
  85.         while (text.contains("  ")) {
  86.             text = text.replace("  ", " ");
  87.         }
  88.         return text;
  89.     }
  90.     /**
  91.      * Returns colored inserted/deleted text representation of given two texts.
  92.      * Uses longestCommonSubsequenceList to determine colored sections.
  93.      *
  94.      * @param text1
  95.      * @param text2
  96.      * @param lcsList
  97.      * @param insertColor
  98.      * @param deleteColor
  99.      * @return - colored result text
  100.      */
  101.     private String markTextDifferences(String text1, String text2,
  102.         ArrayList<String> lcsList, String insertColor, String deleteColor) {
  103.         StringBuffer stringBuffer = new StringBuffer();
  104.         if (text1 != null && lcsList != null) {
  105.             String[] text1Words = text1.split(" ");
  106.             String[] text2Words = text2.split(" ");
  107.             int i = 0, j = 0, word1LastIndex = 0, word2LastIndex = 0;
  108.             for (int k = 0; k < lcsList.size(); k++) {
  109.                 for (i = word1LastIndex, j = word2LastIndex;
  110.                     i < text1Words.length && j < text2Words.length;) {
  111.                     if (text1Words[i].equals(lcsList.get(k)) &&
  112.                         text2Words[j].equals(lcsList.get(k))) {
  113.                         stringBuffer.append("<SPAN>" + lcsList.get(k) + " </SPAN>");
  114.                         word1LastIndex = i + 1;
  115.                         word2LastIndex = j + 1;
  116.                         i = text1Words.length;
  117.                         j = text2Words.length;
  118.                     }
  119.                     else if (!text1Words[i].equals(lcsList.get(k))) {
  120.                         for (; i < text1Words.length &&
  121.                             !text1Words[i].equals(lcsList.get(k)); i++) {
  122.                             stringBuffer.append("<SPAN style='BACKGROUND-COLOR:" +
  123.                                 deleteColor + "'>" + text1Words[i] + " </SPAN>");
  124.                         }
  125.                     } else if (!text2Words[j].equals(lcsList.get(k))) {
  126.                         for (; j < text2Words.length &&
  127.                             !text2Words[j].equals(lcsList.get(k)), j++) {
  128.                             stringBuffer.append("<SPAN style='BACKGROUND-COLOR:" +
  129.                                 insertColor + "'>" + text2Words[j] + " </SPAN>");
  130.                         }
  131.                     }
  132.                 }
  133.             }
  134.             for (; word1LastIndex < text1Words.length; word1LastIndex++) {
  135.                 stringBuffer.append("<SPAN style='BACKGROUND-COLOR:" +
  136.                     deleteColor + "'>" + text1Words[word1LastIndex] + " </SPAN>");
  137.             }
  138.             for (; word2LastIndex < text2Words.length; word2LastIndex++) {
  139.                 stringBuffer.append("<SPAN style='BACKGROUND-COLOR:" +
  140.                     insertColor + "'>" + text2Words[word2LastIndex] + " </SPAN>");
  141.             }
  142.         }
  143.         return stringBuffer.toString();
  144.     }
  145. }