Wednesday, November 6, 2013

ATG Colorizer: libstdc++.so.6: cannot open shared object file: No such file or directory

I was in the middle of my ATG local dev environment setup and started to see an error with small application ATG Colorizer:

libstdc++.so.6: cannot open shared object file: No such file or directory




I tried installing the library as I have done in the past, but somehow my new Ubuntu stopped liking the old install recipe. After checking the web for a while I found a way she liked: 
apt-get install lib32stdc++6

Tuesday, September 10, 2013

ATG: Template Error: category error 2

I started getting this error after a merge of code. No clue why this happened but it was impeding my work.

The CategoryLookup droplet (/atg/commerce/catalog/CategoryLookup) was the one failing . So I turned on debug mode to have more information. I got this:


14:01:43,960 INFO  [CategoryLookup] DEBUG Find item: id=BRAND_OPTIMUM; type=category
14:01:43,961 INFO  [CategoryLookup] DEBUG Item Found:category:BRAND_OPTIMUM
14:01:43,961 INFO  [CategoryLookup] DEBUG Is item in catalog catalog:masterCatalog
14:01:43,961 INFO  [CategoryLookup] DEBUG This item is not in the correct catalog.

A more expert person  on ATG told me there is a catalog maintenance page that is used to solve this kind of issues:

Basic Catalog Maintenance

http://localhost:8080/dyn/admin/atg/commerce/admin/en/maintenance/startService.jhtml?process=BasicMaintProcess


Basically, I just ran the process and issues were solved.

Monday, September 9, 2013

Flyway: No enum const class com.googlecode.flyway.core.api.MigrationState.SUCCESS

This exception thrown by Flyway:

java.lang.IllegalArgumentException: No enum const class com.googlecode.flyway.core.api.MigrationState.SUCCESS 
        at java.lang.Enum.valueOf(Enum.java:214)
        at com.googlecode.flyway.core.api.MigrationState.valueOf(MigrationState.java:21)
        at com.googlecode.flyway.core.metadatatable.MetaDataTable$MigrationInfoRowMapper.mapRow(MetaDataTable.java:382)
        at com.googlecode.flyway.core.metadatatable.MetaDataTable$MigrationInfoRowMapper.mapRow(MetaDataTable.java:370)
        at com.googlecode.flyway.core.util.jdbc.JdbcTemplate.query(JdbcTemplate.java:319)
...

happens because an invalid value in the column state. In my case it was failing because of an extra blank space I didn't notice.

Friday, September 6, 2013

Juniper VPN: sysdeps.error Failed to open /etc/resolv.conf with error 2 (sysdeps.cpp:715)



In my work we use a Juniper client for the VPN connection. Suddenly, I started getting problems to connect. It was like it was going to connect normally but at the end it was exiting like if I was doing it, showing the message that connection was closed successfully. 

Checking the logs I realized of this error:

ncsvc[p10461.t10461] sysdeps.error Failed to open /etc/resolv.conf with error 2 (sysdeps.cpp:715)

I went to check, and effectively this file  /etc/resolv.conf didn't exist. So I created an empty one (in my case it was a broken symlink). And voilà! Problem solved.




Thursday, August 29, 2013

JSP: Get Current Date

Short snippet showing how to get current date in a JSP using scriplet code. In occasions it's needed to have the date served by the server instead of using JavaScript code, which depends of right configuration in user's machine, or differences may arise due to distinct time zones.

<%@ page import="java.util.*" %>
<%@ page import="java.text.SimpleDateFormat"%>
 
<%
   Date dNow = new Date();
   SimpleDateFormat ft = 
   new SimpleDateFormat ("MM/dd/yyyy");
   String currentDate = ft.format(dNow);
%>

<p>The current date is: <%=currentDate%></p>

Tuesday, August 27, 2013

Unit testing vs Integration testing

Though question if someone has to decide between the two, Unit testing and integration testing are not mutually exclusive. Both of them have their merits in the world of automating testing. In this page we will discuss the the advantages and disadvantages of each approach, and will try to provide a recommendation to apply in the Commerce site. There is a good on line article we will use as reference (see reference at bottom of this page) as it makes a good comparison of the two.

Difference in a nutshell 


The distinction between unit testing and integration testing is simple. Unit testing focus on the internal functionality of a single class, while integration testing proves functionality of an entire system, validating that all classes work fine together. In unit testing, when a class depends of another to complete an operation, it's common to use mocking technique to break the dependency and worry only about the class being tested. In integration testing all classes are real implementations and reflects the real work flows of the application.

A brief comparison

