Sunday, December 21, 2014

Registering your app in facebook to use SDK in development - Hash key Issue


This should be trivial but sometimes things don't work and for me this was one of the days where multiple things go wrong some from me and others from facebook and android to make a solid challenge.
In summary I wanted to implement facebook share in android app, I had the sdk but it wasn't plugged in my app, and to do that you need to follow the facebook get started guide by creating an app and adding the id in the manifest 
 <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/>
now at one step facebook tells you to generate a Hash key as signature for your app.. they tell you to use openSSL utility, that just didn't work with me and generated wrong hash so after research I was able to fix my issues and integration with facebook worked.
That day I wrote the below answer to this stack overflow question on this specific issue :
I faced the same issue while development and needed to get the hash key to test sharing on facebook, and while solving this I went through couple of issues
1- the command facebook provide to get the hash key by using openSSL command didn't give me the right hash that I got by extracting the signature from Package info with code. getting the hash by the second way was correct.
2- For some reason, In the documentation they tell you to go to developer settings and add the hash key for 'Sample App' there, I thought every hashkey for a developer should be there, and that was my mistake, every app has it's own hash keys field to add to, go to your app/settings/android.
enter image description here
well that was it.. and for the records I used openssl-0.9.8k_X64 on a Windows 7 x64 bit and it just generates a wrong hash I don't know why
I used this code to get the hash:
private void printKeyHash() {
    // Add code to print out the key hash
    try {
        PackageInfo info = getPackageManager().getPackageInfo("YOUR PACKAGE NAME", PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (NameNotFoundException e) {
        Log.e("KeyHash:", e.toString());
    } catch (NoSuchAlgorithmException e) {
        Log.e("KeyHash:", e.toString());
    }
}
but be careful that this may not also print in logs the correct keyhash, at least on my device and machine, when I debug it, in a watch it shows the correct hash just before printing the logs, but in logs it shows another hash and the first one was the correct one.
anyway you can also use a command or eclipse to view the SHA hexadecimal sequence for your key and convert it to base 64 online, there are websites that may help http://tomeko.net/online_tools/hex_to_base64.php?lang=en
Good luck

Android RecyclerView - Adding Empty View

So RecyclerView was introduced to replace List view and it's optimized to reuse existing views and so it's faster and more efficient as stated in the documentation:

https://developer.android.com/training/material/lists-cards.html

While using it, I faced the issue of missing a useful functionality that is implemented in ListView.
that feature is setting an empty view in case there was no records.

In ListView it was as simple as this

View emptyView = findViewById(R.id.mylist_empty_view);
ListView  myList = ....
myList.setEmptyView(emptyView);

but this method doesn't exist for recycler view so we need a work around until android team fixes this.


and here are the screen shots of both list view and recycler view fix

List view :

Recycler view :



here is how I fixed it:



here is the content of empty_view, it can be anything.



Enjoy.

Sunday, November 30, 2014

Developer Productivity tools

This post will serve as a reference for different tools that help the developer to be more productive
and make his life easier, most for Java, others are general
I'll also list some popular libraries


Suggestions are welcome !

Monday, November 17, 2014

Java Validation standard JSR-303

Every application needs to do some validation, and it varies from simple checking on values to complex business rules, like verifying if the user bill has been paid and payment received before we are able to call the print bill API.

 So the java people have created a standard for us under the number JSR-303 that creates a pretty nice way to validate our entities. javax.validatio, inside the validation-api.jar, is the API package for this standard.

The most popular implementation for that API is Hibernate-validator gradle dependencies : compile 'org.hibernate:hibernate-validator:5.0.1.Final'




What mainly is in the validation-api jar are the constraints and the generic interface ConstraintValidator, these are what I'm going to work with here.

there are two methods in this interface the one that does the work is the isValid method, this what will be called, and this what we need to implement  if we need a custom validation rule.

the standard rules are the following :
AssertFalse, AssertTrue, DecimalMax, DecimalMin, Digits, Future, Max, Min, NotNull, Null, Past,
Pattern, Size.

and they are used like this

class MyClass {

@NotNull
private String id;

}

this is the simplest way of using the validation API, you dont have to do more, just put the hibernate validator in the class path, and instantiate your validator and use it, see this very basic example :
[ it's important that you understand the very basics about validation to continue]
http://hibernate.org/validator/documentation/getting-started/

but in most cases we need to tweak things a bit for our business needs. and what we need more is also integrating this to be an autonomous process, and not call validator in every method, unless there is an explicit need for that.

so the way to do that is by using aspects, and the way I like it is on business logic APIs, but it is up to you to choose where you need to put that and I'll explain two ways, but first let's delegate the validator instantiation to the Spring framework

Spring supports the hibernate validator out of the box (the spring jar for this is spring-context.jar)

in our container configuration we add the following:


this will handle creating the validator instance for us.
the messageSource( ) is my custom messages source for i18n purposes, but it's not required by every one since hibernate validator already provide default messages, you can check them out here:

anyway let's proceed with the two possible locations where we can use the validation

1- If we are using Spring dispatcher servlet, we can out of the box put validation on our Rest/MVC controllers

2- On the business logic beans api.



General preparation:

now we add the validation rules to the user entity:


This what you will think at first will be enough, but actually there are couple of problems in this approach..

You see, now the business objects like the User object is no longer a dummy object just to hold data, it has business logic and that logic is in the validation annotations..it's now part of the API itself so we should use it that way and the best way I found to do that is to create a Business object for each call..

 otherwise, there may be conflicts in validation rules, like in the update method we don't want to validate the password again, it shouldn't be in the user object in the first place, another thing is that we may add another field : passwordConfirmation and validate that it match the password field.

so to correctly place our logic, I prefer to create a Business object for different APIs, example for create API:


and for the update API BO :


this is better, each API has it's own validation rule and does one thing, and does it right.
it's not repetition as it may seem, these are totally different APIs and each has it's own work, but it all comes down to your business logic.

To implement the rule that the password and passwordConfirmation should be the same, we should do that with custom validation annotation.




and the validator :



and based on this our BO :



Note that the last rule is put on the validated class instead of the field and the constraint validator takes Object as the class parameter.


Now regarding where to tell Spring to validate an object or not:


Option #1 - validate on web tier

Spring people like everything to be done on the controller level and they have their reasons and I can think one reason like:

what to do if business services call each other, should we validate or assume we are working with validated data?

Assume our controller will look like this without validation:



Reminder: make sure you provide the validator( ) bean with the same name, don't change it to something like : beanValidator( ) since Spring won't be happy.

What we need to do to tell spring to validate the objects is to add @Valid annotation



Spring will throw MethodArgumentNotValidException [ this is a custom spring exception ] in case of invalid objects, you can handle this exception using @ExceptionHandler annotation, I'll do another blog about ExceptionHandling.

Option#2- Validation on BL


To validate on Business layer API we need use aspects, to do that we need to register a bean MethodValidationPostProcessor :










and to trigger the validation we need to do 2 things

1- add @Valid annotation to the method parameters
2- add @Validated to the class/interface we are calling


this will throw ConstraintViolationException [original exception by validation-api]

here is how I handle this and convert it into my custom object :



Notes:

Database validation

You can use the custom ConstraintValidator to communicate with spring beans, it will do that by default if you use validation on Controller layer, but in case of method validator [BL layer], make sure to register the beans correctly.

here is an example of my code using bean to validate object:


Rules Order can be defined by the annotation @GroupSequence



and that's all you can gracefully start using the validation-api JSR-303

Tuesday, October 28, 2014

Spring 4 and mybatis 3 for data tier

Personally I think Hibernate has its complications and doesn't fit an enterprise SOA applications, It will need a lot of customization that will take the essence of why Hibernate is for.

So I prefer to use another framework for SQL databases and it's Mybatis.

Mybatis in short is an SQL mapping framework that will handle the conversion from SQL to Java and the other way around.

it relies on the concept of SQL maps, which are "originally" xml files that define the mapping between our DAO methods and the queries we execute and describe the results and how they are mapped.

example on a simple map :
https://gist.github.com/c0a1cc76b8c8646e05c6.git


now let's see how to use this query from our java code.

first we have to place our xml file in the classpath, in my case I use gradle as build system and the src/main/resources folder is the best choice for me.

now in some package I should have an interface that will call this map:

[https://gist.github.com/af0ceb439fe560f697b0.git]

note that the name of the interface is the same as the xml map and the name of the id of the select query is the same as the method name.

now what remained is to tell our spring configuration about these files :

[https://gist.github.com/636718cca702f7e1297f.git]

now we can inject the mapper in our dao and use it directly :

[https://gist.github.com/c6070206271c23af0a1c.git]


Now that you know how to use Mybatis and how to write the sql queries there are few things to know:
1- There is a project called Mybatis generator, it reads the database and automatically generate for you the basic CRUD queries and it will cover 70-80% of what you need, so you don't have to manually write every standard query every time.
check for the project here: http://mybatis.github.io/generator/
2- it's easy to customize and optimize the query in Mybatis unlike hibernate and what's good about it, is that it does one thing and it does it right.

3- you can avoid using xml files at all by writing your queries as annotations over the mapper interface methods, example :

package org.mybatis.example;
public interface BlogMapper {
  @Select("SELECT * FROM blog WHERE id = #{id}")
  Blog selectBlog(int id);
}

this is a quick way but it has its limitations and mess.

References:

1-http://mybatis.github.io/mybatis-3/getting-started.html
2-http://mybatis.github.io/generator/

Wednesday, September 24, 2014

Spring 4 + Hibernate 4 / Java configuration / rest service example with gradle

In this post I'll explain the required work to create a rest API utilizing both spring and hibernate version 4, and the configuration will be using java configuration classes not XML.

I'll use gradle to build and for dependency management, it's way easier than maven and keeps you focused on the application, if you are not familiar with gradle and interested in it see my previous post about it.

The first part which is dependency management is covered in gradle post mentioned above.
I'll skip to explain each tier of the project and its configurations:


As you can see we have 4 tiers:

1) DAO tier / data tier
In this tier we configure the datasource and hibernate, I used HSQL in memory db it can be easily substituted with other db engine providing the right dependencies


The DaoConfig defines the data source, transaction manager, session factory and  hibernate properties

The most important part is the annotations :
1) @Configuration : to tell spring that this is a configuration class
2) @PropertySource("classpath:dao.properties") : is to load the properites file for this configuration
3) @ComponentScan({ "com.blabadi.gradle.dao" }) : is to tell spring container to scan the specific packages to look for beans, like Dao classes and entities
4) @EnableTransactionManagement : is similar to xml configuration <tx:annotation-driven>
responsible for registering the necessary Spring components that power annotation-driven transaction management (to be able to use @Transactional).

The rest is the person DO and the person DAO :




2) Business logic tier

