RSS

My Maven Experience


Maven for beginners

Maven in general

 

 

Installing Maven

Brief about How to Install maven for using through command prompt?

  1. M2_HOME : C:\Maven-3.0.3
  2. MAVEN_OPTS (Optional) : -Xmx512m -Xms256m

 

How to install Maven for Eclipse?


How to customize maven usage for Eclipse?

  • Download maven from http://maven.apache.org/download.html
  • Unzip the folder and copy the unzipped folder to your preferred location say (C:\Maven-3.0.3)
  • From Eclipse Go to

    Windows – Perferences –

    Maven – Installation

    • Click on Add – Navigate to Extracted Maven directory (C:\Maven-3.0.3)
  • Edit the C:\Maven-3.0.3\conf\settings.xml

     

Steps to define and add M2_REPO classpath variable manually into Eclipse IDE:

  1. Eclipse IDE, menu bar
  2. Select Window > Preferences
  3. Select Java > Build Path > Classpath Variables
  4. Click on the new button > defined a new M2_REPO variable and point it to your local Maven repository and your done.

About Maven

Apache Maven is a software project management and comprehension tool (Tool to make developer comfortable with development environment quickly). Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information.

Maven started in an attempt to standardize the way to build the projects, a clear definition of what the project consisted of, an easy way to publish project information and a way to share JARs across several projects.

 

Maven’s Objectives

Maven’s primary goal is to make a developer to familiar with the complete state of a development effort in the shortest period of time.

  • Making the build process easy: – By providing a lot of shielding from the detail about the underlying mechanisms.
  • Providing a uniform build system: – Maven allows a project to build using its project object model (POM) and a set of plug-in that are shared by all projects using Maven.
  • Providing quality project information.
    • Change log document created directly from source control
    • Cross referenced sources
    • Mailing lists
    • Dependency list
    • Unit test reports including coverage
  • Providing guidelines for best practices development.
  • Allowing transparent migration to new features.

What is Maven Not?

  • Maven is a site and documentation tool.
  • Maven extends Ant to let you download dependencies.
  • Maven is a set of reusable Ant scriptlets.

Maven Feature Summary

  1. Simple project setup that follows best practices – get a new project or module started in seconds
  2. Consistent usage across all projects means no ramp up time for new developers
  3. Superior dependency management including automatic updating, dependency closures (also known as transitive dependencies)
  4. Able to easily work with multiple projects at the same time
  5. A large and growing repository of libraries and metadata to use out of the box, and arrangements in place with the largest Open Source projects for real-time availability of their latest releases
  6. Extensible, with the ability to easily write plug-in in Java or scripting languages
  7. Instant access to new features with little or no extra configuration
  8. Ant tasks for dependency management and deployment outside of Maven
  9. Model based builds: Maven is able to build any number of projects into predefined output types such as a JAR, WAR, or distribution based on metadata about the project.
  10. Release management and distribution publication: Without much additional configuration, Maven will integrate with your source control system such as CVS and manage the release of a project based on a certain tag.
  11. Dependency management: Maven encourages the use of a central repository of JARs and other dependencies.

     

Maven Basic Principle “Convention over Configuration”

Convention over configuration is a simple concept. Systems, libraries, and frameworks should assume reasonable defaults. Without requiring unnecessary configuration, systems should “just work”.

Maven incorporates this concept by providing sensible default behavior for projects.

  • Source code is assumed to be in ${basedir}/src/main/java 
  • Resources are assumed to be in ${basedir}/src/main/resources.
  • Tests are assumed to be in ${basedir}/src/test,
  • Project is assumed to produce a JAR file
  • Maven assumes that you want the compile byte code to ${basedir}/target/classes and then create a distributable JAR file in ${basedir}/target

Maven’s strength comes from the fact that it is “opinionated”, it has a defined life-cycle and a set of common plug-in that know how to build and assemble software. If you follow the conventions, Maven will require almost zero effort – just put your source in the correct directory and Maven will take care of the rest.

Mavens Side Effect, Possible stoppers?

One side-effect of using systems that follow “convention over configuration” is that end-users might feel that they are forced to use a particular methodology or approach. While it is certainly true that Maven has some core opinions that shouldn’t be challenged, most of the defaults can be customized.

For example, the location of a project’s source code and resources can be customized, names of JAR files can be customized, and through the development of custom plug-in, almost any behavior can be tailored to your specific environment’s requirements. If you don’t care to follow convention, Maven will allow you to customize defaults in order to adapt to your specific requirements.

 

Maven terminologies

POM:
POM stands for “Project Object Model“. It is an XML representation of a Maven project held in a file named pom.xml.  (Located at root of project)

 

Super POM: All Maven project POMs extend the Super POM, which defines a set of defaults shared by all projects. This Super POM is a part of the Maven installation and can be found in the maven-3.0.3-uber.jar file in ${M2_HOME}/lib.

 

Local Repository: Location on your computer where all dependencies are downloaded and stored