Let's compare a few aspects between the two methods. 


Driving the design


Not only in theory, but also for personal experience, we know that unit testing helps to enforce correct designed solutions in the code. Let's be honest, if you have big chunk of code in a single class method, you will find that there is no “clean” way to unit test the core logic. You will wish to go back in time and prevent yourself from writing nasty code. 

That's one reason why unit testing should be done very closely with production code. If it is pushed forward, the poor person in charge of the unit testing code will find himself having to apply refactoring, with the fear of breaking already tested approved shiny functionality. No one wants to face business explaining why application went down for applying simple tests. You can always make your QA team to regress test everything, but that makes it more expensive.

Integration testing does not improve the design, as it doesn't depend of the underlying implementations. This is a pro and con at the same time. By one hand you don't have to worry about refactoring the code just to apply testing, but it won't help improving the code which is also a good thing in terms of maintenance productivity.


Easy to write 


Unit tests are easy to write if they are done side to side with production code. It can get complicated if refactoring is required to make the code unit testable. Integration tests are easy to write in general. It can get complicated depending of the configuration required to prepare the setups required to initialize the test, and to finalize it. For example, if a user story requires interaction with a database, some initial setups will be required to leave the database in a particular state. After the test, another code will need to be run to leave the database as it was before running the test. Depending also of the framework used, coding tests in a web application context (in-container testing) can take a while to learn the first time. Once learning curve is passed, it might get easier.


Confidence in the test 


Unit testing provides a good level of confidence in the application code, but since it doesn't test integration among subsystems, it doesn't give the level of confidence an integration test provides. Integration tests are the best for regression testing. 


Fail troubleshooting 


With any type of x-unit, it will be common for a test to fail. That is the all point of the automated tests. To discover when someone screws up the application, breaking the functionality that a test is 
supposedly covering. 

Tests need to be maintained. It means that if a test fails, someone has to spend sometime figuring out what happened with the test. Why it failed? With unit testing is pretty straightforward. The test points the exact class method that failed. With integration testing you don't know at first glance what was the specific code that failed the entire operation. Therefore, it's more difficult to troubleshoot an integration test when it fails.


Documentation


Unit tests and integration tests are both good ways to document the system. Unit tests document the internal implementations. Integration tests documents user stories.


Speed


Unit tests are definitely faster than integration tests. Since integration tests can interact with databases, web services, application framework stacks, etc, they might become very slow. Usually they are not run as usual as unit tests, which are very common for developers to run to verify nothing got broken during development.

Summary Table

Here's a summary table with our rating of the different aspects commented before. This might be a little subjective as any rating system, but it provides a general overview of both methods. You can see each one has its strengths and weaknesses.

Unit Testing
Integration Testing
Confidence in the application
Documentation
Driving the design
Easy to write
Fail Troubleshooting
Friendly with Legacy Code
Speed

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!

Thursday, June 27, 2013

Java version of a .class


Sometime ago I had an issue with a code that was sent to us already compiled (no sources attached). During deployment we were facing an exception like this one: javax.servlet.ServletException: Bad version number in .class file

What I found reading on the web about this problem is that the problem was probably caused by compiling the Java project in a Java version higher than the one running in the JVM on the server. In my particular case I found that the code was compiled in Java 6, while the JVM was running Java 5.

To confirm this I learned a trick on how to find the Java version of a .class. For this there is a command: javap -verbose ClassName
(The .exe can be found in the JDK bin directory)

It is recommended to save the result of the command on a file since it throws a lot of information. What you need to look for is the combination of minor and major version that is found in the beginning. These two values are the key to determine the Java version used to compile the class.

major  minor Java platform version 
45       3           1.0
45       3           1.1
46       0           1.2
47       0           1.3
48       0           1.4
49       0           1.5
50       0           1.6

Monday, May 20, 2013

Function-based indexes used as constraints


Let's suppose we want to avoid duplicity in the values of a column produced by a bad checking in a formulary of a program, that ends up allowing to add existing values, with the only difference that the user adds leading/trailing blank spaces, or changes one letter to upper/lower case.

A function based index does not only permits to speed up queries by expresion. I recommend this video for a brief explanation:


A function based index can also be used as a type of constraint. Given the example at the beggining, we could create an index of type "UNIQUE" to prevent duplicity cleaning the value to be inserted and checking its uniqueness.

create unique index INDEX_NAME on TABLE (lower(trim(COL_1)));

Once the index is added to the table, any insertion with a duplicate value (with blank spaces or lower/upper case changed) will throw the follow exception:

