Blog for Software and Technology
  • Blog
  • About
  • Contact

TUTORIAL ALERT: CHAIN OF RESPONSIBILITY PATTERN WITH JAVA

1/20/2022

0 Comments

 
Picture
​In a java outsourcing company, developers design their code efficiently to make it more reliable with the help of design methodologies. In this article, you will learn about the chain of responsibility pattern used by professionals to make the code more reliable.

Introduction
​
In Java, to make the code more reliable we should design our code efficiently which can be done by applying design methodologies such as OOPs, OOAD, design principles, and patterns into applications.
 
Chain of Responsibility pattern is a behavioral design pattern that actually makes the code lose coupling. It decouples the sender of the request to the receiver, where the chain of objects are there to process the request and the request used to starts or process with the first object in the chain, it proceeds if that object has the solution otherwise the request is forwarded to next object in the chain in order to handle or process that request. This chaining will happen until finding the solution object is in the chain.
 
GOF states that – it “Gives more than one object an opportunity to handle a request by linking receiving objects together.”
Picture

Handler – interface to handle the requests
 
Concrete Handler – A request handler that handles the request that they are responsible for, otherwise it sends the request to its successor.
 
Client – send the request to the handler to process the request. The first handler object in the chain would be invoked by the client.
 
Fore.g.
 
java.util.logging.Logger, javax.servlet.Filter are the examples that are followed by a chain of responsibility design pattern.
Let us take an example of Gmail, where we could see the mails are categorized as Primary, Social, and Promotion.
 
Social – Emails from Facebook, Twitter, Google plus are in the social category

Promotion – Emails from Paytm, Flipkart, Amazon offers are in the promotion category

Primary – Other emails from people and friends are companies are in the primary category

We can also have our own folder or category or rule for the basis of the incoming email on the subject, from, to, and all.
So, how could we do this in code with good design?

// Handler interface
 
public interface GmailHandler {
 
   public void setNext(GmailHandler gmailHandler); //to set next handler
 
   public void handleRequest(Email email); //to handle or process the emails
 
}
// Request object
 
public class Email {  
 
   private boolean is Social;
 
   private boolean is Promotion;
 
   private boolean is Primary;
 
   private Boolean is Spam;
 
   public boolean is Social() {
 
         return is Social;  // returns true when emails from facebook, twiiter, google plus
 
    }
 
  public boolean is Promotion() {
 
         return is Promotion; // returns true when emails from paytm, flipkart, amazon offers     
 
    }
 
  public boolean is Primary () {
 
        return is Primary; // returns true when emails not from social and shopping sites      
 
    }
 
   public boolean is Spam() {
 
         return is Spam;      
 
    }
 
   // more members and methods on content of email and other details
 
}
// Concrete Handler or Request Handler
 
public interface SocialEmaiHandler {
         
        private GmailHandler handler;

public void setNext(GmailHandler handler) {
 
        this.handler = handler;
 
   }
 
   public void handleRequest(Email email) {
 
         if(email.isSocial()) {
 
                    // proceeds or handles social email contents, keeps in social category
 
          } else {
 
                   handler.handleRequest(); // proceeding with next handler in the chain
 
          }
 
   }
 
}
// Concrete Handler or Request Handler
 
public interface PromotionEmailHandler {
 
   private GmailHandler handler;
 
   public void setNext(GmailHandler handler) {
 
        this.handler = handler;
 
   }
 
  public void handleRequest(Email email) {
 
         if(email.isPromotion()) {
 
                    // proceeds or handles promotion email contents, keeps in promotion category
 
          } else {
 
                   handler.handleRequest(); // proceeding with next handler in the chain
 
          }
 
   }
 
}
// Concrete Handler or Request Handler
 
public interface PrimaryEmailHandler {
 
   private GmailHandler handler;
 
   public void setNext(GmailHandler handler) {
 
        this.handler = handler;
 
   }
 
   public void handleRequest(Email email) {
 
         if(email.isPrimary()) {
 
                    // proceeds or handles primary email contents, keeps in primary category
 
          } else {
 
                   handler.handleRequest(); // proceeding with next handler in the chain
 
          }
 
   }
 
}
// Client
 
public class EmailClient {
 
  private GmailHandler handler;
 
  public EmailClient() {
 
        createProcessChain();
 
  }
 
  public void addRule(GmailHandler handler){
 
       if(this.handler == null)
 
             this.handler = handler;
 
       else
 
                this.handler.setNext(handler);
 
  }
 