(C:\Users\USERNAME\.m2\)

 

M2_REPO: M2_REPO is just a normal “classpath variable” in Eclipse to find your local Maven repository.

 

archetype: Archetype is a Maven project templating toolkit. An archetype is defined as an original pattern or model from which all other things of the same kind are made.

 

goal: A goal is a task in Maven terminology. Usually, goals are specified as an argument to Maven on the command line, but there are some default goals that may be called by other goals. Goals are typically available from installed plug-in.

 

groupId:artifactId:version are all required fields. The three fields act much like an address and timestamp in one. This marks a specific place in a repository, acting like a coordinate system for Maven projects.

groupId: This is generally unique amongst an organization or a project.The dots are replaced by OS specific directory separators (such as ‘/’ in Unix) which becomes a relative directory structure from the base repository. In the example given, the org.codehaus.mojo group lives within the directory $M2_REPO/org/codehaus/mojo.

 

artifactId: The artifactId is generally the name that the project is known by. In the case of the above project, my-project lives in $M2_REPO/org/codehaus/mojo/my-project.

 

version: This is the last piece of the naming puzzle. groupId:artifactId denote a single project but they cannot delineate which incarnation of that project we are talking about.

 

packaging: Defines Package type of output eg. Jar,War,POM,SWC,Swf

 

Snapshots: Project version under development means “work in progress”

Dependency: Libraries required to build or run project are called as “dependencies” inside Maven.

Plugin: POM
tag to add module of functionality to add/customize features for project

Important Commands to Use maven effectively

  1. To Download Dependency: Goto Project directory from command prompt

mvn dependency:copy-dependencies -DoutputDirectory=./libs

  1. To clean Build : Goto Project directory from command prompt

mvn clean install

  1. To install third party Libraries

     

    mvn install:install-file -Dfile=(Full location of Jar file)C:\install\tsdb-1.0.0.jar

    -DartifactId=(Name of the package holding jar)tsdb -Dversion=(Version of Jar)1.0.0

    -DgroupId=net.opentsdb -Dpackaging=jar

     

  2. To remove the repository cached updates (-U)

    mvn clean install –U

     

  3. To run test cases

    mvn test

     

  4. To Skip the test while building the Application use

    mvn clean install -DskipTests=true

     

  5. To list active profiles

    mvn help:active-profiles

     

  6. To generate output for certain environment configured by profile use

    mvn install -Denvironment.type=dev

     

  7. How to use help for maven

    mvn –help

     

  8. To remove POM related errors from eclipse run

    mvn eclipse:eclipse

  9. Command to configure eclipe workspace for maven

mvn -Declipse.workspace="your Eclipse Workspace" eclipse:configure-workspace

 

 

Understanding Maven is nothing but the understanding the POM

 

What is the POM?

POM stands for “Project Object Model“. It is an XML representation of a Maven project held in a file named pom.xml.  It is a one-stop-shop for all things concerning the project. In fact, in the Maven world, a project need not contain any code at all, merely a pom.xml.

What does POM do?

The POM tells Maven what sort of project it is dealing with and how to modify default behavior to generate output from source. In the same way a Java web application has a web.xm that describes, configures, and customizes the application, a Maven project is defined by the presence of a pom.xml. It is a descriptive declaration of a project for Maven; it is the figurative “map” that Maven needs to understand what it is looking at when it builds your project.

You could also think of the pom.xml as analogous to a Makefile or an Ant build.xml.

This is How the POM is structured in four layers J


The POM contains four categories of description and configuration:

 

General project information

This includes a project’s name, the URL for a project, the sponsoring organization, and a list of developers and contributors along with the license for a project.

 

Build settings

In this section, we customize the behavior of the default Maven build. We can change the location of source and tests, we can add new plugins, we can attach plugin goals to the lifecycle, and we can customize the site generation parameters.

Build environment

The build environment consists of profiles that can be activated for use in different environments. For example, during development you may want to deploy to a development server, whereas in production you want to deploy to a production server

POM relationships

A project rarely stands alone; it depends on other projects, inherits POM settings from parent projects, defines its own coordinates, and may include submodules

POM Basics

As we know POM contains all necessary information about a project, as well as configurations of plugins to be used during the build process. 

POM is, effectively, the declarative manifestation of the “who”, “what”, and “where”.

And the build lifecycle is the “when” and “how”

 

<project xmlns="http://maven.apache.org/POM/4.0.0"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

                      http://maven.apache.org/xsd/maven-4.0.0.xsd">

    

    <modelVersion>4.0.0</modelVersion>

 

    <groupId>org.codehaus.mojo</groupId>

    <artifactId>my-project</artifactId>

    <version>1.0</version>

    <packaging>war</packaging>

 

</project>
				

 

Maven Coordinates

 

groupId:artifactId:version are all required fields. The three fields act much like an address and timestamp in one. This marks a specific place in a repository, acting like a coordinate system for Maven projects.