configuration here is simple, and the person service is utilizing the @Transnational  annotation

3) Rest tier

this is where the web app configuration is, and exposes the Person APIs

The WebConfig.java contains the spring web configuration for the rest project, it uses the @EnableWebMvc to configure the spring dispatcher servlet.

The WebAppInit.java is actually the replacement for web.xml in the java servlet 3 standard it looks for a class the implements  WebApplicationInitializer interface as replacement for the web.xml

Note that I had to add the dependency for servlet-api-3.0.1 to my gradle as compile time dependency but that's not the best way, because it will be provided by the application server.


Sunday, September 21, 2014

Gradle : Next-gen build tool introduction

I've been recently reading about maven 3 and from a page to another I read a bit about gradle, and got interested in it, so I want to try it now and see how it feels and works in practice

so to get started you need to download gradle from here: http://www.gradle.org/downloads
then add the path to gradle bin directory to the PATH system variable and go to CMD/shell then run:

> gradle

if it worked and you got build successful let's move to setup our project structure.

a word about gradle first, is that it promises to keep the great conventions Maven provided but with the flexibility ANT  had since Maven can give you a hard time if you need to customize something.
it's a convention over configuration, yet flexible.

so back to the track, what I want to do in this project is to setup a full spring-mvc rest API server, with multiple tiers (projects) that contains DAOs, Business Entities, Services, and REST tier.