  public void sendRequest(Email email){
 
       this.handler.handleRequest(email);
 
  }
 
  public void createProcessChain() {
 
       addRule(new SocialEmailHandler());
 
       addRule(new PromotionEmailHandler());
 
       addRule(new PrimaryEmailHandler());      
 
  }
 
  public static void main(String[] aa){
 
      EmailClient client = new EmailClient();
 
      Email email = new Email();
 
      email.setIsPromotion(true);
 
      client.sendRequest(email);
 
      Email email = new Email();
 
      email.setIsPrimary(true);
 
      client.sendRequest(email);
 
      Email email = new Email();
 
      email.setIsSocial(true);
 
      client.sendRequest(email);
 
  }
 
}

Conclusion: 
​
Just think that, if we didn’t follow this chain of responsibility design pattern how would we achieve this solution? We would write if and else if block on each case or category!!?? If we do so, it creates an n-path complexity problem to our code and it is very difficult to change the code to adapt a new feature i.e. each time we have to rework with the implementation.

So, the Chain of responsibility pattern helps us to make the code loose coupling and easy to adopt a new feature i.e. if we want to add a new rule or category like spam to email simply we can add a new concrete handler called SpamEmailHandler that implements Handler interface and most importantly we are adding the feature to our code without touching the existing implementation.
 
As you now know that chain of responsibility is a behavioral design pattern used by Java outsourcing company professionals to design the code. Any point you did not get can be asked in comments.

Related Articles:
How to Use Spring Batch and Connect It to Database in Java Development?How To Benefit Out Of Mobile Responsive Java Application Development And Make It Big?
0 Comments

USE OF SPRING CLOUD STREAM IN JAVA

1/16/2022

2 Comments

 
Picture
Technology: Spring Cloud Stream is the framework for building message-driven applications using spring boot. It supplies a way to combine with other applications, without depending on other applications; it utilizes Spring Integration to communicate with other applications.
Spring cloud stream gives abstractions, primitives for a simple way to develop message-driven applications.


Application Model
:
Spring cloud stream contains middleware and application core. The application will communicate with the outside world using input/output channels that are introduced by the spring cloud stream.
Picture
Channels are combined to middleware using binders; spring cloud stream gives different binders for another middleware like Apache Kafka, RabbitMQ.

Binder Abstraction:
Applications individually choose to which middleware they want to connect, by default spring cloud stream is dependent on spring boot auto-configuration, if more than one binder is present on the class path then, using the application.properties or application.yml we need to provide the binder configurations, we can also choose binder at channel level also, means for one channel we can use Kafka middleware and for another channel we can choose RabbitMQ channel, etc.


Persist Publish Subscribe: Communication between applications will use a publish-subscribe model where data is shared among the all connected client. The below diagram shows a typical flow between applications.

Picture
Where data is coming from HTTP source will send to a spring cloud stream application endpoint and it will process the incoming data and it will publish the data to middleware, the connected applications to middleware will get the data. This model will reduce the complexity of the producer and consumer, allow the addition of new applications to middleware without disturbing of existing flow. By using middleware native support spring cloud stream simplifies our job in publishing the messages to different middleware applications.
​

Consumer Groups:The Publish subscribe provides the ability to scale up by creating multiple instances of the application. When multiple instances of the same application running we need to consume messages by only one of the instances of the application. Spring cloud stream implements this behavior by providing the group name for consumers so that only one of the instances per group will be handled. We can specify the group name in application.properties file:

spring.cloud.stream.bindings.<channelName>.group

Picture

All the groups subscribed to groups will receive a copy of published data, but only one of the group members will receive the message from the destination when the group is not specified spring cloud stream assigns an anonymous group and independent single-member consumer group along with other consumer groups.

Durability: The applications sent to consumer group y default are durable, the binder implementations ensure that they are persistent, once at least one subscription for a group has been created, the group will receive messages, even if they are sent while all applications in the group are stopped. We must specify the group name so that no duplicate messages will be handled again.
 
Programming Model: We can turn the spring application into a spring cloud stream by adding @EnableBinding on one of the application configuration files, this annotation is meta-annotated with @Configuration and it triggers the annotation of spring cloud stream.


@Configuration
 
@Import({ChannelBindingServiceConfiguration.class,
BindingBeansRegistrar.class,
BinderFactoryConfiguration.class,
 
SpelExpressionConverterConfiguration.class})
 