groupId: This is generally unique amongst an organization or a project. In the example given, the org.codehaus.mojo group lives within the directory $M2_REPO/org/codehaus/mojo

artifactId: The artifactId is generally the name that the project is known by. In the case of the above project, my-project lives in $M2_REPO/org/codehaus/mojo/my-project.

version: version of project

packaging: Defines Package type of output eg. Jar,War,POM,SWC,Swf

classifier: The classifier allows to distinguish artifacts that were built from the same POM but differ in their content. It is some optional and arbitrary string that – if present – is appended to the artifact name just after the version number. (Build is for JDK 1.4 or JDK 1.5)

Projects are displayed as groupId:artifactId:packaging:classifier:version.

 

 

We can have different types of POM’s

  1. The Super POM

All Maven project POMs extend the Super POM, which defines a set of defaults shared by all projects. This Super POM is a part of the Maven installation and can be found in the maven-3.0.3-uber.jar file in ${M2_HOME}/lib.


Figure 3.2. The Super POM is always the base Parent

  1. The Simplest POM

Do not have Maven project, Start with simple pom with default packaging as jar that will result

target/simple-project-1.jar

<project>

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.sonatype.mavenbook.ch08</groupId>

    <artifactId>simplest-project</artifactId>

    <version>1</version>

</project>

  1. The Effective POM

     

    $ mvn help:effective-pom
    

 

Executing the effective-pom goal should print out an XML document capturing the merge between the Super POM and the POM from Simplest POM

 

  1. Real POMs

 

Maven is something of a chameleon (Changeable, Customizable); you can pick and choose the features you want to take advantage of. The POM satisfying your project need will be the real POM for you.POM Relationships

Project may have different relationship with each other

  • dependencies (and transitive dependencies),
  • inheritance,
  • aggregation (multi-module projects).

Maven solves :

“Jarmageddon” : quickly ensues as the dependency tree becomes large and complicated. 

“Jar Hell” : follows, where versions of dependencies on one system are not equivalent to versions as those developed with, either by the wrong version given, or conflicting versions between similarly named jars

 

Jar Dependency, swc dependency,swf dependency,POM dependency

 

The cornerstone of the POM is its dependency list. Most every project depends upon others to build and run correctly, and if all Maven does for you is manage this list for you, you have gained a lot. Maven downloads and links the dependencies for you on compilation and other goals that require them. As an added bonus, 

Transitive dependencies : - Maven brings in the dependencies of those dependencies , allowing your list to focus solely on the dependencies your project requires

 

For a project may depend upon a jar that has a closed-source license which prevents it from being in a central repository. There are few methods for dealing with this scenario.

  1. Install the dependency locally using the install plugin. The method is the simplest recommended method. For example:
  2. mvn install:install-file -Dfile=non-maven-proj.jar -DgroupId=some.group -DartifactId=non-maven-proj -Dversion=1 -Dpackaging=jar

    Notice that an address is still required, only this time you use the command line and the install plugin will create a POM for you with the given address.

  3. Create your own repository and deploy it there. This is a favorite method for companies with an intranet and need to be able to keep everyone in synch. There is a Maven goal called deploy:deploy-file which is similar to the install:install-file goal (read the plugin’s goal page for more information).
  4. Set the dependency scope to system and define a systemPath. This is not recommended, however, but leads us to explaining the following elements:

 

Basic Level POM with Dependency:

<project ….>

    

    <modelVersion>4.0.0</modelVersion>

 

    <groupId>org.codehaus.mojo</groupId>

    <artifactId>my-project</artifactId>

    <version>1.0</version>

    <packaging>war</packaging>

 

<dependencies>

 

       <dependency>

      <groupId>org.apache.maven</groupId>

      <artifactId>maven-embedder</artifactId>

      <version>2.0</version>

      <type>jar</type>

      <scope>test</scope>

      <optional>true</optional>

 

      <exclusions>

        <exclusion>

          <groupId>org.apache.maven</groupId>

          <artifactId>maven-core</artifactId>

        </exclusion>

      </exclusions>

      </dependency>

 

 </dependencies>

</project>

 

  • type: Corresponds to the dependant artifact’s packaging type. This defaults to jar.  
  • scope: This element refers to the classpath of the task at hand (compiling and runtime, testing, etc.) as well as how to limit the transitivity of a dependency. There are five scopes available:
    • compile – this is the default scope, used if none is specified. Compile dependencies are available in all classpaths.
    • provided – this is much like compile, but indicates you expect the JDK or a container to provide it at runtime. It is only available on the compilation and test classpath, and is not transitive.
    • runtime – this scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.
    • test – this scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.
    • system – this scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.
  • systemPath: is used only if the dependency scope is system. Otherwise, the build will fail if this element is set. The path must be absolute, so it is recommended to use a property to specify the machine-specific path (more on properties below), such as ${java.home}/lib.
  • optional:
    Marks optional a dependency when this project itself is a dependency. Confused? For example, imagine a project A that depends upon project B to compile a portion of code that may not be used at runtime, then we may have no need for project B for all project. So if project X adds project A as its own dependency, then Maven will not need to install project B at all. Symbolically, if => represents a required dependency, and –> represents optional, although A=>B may be the case when building A X=>A–>B would be the case when building X.