o---[ REST ] -- uses --> [Services] -- uses --> [DAOs] --- > (DB)
           |                                 |                              |
    [                          Business Entitiess                          ]

this is a simple enterprise architecture to provide loosely coupled  tiers, to simulate a real project structure to test what gradle has to offer here.

In maven I would go and create a parent project then add these projects as modules, but when I need to build a project I'll have to build every thing which takes a lot of time.

ok so in gradle we have 3 options to structure our build files [build.gradle]
1) Individual : each sub project has it's own build file
2) Unified : one build file in the master project to build all sub projects
3) Hybrid: a build file in the master project that contains common build configurations and build files in each sub project that are specific for each build file

the Hybrid in my opinion gives you the best of the two worlds so i'll use it here, the other two approaches will implicitly be implemented.

A. Setting up the project structure 

Now the directory structure of our project, i'll go to file system and create the following JSON tree:

master-proj {
build.gradle,
settings.gradle,
dao : { src :{ main : { java : {} , resources : {} } , test :{}} ,  build.gradle },
be : { source :{ code : { java : {} , res : {} }  ,  test :{} }, build.gradle },
bl : { src :{ main : { java : {} , resources : {} } , test :{}} ,  build.gradle },
rest :{ src :{ main : { java : {} , resources : {} } , test :{}} ,  build.gradle }
}

note: i'll be using git also in this tutorial to keep a reference for the code.

if you notice the 'be' src structure is different to test how easy it is to changed default project layout (src/main/java and src/main/resources) that follows maven conventions.