@EnableIntegration
 
public@interfaceEnableBinding {
 
       /**
 
        * A list of interfaces having methods annotated with {@link Input} and/or
 
        * {@link Output} to indicate bindable components.
 
        */
 
       Class<?>[] value() default {};
 
}


This remark will accept one or more than one example contains methods which represent the bind methods.

Creating binding interface: Spring cloud stream application can have any number of input, output channels clarified in an interface remarked with @Input, @output, and we require to pass this interface in @EnableBinding annotation, this will trigger the spring cloud stream and creates orders,hotDrinks,coldDrinks message channels.

public interface Hotel {
 
            @Input
 
            SubscribableChannelorders();
 
            @Output
 
            MessageChannelhotDrinks();
 
            @Output
 
            MessageChannelcoldDrinks();
 
}

Customizing the Channel names: 
We can customize the channel name using value attribute in Input, Output annotation.

public interface Hotel {
 
            @Input("inboundOrders")
 
            SubscribableChannelorders();
 
            ...
 
}


The generated bound channel will named Inbound Orders.

Spring cloud stream provides 3 interfaces for common use cases. 

Sink: It is interface used for single inbound channel.

Source: It is interface used for single outbound channel.

Processor: It is interface used for both single inbound/outbound channels. Spring cloud stream does not gives any special handling for these interfaces, they supplied only for reference.

Injecting interfaces into Spring Beans: Then methods clarified in interfaces given in @EnableBinding annotation will generate a channel based on its type (like input channel for @Input and output channel for @Output), and using methods in interfaces we can send/receive the messages.

Injecting Message Channels Directly: Instead of depending these interfaces we can also directly inject channels directly into beans.


@Component
 
public class SendingBean {
 
            privateMessageChannel output;
 
            @Autowired
 
            publicSendingBean(MessageChannel output) {
 
                        this.output = output;
 
            }
 
            public void sayHello(String name) {
 
                        output.send(MessageBuilder.withPayload(body).build());
 
            }
 
}


MessageChannel is injected with channel name output, we can also customize by passing channel name to MessageChannel.


Eg: @Output("customOutput")
 
MessageChanneloutput();


Spring cloud stream also supports spring-messaging and spring-integration annotations like @SendTo, @MessageMapping,@Transformer,@ServiceActivator etc.

Binders: Spring cloud stream gives Binder interface for connecting with various middleware suppliers.
The interface has bindProducer method to return the producer, the method has three arguments, and first argument take the channel name, and second argument is the channel instance to send the messages, third parameter points to channel extra properties.

The interface has bindConsumer method is to return the customer, the method has four arguments, first argument refers to destination name, and second argument refers to logical group name, third argument refers to channel instance to receive the message and four argument refers to extra customers properties.


public interface Binder<T, C extends ConsumerProperties, P extends ProducerProperties> {
 
Binding<T>bindConsumer(String name, String group, T inboundBindTarget, C consumerProperties);
 
Binding<T>bindProducer(String name, T outboundBindTarget, P producerProperties);
 
}

Specifying Properties for each channel:
We can also clarify properties for each channel like clarifying binder, binder configuration, content-type of the message, max-retries for each channel etc.
We can clarify channel properties using prefix in application.properties file.


spring.cloud.stream.bindings.<channelName>


List of properties assisted by channel specific are expose in BindingProperties.java file.
We can specify the manufacturer related properties using prefix spring.cloud.stream.bindings.

<channelName>.producer

Consumer properties using spring.cloud.stream.bindings.<channelName>.consumer prefix.

We can also specify the host details of binder using 

spring.cloud.stream.binders.<binding-name>.environment.spring.rabbitmq.host property.


Conclusion: Spring cloud stream is framework for growing stream based application in an simple way, which is used to expand application in flexible way(independent applications), we can lightly hosted on spring data flow servers, we can combine with different middleware applications using native middleware support. We can also identify the global configuration and also channel specific binder properties, and also if the application is hosted on cloud using cloud connectors we can identify the cloud instances of middleware applications.

You can download the producer and consumer of the applications using below github repositories.

https://github.com/sravan4rmhyd/Spring-Stream-RabbitMQ.git

Have you tried Spring Cloud Stream for java web development yet? Share your experience with the readers and let them know about this framework.

Related Articles:
How can you become a professional Java developer in 6 months?
​Boost your revenue by teaching cybersecurity skills to your staff.
2 Comments