SQL Error: ORA-00001: unique constraint (TABLE.INDEX_NAME) violated
00001. 00000 -  "unique constraint (%s.%s) violated"
*Cause:    An UPDATE or INSERT statement attempted to insert a duplicate key.
           For Trusted Oracle configured in DBMS MAC mode, you may see
           this message if a duplicate entry exists at a different level.
*Action:   Either remove the unique restriction or do not insert the key.

Wednesday, May 1, 2013

Spring Jackson library example to consume JSON returned by REST service


A brief example of how to use the Spring Jackson library to consume a JSON returned by a REST service. The class below is a Singleton that initializes the RestTemple one time only.

import java.util.ArrayList;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.http.client.CommonsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

public class RestJsonTest {
 
 private static RestJsonTest instance;
 private RestTemplate restTemplate;
 private String url ="http://rest.service.url";
 
 public static RestJsonTest getInstance() {
  if (instance == null) {
   instance = new RestJsonTest();
  }
  return instance;
 }
 
 private RestJsonTest() {
  // Setup the RestTemplate configuration.
  restTemplate = new RestTemplate();
  restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory());
  List<HttpMessageConverter<?>> messageConverterList = restTemplate.getMessageConverters();
  
  // Set HTTP Message converter using a JSON implementation.
  MappingJacksonHttpMessageConverter jsonMessageConverter = new MappingJacksonHttpMessageConverter();
  
  // Add supported media type returned by BI API.
  List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
  supportedMediaTypes.add(new MediaType("text", "plain"));
  supportedMediaTypes.add(new MediaType("application", "json"));
  jsonMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
  messageConverterList.add(jsonMessageConverter);
  restTemplate.setMessageConverters(messageConverterList);
 }
 
 public SearchResults searchResults() {
  return restTemplate.getForObject(url, SearchResults.class);  
 }
 
 public static void main(String[] args) {
  RestJsonTest jsonTest = RestJsonTest.getInstance();
  SearchResults results = jsonTest.searchResults();
 }
}

The mapping of the JSON to Java classes can be done via annotations like it's shown here:
package com.bodybuilding.api.commerce.clientservice;

import java.util.List;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;


/**
 *{
 * "search_keywords":"Social Networks",
 *  "total_time":200,
 *  "results":{
 *   "result_01":{
 *    "url":"http://www.facebook.com",
 *    "rank": "1"
 *   },
 *   "result_02":{
 *   "url":"http://www.twitter.com",
 *    "rank": "2"
 *   }
 *  }
 * }
 */
@JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResults {
 
 @JsonProperty("search_keywords")
 private String keywords;
 
 @JsonProperty("total_time")
 private long totalTime;
 
 @JsonProperty("results")
 private List<SearchResult> results;
 
 public String getKeywords() {
  return keywords;
 }
 public void setKeywords(String keywords) {
  this.keywords = keywords;
 }
 public long getTotalTime() {
  return totalTime;
 }
 public void setTotalTime(long totalTime) {
  this.totalTime = totalTime;
 }
 public List<SearchResult> getResults() {
  return results;
 }
 public void setResults(List<SearchResult> results) {
  this.results = results;
 } 
}

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResult {
 
 @JsonProperty("url")
 private String url;
 
 @JsonProperty("rank")
 private int rank;
 
 public String getUrl() {
  return url;
 }
 public void setUrl(String url) {
  this.url = url;
 }
 public int getRank() {
  return rank;
 }
 public void setRank(int rank) {
  this.rank = rank;
 }
}

The RestTemplate bean can be also configure with Spring injection:

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
     <property name="requestFactory">
      <bean id="clientHttpRequestFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory" />   
     </property>
     <property name="messageConverters">
      <list>
       <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
         <list>
          <bean id="jsonMediaTypeTextPlain" class="org.springframework.http.MediaType">
           <constructor-arg value="text"/>
          <constructor-arg value="plain"/>
          </bean>
          <bean id="jsonMediaTypeApplicationJson" class="org.springframework.http.MediaType">
           <constructor-arg value="application"/>
          <constructor-arg value="json"/>
          </bean>
         </list>
        </property>
       </bean>
      </list>
     </property>  
</bean>

Friday, February 22, 2013

Unit, Integration and functional tests


There seems to be confusion among developers when referring to unit, integration and functional tests. It makes it worst when these concepts are also used under different names. The idea of this post is to define clearly these terms using an authority on the field to remove the subjectiveness contra argument.

I will use the definitions proposed by Gerard Meszaros on the book xUnit Test Patterns, Refactoring Test Code.



Unit Tests


