Tuesday, 21 April 2015

Propel 2 and Symfony 2.6

Have you ever tried installing Propel 2 with Symfony 2.6 and wondered what the hell is wrong with my machine OR with my code. I am being particular about versions as I am not a full fledged Web developer.

History:
A friend of mine was playing with Symfony and came across Propel (ORM) and after spending some time, he called me to help him in configuring same. It was not as easy as we thought it would be. Here are our findings:

(NOTE : This post is all about my personal experience and these are my viewpoints)

a) Propel2 Documentation on official Symfony site is not up to date, it still shows some old configuration to install propel.

Official Documentation link :

It says use
{
    "require": {
        // ...
        "propel/propel-bundle": "1.2.*"
    }
}
in composer json file (Note: You should change propel version required as per symfony version you are using)

However It never worked for us, It could not download bundle along with it. After spending sometime searching for this (more appropriately struggling for sometime) , We came across some blog post (Do not remember link now) which suggested to try :


"require" : {
                "propel/propel": "~2.0@dev",
                "propel/propel-bundle": "~2.0@dev"
                }

in composer.json and to our surprise it worked for us, No more Bundle Not found error. 

Now Next Step was  not that difficult, we missed entry of Propel Bundle in AppKernel (infact many people does same). Simply Add 

new Propel\PropelBundle\PropelBundle(),

in $bundles array in app/AppKernel.php

Now it should work like charm, So we followed this link and tried to setup DB connection so we can start work happily.

But wait, life is not that simple. It says "dbal is unrecognised under propel". When googled this error, every second page was talking about some multi connections in propel. But we did not have any clue, we wanted only single connection.

As we know, patience always pays. Finally we found propel_link , however no where was mentioned about symfony integration, this is what we tried in our config,yml file:

#Propel ORM configurations
propel:
    database:
        connections:
            con1:
                adapter:   "%database_driver%"
                user:     "%database_user%"
                password: "%database_password%"
                dsn:      "%database_driver%:host=%database_host%;user=root;dbname=%database_name%;password=mysql;charset=%db_charset%"
    runtime:
        defaultConnection: con1
        connections:
            - con1
    generator:
        defaultConnection: con1
        connections:
           - con1

We had to give name to connection (con1 in our case) and had to mention that it is default connection. Finally our first command 

php app/console propel:database:create

executed and database was created.

And this is not good ending of story. My friend had existing database so he wanted to generate xml file from existing tables. So we read propel_existing_db and as given we tried running command :

php app/console propel:database:reverse "mysql:host=localhost;dbname=db;user=root;password=pwd"

and it never worked (probably only for us , thrown some error)

Before quitting, we simply tried to write connection name (like our soul felt to do so) which we gave in config.yml (con1), So tried 
php app/console propel:database:reverse con1


And finally it worked. With default configuration it created a folder named "generated-reverse-database" and a file "schema.xml" inside it (Ofcourse you can rename these by providing parameters to above command). Run

php app/console propel:database:reverse --help

and you will get to know all possible inout parameters.

So we were happy here and thought to generate model classes so that we can start work. We followed propel_build and ran following command :

php app/console propel:model:build 


and we encountered this exception :
No schema files were found (matching your schema fileset definition)
And after google sometime we reached this link propel_issue_schema and following it , we moved our schema.xml to Bundle/Resources/config/schema.xml

Now after running same build command :

Following exception came :

Please define a `package` attribute or a `namespace` attribute for schema `schema.xml`



Here we felt propel is guiding us with proper message in exception, so we did as it asked, added package name in <database> tag so that it applies to all tables as per documentation.

After adding package name, we ran again build command :

php app/console propel:model:build 

But to our surprise it started ignoring our schema file and thrown error :


No schema files were found (matching your schema fileset definition)

Now we could not understand what is exactly causing this, no much clue on internet even. If we remove package attribute from schema file it says "please define package or namespace", if we add package attribute, it started ignoring schema file. One thing was sure that it is able to read schema file from Bundle but second time it was expecting it somewhere else.