How the upcoming Java Update would make Yahoo as your default search engine

7/7/2015

0 Comments

 
Are you prompted to upgrade Java software on your laptop or pcs? Read the info properly, or you might become a yahoo user unintentionally. You should know that Yahoo has signed a deal with Oracle to get into promotion stuff. It has started, in June and people are prompted to upgrade their Java version and asked if they wish to make Yahoo as a default search engine on Google Chrome. If the box remains checked by mistake, Chrome will set the Yahoo as a default search engine. It is the latest partnership by Yahoo to promote its services among users.
Picture
Picture
It is believed by the management that these deals will boost yahoo’s meager share of the search market. Java runs on billions of laptops and personal computers across the world including the 90% of PCs in the United States.

​Currently, Yahoo is focusing on the integration of its search product with the available third-party applications, using a software development kit that released earlier this year. Yahoo search service already integrated into Touch Pal. It’s a default keyboard app available on some Android smartphones.

No other information shared on the bulletin. You can keep yourself updated by staying tune with us. Look at this space for more related java development news. Do read our other articles and stories and share your reviews. Thanks for the visit.
The previous year in December, yahoo search engine set as default search service in Mozilla browser and replaced Google. This deal yields profits to the company, Mayer of the company disclose this info without giving further details. The company is also aiming to set its search browser as default in Apple’s Safari browser when the deal between Apple and Google gets over this year.
0 Comments

Why You Should Outsource Your Java Development Work

5/28/2015

6 Comments

 
The corporate world is getting more dependent on IT- the outsourcing software development practices have made an intense contribution to IT development and growth. More businesses have started considering offshore software development companies to outsource their dream project. Why? Do they get any benefit from it? Maybe, but their business surely gets on high. Outsourcing to offshore vendors is pretty inexpensive and time-saving. You could save much time and use it in the promotion and marketing of your services and products
Outsourcing your Java development work eliminates the frustration and time related to finding and analyzing candidates’ skills. The development team starts working on your project with a single phone call. You don’t have to worry when you hire experienced professionals because they know, what are your desires and requirements. They understand your business and accordingly make a design for the application. Associating with a premium partner ensures that each new resource has been tested and scrutinized by the team.

Outsource Java Development Company allows, the development team to rapidly determine the effectiveness of new employee and quickly on-board employees. If everything is under control, you can get new resource reporting with a single call.
Picture
Why Did Most Organizations believe In Outsourcing?

These are the three key reasons that, outsourcing decides:

1.       Lack of experienced staff to handle business process

2.       Lesser availability of cheaper labor

3.       Feasibility and ability to focus on other business processes that are extremely crucial for business growth.


Due to all of these three factors, these organizations generally outsource to offshore development partners and get their work done. Technical expertise, excellent communication capabilities, and suitable packages are major benefits you can avail while outsourcing Java development work to India.

Read more - JEP 359: The Best New Thing for a Long Time for JAVA

What Benefits You Can Avail?​
1. Expertise and swiftness
Most of the time companies outsource their tasks to vendors who are experienced enough to deliver the exact output. The outsourced vendor possesses specialized skills and tools set that assist the developers during development and completion of tasks.

2. Core process handling
By outsourcing Java services, companies can have more time to work on their core processes and strengthen them simultaneously.

3. Risk Sharing
Risk sharing is a crucial factor because outsourcing helps companies to shift responsibilities completely or partially to the outsourced vendor.

4. Low operation cost
Not all organizations need, in-house IT development team and thus they outsource. Outsourcing development services elude the requirement to hire experts, in-house and in this way, you are one step ahead to low operation cost.​

5. You can get a fresh perspective
IT consultants can bring you a fresh perspective when you outsource to them. The Java web development team can provide unique ideas, intuitive approaches, and brilliant results that one can ​never expect from a novice or fresher.

See more at - 
  • Spring Boot for Apache Geode and Pivotal GemFire Released (Ver. 1.2.0)
  • Introduction JAX-RS Security for Restful Services Using Java 8

6 Comments

Developing A 3-Tier App With Java EE Development -A Secure Decision

2/18/2015