Exclusions

Exclusions explicitly tell Maven that you don’t want to include the specified project that is a dependency of this dependency

  • exclusions: Exclusions contain one or more exclusion elements, each containing a groupId and artifactId denoting a dependency to exclude. Unlike optional, which may or may not be installed and used, exclusions actively remove themselves from the dependency tree.

Dependency Management in Inheriting POM

dependencyManagement: is used by POMs to help manage dependency information across all of its children. If the my-parent project uses dependencyManagement to define a dependency on junit:junit:4.0, then POMs inheriting from this one can set their dependency giving the groupId=junit and artifactId=junit only, then Maven will fill in the version set by the parent. The benefits of this method are obvious. Dependency details can be set in one central location, which will propagate to all inheriting POMs.

  1. Inheritance in project with POM

The packaging type required to be pom for parent and aggregation (multi-module) projects. These types define the goals bound to a set of lifecycle stages. For example, if packaging is jar, then the package phase will execute the jar:jar goal. If the packaging is pom, the goal executed will be site:attach-descriptor. Now we may add values to the parent POM, which will be inherited by its children. The elements in the parent POM that are inherited by its children are:

  • dependencies
  • developers and contributors
  • Roles
  • Plugin lists
  • Reports lists
  • Plugin executions with matching ids
  • Plugin configuration

 

 

Sample Parent POM can be as follows

<project ….>

  <modelVersion>4.0.0</modelVersion>

 

  <groupId>org.codehaus.mojo</groupId>

  <artifactId>my-parent</artifactId>

  <version>2.0</version>

  <packaging>pom</packaging>

</project>

Inherited Children POM

<project  …..>

  <modelVersion>4.0.0</modelVersion>

 

  <parent>

    <groupId>org.codehaus.mojo</groupId>

    <artifactId>my-parent</artifactId>

    <version>2.0</version>

    <relativePath>../my-parent</relativePath>

  </parent>

 

  <artifactId>my-project</artifactId>

</project>

A project with modules is known as a multimodule, or aggregator project. Modules are projects that this POM lists, and are executed as a group. Maven will topologically sort the modules such that dependencies are always build before dependent modules.

 

<project xmlns="http://maven.apache.org/POM/4.0.0"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

                      http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

 

  <groupId>org.codehaus.mojo</groupId>

  <artifactId>my-parent</artifactId>

  <version>2.0</version>

  <packaging>pom</packaging>

 

  <modules>

    <module>my-project</module>

    <module>another-project</module>

  </modules>

</project>

 

Build Profiles

Profiles can encourage build portability. If your build needs subtle customizations to work on different platforms or if you need your build to produce different results for different target platforms, project profiles increase build portability.

Control Environment specific builds (Development environment, Production environment)

One of the core motivations for Maven project profiles was to provide for environment-specific configuration settings. In a development environment, you might want to produce bytecode with debug information and you might want to configure your system to use a development database instance. In a production environment you might want to produce a signed JAR and configure the system to use a production database.

<profiles>  ------1

        <profile>

            <id>development</id> ------------2

            <activation>

                <activeByDefault>true</activeByDefault>

                <property>

                    <name>environment.type</name>

                    <value>dev</value>

                </property>

            </activation>

            <properties>

                <database.user>development_user</database.user>

                <database.password>development_password</database.password>

            </properties>

        </profile>

        <profile>

            <id>production</id>

 

        <build> ------------3

            <plugins>

               <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-compiler-plugin</artifactId>

                <configuration>

                    <debug>false</debug> ---------4

                    <optimize>true</optimize>

                </configuration>

                </plugin>

            </plugins>

        </build>

            <activation>

                <property>

                    <name>environment.type</name>


					<value>prod</value>

                </property>

            </activation>

            <properties>

                <database.user>prod_user</database.user>

            </properties>

        </profile>

    </profiles>

 

 

To Clean Install for particular profile

mvn install -Denvironment.type=dev    (prod)

TO list all active profiles

mvn help:active-profile

 

1. The profiles element is in the pom.xml, it contains one or more profile elements. Since profiles override the default settings in a pom.xml, the profiles element is usually listed as the last element in a pom.xml.

2. Each profile has to have an id element. This id element contains the name which is used to invoke this profile from the command-line. A profile is invoked by passing the -P<profile_id> command-line argument to Maven.

3. A profile element can contain many of the elements which can appear under the project element of a POM XML Document. In this example, we’re overriding the behavior of the Compiler plugin and we have to override the plugin configuration which is normally enclosed in a build and a plugins element.