Unit tests verify the behavior of a single class or method that is a consequence of a design decision. This behavior is typically not directly related to the requirements except when a key chunk of business logic is encapsulated within the class or method in question. These tests are written by developers for their own use; they help developers describe what “done looks like” by summarizing the behavior of the unit in the form of tests.

Integration Tests


Component tests verify components consisting of groups of classes that collectively provide some service. They fit somewhere between unit tests and customer tests in terms of the size of the SUT being verified. Although some people call these “integration tests” or “subsystem tests,” those terms can mean something entirely different from “tests of a specific larger-grained subcomponent of the overall system.”

Functional Tests



Customer tests verify the behavior of the entire system or application. They typically correspond to scenarios of one or more use cases, features, or user stories. These tests often go by other names such as functional tests, acceptance tests, or end-user tests. Although they may be automated by developers, their key characteristic is that an end user should be able to recognize the behavior specified by the test even if the user cannot read the test representation.




Figure 6.1 A summary of the kinds of tests we write and why. The left column contains the tests we write that describe the functionality of the product at various levels of granularity; we perform these tests to support development.
The right column contains tests that span specific chunks of functionality; we execute these tests to critique the product. The bottom of each cell describes what we are trying to communicate or verify.


Tuesday, January 8, 2013

Android: Mini Math Game

For practicing purposes I made this program with humble intentions to be a Math game. It creates basic operations like sums, subtractions, multiplications and divisions, in a randomly fashion, along with the right answer and two incorrect answers. Each valid answers adds a point to the user.


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.example.mytoolbox.utilities.NumberUtilities;

public class MathRallyActivity extends Activity implements OnClickListener {
 
 public enum Operation {
  SUM, DIVISION, MULTIPLICATION, SUBSTRACT  
 }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_math_rally);
        
        Button buttonOption1 = (Button) findViewById(R.id.buttonMath1);
        Button buttonOption2 = (Button) findViewById(R.id.buttonMath2);
        Button buttonOption3 = (Button) findViewById(R.id.buttonMath3);
        ImageButton buttonHome = (ImageButton) findViewById(R.id.imageButtonHome);
        
        buttonOption1.setOnClickListener(this);
        buttonOption2.setOnClickListener(this);
        buttonOption3.setOnClickListener(this);
        buttonHome.setOnClickListener(this);
        
        createOperation();        
    }
    
    private void createOperation() {
     Operation operation = generateRandOperation();
     
     int operand1 = NumberUtilities.generateRandNumber(2, 100);
     int operand2 = NumberUtilities.generateRandNumber(2, 100);
     
     String operationText = String.valueOf(operand1) + " " +
       getOperationString(operation) + " " + String.valueOf(operand2) + "?";
     
     TextView textViewOperation = (TextView) findViewById(R.id.textViewOperation);
     textViewOperation.setText(operationText);
     float rightValue = calculateRightValue(operation, operand1, operand2);
     
     rightBox = NumberUtilities.generateRandNumber(1, 3);
     float randWrongValue1 = NumberUtilities.generateRandNumber(2);
     float randWrongValue2 = NumberUtilities.generateRandNumber(2);
     
     Button buttonOption1 = (Button) findViewById(R.id.buttonMath1);
        Button buttonOption2 = (Button) findViewById(R.id.buttonMath2);
        Button buttonOption3 = (Button) findViewById(R.id.buttonMath3);
     
     switch (rightBox) {
      case 0:
       buttonOption1.setText(String.valueOf(rightValue));
       buttonOption2.setText(String.valueOf(randWrongValue1));
       buttonOption3.setText(String.valueOf(randWrongValue2));
       break;
      case 1:
       buttonOption2.setText(String.valueOf(rightValue));
       buttonOption1.setText(String.valueOf(randWrongValue1));
       buttonOption3.setText(String.valueOf(randWrongValue2));
       break;
      case 2:
       buttonOption3.setText(String.valueOf(rightValue));
       buttonOption1.setText(String.valueOf(randWrongValue1));
       buttonOption2.setText(String.valueOf(randWrongValue2));
       break;
     }     
    }
    
    private float calculateRightValue(Operation oper, int operand1, int operand2) {
     float calculation = 0;
     
     if (oper == Operation.SUM) {
      calculation = operand1 + operand2;
     } else if (oper == Operation.MULTIPLICATION) {
      calculation = operand1 * operand2;
     } else if (oper == Operation.SUBSTRACT) {
      calculation = operand1 - operand2;
     } else if (oper == Operation.DIVISION) {
      calculation = operand1 / operand2;
     }
     
     return calculation;
    }
    
    private String getOperationString(Operation oper) {
     String operationText = "";
     if (oper == Operation.SUM) {
      operationText = "+";
     } else if (oper == Operation.MULTIPLICATION) {
      operationText = "*";
     } else if (oper == Operation.SUBSTRACT) {
      operationText = "-";
     } else if (oper == Operation.DIVISION) {
      operationText = "/";
     }
     return operationText;
    }
    
    private Operation generateRandOperation() {
     int rand = NumberUtilities.generateRandNumber(1, 4);
     Operation operation = null;
     
     switch(rand) {
      case 0:
       operation = Operation.SUM;
       break;
      case 1:
       operation = Operation.DIVISION;
       break;
      case 2:
       operation = Operation.MULTIPLICATION;
       break;
      case 3:
       operation = Operation.SUBSTRACT;
       break;
     }
     return operation;
    }
  
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_math_rally, menu);
        return true;
    }

 @Override
 public void onClick(View view) {
  boolean correct = false;
  boolean play = true;
  
  switch(view.getId()) {
   case R.id.buttonMath1:
    if (rightBox == 0) {
     correct = true;
    }
    break;
   case R.id.buttonMath2:
    if (rightBox == 1) {
     correct = true;
    }
    break;
   case R.id.buttonMath3:
    if (rightBox == 2) {
     correct = true;
    }
    break;
   case R.id.imageButtonHome:
    startActivity(new Intent(MathRallyActivity.this, ChooseActivity.class));
    play = false;
    break;
  }
  if (correct) {
   points++;
   updateScore();
  } if(play) {
   createOperation();
  }
 }
 
 private void updateScore() {
  EditText editText = (EditText) findViewById(R.id.editTextPoints);
  editText.setText(String.valueOf(points));
 }

 private int rightBox;
 private int points;
}