after creating this structure the content of build.gradle in the master project for now will only contain:
allProjects {
 apply plugin: 'java'
}
this tells gradle that all sub projects will use the java plugin without explicitly saying that in the sub projects build files

the contents of settings.gradle will be :
include 'dao', 'be', 'bl', 'rest' 

these are the names of the directories that contain the sub projects

navigate in cmd to master-proj directory and and run :
 > gradle build

what you will get is build directories inside each project like this:


Now let's go to be/build.gradle and add the following segment :

apply plugin: 'java'
sourceSets {
    main {
        java {
            srcDir 'source/code/java'
        }
        resources {
            srcDir 'source/code/res'
        }
    }
}
This will tell gradle java plugin where to find our source code, i'll leave test directory for later.

add the following class in  be/source/code/java folder (don't forget to add the directories for the package) :

package com.blabadi.gradle.be;
public class Person {
}
and in the be/source/code/res folder add an empty file call it : be.properties
 navigate to master-proj/be and run :

>gradle build
 go to master-proj\be\build, you will find more directories : (classes, dependency-cahce, resources)
open the compiler jar in lib to see it's contents:



so now we have something we can work with as start point.

now we want to import this to eclipse but we need to add eclipse config files ( .classpath, .project, .settings) gradle has a plugin for that and we can include it like the java plugin under our master project build file :

allprojects {
  apply plugin: 'java'
  apply plugin: 'eclipse' 
}

now while you are in in master-proj dir , run : 

gradle eclipse

now all your projects can be imported to eclipse to work with easier.

let's go ahead and do that:




it also figured out about our custom source directory in project 'be'



B. Dependency management

in our work we usually need the following types of dependencies:

1- 3rd party dependencies in runtime (spring jars)
2- 3rd party dependencies in compile time only ( javax.servlets )
3- 3rd party testing dependencies (junit)
4- our own frameworks jars / generated web services client jars
5- projects dependencies

some of these are on maven repositories and others aren't, gradle allows us to do everything from importing a jar from file system like ant or use central maven repo or use our own maven repo if we have one, to test this let's plan to add the following dependencies:

for DAO project it will depend on :
- spring for Dependency injection
- hibernate for persistence
- business entities project

for BL :
- spring for Dependency injection
- our own utility library [local jar]
- business entities project
- Junit4 for testing

for REST :
- spring for Dependency injection & spring web
- BL project
- BE project

BE project won't have any dependencies for now.

easiest way to get spring dependencies is to use maven central repo, and since spring core is common between more than one project let's configure this in one place.

In the master project build file i'll add this :

allprojects {
  apply plugin: 'java'
  apply plugin: 'eclipse'

  repositories {    mavenCentral()  } 
}


[':bl', ':dao', ':rest'].each { 
pn -> project(pn) {  dependencies 
      { compile 'org.springframework:spring-context:4.1.0.RELEASE'  }  
   }
}

this tells gradle to user maven central repo to download the spring context jar (and it's dependencies)
and for each of the three projects add the spring-context jar as a compile time dependency

now run gradle eclipse in the master project, it will download the spring jars then update the class path for the three projects to reference the spring-context jar from the local

for the REST project it needs spring-webmvc.jar to expose our rest api's so in rest/build.gradle
add this :

dependencies {
compile 'org.springframework:spring-webmvc:4.1.0.RELEASE'
}

and run gradle eclipse to update classpath file

for the dao we will need hibernate jars so add this to its build.gradle:

dependencies {
compile 'org.hibernate:hibernate-core:4.3.6.Final'
}

now let's convert REST project to a WAR instead of JAR, to do that add the following plugin at the top of its build file :

apply plugin: 'war'

and add the following dependency :

dependencies {
compile 'org.springframework:spring-webmvc:4.1.0.RELEASE'
compile project(':bl')}

this is how we add a dependency  between the projects

now also add the following to complete the dependency between our projects :
in master-project/build.gradle :

[':bl', ':dao', ':rest'].each { pn ->
project(pn) {
dependencies {
compile 'org.springframework:spring-context:4.1.0.RELEASE'
compile project(':be') }
}
}

and in the bl/build.gradle:

dependencies {
compile project(':dao')
}
to add a local jar (not 3rd party and not in a Maven repo) we can do the following:
assume we want our library in the root project in folder called libs, for example I have put xpp3.jar in that folder and I want to reference it inside my projects

1- add flat directory repository :
repositories {
mavenCentral( )
flatDir {
    dirs "$rootDir/libs"
    }
}
$rootDir is a DSL variable that points to the root project base directory.

and in the dependencies add :

compile 'xpp3:xpp3:1.1.4'

it will now be resolved to the libs directory without the need to complex configuration like maven.

another way to do this is to use the files( ) method without declaring a flatDir repository:

compile files('../libs/commons-fileupload-1.3.1.jar')  //[assuming we are in a subproject depedency ]


see the master-proj build.gradle :




ok now the final step is prepare our application for deployment, I have took some time to add the required spring configurations and wire everything together I added few dependencies for junit in the master project build.gradle:

[':bl', ':dao', ':rest'].each { pn ->
project(pn) {
dependencies {
compile 'org.springframework:spring-context:4.1.0.RELEASE'
compile project(':be')
testCompile group: 'junit', name: 'junit', version: '4.+'
testCompile 'org.springframework:spring-test:4.1.0.RELEASE'
}
}
}
notice the scope of junit is for test compile only so it won't be packaged with the final war.

to deploy the project run :

gradle build and you will get a war from the rest project, drop that in your server and you're good to go

visit the final project setup here on git hub:
https://github.com/blabadi/hello-world/tree/dev/test-gradle/master-proj


Summary :
Gradle is simple, flexible and really powerful, the only thing took time is boilerplate required for the initial structure which I did manually on purpose to understand the very basics of gradle.

Gradle yet has more interesting features, and what I only covered is mainly the java plugin and maven in gradle, the possibilities are endless, since you are using groovy scripting for the build domain (DSL) which provides easy to change conventions.


refs :
1- http://www.gradle.org/docs/current/userguide/
2- http://spring.io/guides/gs/gradle/

Thursday, September 11, 2014

Using git hub with eclipse (EGit)

UPDATE: the first section talks about dealing with existing local repo
I added a new section to clone a repo from the scratch by EGit without using any external tool like Git Bash


Section 1 : Working with existing Repo

Today I'm going to try EGit to integrate a local and remote repository with eclipse

let's start by running eclipse > File > Import :

1
2
3




4

5


6

Then I added a Class called Tester to this project and committed it through git bash ( to test if eclipse will sync if I use git bash)

7


8

9

 Until then the project didn't look like it was connected with my local repository, I right-clicked the project in eclipse > Team > share project :

10


11

After I clicked finish the source control icons in eclipse appeared :

12

so eclipse connected well to the local repository without loosing any info as you can see 'Tester.java' is appearing as committed.

Now we will start using EGit, and to do that I added another class 'Tester2' and committed it:

13
14

Now the file is committed, let's try to push it to the remote repository:
right click the project > Team > push branch 

15


16


17

Done! very smooth process with good GUI from eclipse to do basic functionality like adding files and committing then push to remote, lets try more features.

1- branching

create new branch 'dev-adding-feature1':
1
2

add new Interface : Feature1.java, at first the file won't be tracked by git, to add it to the tracking tree right click the file > Team > Add to Index :




3
This file will now appear like this in the commit screen:

4

 but we also want to remove the configuration files from appearing here since they are not to be committed, let's add them to the ignore list:
switch to navigator view (  window -> open view -> navigator )
5
Now the commit screen is clean :

6

Now let's commit and push to the remote repo:

7

8


9



10


this will create a new remote branch on git-hub
11

let's do a pull request and merge dev with dev-adding-feature1

12

Now dev has feature1 folder and interface:

13

Now let's switch locally to the dev branch instead of dev-adding-feature1 to update our local dev branch with the new changes:

before update (no feature 1)

go to Team > Remote > Fetch From ..

14








15

16

17


Now the HEAD changes are fetched for all repositories, we will need to merge the remote dev branch with our local dev branch to see the changes: 

go to Team > Merge..

from local section, dev branch will be selected, and from Remote section, select origin/dev
Now the new commits (changes) will be available in our local dev branch.

another way to do this is to do a Pull. it will automatically do a fetch then merge.


if a conflict happens we will need to resolve it before merge is possible.


Section 2 : only using EGit to clone the repo:

to clone a repo go to File > Import , Select Git




Select Clone URI, then copy the https url and put in your git hub user name and password:




after that the info of the repository will be fetched


Click next and choose the branch that you want to work in, for now I selected master.
after that you will be promted to select a project, in my master I didn't had any so I had to finish the wizard there.



Now because I didn't select the proper branch [ has no projects ] to switch branches in EGit go to to:

Window > Show view > Others : Git > Git Repositories



right click the repo name and you can switch branches :


then create a new local branch and check it out then import the project as in section 1.





Istio —simple fast way to start

istio archeticture (source istio.io) I would like to share with you a sample repo to start and help you continue your jou...