After digging into codebase via trace of exception, we realised it is looking for schema file inside cache directory of app folder. 

app/cache/dev/propel/schema_file_name.xml

(here dev is environment)

Now final solution we found was move schema.xml file to propel directory in env(dev/prod/test) inside cache.

And after this we were able to generate model classes with
php app/console propel:model:build 

If you still get error, make sure schema file is only at one position, i.e in your cache directory. Delete from your Resource directory in your bundle.

(One more weird solution we found to above problem, if you do not want to move schema file inside cache yourself, run generate schema command once and then move generated schema to Bundle/Resources/config and then run generate reverse schema command again, propel will automatically create a file name BundleName-schema.xml inside cache directory and you can run build model command -

php app/console propel:database:reverse con1

Now move generated schema.xml to Bundle/Resources/config/
 (Do not forget to add package/namespace attribute) and run

php app/console propel:database:reverse con1

again, propel will generate one file named BundleName-schema.xml in propel directory in cache. Do not forget to delete schema.xml file present in your Bundle/Resources/config

And finally,
php app/console propel:model:build 

Worked but with new welcoming exception :

  Invalid database name: no configured connection named `default`.  

It did not consume much time of ours, we tried replacing name which was default with connection name we had given in our config file under propel (in our case it was con1).

Finally it generated models as expected in given package attribute in file.

Now before using these generated models you need to run following command:
composer dump-autoload -o

P.S This might be very simply configuration to do,it is just some blockers we faced and thought to share, might help someone.


Wednesday, 15 October 2014

Serialization in Android

We use Java Serialization in our day to day activity for use cases like Sending Object Over Network, Save Object to a file, Saving user preferences in Object etc etc.

Note: We will not be learning about Java Serialization here, visit Serialization_Official to learn about same. I assume you have working knowledge of Serialization to proceed.

What is here so special about Serialization in Android. No doubt you can use serialization the same way you do in Java and deserialize it later on.

But point to remember here is Android application is client side code. Many tools are available in market to convert your dex files to java classes and then decompile your classes to java files.

To safeguard our logic/code from malicious programmers we do use some tools like proguard to obfuscate our code. Now these tools change Class names, variable names and assign some not readable names so that even if somebody gets your java files, either they are of no use OR very difficult to read.

Here comes the problematic part which we are interested in, Serialazation + Proguard. Now assume your class (some sound setting which user has personalised)  name is:

com.example.khanna.SoundSetting

Now during development you serialize and deserialize Object of SoundSetting class and it works perfectly fine.

Suddenly at production you start getting exceptions like ClasNotFoundException while deserializing and you start hitting your head WTF happened and those with prior experience in java Serialization start hitting serialVersionUID and in your next releases you find the same problem occurring sometime and working perfectly sometime.

Lets come to point, when we use tool like proguard, there are certain set of guidelines which these tools follows and convert our java files to some unreadable format. Say named java file "com.example.khanna.SoundSetting" to "com.example.khanna.ae"

Now when you serialize OR deserialize it, ae is the class name used by JVM.

Suppose you release your next version and if you are lucky enough that class name was named again "com.example.khanna.ae" and deserialize will work even after upgrade.

But usually if you have changed something in that package and which makes proguard guidelines to change your file name from "com.example.khanna.SoundSetting" to "com.example.khanna.bd"

Now before upgrade you serialize with ae but after upgrade ae does not exist OR even if it does, it is not the class which you are expecting.

Hope you understand problem !!

Solution to this problem is quite simple, either set your file in proguard settings not to change its name, so "SoundSetting" will always be "SoundSetting" even after obfuscation.
Or Use custom Serialization (readObject and writeObject) where you own the process and serialize and deserialize premitives, so your class name is not required.

happy coding :)


Thursday, 20 September 2012

Random Key Generator

Sometimes we do need some sort of random key , say for example :

* Sending some unique password / key for one time authentication
* Generating some random user name
* Generating one time password
* validate email / mobile number

