How to transform Either[Future[A],Future[B]] to Future[Either[A,B]]

Hey folks, I hope all you guys are doing well !
Recently I came across one weird situation in which I was getting an
Future[Either[String , Future[A]]] and it was getting more and more complex so I thought of taking out the Future from the Either and then flattening it out , as most of us do always 😉

But this time this simple thing was not happening and I was getting frustrated and then while searching for it I came across a very good library for scala known as Cats which seems to solve my problem.

Just FYI, Cats is a library which provides abstractions for functional programming in the Scala programming language. The name is a playful shortening of the word category.
(Copied 😉 from Github )

So this is how I got introduced to Cats !
So how I solved my problem is via writing a function using cats.Functor

For using Cats you need to add the cats dependency in your build.sbt

name := "scala-cats"

version := "0.1"

organization :="com.internity"

scalaVersion := "2.12.3"

scalacOptions += "-Ypartial-unification"

libraryDependencies += "org.typelevel" %% "cats-core" % "1.0.0-RC1"

 

case class A(a:String)

import scala.concurrent.Future

import scala.concurrent.ExecutionContext.Implicits.global

import cats.implicits._

import cats.Functor

val eitherOfFutures:Either[Future[String], Future[A]]=Right(Future.successful(A("Shiv")))

val futureOfEitherOfFuture=Future.successful(eitherOfFutures)

def eitherFmap[F[_], A, B](either: Either[F[A], F[B]])(implicit F: Functor[F]): F[Either[A, B]] = either.fold(f => F.map(f)(Left(_)), f => F.map(f)(Right(_)))

val futureOfEither=futureOfEitherOfFuture.flatMap(eitherFmap(_))

 

You can also see it on the sbt Console

CatsConsole

 

So this is how we can convert Either[Future[A],Future[B]] into Future[Either[A,B]].

Method 3: Without Functor’s boilerplate  code.

As per comment from M50d pointed out a easier solution :

You can also do it in a more simpler way by using bisequence in cats.instances._ as pointed out by M50d

import cats.instances._

eitherOfFutures.bisequence

biseq

Edit :

Recently from the comments from Reddit on this post , I have found a new apporach in simple scala  I am adding it here thanks to the user @jangchoe for this code snippet

eitherOfFutures.fold(f => f.map(Left(_)), f => f.map(Right(_)))

If you have any problems look me up on twitter and let me know !

We are also developing a community of developers for bridging the gap between Corporates and the colleges ! If you want to be a part of this movement ! Signup on InternityFoundation

Till then Happy hAKKAing 🙂

References :

  1. StackOverflow
  2. Herding Cats

 

 

Advertisements

Integrating Play app with Lagom application

Playing with play and Lagom !

Knoldus

logom

What is Lagom?

Simply put, it is a microservices tool.

Lagom is a microservices framework that guides developers in moving from monolithic to a scalable, resilient microservice based systems. It is a platform delivering you not only the microservice framework but also a whole tool set for developing applications along with creating, managing and monitoring your services.

According to Lightbend the focus should not be on how small the services are, but instead they should be just the right size, “Lagom” size services.

Most microservices frameworks focus on making it easy to build individual microservices. Lagom allows developers to run a whole system of microservices from a single command.

Before you begin creating your microservices, you need to make some selections:

View original post 242 more words

Introduction To HADOOP !

Knoldus

Here I am to going to  write a blog on Hadoop!

“Bigdata is not about data! The value in Bigdata [is in] the analytics. ”

-Harvard Prof. Gary King

So the Hadoop came into Introduction!

Hadoop is an open source, Java-based programming framework that supports the processing and storage of extremely large data sets in a distributed computing environment. It is part of the Apache project sponsored by the Apache Software Foundation.

                                                                                                                -Cloudera

Hadoop was created by computer scientists Doug Cutting and Mike Cafarella in 2006 to support distribution for the Nutch search engine. It was inspired by Google’s MapReduce.

Why HADOOP?

The problem with RDBMS is , it can not processed semi-structured and unstructured data (text, videos, audios, Facebook posts, clickstream data, etc.). It can only work with structured data(banking transaction, location information, etc.). Both are also different in term of processing data.

RDBMS architecture with ER…

View original post 753 more words

Scalafmt – Styling The Beast

Styling your Scala code !

Knoldus

“I have never seen elegance go out of style” – SONYA TECLAI

Scala (The Beast) has imported efficiency and elegance to the programming world by combining coziness of object oriented programming with the magic of functional programming. This blog illuminates the work of Ólafur Páll Geirsson who has done a great job of styling the beast. In the bulk below I will discuss my experience of using Scalafmt, its installation process and some of its cool code styling features. Stuff we would be using in this blog

  • Editor -> Intellij (v 2017)
  • Build Tool -> sbt (v 0.13.15)
  • Language -> Scala (v 2.12.1)