4. We’re overriding the configuration of the Maven Compiler plugin. We’re making sure that the bytecode produced by the production profile doesn’t contain debug information and that the bytecode has gone through the compiler’s optimization routines.

(NOTE: Sensitive data such as password for production should not be added to POM these shall be added to the setting file available in your installation folder as below)

<settings>

    <profiles>

        <profile>

            <activeByDefault>true</activeByDefault>

            <properties>

                <environment.type>prod</environment.type>

                <database.password>m1ss10nimp0ss1bl3</database.password>

            </properties>

        </profile>

    </profiles>

</settings>

 

How to use Environment and Properties inside POM?

Properties are the last required piece in understanding POM basics. Maven properties are value placeholder, like properties in Ant. Their values are accessible anywhere within a POM by using the notation ${X}, where X is the property. They come in five different styles:

  1. env.X: Prefixing a variable with “env.” will return the shell’s environment variable. For example, ${env.PATH} contains the PATH environment variable. Note: While environment variables themselves are case-insensitive on Windows, lookup of properties is case-sensitive. In other words, while the Windows shell returns the same value for %PATH% and %Path%, Maven distinguishes between ${env.PATH} and ${env.Path}. As of Maven 2.1.0, the names of environment variables are normalized to all upper-case for the sake of reliability.
  2. project.x: A dot (.) notated path in the POM will contain the corresponding element’s value. For example: <project><version>1.0</version></project> is accessible via${project.version}.
  3. settings.x: A dot (.) notated path in the settings.xml will contain the corresponding element’s value. For example: <settings><offline>false</offline></settings> is accessible via ${settings.offline}.
  4. Java System Properties: All properties accessible via java.lang.System.getProperties() are available as POM properties, such as ${java.home}.
  5. x: Set within a <properties /> element. The value may be used as ${someVar}.

Maven Resources and references used to generate the document: –

Complete reference for Maven

http://books.sonatype.com/books/mvnref-book/reference/

How to download the latest version of maven?

http://maven.apache.org/download.html

How to install maven in my System?

http://maven.apache.org/download.html (Go to Section – Installation Instructions)

Where to get List of supported plug-in by maven

http://maven.apache.org/plugins/

Where can I get the list of Best Maven Articles?

http://maven.apache.org/articles.html (Go to section Articles on Maven)

Where to contribute new projects for maven repository?

http://maven.apache.org/repository/index.html

 

 
1 Comment

Posted by on October 5, 2012 in 1

 

From “Flex with Shashank” to “Tech Stack by Shashank”


Really astonishing,Amusing Technology, Best framework, Best RIA , Best of Charting, Superb integration with .net .Php,ColdFusion,Ruby on Rails and seamless integration with Java….wow

But Adobes Flex becoming Apache Flex may be best of the move,It certainly alarmed the things to make the mind for learning the new technologies and be more techie. So going ahead I am planning to get on with lots of new things, which I have evaluated during this time.

Probably plan of action for Flex Developer trying to add more skills

1. Decide Secondary skills i.e alternative strong technology for Flex i.e If Flex-Java is your technology stack Create your own things in Java and integrate them with Flex. Explore more Java and use less Flex

2. JFC Swing is good starting point to get hands on to Java things.

3. If You feel you don’t have a strong secondary technology to append to Flex,Sencha Ext JS is best alternative

http://jessewarden.com/2012/02/sencha-ext-js-is-viable-technology-choice-for-flex-developers.html

Jesse Warden explains it beautifully

4. Learn lots of new tools Ant , Maven

5. Try HTML5 , I guess its hard to digest

Please feel free to add more to list.

Finally bye bye to Tag line “Flex with Shashank” now it will be “Tech Stack by Shashank

Note: I surly don’t mean close the Flex , I still feel it is strong enough, Will be becoming more stronger. I am still moving strongly with Flex development  and will be doing lots of flex in near future too”

Best Luck,

Thanks and Regards,

Shashank Kulkarni,

Feel free to comment on the post🙂

 
Leave a comment

Posted by on May 3, 2012 in 1

 

Tags:

Unrecognized Windows Sockets error: 0: JVM_Bind Flex, the workaround


Ohoooo , Its again the unsolved one, Sadly a page to Flex(Amazing Errors).

Its been happening with Flex Builder on my  machine mostly when i tried to do the debug of my code and it simply  stops my working (i.e. it only disables my debugging functionality) , sometimes till i restart my machine.

Error I am getting: ” Unrecognized Windows Sockets error: 0: JVM_Bind “

My Environment Details is :

Windows 7

Flex Builder (Eclipse Plug-in ) ( Flex Builder 3)

JBoss server running inside the Flex Builder environment

Workarounds i tried most of the time are :

  • Switching the Server mode to debug, sometimes help.
  • Closing all the Java instances apart from my Flex Builder sometimes helps.

If both of above does not work , Solution is “Leave with the Pain of debugger functionality unavailability”