and so on ...

So why to bother every time writing some code for generating random number. Here is solution :

Download Random Generator Jar

Just include this jar file and use utility functions :

Example :


package testing;

import com.affiance.yim.gaurav.random.RandomKeyGenerator;

public class Testing {
public static void main(String[] s) {
System.out.println(RandomKeyGenerator.getRandomAlbhabeticKey(10));
System.out.println(RandomKeyGenerator.getRandomAlphaNumericKey(10));
System.out.println(RandomKeyGenerator.getRandomNumericKey(10));
}
}


Functions take a parameter, length of key you want to generate.

Enjoy Coding !















keywords for SEO  : java j2ee random secret unique key password alphanumeric alphabetic numeric length

Monday, 2 July 2012

Android Emulator Networking


Android Networking Issues :

connect form host to emulator , connect from emulator to host machine , ping host from emulator , ping emulator from host , server running in emulator and connect from through host, server running in host machine and connect from emulator


One of the simplest (but time eater) scenario I have faced is networking between your Android emulator and your Host machine.
Two problems I have faced are :

1) Connect Emulator to a Server running in host machine
2) Connect Host Machine to Server running in emulator


Out of these two, second one became real headache for me. But atlast solution I found was so simple.

**********************************************************************


Solution 1  : Connect emulator to server running in host machine :

For emullator , IP address of host machine is 10.0.2.2

So you can use this IP to connect to your host machine, for example:

Let us assume a web application ""sample" is running at port 8084 in your host machine.

Type

http://10.0.2.2:8084/sample

and press enter, it will print your desired output.


**********************************************************************


Solution 2:

Connect Host machine to server running in emulator :

By default emulator IP is 10.0.2.15 , but problem you will be facing is you can not connect using this IP and even
you can not ping this IP.

So solution I found was port redirection, very simple to do :

Assume one instance of emulator is running

Steps:

i) open command prompt
ii) type " telnet localhost 5554 "  ans press enter  
iii)type " redir add tcp:fromPort:whichPort " and press enter

Step 3 here redirect your request, mean any request you will make using localhost:fromPort will deliver to emulator:toPort

iv) you can del redirection using command :

redir del tcp:fromPort

v) If you are working with udp, then use udp instead of tcp in command


Sunday, 1 July 2012

Java : Inheritance and Interfaces , A magic or what ?




In Java usually we see there are event listeners ( say OnClickListener, OnTouch, OnDataArrived  or any other ) , what we do is simply pass reference of our object to required method and it automatically calls
appropriate methods of our class based on events. Most of people think it as magic or do not think it at all. Now we are going to see after all how does it work !

All this thing is based on mainly two imoprtant properties of Java : Inheritance and Polymorphism.

To understand how the main stuff happens, you must have clear idea of these two properties. Let us dive into both one by one.

Inheritance :

Inheritance can simply be defined as inheriting properties of a class by another class. It is important to note we can inherit only  " public ,default and protected members " in same package and
only " public and protected members " in other packages. Take an example :

package first;               

public class Animal {
int defaultInt;
protected int protectedInt;
protected int age;

public void printAge(){
System.out.println("printing Animal's age");
}

public void animalSound(){
System.out.println("animal sound @@@@");
}

}


public class Dog extends Animal {

public void checkDefault( ) {

defaultInt = 9;                                                    // valid because Dog inhertis Animal and because of same package

}

public void checkProtected() {

protectedInt = 9;                                                            // valid because Dog inhertis Animal and because of same package


}

public void printAge(){
System.out.println("printing dog's age");
}


public void sound(){
System.out.println("bhow bhow");
}

}


***************************************************************************************

package second;
import first.Animal;

public class Cat  extends  Animal {


public void checkDefault( ) {

defaultInt = 9;                                                    // not valid because of different package

}

public void checkProtected() {

protectedInt = 9;                                                            // valid because Cat  inhertis Animal


}

public void printAge(){
System.out.println("printing cat's age");
}

public void sound(){
System.out.println("meaau meaau");
}

}