One of the most important aspect of good code is its readability which comes with good and standard formatting. Ever wondered how an entire project having around 1000 Scala files of poorly formatted code could be formatted without having a headache? Well going shft + ctrl + alt…

View original post 634 more words

Basic of The Gherkin Language

Introduction to Gherkin ! New way of testing !

Knoldus

Hello Everyone ,

In this blog we will discuss about Gherkin Language  which we used in BDD for writing test cases.we will take a look on below topic.

Introduction:

Gherkin’s grammar is defined in the parsing expression grammars. It is Business Readable, DSL created specifically for behavior descriptions without explaining how that behaviour is implemented. Gherkin is a plain English text language.

Gherkin serves two purposes — documentation and automated tests. It is a whitespace-oriented language that uses indentation to define structure.

The Gherkin includes 60 different spoken languages so that we can easily use our own language.The parser divides the input into features, scenarios and steps.

Here is a simple example of Gherkin:

Screenshot from 2017-04-18 11-31-45

When we run this feature this gives us a step definition.In Gherkin, each line is start with a Gherkin keyword, followed by any text you like.

The main keywords are:

  • Feature
  • Scenario
  • Given
  • When
  • Then

Feature:

View original post 198 more words

Getting Started with Apache Cassandra

Cassandra101

Knoldus

Why Apache Cassandra?

Apache Cassandra is a free, open source, distributed data storage system that differs sharply from relational database management systems.
Cassandra has become so popular because of its outstanding technical features. It is durable, seamlessly scalable, and tuneably consistent.
It performs blazingly fast writes, can store hundreds of terabytes of data, and is decentralized and symmetrical so there’s no single point of failure.
It is highly available and offers a schema-free data model.

Installation:

Cassandra is available for download from the Web here. Just click the link on the home page to download the latest release version and Unzip the downloaded cassandra  to a local directory.

Starting the Server:

View original post 221 more words

Neo4j Apoc : A Blessing For Developer

Knoldus

Hello Folks,

As we know about Neo4j, it pulls out developers life from the trouble and black & white screen of the databases. It doesn’t give freedom from the old databases also provides best support with it’s predefined procedures.

As we know that in the Relational Database, Procedure provide advantages of better performance, scalability, productivity, ease of use and security and Neo4j also provides some amazing tool which can perform as mention above.

Yes, I am talking about the Apoc and using of Apoc with Neo4j, is a blessing for the developers. It provides many predefined procedures or user defined functions/views so that we can easily use it and improve our productivity in very simple manner.

APOC is stands for ‘Awesome Procedure On Cypher‘. APOC is a library of procedure for the various areas. It is introduce with the Neo4j 3.0

There are many areas where we use…

View original post 898 more words

Industrial-IOT : Introduction to MODBUS protocol

Hey Folks,

Its been for a while since we talked on Internet of things ! (One year I guess since its 2017 itself  😉 )

So here we are now again , and this time the topic is Introduction to MODBUS protocol !
Again we have three questions , What ? why ? and How ?

So let’s get started ,

What is MODBUS ?

Modbus is a serial communications protocol originally published by Modicon (now Schneider Electric) in 1979 for use with its programmable logic controllers (PLCs). Simple and robust, it has since become a de facto standard communication protocol, and it is now a commonly available means of connecting industrial electronic devices.

Since it first appeared in 1979, Modbus has evolved into a broad set of protocols over a variety of physical links (for example, RS-485). At its core, Modbus is a serial communications protocol that follows a master–slave model. A master sends a request to a slave device, and the slave returns a response. In a standard Modbus network, there is one master and up to 247 slaves (although 2 byte addressing can significantly expand this limit).

Why Modbus ?

When it comes to choosing a network for your device, Modbus TCP/IP offers several significant advantages:

  • Simplicity: Modbus TCP/IP simply takes the Modbus instruction set and wraps TCP/IP around it. If you already have a Modbus driver and you understand Ethernet and TCP/IP sockets, you can have a driver up and running and talking to a PC in a few hours. Development costs are exceptionally low. Minimum hardware is required, and development is easy under any operating system.
  • Standard Ethernet: There are no exotic chipsets required and you can use standard PC Ethernet cards to talk to your newly implemented device. As the cost of Ethernet falls, you benefit from the price reduction of the hardware, and as the performance improves from 10 to 100 Mb and soon to 1 Gb, your technology moves with it, protecting your investment. You are no longer tied to one vendor for support, but benefit from the thousands of developers out there who are making Ethernet and the Internet the networking tools of the future. This effort has been complemented opportunely with the assignment of the well-known Ethernet port 502 for the Modbus TCP/IP protocol.
  • Open: The Modbus protocol was transferred from Schneider Electric to the Modbus Organization in April 2004, signaling a commitment to openness. The specification is available free of charge for download, and there are no subsequent licensing fees required for using Modbus or Modbus TCP/IP protocols. Additional sample code, implementation examples, and diagnostics are available on the Modbus TCP toolkit, a free benefit to Modbus Organization members and available for purchase by nonmembers
  • Availability of many devices: Interoperability among different vendors’ devices and compatibility with a large installed base of Modbus-compatible devices makes Modbus an excellent choice.