But to me the query is that what the hell is happening with my Flex Builder?

Adobe forums are with no help about this topic, with the two query seems to be unresolved on the forums. I haven’t found any definite solution on it. If u have one please don’t forget to comment it, It will be great help

http://forums.adobe.com/message/15429

http://forums.adobe.com/thread/682171

It certainly is not the happy coding way with the above scenario, I really feel Adobe needs to address this one.

Any links, comments or suggestions  are highly welcomed

Best Luck.

Thanks and regards,

Shashank Kulkarni

Feel free to comment on the post :)

 
4 Comments

Posted by on August 21, 2010 in Flex(Amazing Errors)

 

Validating if the url exists or not on Client side with FLEX


Yup, Quite interesting isn’t it ?

Mission: Validate URL Existance on client side.

Expected Result: Anyhow create POC of a code with the efforts to check the possibility of verifying URL existence from Flex i.e. from client side only.

Result: . I think i managed to crack it with a simple solution, When code not deployed works very smooth and gives result as expected.

On Local Environment Without server deployment of code

Result is great !

But at last Buck Stops at “Security Sandbox Error” when we deployed it on to the server.

Path Followed:

Knowing flash.net package : The flash.net package contains classes for sending and receiving from the network, such as URL downloading and Flash Remoting.

http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/net/package-detail.html

Understand HTTP response status meanings

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

With Some 2-3 days reading i just went on to build one example with URL existence verification application.

If Somebody is intrested to solve this puzzle, take the below code.

Project Hierarchy:

src-assets-HttpCodes.xml

src-ValidateURL.mxml

Lets Walk Through the code, I am sure the written code is pretty simple to understand so wont be elaborating it.

Code for “ValidateURL.mxml


<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:net="flash.net.*"
layout="absolute"
creationComplete="httpIOError.send();">

<mx:Script>
<![CDATA[

import mx.controls.Alert;
import mx.utils.ObjectUtil;
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import flash.net.*;

private var httpCode:int;

private var errorCodesAC:ArrayCollection = new ArrayCollection();

private function loadURL():void
{
var urlReq:URLRequest = new URLRequest('http://'+ urlString.text);
urlStream.load(urlReq);
}

private function checkUrl(e:HTTPStatusEvent):void
{
httpCode=e.status;
}

private function ioErrorHandler(e:IOErrorEvent):void
{
for(var i:int=0;i<errorCodesAC.length;i++)
{
if(httpCode==errorCodesAC[i].number)
{
responseText.text = "Status Code: "+httpCode.toString() + "\nError Details: \n"+errorCodesAC[i].details;
}
}
}

private function returnSuccess(e:Event):void
{
responseText.text = "Status Code: "+httpCode.toString() + "\nURL is valid."
}

private function securityErrorHandler(e:SecurityErrorEvent):void
{
Alert.show(ObjectUtil.toString(e),"Security Error Details");
}

private function faultHandler(e:FaultEvent):void
{
Alert.show(ObjectUtil.toString(e));
}

private function resultHandler(e:ResultEvent):void
{
errorCodesAC = e.result.HttpStatus.statusCodes.statusCode
}

]]>
</mx:Script>

<mx:HTTPService id="httpIOError" url="assets/HttpCodes.xml" result="resultHandler(event)" fault="faultHandler(event)"/>

<net:URLStream  id="urlStream"  complete="returnSuccess(event)" httpStatus="checkUrl(event)"
ioError="ioErrorHandler(event)" securityError="securityErrorHandler(event)" />

<mx:Label x="135" y="30" text="Enter Url to be validated:"/>
<mx:Button x="321" y="84" label="Check URL" click="loadURL()"/>
<mx:TextInput id="urlString"  x="288" y="28"/>
<mx:Text x="288" y="58" text="eg: www.shashankkulkarni.wordpress.com"/>
<mx:TextArea  id="responseText" x="135" y="133" height="93" width="414" editable="false" wordWrap="true"/>
<mx:Label x="135" y="107" text="Response Description:"/>
</mx:Application>

 “HttpCodes.xml” is as below


<HttpStatus>

<statusCodes>

<statusCode number="400">
<details>
Unable to understand request.[Bad Request]
</details>
</statusCode>

<statusCode number="401">
<details>
User authentication required. [Unauthorized Request]
</details>
</statusCode>

<statusCode number="403">
<details>
Server refuses the response. [Forbidden Request]
</details>
</statusCode>

<statusCode number="404">
<details>
Page Not Found. [Page Not Found ]
</details>
</statusCode>

<statusCode number="407">
<details>
Proxy Authentication required. [Proxy Authentication]
</details>
</statusCode>

<statusCode number="408">
<details>
Request failed to reach server within specified time. [Request Timeout]
</details>
</statusCode>

<statusCode number="500">
<details>
Unexpected condition occured. [Internal Server Error]
</details>
</statusCode>