0 Comments

 
Virtual technology summits are one of its kind technology class to make the programmer understand to look through the software based on the language used. I got to know about the software list to use for building a 3- tier APP with JAVA development (Java EE) and thought to share it with everyone around. Here is a picture of Java enterprises edition to make it a little simple to understand.
Picture
I have been through a nice bunch of Java EE Technology during the development of this application in the summit
Picture
Picture
The Java EE development platform uses a distributed multitier app model with which programmers build enterprise applications.  Though an app can have all tiers as shown in below figure 1.1, Java EE multitier app solutions have a 3-tier distributed network having locations- Java EE server machine, client machine, and legacy machine at the back end.
Picture
Hope it gives you a better understanding about how to use the Java EE platform for the better Web development. Along with this here is a list of required updated application before you start working on Java EE 7.
Major components of Java EE
  • JSP technology, Java Servlet and JavaServer Faces components- web components run on the server
  • Applets and Application clients components- run on the client
  • EJB (Enterprise JavaBeans) components are corporate components- run on the server

Security

Java EE has a secured environment which enables and defines the security chain of codes (also known as constraints) during deployment moment. The platform offers portability and enables developers to shield the apps with a wide range of security implementation. The platform offers standard declarative access control rules defined and interpreted by the Java development team when the app deployed over the server. Java EE development platform also offers, standard login mechanisms and hence, the team does not need to implement these mechanisms inside their developed apps. The application works and performs in distinct security environments without making changes to the source code.

Hence, creating 3-tier applications with Java EE development is a secure decision to make. You can find out more about the development of 3-tier applications with Java EE online and build your app without hassle.

Read more - The cultural impact of cloud technology
Top 5 Java-Based Tools for Business Intelligence



0 Comments

Top Reasons That Explain the Requirement of ROR for Java Developers in India

12/26/2014

1 Comment

 
Picture
Talking about the current situation each company is trying to find new ways to reduce Web application development costs and time by choosing the right programming tools and frameworks. It is why the need for getting familiar with multiple programming language and development framework has become crucial for developers. Java, being an object-oriented, class-based and concurrent programming language, requires least implementation dependencies. Professional Java developers are ready to operate code without having to re-integrate code into multiple platforms

  • Avoid repetitive code
Java is a powerful programming language which requires developers to write longer code lines to accomplish certain tasks. With ROR, Java developers can accomplish transaction management, logging, security, and many other cross-cutting concerns through modules. Developers are ready to use modules to develop functionality in the classroom without using repeated code. They can easily replace other Java frameworks with ROR to attain these cross-cutting concerns.
A study done by experts says that ROR or Ruby on Rails demand is constantly raising in the enterprises for web app development projects. ROR is an open-source, web app development program that written in Ruby programming language. However, researchers give credit to ROR for making Ruby programming language so much popular in the industry. It is why it has become essential for Java developers and programmers (working in India based development companies) to get familiar with ROR to reap major profits
  • It simplifies web development process
ROR supports few widely used software development paradigms such as active record pattern, model-view-controller, COC (convention-over-configuration), and DRY (Don't Repeat Yourself). It simplifies the job of Java developers and allows them to recycle and organize their code. In addition, they can keep presentation and business logic different to reduce the time required to create complex and large web applications. Developers should learn ROR to save their time and efforts
  • ROR and Java combo boosts the internet app performance
Twitter is an instance of ROR and Java combo that run the micro-blogging site 3 times faster. Initially Twitter was designed using ROR; however, engineers later took Java assistance to develop highly scalable and flexible web services, which are required to support massive traffic. The ROR and Java combo optimizes the twitter capability to maintain traffic and enhance search latencies.

Java developers (India) should learn about ROR as well to avail such benefits and to make the most efficient deliveries
Read Related Article:

Building a Real Estate App Easier with Java Open Source Development)
1 Comment

    RSS Feed

    SoftWeb Solution

    Aegis Soft Tech is a well-known name in IT industry. We have stable team of resources working on various technologies for the last 10 years. We are also prominent as 'Future of IT ' in India. Today, we are giving quality IT outsourcing services to our clients with wonderful exposure to different IT domains.

    Categories

    All
    3tier-app
    Angular 2
    Angular JS 2
    Aspnet Development
    Aspnet-development
    Big Data
    Java
    Java Developers
    Java Developers India
    Java Development
    Java Development News
    Java Development Team
    Java EE Development
    Java Outsourcing
    Java Programmers
    JavaScript
    Java Update
    Java Web Development
    .Net Development
    Outsource Your Java Development
    Python Development
    ServiceNow
    Software Development

Powered by Create your own unique website with customizable templates.