Wednesday, September 14, 2016

Show alertdialog from a service in Android




Use this code segment in your service

AlertDialog alertDialog;     
  AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getBaseContext());

    alertBuilder.setTitle("New Approvals Alert")
                       .setMessage("You have " + jObj.length() + " new transactions for your approvals")
                       .setCancelable(false)
                       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                });
                        

alertDialog = alertBuilder.create();
                                      alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();

Add this permission to your AndroidManifest.xml

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

 

Get more from  : http://techprogramme.com/

Monday, June 20, 2016

RESTful Web Services(JAX-RS) in JavaEE with IntelliJ IDEA

What Are RESTful Web Services?

RESTful web services are built to work best on the Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.

Create a new JavaEE Web Module 

File - New Project - Select JavaEE Web Module 




In the IntelliJ IDEA, the RESTful Web Services development is based on the Java EE: RESTful Web Services (JAX-RS) plugin. Usually this plugin is bundled with IntelliJ IDEA and enabled by default.
To check whether plugin is enable or not go to Setting Dialog (Ctrl+Alt+S), from the left hand side select Plugins, After that type restful in the search box and check whether Java EE: RESTful Web Services (JAX-RS) is selected. if it's not make sure to enable that.

To add JAX-RS to the project right click on the project and click on Add Framework Support and put a tick to Restful Web Service element and make sure to select Download option to download the required libraries, and press OK



After that again right click on the project and click Open Module Settings - Go to libraries and click on the Change Version button and select jax-rs-jersey-1.12 and click OK. In the latest Jersey library HttpServerFactory class is not included but in this example we are using that class to create the server therefor we need to change the version in to jax-rs-jersey-1.12.



Now lets create the Restful Server

First Create a Class called CompanyDetails and modify it as below, This class we are using as a Data Model to return a details object.

/**
 * Created by easywayforcoadings on 6/20/16.
 */
public class CompanyDetails {

    private String welcomeMessage;
    private String companyName;
    private String companyAddress;
    private Integer companyPhone;

    public String getWelcomeMessage() {
        return welcomeMessage;
    }

    public void setWelcomeMessage(String welcomeMessage) {
        this.welcomeMessage = welcomeMessage;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getCompanyAddress() {
        return companyAddress;
    }

    public void setCompanyAddress(String companyAddress) {
        this.companyAddress = companyAddress;
    }

    public int getCompanyPhone() {
        return companyPhone;
    }

    public void setCompanyPhone(int companyPhone) {
        this.companyPhone = companyPhone;
    }
}


Create a new Class Called RestServer and change it as below Code Segment. This is the class we are going to use as the Server.

/**
 * Created by easywayforcoadings on 6/20/16.
 */

import com.sun.net.httpserver.HttpServer;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;

@Path("/company_service/{username}")
public class RestServer {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public CompanyDetails getCompanyDetails(@PathParam("username") String userName) {

        CompanyDetails companyDetails = new CompanyDetails();
        companyDetails.setWelcomeMessage("Hello "+userName);
        companyDetails.setCompanyName("MY COMPANY PVT");
        companyDetails.setCompanyAddress("No. 111/1, MY ADDRESS");
        companyDetails.setCompanyPhone(123456789);
        return companyDetails;
    }