<statusCode number="501">
<details>
Functionality required is not supported. [Functionality not supported]
</details>
</statusCode>

<statusCode number="502">
<details>
Invalid response received by server. [Bad Gateway]
</details>
</statusCode>

<statusCode number="503">
<details>
Service is not available temporarily.[Service Unavailable]
</details>
</statusCode>

<statusCode number="504">
<details>
Timely response not received. [Gateway Timeout]
</details>
</statusCode>

<statusCode number="0">
<details>
Input stream is not well Formatted [IOError]
</details>
</statusCode>

<statusCode number="200">
<details>
Yes! This URL exists. [Success]
</details>
</statusCode>

</statusCodes>

</HttpStatus>

I gone through details of Sandbox Security restriction with Flash player ( http://www.adobe.com/devnet/flashplayer/articles/flash_player_9_security.pdf ) but unfortunatly could not solve it to success,  i really feel this should have been done from Flex itself.

I would have been happy to see it working, But I guess some more understanding is needed on my part. I am still finding the missing things.

There must be some way to DO it ???? Still searching the answer, If some body finds it… Just ping it down here. I will be glad to resolve it.

Any suggestions are welcomed.

Best Luck & Happy coding :)

Thanks and regards

Shashank Kulkarni

Feel free to comment on the post :)

 
 

Could not resolve to a component implementation… Simple solution steps


Just installed Adobe Flash Builder 4 Plug-in to my Eclipse installation at different location but amusingly My Existing Flex 3.4 SDK  stops working after first restart of Eclipse. IT started foul crying “Could not resolve <mx:AdvancedDataGrid> to a component implementation. ”  and I was stuck…..  I restarted my Flex Builder but no Luck ,Then  on doing some Googling I just went to Adobe Site for Flex 3 Release notes at  http://www.adobe.com/support/documentation/en/flex/3/releasenotes_flex3_sdk.html which says,

Using The Data Visualization Components with Flex SDK

“A new version of the data visualization libraries needs to be downloaded and installed into the SDK 3 installation to leverage features such as charts and the Advanced DataGrid”

It just gave me a direction that somehow my Existing Eclipse based Flex 3.4 SDK has lost two library files namely

1. “datavisualization.swc”

Location:  C:\Program Files\Adobe\Flex Builder 3 Plug-in\sdks\3.4.0.9271\frameworks\libs

2.  “datavisualization_rb.swc”

Location :

C:\Program Files\Adobe\Flex Builder 3 Plug-in\sdks\3.4.0.9271\frameworks\locale\en_US

(Note: Please refer your native installation path)

The library can be downloaded from the main Flex download page:
http://www.adobe.com/products/flex/flexdownloads/

Steps to Resolve:

  1. Goto C:\Program Files\Adobe\Flex Builder 3 Plug-in\sdks\3.4.0.9271\frameworks\libs and check for “datavisualization.swc”
  2. Goto

C:\Program Files\Adobe\Flex Builder 3 Plug-in\sdks\3.4.0.9271\frameworks\locale\en_US

Check for “datavisualization_rb.swc”

3. Download these from http://www.adobe.com/cfusion/entitlement/index.cfm?e=flex3sdk

Which is located under heading “ ADOBE FLEX 3.5 DATA VISUALIZATION COMPONENTS FOR FLEX BUILDER

Unzip ‘datavisualization_SDK3.5.zip’ which will extract SDK 3 installation

  • datavisualization.swc into the frameworks\libs folder
  • the datavisualization RSL into the frameworks\rsls folder
  • datavisualization_rb.swc into the appropriate frameworks\locale\<locale> folder

Now get those SWC and place to your installation location

If it Still not work try to toggle between SDK s from Project Properties – Flex Compiler option and Restart your installation.

Hope it will work out for you ! If still does not work just drop a comment to resolve

Best Luck & Happy coding🙂

Thanks and regards

Shashank Kulkarni

Feel free to comment on the post🙂

 
2 Comments

Posted by on July 16, 2010 in Flex(Amazing Errors)

 

How Clone() method works and Why to Write it?


Small round up to Events basic, I think that is important 🙂

As we know “Event” class is used as the base class for the creation of Event objects, which are passed as parameters to event listeners when an event occurs. So to make avail the Event Object and its properties we always extends Event

Basically in Event class(flash.events.Event class) there is one method called as clone()

How clone() method works?
clone() method duplicates an instance of an Event subclass. Returns a new Event object that is a copy of the original instance of the Event object.

Why To write clone() method?

When creating your own custom Event class, we must override the inherited Event.clone() method in order for it to duplicate the properties of your custom class.

What if I don’t override clone() method?

This works fine if implementation doesn’t re-dispatch the event, but as soon as we re-dispatch the event (by calling dispatchEvent(event) in a handler that is handling event), we get a TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event@28ef5b1 to events.

Lets Produce the error🙂