How it works ?

Modbus Architecture :

There are many types of MODBUS protocols like MODBUS RTU , MODBUS TCP , MODBUS ASCII and many more but we are using MODBUS TCP for our system.

In the architecture of MODBUS there are mainly two things,

  1. Modbus Slave : In general terms, we call it Server, the entity that provides the data, currently we are using a Simulator for this. Actually our Data Collector would work as a Modbus Slave.
  2. Modbus Master: In general terms We call it Client , the entity that consumes data, hence our service will be a client.

This is how Modbus Architecture looks like :

modbus-request-response

MODBUS may seem complicated and confusing to some, but it is a very simple protocol when you understand how it works.  MODBUS is a request and response protocol.   A MODBUS master will initiate a request and a slave will respond with either an error or the data requested.  This is the simple concept of MODBUS.

 Modbus Message Structure :

So  MODBUS Message Structure looks something like this :

modbuspacket

For different other types it looks something like this :

modbus-frame-1

Modbus addressing

The first information in each Modbus message is the address of the receiver. This parameter contains one byte of information. In Modbus/ASCII it is coded with two hexadecimal characters, in Modbus/RTU one byte is used. Valid addresses are in the range 0..247. The values 1..247 are assigned to individual Modbus devices and 0 is used as a broadcast address. Messages sent to the latter address will be accepted by all slaves. A slave always responds to a Modbus message. When responding it uses the same address as the master in the request. In this way the master can see that the device is actually responding to the request.

Within a Modbus device, the holding registers, inputs and outputs are assigned a number between 1 and 10000. One would expect, that the same addresses are used in the Modbus messages to read or set values. Unfortunately this is not the case. In the Modbus messages addresses are used with a value between 0 and 9999. If you want to read the value of output (coil) 18 for example, you have to specify the value 17 in the Modbus query message. More confusing is even, that for input and holding registers an offset must be subtracted from the device address to get the proper address to put in the Modbus message structure. This leads to common mistakes and should be taken care of when designing applications with Modbus. The following table shows the address ranges for coils, inputs and holding registers and the way the address in the Modbus message is calculated given the actual address of the item in the slave device.

modbus-addressing

Modbus function codes

The second parameter in each Modbus message is the function code. This defines the message type and the type of action required by the slave. The parameter contains one byte of information. In Modbus/ASCII this is coded with two hexadecimal characters, in Modbus/RTU one byte is used. Valid function codes are in the range 1..255. Not all Modbus devices recognize the same set of function codes. The most common codes are discussed here.

Normally, when a Modbus slave answers a response, it uses the same function code as in the request. However, when an error is detected, the highest bit of the function code is turned on. In that way the master can see the difference between success and failure responses.

modbus-function

There is a still lot that we need to know about MODBUS , that you can read by going to the references to this post 🙂

In this series there would be three blogs , this being the first one.

  1. Industrial-IOT : Introduction to MODBUS protocol
  2. Industrial-IOT : A basic Scala implementation for MODBUS Master.
  3. Industrial-IOT  : MODBUS Spark Custom Receiver.

I will add the links accordingly to these blogs.

And yeah I will be writing the Spark-IoT Series soon , sorry for the delay 😉
So be patient and stay connected and tuned 🙂

The next blog will be out soon.

If you want to know anything about me , please visit the link below. You can get in touch with me anytime. Always welcomed 🙂

Refrences:

  1. http://gridconnect.com/blog/tag/modbus-explained/
  2. https://www.csimn.com/CSI_pages/Modbus101.html
  3. https://www.lammertbies.nl/comm/info/modbus.html

About the Author :

Shivansh Srivastava , Sr. Software Enginner @ Chirpanywhere Inc. (Scala , Spark , IoT specialist )
Know more : about.me/shiv4nsh

Neo4j With Scala: Neo4j vs ElasticSearch

Knoldus

Hello Graphistas,

Are you missing this series 😉 ?

Welcome back again in the series of Neo4j with Scala 🙂 . Let’s start our journey again. Till now we have talked and learnt about the use of Neo4j with Scala and how easily we can integrated both two amazing technologies.

Before starting the blog here is recap :

  1. Getting Started Neo4j with Scala : An Introduction
  2. Neo4j with Scala: Defining User Defined Procedures and APOC
  3. Neo4j with Scala: Migrate Data From Other Database to Neo4j
  4. Neo4j with Scala: Awesome Experience with Spark

ElasticSearch is a modern search and analytic engine based on Apache Lucene. ElasticSearch is a full-text search engine and is highly scalable. It allows RESTful web interface and schema-free documents. ElasticSearch is able to achieve fast search responses because it searches an index instead of searching the text directly. ElasticSearch also provides the capability of store data…

View original post 446 more words