Monday, January 7, 2013

Design Patterns Short Test


A time ago I prepared this test for a course in the internal training program of the company I worked for. I gave a quick training of design patterns using the most common ones as described in the Gang of Four book. You can get it from my drive in Google, or read it here. 


  1. The follow applicability a system should be configured with one of multiple families of products.”, describes the pattern:
    1. Builder
    2. Decorator
    3. Singleton
    4. Abstract Factory

  1. The diagram below is read as
                             
  1. A is an aggregate class
  2. B implements A
  3. B extends from A
  4. A is an abstract class

  1. These two patterns can be used for undo operations.
    1. Decorator & Visitor
    2. Memento & Command
    3. Factory Method & Chain of Responsibility
    4. Command & Observer

  1. Loose coupling is when
    1. A class has just a small number of lines of code
    2. An application is designed with a small set of classes
    3. Reflection is used to instance the objects
    4. A class has little knowledge of another implementing class


  1. Which pattern uses a pool to share objects instead of instancing an excessive amount of them?
    1. Adapter
    2. Flyweight
    3. Proxy
    4. None of above


  1. Which of the follow is a general principle of class designing?
    1. Favor inheritance over composition
    2. Avoid polyphormism
    3. Use only creational patterns
    4. Favor composition over inheritance

  1. Incompatible interfaces can be overcome with the pattern:
    1. Interpreter
    2. Observer
    3. Adapter
    4. Bridge

  1. Which statements are correct about design patterns?
    1. They are proven solutions to common design problems
    2. They benefit code reusability
    3. They provide a common language among programmers
    4. All mentioned

  1. The capacity to add responsibilities on runtime to individual objects, that is, without affecting other objects, can be accomplished with this pattern.
    1. Decorator
    2. Proxy
    3. State
    4. Façade

  1. One applicability of the Observer pattern is :
    1. When a class should have all its attributes declared as public
    2. When an object should be able to notify others about an event
    3. When a class should have all its methods declared as public
    4. All of them

  1. Which pattern is represented in this diagram?
    1. Composite
    2. Prototype
    3. Façade
    4. Singleton

  1. Which pattern is being used in this line of code?
MyPattern s1 = MyPattern.Instance();

  1. Singleton
  2. Prototype
  3. Factory Method
  4. Command

  1. Which type of pattern is described in the next sentence: “Are concerned with algorithms and the assignments of responsibilities between objects”
    1. Creational
    2. Structural
    3. Behavioral
    4. None

  1. This pattern has two types: virtual & security.
    1. Façade
    2. Iterator
    3. Singleton
    4. Proxy

  1. Suppose there is a class that has a request, but you don’t want to hard code the class that will satisfy that request, but more than one class can satisfy it. You will use the follow pattern:
    1. Façade
    2. Chain of responsibility
    3. Proxy
    4. Command