Category: Architecture & Developing

Android SDK Tips

Little simple things where I lost some time finding out the resolution when developing for Android.

Emulator with PANIC error:

PANIC: Could not open: C:\Users\

This error happens all the time in windows environment. The most cause is because your username has some non-english characters like “éáç…”, and Android SDK uses your home folder in the operating system as a default to create the emulators.

Possible solution:

make a copy of the avd folder and configure the ini file to point to the new folder.

  1. Go to the emulator folder (for instance: c:\users\usernamewithnonenglishlike-áéíç\.android\avd\)
  2. Copy the “avd” folder to another folder without non-english characters (c:\myAvds\…")
    1. Don’t remove the original
  3. In the original folder open the “init” file: (for instance: c:\users\usernamewithnonenglishlike-á\.android\avd\AVD_for_2_7in_QVGA.ini)
  4. Change the path value to the new folder:
    1. path=newFolderWithoutNonEnglishCharacters\avd\AVD_for_2_7in_QVGA.avd
  5. Start the emulator, it must work now!

PS: Another way is creating manually the AVD and place it in a custom folder:

 

Associate the resource layout (xml file) with the Activity java class:

In the activity java file just add a line to link to the resource file.

Create your resource file or “design file” at res\layout\your_resource.xml

    1. use only lowercase characters combined with numbers and “_”
  1. In the Activity Java Class, in the “onCreate” method, use “setContentView(R.layout.your_resource) like the code below.











 

 

 

Can’t configure Android SDK in IntelliJ 12 when creating a new project

Intellij doesn’t have configured any jdk, so we must configure at least one!

  1. Create the project without the Android SDK configured.
  2. Add some jdk (1.5, 1.6, 1.7) in File->Project Structure
  3. Then choose Android SDK for your project!

 

 

Singleton Pattern without explicit “if” and initialization!

One of the most elegant features of Java are the anonymous initializers! They came in two flavors, static and instance. These kind of initializers are anonymous because they are run by the JVM, at “load byte code” time for static initializers, and at “construction time” for the instance initializer.

The Singleton pattern its very easy to implement, we just have to hide the default constructor (writing it as private) and create a way to call it, usually using a public static method which verifies with a local field if it has already created an instance or not. If so, then ignores the creation, else it creates the instance and returns it. With this, we have only one instance possible in all the application.

Well, with static initializer you don’t need to verify the construction of the object, lets give this job to the JVM at load time! The static anonymous block runs when the JVM loads the class, which is the perfect time to create the instance! After this initialization, when calling any method of this class we are certain the instance already exists and we don’t have to develop any “if” to verify that.

An example of a very simple singleton below.

 

 

There are other ways to create the object without using the “if” (sometimes called lazy instantiation), like declaring the static field with an instance of the class:

but this solution doesn’t allowing me (in a elegant way) to run any other code at “load byte time”, so I really prefer the “static initializer way”.

Shared or Static – Visual Basic vs Java?

MP900386814 In Java there are 2 fundamental concepts that any developer should know: instances and classes. Class its the base of your code, your specification about an entity, like Account, Customer or Supplier. Instance its what you get after a “new ” (an object in the heap). So you have at maximum 1 class and N instances of that class.

Although a class its just the specification, in Java a class could have state and behavior like an instance, but with the condition “There could be only one” shared for all instances! Everything that are declared as static are executed(static blocks for instance)/initialized at class load time by the JVM, the rest (instances) are executed/initialized in runtime, after load time.

This word, static comes from very long time, since C, C++, C# and others, but Visual Basic uses other word “shared which somehow implies the behavior of the fields declared as static(java) or shared(visual basic) after a Class “is running”! After the JVM has loaded your class, every static(java) field are shared(visual basic) between all instances, so the question is:

What of these words captures better this behavior (of static) “static” vs “shared”?

So, although I really like a lot languages like C++, Java and C#, I must admit Visual Basic its somehow more expressive and more closely related with the true meaning of “shared” fields!

The not so ACID transaction properties

If you work with Database Servers you know that ACID its not implemented/active by default! And if you have it implemented you have a really poor performance on your database server!

Lets examine each one of these properties:

A = Atomicity

Definition by wikipedia: “Atomicity requires that each transaction is “all or nothing”: if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged. An atomic system must guarantee atomicity in each and every situation, including power failures, errors, and crashes.

WRONG!

– “… and the database state is left unchanged“. Unless you configure your database server with ISOLATION LEVEL SERIALIZABLE this is not true. By default most SGBD are configured with Read Commited, with allows some changes like phantom reads.

C = Consistency

Definition by wikipedia: “The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written to the database must be valid according to all defined rules, including but not limited to constraintscascadestriggers, and any combination thereof.”

RIGHT for schema state, WRONG for value state (explained in atomicity above)

I = Isolation

Definition by wikipedia: “The isolation property ensures that the concurrent execution of transactions results in a system state that could have been obtained if transactions are executed serially, i.e. one after the other. Each transaction has to execute in total isolation i.e. if T1 and T2 are being executed concurrently then both of them should remain unaware of each other’s presence

WRONG! Only in dreams! its possible, yes, but in the way you encounter DEADLOCKS and Poor performance. If you want a performance database server you must drop the isolation to the lowest level possible! Its the price to pay for having fewer locks in the middle of your transactions.

D = Durability

Definition by wikipedia: “Durability means that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors. In a relational database, for instance, once a group of SQL statements execute, the results need to be stored permanently (even if the database crashes immediately thereafter).”

RIGHT! Well, I give this one, and I’m glad I could, what was a database server without it! 😉 However, actual high performant database servers have some kind of memory cache where there is a risk of loosing data, but, as far as my knowledge goes, it only happens in some NoSql databases… I hope…

 

 

 

What I dont like about Java Application Servers

I have a lot of experience with Java Application Servers, from Weblogic to jBoss 5,6,7 and Glassfish. I’m a Java and J2EE Trainer too. So, I’m not here to make an argument against the use of Java Application Servers, I use them every day, however I must say some things that I really dont understand (from a user/developer perspective) about Java Application Servers:

Why Java Application Servers don’t isolate a deployed application? How many times are you deploying an application and you have to configure, customize, remove jars, add another’s jars, create additional files just because the application server already has some of the jars you use in your application? For instance, in my team, we are migrating sites and web services from weblogic and its a nightmare, jboss already have some of the jars, and at deployment time throws exceptions that are not so easy to understand at first sight. (like logging jars – in our case slf4g with logback) If an application could be isolated like a file system application its isolated in an operating system like linux or MAC OS these problems dont even existed! I just wanted to deploy my application with the jars I need, and don’t think about what jars the application already have.

I have experienced deploying applications in Microsoft IIS and in Java application servers. Using Microsoft Servers its much more easy than using similar java products. Usually, when starting and developing Microsoft products I spend 80% of the time focused in developing and  testing the product, and the other 20% finishing configuring and deployment. With Java Application Servers, first you must study the application server, know about several XML files with specific names, to configure datasources, jms queues, etc. Then you hope that exists some eclipse plugin or netbeans plugin that really works. I have experienced plugins for weblogic and jboss but sometimes when you deploy an application its just a view for your eyes, the application doesnt get really deployed to the application server, so I have to go to the localhost website, and deploy it. The inverse its also true. So, 80% configuring and preparing, learning and training and the rest 20% of time developing.

Don’t get me wrong, my experience its divided between these two worlds (Microsoft and Java), I like Java, after all the configuration its done everything will work as expected, but its a really tough job to put everything to work at first in Java Application Servers World!

 

Do you know ForkJoinPool Java 7?

Java 7 brings and/or improves thread management to handle heavy and complex tasks.

You can use threads, ExecutorServices and this: ForkJoinPool.

There is an increasing developers movement to coding in a functional state of mind, using Ruby, Scala, Clojure and other similar programming languages. Java 8 will follow this path too, with lambdas. If you are not using a functional approach in programming, I invite you to do so, its a very different way of thinking where the “divide to conquer” its a must!

In Java 7 you can use this way of thinking to resolve complicated problems, the ones where its necessary to think recursively where you can split a heavy task in simples ones, like when you are sorting a big list using quick sort, transverse a file system including every folder and file, etc. These are problems that seems complicated at first, but thinking recursively it turns out to be very simple tasks.

The main algorithm to implement a recursively task its always something like:

  1. What is the stop condition? (Here you return a “real” value)
  2. Call the method recursively calling it itself with some sort of improvement in the parameters, like if you are in a for.. loop.

For instance, long factorial(long n)

  1. stop condition: if( n <= 1) return 1;
  2. calling recursively like a loop: return n * factorial(n-1)

Has you know by now, the factorial(n-1) will have to stop in the future, because n-1 its decreasing until it reaches  n <= 1, and then n * will be really calculated!

 

In Java 7 you have a Class ForkJoinPool that automatically handle threads to execute the smaller tasks like the above: n and  factorial(n-1).

The recursively method will always be the protected Long compute(), which must be an @override because the class will extend: RecursiveTask, where will be the return value of the compute method!

In the example below, I have implemented a very simple example to calculate the sum between 2 numbers, using recursive smaller tasks.

I start with some range, if the stop condition (end – start), its below 10, then I return the sum between the start and end, otherwise I split the range in 2 parts, the first one executes concurrently (using fork witch puts the thread in the ForkJoinPool) the second half of (end – start) and the first one computes the sum delegating its execution to the compute method (itself!), or the other half.

Observe the last return: return t2.compute() + t1.join(); where the second thread calls the compute and then waits for the fork previously executed as the first thread!


 

I think the code its very clear and simple, if you have questions or comments don’t hesitate to post them!

This Is a very useful tool to resolve complex problems that I really invite you to learn and use it!

jBoss 7 – Web service client – popular exception “definitions”

In the process of migrating some J2EE Applications from Weblogic to jBoss 7 I’ve been found several issues that puts the popular java statement “Write once run everywhere” in cause. I will not start here any discussion about this, if the cause its j2ee, jboss, weblogic, axis, although you are free to do it so, and I will have arguments pro and con, but it was not so smooth as I was expecting it to be.

One of the last errors that toke me some time to figure it out, and I found the solution by intuition trial and error was when I had to generate a web service client for a jBoss j2ee appilcation that works great in weblogic but in jboss throws the following error when calling a web service:

… several stack trace lines but the main one:

… at some point in the stack trace

Caused by: javax.wsdl.WSDLException: WSDLException (at /html): faultCode=INVALID_WSDL: Expected element ‘{http://schemas.xmlsoap.org/wsdl/}definitions’.

So, I’ve tried every possible solution, from generating different kinds of web service clients, using Axis, jboss, CFX, to changing Jaxb versions on eclipse facets to 2.0, 2.1, 2.2.

About the solution:

In the construction of the web service call

MyWebService_Service service1 = MyWebService_Service(new URL(wsdl));
MyWebService port1 = service1.getMyWebServicePort();

 

In Weblogic a possible URL could be passed on the web service class constructor as :

– “http://10.192.33.93:8080/app/webservice

But In jBoss, the URL must use the “?wsdl” at the end of the url! like this:

– “http://10.192.33.93:8080/app/webservice?wsdl

 

I dont know why, maybe when I have time I can discover the reason, but for know it was the solution I’ve found for this kind of exception that apparently its a popular problem around forums.

Hope my solution can help you anyway, or if you find another reason for this exception, be my guest to put it on the comments area!

Java Blocks–Advanced–Part 1

Following a previous post I will deep into the discussion about anonymous blocks mixed with static variables.

Lets see a simple example, and then we will complicate a little bit.

public class TestStaticInitializer {

{
System.out.println(“block 1”);
}

public TestStaticInitializer() {
System.out.println(“static x = ” + x);
}

private static int staticInitialization() {

System.out.println(“static initialization of x”);

return 5;
}

{
System.out.println(“block 2”);
}

static int x = staticInitialization();

public static void main(String[] args) {

System.out.println(“static main block before calling the constructor”);

TestStaticInitializer test = new TestStaticInitializer();

System.out.println(“static main block after constructor”);
}

{
System.out.println(“block 3”);
}

}

You can observe that:
– There is a static variable ‘x’ that its initialized calling a static method.
– There are 3 anonymous blocks.
– The constructor calls the static variable.

The main method references the class.

At first sight we can think the anonymous blocks are called in sequence, which it’s true. Although if there is a static variable initialized in anyway, this initialization runs before any anonymous block.(Why? Because a class is loaded in 2 phases: load class, run class. At load the JVM after some verification, initialized every static variable and runs any static anonymous initializer, and only after runs the class, or our instance.)

You can observe this by looking to the execution output:

static initialization of x
static main block before calling the constructor
block 1
block 2
block 3
static x = 5
static main block after constructor

The anonynous blocks are executed by sequence, but the initialization variable “static initialization of x” runs first, although its declaration is after “block 2”.

The sequence is:

1 – Initialize the static variable x

2 – run main method

3 – initialize the class (because I’m calling the constructor)

4 – run anonymous blocks

5 – runs the constructor (only after the static blocks)

6 – runs the other “main” statements.

 

You must be wondering why I underlined “The main method references the class” above.

Lets see if I remove (I will just comment it) the call to the class constructor.

public class TestStaticInitializer {

{
System.out.println(“static block 1”);
}

public TestStaticInitializer() {
System.out.println(“static x = ” + x);
}

private static int staticInitialization() {

System.out.println(“static initialization of x”);

return 5;
}

{
System.out.println(“static block 2”);
}

static int x = staticInitialization();

public static void main(String[] args) {

System.out.println(“static main block before calling the constructor”);

//TestStaticInitializer test = new TestStaticInitializer();

System.out.println(“static main block after constructor”);
}

{
System.out.println(“static block 3”);
}

}

 

and the output is:

static initialization of x
static main block before calling the constructor
static main block after constructor

 

Well, where are the anonymous blocks initializers? Thet are not needed! We haven’t crated any instance of the class, so the JVM just considered the static stuff!

And if a static block references the static variable x?

public class TestStaticInitializer {

{
System.out.println(“block 1”);
x = 7;
System.out.println(“block 1 after x = 7”);
    }

public TestStaticInitializer() {
System.out.println(“static x = ” + x);
}

private static int staticInitialization() {

System.out.println(“static initialization of x”);

return 5;
}

{
System.out.println(“block 2”);
}

static int x = staticInitialization();

public static void main(String[] args) {

System.out.println(“static main block before calling the constructor”);

//TestStaticInitializer test = new TestStaticInitializer();

System.out.println(“static main block after constructor”);
System.out.println(“x = ” + x);
    }

{
System.out.println(“block 3”);
}

}

The output:

static initialization of x
static main block before calling the constructor
static main block after constructor
x = 5

The initialization of “x = 7” in the first anonymous block is simple ignored, because the code was never ran!

static int x;// = staticInitialization();

The output will show you “x = 0”.

 

I hope this post will help you understand the mix between anonymous and static initialization blocks. In a future post I will bring some class hierarchy to this discussion.

 

Anonymous Java Classes and Interfaces

In java you can use Anonymous Classes and Anonymous Interfaces.

Anonymous classes

class MyMessage {
    public void printMessage() {
        System.out.println("Original message");
    }
}

public class TestAnonymousClass {

    public static void main(String[] args) {
        TestAnonymousClass tac = new TestAnonymousClass();

        MyMessage m = new MyMessage();
        m.printMessage();
       
        tac.showGeneralMessage(new MyMessage() {
            public void printMessage() {
                System.out.println("Override message");
            }
        }
);
    }

    void showGeneralMessage(MyMessage msg) {
        msg.printMessage();
    }
}

The Bold source shows how to create the anonymous class. As you can see it’s not so anonymous as we expected, it’s just the name that is anonymous.

In anonymous classes the only think we can do it’s to instantiate an existing class, and override or add some methods.  What are we really doing is extending another class(in our example we are extending “MyMessage”) with the possibility to override or add new methods.

If you run the code above the output will be:

Original message

Override message

 

Anonymous Classes with interfaces

interface MyMessage {
    void printMessage();
}

public class TestAnonymousClass {

    public static void main(String[] args) {
        TestAnonymousClass tac = new TestAnonymousClass();

        tac.showGeneralMessage(new MyMessage() {
            public void printMessage() {
                System.out.println("Override message");
            }
        }
);
    }

    void showGeneralMessage(MyMessage msg) {
        msg.printMessage();
    }
}

Now with interfaces, you can observe that the syntax it’s the same, but we are creating a class by “implementing” the interface MyMessage.

Look that I only changed the MyMessage class to be and interface,  but the remaining code is still the same and works with the same behavior (ok, now the output doesn’t have the “Original Message”, because we don’t have one! We lost it when we changed the class to be an interface.)

Hope it helps you in your projects, to implement callbacks, using swing components to register listeners, etc..

Technorati Tags: ,,,

Windows Live Tags: Anonymous,Java,Classes,Interfaces

WordPress Tags: Anonymous,Java,Classes,Interfaces

Java Initialization Blocks

Java has some features that are not well know from a lot of Java Developers, even developers with 5 and 10 years of Java Experience.As a Oracle/Java trainer I must study all of them to teach my students and prepare them well for the Java Certification.

One of these bot well know features are java Initialization blocks. One of these are blocks runs before the JVM runs any code (at class loader level) and the other one runs at constructor time.

Lets see an example and an explanation:

Instance Block
class MyClass {
    private int x;
    {
         x = 7;
         System.out.println(“This is called inside constructor, just after super(…)”);
     }

     public MyClass() {
         System.out.println(“the constructor”);
     }
}
Static Block
class MyClass {
    private int x;
    public static int y;
    static { 
        y = 7; // y must be static!
        System.out.println(“This is called by class loader before your program runs!”);
        // x = 5; it’s illegal because this is class context and not instance context
    }

    public MyClass() {
        System.out.println(“the constructor”);
    }
}

 

So, there are 2 types of code initialization blocks:

Instance

When we talk about instances we talk about objects, something that was already created and has memory allocated.

The instance code block is executed right after the call to super in any constructor called.

It’s a way to initialize variables in all constructors without write code in any of them, which it’s a great way to organize initialization code, too.

 

Static

Static context it’s called class context too. Everything that is static it’s only visible when we use de class name before the field, method or inner class. (ok, unless we use import static…)

When we talk about classes we are talking about the blueprint or definition of the object. This definition “runs” before the instance is created, so the static initialization block runs before the java interpreter and before any constructor called. So, who runs the static initialization blocks? The class loader of the Java Virtual Machine.

This is the place to initialize ONLY static variables, because they are the only ones that are visible at this time and in this context.

In the future I will post more about not so know java features.

 

Technorati Tags: ,,,,,,,,,
Windows Live Tags: Java,Initialization,Blocks,Instance,Static,constructor,initialize,variables,context,class
WordPress Tags: Java,Initialization,Blocks,Instance,Static,constructor,initialize,variables,context,class

Bad Behavior has blocked 113 access attempts in the last 7 days.

Hyper Smash