Main Application Code

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*" creationComplete="onCreationComplete()">
	<mx:Script>
		<![CDATA[
			import events.DemoCloneImportance;
			import mx.controls.Alert;
			private function onCreationComplete():void
			{
				demoCloneDispatcher.addEventListener(DemoCloneImportance.CLONE_EVENT,cloneDemoHandler);
				this.addEventListener(DemoCloneImportance.CLONE_EVENT,cloneRedispatchHandler);
			}
			
			private function cloneDemoHandler(event:DemoCloneImportance):void
			{
				Alert.show('In Dispatch Handler');
				this.dispatchEvent(event);		
			}
			
			private function cloneRedispatchHandler(event:DemoCloneImportance):void
			{
				Alert.show('In Redispatcher Handler');
			}
			
		]]>
	</mx:Script>

	<local:CloneInvokerComponent id="demoCloneDispatcher"/>
	
</mx:Application>

Component Class is as follows:


<?xml version="1.0" encoding="utf-8"?>
<!--CloneInvokerComponent.mxml-->
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">
	<mx:Script>
		<![CDATA[
			import events.DemoCloneImportance;
		]]>
	</mx:Script>
<mx:Metadata>
	[Event(name="CloneEventDemo", type="events.DemoCloneImportance")]
</mx:Metadata>
	<mx:Button label="Dispatch Event" id="btnDispatch" click="dispatchEvent(new DemoCloneImportance(DemoCloneImportance.CLONE_EVENT,true))"/>
</mx:VBox>

Wrong Implementation of Event Class, (Without overriding clone() method )Must avoid it🙂

package event
{
import flash.events.Event;

public class DemoCloneImportance extends Event
{
public function DemoCloneImportance(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}

public static const CLONE_EVENT:String = 'CloneEventDemo'		// Override the inherited clone() method.

}

}

Run the Application and we get Runtime error (Visible if Flash Debugger installed)

Now To Resolve it make Custom Event class implementation right🙂

package event
{
import flash.events.Event;

public class DemoCloneImportance extends Event
{
public function DemoCloneImportance(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}

public static const CLONE_EVENT:String = 'CloneEventDemo'		// Override the inherited clone() method.

override public function clone():Event {
return new DemoCloneImportance(type, true,false);
}

}

}

This is something very basic but i think most important also🙂

Best Luck & Happy coding🙂

Thanks and regards

Shashank Kulkarni

Feel free to comment on the post :)

 
9 Comments

Posted by on March 30, 2010 in Flex(Amazing Errors)

 

Flex application not working without debug version of Flash Player


Recently, I was having a requirement to develop the Flex Log management functionality. After doing lots of research and investing a time for 3 to four days I successfully managed the things to achieve the flex logging Mechanism which can log Line Number, Function Name, Class name into log File.

After delivering the functionality I was happy that I have done it  Its really a nice feeling. I was hoping for appreciation but result was bit different I have received a clients mail saying that on some of the machines Flex app not working without debug version of Flash Player , It was really an Head scratching experience when application just stopped running with a white background in screen with clock display.  I was quite surprised that application which were running perfectly well on my PC, wasn’t displayed properly on some of the PCs.

Hmm.. No Clues at all. I must say Adobe Sometimes handles such situation in very ugly, and with very unprofessional manner, its a horrible handling of such situation by Adobe Flex Framework Developers must criticized them for such things.

After lots of efforts and lots of revision to the newly added code, after doing everything finally the application showed up on one of the problematic machine when I changed the Flash Player version from standard one to debug.

Scenario and Solution

I was using following code

//Call To The Function traceDetails(new Error())

private function traceDetails(err:Error):void { err.getStackTrace(); } On My part i was using the method “getStackTrace()” Here the thing to remember is that getStackTrace() method is only available with Flash Debugger and Not With Flash player. So wherever i do not have Flash Debugger installed my application stops running.

So Things to do

1. Check if You’re using any API call that are only available in Flash Debugger and Not in Flash player (If You found Try commenting that line Application will start running).

2. Solutions may be Install Flash Debugger Version wherever you are running your application but not feasible considering end user because your application is not loaded successfully and you cannot prompt user.

3. In wrapper class put a check with JavaScript for Flash Debugger version availability and if it is not available through JavaScript Message Saying you need to have flash layer Debugger version installed along with link to install it J

4. Simply before your Flash Debugger API calls Check if(Capabilities.isDebugger) only then use those API or Skip those lines.

I am sure this will solve many peoples problem.

Following thread discussed the same problem

http://stackoverflow.com/questions/1137223/flex-app-not-working-without-debug-version-of-flash-player

Another Example how developer suffer due to some mismanaged framework things

http://stackoverflow.com/questions/867788/compile-flex-application-without-debug-optimisation-options-for-flex-compiler

Best Luck & Happy coding🙂

Thanks and regards

Shashank Kulkarni

Feel free to comment on the post :)

 
3 Comments

Posted by on August 27, 2009 in Flex(Amazing Errors)

 

Tags: , , , , , ,