    public static void main(String[] args) throws IOException {

        HttpServer server = HttpServerFactory.create("http://localhost:9998/");
        server.start();

        System.out.println("Server running");
        System.out.println("Visit: http://localhost:9998/company_service/[userName]'");
        System.out.println("Hit return to stop...");
        System.in.read();
        System.out.println("Stopping server");
        server.stop(0);
        System.out.println("Server stopped");
    }
}

After that Save All, right click on the RestServer Class and click on Run 'RestServer.Main()' to start the server

Open the browser and check whether service is working or not via this address 

http://localhost:9998/company_service/easywayforcoadings123


Stop the server and lets create a Client to access our Restful Service

In the same project create a new Class called RestClient and change it as below 

/**
 * Created by easywayforcoadings on 6/20/16.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RestClient {

    public static void main(String[] argv) {

        try {

            URL url = new URL("http://localhost:9998/company_service/easywayforcoadings123");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Json Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }

            conn.disconnect();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }


    }
}

Save All and Right click on the RestServer to start the server first by clicking on Run 'RestServer.Main()' and finally right click on the RestClient and click on Run 'RestClient .Main()'


Output Result -:



Get more from  : http://techprogramme.com/



Wednesday, May 25, 2016

Factory Pattern With Reflection



An important aspect of software design is the manner in which objects are created, although far more time is often spent considering the object model and object interaction. But if this simple design (of object creation) aspect is ignored, it will adversely impact the entire system. Thus, it is not only important what an object does or what it models, but also in what manner it was created. 
Factory pattern is one of the most widely used pattern for these kind of situations. In this article lets see how to use Factory pattern with Reflection.  

What is Reflection ? 

Reflection provides objects (of type Type) that describe assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them. 

Example -: 

int
 i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

Output -: System.Int32


Factory pattern without Reflection

------------------- IFruit Interface (IFruit.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    interface IFruit
    {
        string Name { get; }

        void eatMe();

        void donEatMe();
    }
}

------------------- Apple Class(Apple.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Apple: IFruit
    {

        public string Name
        {
            get { return "I am an Apple"; }
        }

        public void eatMe()
        {
            Console.WriteLine("Apple -: Eat me, I'm very delicious");
        }

        public void donEatMe()
        {
            Console.WriteLine("Apple -: Don't eat me, I'm not a good fruit");
        }
    }
}


------------------- Orange Class(Orange.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Orange : IFruit
    {
        public string Name
        {
            get { return "I am an Orange"; }
        }

        public void eatMe()
        {
            Console.WriteLine("Orange -: Eat me, I'm very delicious");
        }

        public void donEatMe()
        {
            Console.WriteLine("Orange -: Don't eat me, I'm not a good fruit");
        }
    }
}

------------------- Kiwi Class(Kiwi.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Kiwi : IFruit
    {
        public string Name
        {
            get { return "I am a Kiwi"; }
        }

        public void eatMe()
        {
            Console.WriteLine("Kiwi -: Eat me, I'm very delicious");
        }

        public void donEatMe()
        {
            Console.WriteLine("Kiwi -: Don't eat me, I'm not a good fruit");
        }
    }
}


------------------- NoFruit Class(NoFruit.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class NoFruit:IFruit
    {
        public string Name
        {
            get { return "I am not a Fruit"; }
        }

        public void eatMe()
        {
            Console.WriteLine("You can't eat me");
        }

        public void donEatMe()
        {
            Console.WriteLine("You can't eat me");
        }
    }
}



------------------- FruitFactory Class(FruitFactory.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class FruitFactory
    {
        public static IFruit getFruit(string fruitName)
        {
            switch (fruitName)
            {
                case "Orange":
                    return new Orange();
                 
                case "Apple":
                    return new Apple();
               
                case "Kiwi":
                    return new Kiwi();
             
                default:
                    return new NoFruit();
                 
            }

        }
    }
}


------------------- Program Class(Program.cs) ---------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            IFruit myFruit = FruitFactory.getFruit("Orange");
            Console.WriteLine(myFruit.Name);
            myFruit.eatMe();          

            Console.ReadLine();
        }
    }
}


Factory pattern with Reflection

Change FruitFactory.cs and Program.cs Classes as below


------------------- FruitFactory Class(FruitFactory.cs) ---------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class FruitFactory
    {
         Dictionary<string, Type> cars;

         public FruitFactory()
        {
            TypesToReturn();
        }

        public IFruit CreateInstance(string carName)
        {
            Type t = TypeToCreate(carName);

            if (t == null)
            {
                return new NoFruit();
            }
            else
            {
                return Activator.CreateInstance(t) as IFruit;
            }
        }

        public Type TypeToCreate(string carName)
        {
            foreach (var car in cars)
            {
                if (car.Key.Contains(carName.ToUpper()))
                {
                    return cars[car.Key];
                }
            }
            return null;
        }

        public void TypesToReturn()
        {
            cars = new Dictionary<string, Type>();

            Type[] typesInCurrentAssembly = Assembly.GetExecutingAssembly().GetTypes();

            foreach (Type type in typesInCurrentAssembly)
            {
                if(type.GetInterface(typeof(IFruit).ToString()) != null)
                {
                    cars.Add(type.Name.ToUpper(), type);
                }
            }
        }
    }
}


------------------- Program Class(Program.cs) ---------------------

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            FruitFactory fruitFactory = new FruitFactory();

            IFruit myfruit = fruitFactory.CreateInstance("Orange");

            Console.WriteLine(myfruit.Name);
            myfruit.eatMe();
            //myfruit.donEatMe();

            Console.ReadLine();

        }
    }
}











Monday, April 25, 2016

Constructor Dependency Injection Pattern With C#



Dependency Injection (DI) is a design pattern that demonstrates how to create loosely coupled classes. The term "loosely coupled" deserves clarification and sometimes the best way to explain something is by first describing its opposite, which in this case is "tight coupling." When two classes are tightly coupled, they are linked with a binary association. For example, you can see in the below code, Calculate and ErrorHandler, that are joined together as an aggregation. 

Without Constructor Dependency Injection Pattern 

create an interface IErrorHandler which has one method to show the Error occurred. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    public interface IErrorHandler
    {
        void showError(string erroMessage);
    }

}

Next create a class called ErrorHandler, which inherits the IErrorHandler interface and implement it's showError method, which we are going to use to show the Error message. 


using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    class ErrorHandler : IErrorHandler
    {
     
        public void showError(string erroMessage)
        {
            Console.WriteLine(erroMessage);
        }
      
    }
}

Now lets create a another class called Calculate to understand the concept of tight coupling. 



using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    public class Calculate
    {
        IErrorHandler errorHandler = new ErrorHandler();
        public void calcValues()
        {
          
            try
            {
                int no1 = 20;
                int no2 = 0;
                int total = no1 / no2;
                Console.WriteLine("Result is : " + total.ToString());
            }
            catch (DivideByZeroException ex)
            {
                errorHandler.showError("Can't Divide Value By 0");
            }


        }
    }
}

Above class has an interface IErrorHandler instance which reference the ErrorHandler class. because of this the Calculate class is tightly coupled with the ErrorHandler class. 

Now lets call the calcValues method from main class.



using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Calculate calculate = new Calculate();
            calculate.calcValues();        

            Console.ReadLine();
        }
    }
}

this will show the below output, but as you can see this is not a good design because of tightly coupled.


With Constructor Dependency Injection Pattern 

The basic idea of constructor-injection is that the object has no defaults or single constructor; instead specified values are required at the time of creation to instantiate the object. In other words Constructor injection uses parameters to inject dependencies.

Advantages
  • Construction Injection makes a strong dependency contract
  • Construction Injection supports testing, because dependencies can be passed in the constructor.
  • A dependency may be made immutable by making the dependency reference final by means that it prevents circular dependency.
Disadvantages
  • It requires up front wiring of the entire dependency graph.
The class that needs the Dependency must be exposing a public constructor that takes dependent class as constructor argument. In most cases, this should be the only one available constructor but if more than one Dependency is required then additional constructor arguments can be used.


Now lets create a CalculationEvent, That class has a parameter constructor. This constructor will be used to inject dependencies in the object. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    public class CalculationEvent
    {
        IErrorHandler errorHandler;

        public CalculationEvent(IErrorHandler errorHandler)
        { 
            this.errorHandler = errorHandler;        
        }

        public void PerformCalculation()
        {
             try
            {
                int no1 = 20;
                int no2 = 0;
                int total = no1 / no2;
                Console.WriteLine("Result is : " + total.ToString());
            }
            catch (DivideByZeroException ex)
            {
                errorHandler.showError("Can't Divide Value By 0");
            }
        }
    }
}

you can see that the CalculationEvent class is not depend on any other class. 


using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjectionApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            CalculationEvent calculationEvent = new CalculationEvent(new ErrorHandler());
            calculationEvent.PerformCalculation();

            Console.ReadLine();
        }
    }
}