***************************************************************************************
Java allows us to define an object by :

ClassName object = new ClassName();

and

SuperClassName object = new SubClassName();                                    // valid , but we are restricting our object to call only methods and properties present in class SuperClassName

but

SubClassName object = new SuperClassName();                                    // invalid

***************************************************************************************



***************************************************************************************
***************************************************************************************

Now coming to Polymorphism :

Simplest Definition will be : one name , multiple behavior.

Like we can have more than one same name function in a class, only diefference we  make is between their parameters.

These functions are called overloaded functions.

But there is one more term called overriding, it come into existance during inheritance. (I am not gonna explain overriding in detail here)

Simply Overriding mean having same signature of a function in both superclass and subclass with rules specified by Java.

As we saw above Java allows us :

SuperClassName object = new SubClassName();

considering above Animal example:

Animal animal = new Cat();

but now we can not call any cat specific function, since our reference is through Animal. We are restricted to call only functions present in Animal.

i.e :   animal.sound()                              // it is invalid

            animal.printAge()                       // is valid

            animal.animalSound()                // is valid

as expected
            animal.animalSound() will print "animal sound @@@@"

            but what do you expect on calling :

            animal.printAge();                      // printing animal's age   ??

but here polymorphism comes into picture

and output is :   printing cat's age

it mean in Java at compile time we can call only those methods which are present in Reference class, but at runtime if Actual class of which object was initialized ( using new )
overrides function, Java calls overridden function.

And that is how EventListener works in Java.

As you might have noticed almost all EventListeners are interfaces which incorporates some abstract functions that you might be interested if that event happens. So what actually happens is when we implement any
such interfacewe do implement all those functions. and I assume you are familiar with following term:

 ( YourClass impements OnClickListener )

button.setOnClickListener(this);              // assuming you are having any button in your class and want to know when its click event happens, this way you register your class and binds

Now have you ever wondered what magic happens at the other end (In Button class) , how button class knows about your object and passes proper events to your implemented function

Answer is polymorphism that we saw just in above example (Animal)

In Button class , It do nor need your object but it needs OnClickListener Object and since your class is implementing the same, so it becomes the required

Now in Button Class any whenever event happens, it just simply calls

clickListener.onEvent();

and due to polymorphism, your class function gets called.


Any question , you can email me at : khannasahab.gaurav@gmail.com

**********************************************************************************

Thursday, 12 April 2012

Java bypass proxy with code

Setting proxy in / with java code

As We normally use httpconenction class for url connection. Sometimes it can create problem, specially
when you are working in a System in which internet is blocked by any proxy. So you have to authenticate yourself by giving username and password .

Before your credentials you need to tell JVM which proxy you have and it is running on which port. This can be accomplished by following two lines.

   System.setProperty("http.proxyHost", PROXY);
            System.setProperty("http.proxyPort", PROXY_PORT);

Now we need to authenticate ourselves which can be done by using simple one line code given below :

            Authenticator.setDefault(new MyAuthenticator());

Here MyAuthenticator is authenticator class used to authenticate user, username and password, just
overide getPasswordAuthentication() function, i.e :


public class MyAuthenticator extends Authenticator {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {

        return new PasswordAuthentication("UserName", "Password".toCharArray());
    }
}


Copy and paste above Authenticator class in your project and replace username and password with yours.

                     Note:  Do all above task before making your URLConnection

Java Client http / https connection

Hi,

If you are facing as simple problem as hitting an URL through java code and getting response back, you are at right place. It is damn simple. Just follow steps given below :

1 ) Include myclient.jar file in your project.  click here to download jar file

2) Make an object of ClientURLConnection.

3) Pass URL you want to hit.

3) Set method you want to send request (GET or POST)

4) Add parameters (key-value pair) , if any you want to send along with request.

5) Call method yourObject.getInputStream()

And it is done !! Now do not waste time here and complete your task :)