Appium-Mobile App Automation[Test an app]Part-2


In our last blog we describe Installation and configuration of Appium on Ubuntu machine.Now we explain how to run automation test case on android device using appium.

So for test the app we have to put the app apk in android device which we want to test.After that we start the writing the code using selenium webdriver.We are using TestNg famework with selenium webdriver.

So when we run the program, appium server automatically start the mapping with emulator and run the script on emulator.

appiumcode

appium-server-start

Here is the result of automation test case.

report

Feel free to ask me any question.

Thanks.

Posted in Scala | Tagged , , , , , , , , | Leave a comment

Appium-Mobile App Automation[configuration and Installation]Part-1


Appium is open source test automation framework which is used for testing the hybrid app,native app and mobile web app on Android and iOS using webdriver.

Appium work on distributed open source mobile UI testing framework. It run the automation test on real devices, emulator, simulator. Appium translate the selenium web-driver command into UIautomation like android device. Appium support lot of language like java,php,ruby,python,JavaScript,node.js etc.

How to use Appium:

For using the Appium we have to need follwing things…

1-Android sdk

2-java

3-TestNg

4-Appium for Ubuntu

5-Selenium jar

6-Apk app

So we start from Android sdk. First of all download the android sdk. After downloading the sdk ,run the command in terminal

$android

it will download the all the android API whatever you used after that we enter emulator open command. It will open the emulator.

android-avd

emulatorstart

We start the emulator which work on android api 5.0.1

android-emulaoropen

After that we will install the Appium on Ubuntu machine.

> brew install node      # get node.js
> npm install -g appium  # get appium
> npm install wd         # get appium client
> appium &               # start appium
> node your-appium-test.js

After installation the appium we start the appium server.

appium

we  can see our connected device listed in Command Prompt type adb devices on terminal

adbdevice

Appium does not support android version lower than 4.2 So if you want to test the lower version of android you can use Selendroid.

If you have any query feel free to ask me.

Thanks.

Posted in Scala | Tagged , , , , | 2 Comments

Introduction to Scala Parser And Combinators


Scala parser combinators are a Powerful way to build parsers that can be used in everyday programs. But it’s hard to understand the plumbing pieces and how to get started. After you get the first couple of samples to compile and work, the plumbing starts to make sense,this is very easy way to design your own programming language, using its parser library

so lets get started first thing is that we need to extend the regex parser

to use scala parser combinators you need to add following dependencies in your build.sbt

libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.5"

sbt version is 2.11.3

EBNF grammar for this language would look something like this:

def symbol: Parser[Any] = "+" | "-" | "*"

def number: Parser[Int] = """(0|[1-9]\d*)""".r ^^ { _.toInt }

symbol is our parser of type any that state that it will contain either the +,-, * symbol using | operator

number is parser of type int looking at it you might get confused ,it states that it will evaluate a regular expression of type int,then you might  think what is is  ^^ symbol is doing it denotes the operation that needs to be performed when the left hand side expression is evaluated so here it is converting this expression value to integer

def expression = {
  number ~ symbol ~ number ^^ { case firstOperand ~ operator ~ secondOperand =>
    validateAndExtractFirstValue(firstOperand) + validateAndExtractSecondValue(secondOperand)
  }

now what is this method is doing

~ symbol in scala parser is used to seperate out the token in scala,it will parse the expression if the expression contain a number followed by a symbol followed by another number,then it simply add those two numbers

to be more concise here is the full code

import scala.util.Try
import scala.util.parsing.combinator.RegexParsers

class ScalaParser extends RegexParsers {

  def expression = {
    number ~ symbol ~ number ^^ { case firstOperand ~ operator ~ secondOperand =>
      validateAndExtractFirstValue(firstOperand) + validateAndExtractSecondValue(secondOperand)
    }
  }

  def symbol: Parser[Any] = "+" | "-" | "*"

  def number: Parser[Int] = """(0|[1-9]\d*)""".r ^^ { _.toInt }

  def validateAndExtractFirstValue(firstOperand: Any): Int = {
    val firstValue: Try[Int] = Try(firstOperand.toString.toInt)
    firstValue match {
      case util.Success(value) => value
      case util.Failure(exception) => throw new Exception("can not convert values to integer")
    }
  }

  def validateAndExtractSecondValue(secondOperand: Any): Int = {
    val secondValue = Try(secondOperand.toString.toInt)
    secondValue match {
      case util.Success(value) => value
      case util.Failure(exception) => throw new Exception("can not convert values to integer")
    }
  }
}

object TestSimpleParser extends ScalaParser {
  def main(args: Array[String]) = {
    parse(expression, "5 + 4") match {
      case Success(result, _) => println(result)
      case Failure(msg, _) => println("FAILURE: " + msg)
      case Error(msg, _) => println("ERROR: " + msg)
    }

  }
}

to be clear to call the parser you have to call the parse method it takes two arguments one is type of parser and second one is statement to be parsed

i think this blog will help to getting started with scala parser and combinators

KNOLDUS-advt-sticker

Posted in Scala | Leave a comment

Knolx- BDD With Cucumber


Hi all,

Knoldus has organized a 40 min session on 24th Feb 2017 at 4:30 PM. Topic was BDD With Cucumber. Many people have joined and enjoyed the session. I am going to share the slides here. Please let me know if you have any question related to linked slides.


KNOLDUS-advt-sticker

Posted in Scala | Leave a comment

Neo4j With Scala: Rest End Points with AKKA HTTP


Hello Folks,

Welcome back again in the series of Neo4j with Scala 😉. Let’s start our journey again. But before starting our journey here is the links for recap who join late us in the journey :

  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
  5. Neo4j vs ElasticSearch and Full Text Search

Today we will discuss about Neo4j, Scala with Akka-HTTP. We will create rest-endpoints and try to connect with server with them.

The basic idea behind using Akka-HTTP for creating Rest end points is modules implement a full server and client-side HTTP stack on top of akka-actor and akka-stream. We can customize these routes according to our use case. It’s not a web-framework but rather a more general toolkit for providing and consuming HTTP-based services.

We will talk step by step to development this Rest API after which you will able to run this API on your server and start hitting Rest end points.

Now we start coding :

  1. build.sbt:
    We will start our implementation with the build.sbt file. We will keep all require dependencies in this file.
  2. Factories:
    This is the part where we interact with the Neo4j database. This code shows how to do CRUD operations and Create Relation between the nodes. We will define our Cypher here and execute them. Example:

     def retrieveRecord(email: String): Option[User] = {
        val driver = GraphDatabase.driver(neo4jUrl, AuthTokens.basic(userName, userPassword))
        val session = driver.session
        val script = s"MATCH (a:Users) WHERE a.name = '$email' RETURN a.name AS name, a.email AS " +
                     s"email, a.age AS age, a.city AS city"
        val result = session.run(script)
        val record_data: Option[User] = if (result.hasNext()) {
          val record = result.next()
          val results: User = new User(record.get("name").asString(),
            record.get("email").asString(),
            record.get("age").asInt(),
            record.get("city").asString())
          Some(results)
        } else {
          None
        }
        session.close()
        driver.close()
        record_data
      }

    Continue reading

Posted in akka-http, Scala, scalatest | Tagged , , | 1 Comment

Object Oriented JavaScript: Polymorphism with examples


oopjsAgain this is not the advance topic of JavaScript but it relies under Object Oriented JavaScript & polymorphism is one of the tenets of Object Oriented Programming (OOP), we all know what is Polymorphism from other languages (like C#, Java etc) but we always think when to use it, why to use it and how to this, and most of us are still in confusion that should we really use it? blah !!!.

JavaScript is dynamically typed language [a big issue to discuss], but for understanding purpose:

Statically typed programming languages do type checking (the process of verifying and enforcing the constraints of types) at compile-time as opposed to run-time. (Java, C etc)

Dynamically typed programming languages do type checking at run-time as opposed to Compile-time. (JavaScript etc)

Though in JavaScript it is a bit more difficult to see the effects of polymorphism because the more classical types of polymorphism are more evident in statically-typed systems.

 

Continue reading

Posted in JavaScript, Scala | Tagged , , , , | 2 Comments

AWS | Running micro-services on Amazon ECS


Hi all,

Knoldus had organized half an hour session on 27th January 2017 at 4:00 PM. Topic was Walk-through on Amazon ECS. Many enthusiasts joined and learned from the session. Below are slide and video from the session. Please let me know if you have any questions/concerns.

Slide:

Video :

Thanks !! 🙂


KNOLDUS-advt-sticker

Posted in Amazon, Amazon EC2, AWS, AWS Services, Scala | Leave a comment

Spark Cassandra Connector On Spark-Shell


Using Spark-Cassandra-Connector on Spark Shell

Hi All , In this blog we will see how we can execute our spark code on spark shell using Cassandra . This is very efficient at testing or learning time , where we have to execute our code on spark shell rather than doing on any IDE .

Here we will use spark version –  1.6.2 

you can download the version from Here

and off course its appropriate spark Cassandra connector as

Cassandra Connector –  spark-cassandra-connector_2.10-1.6.2.jar .

you can download the connector(jar file) from Here .

So lets Begin : –

Step 1 ) Create any test table in your Cassandra ( I am using Cassandra version Cassandra 3.0.10 ) .

CREATE TABLE test_smack.movies_by_actor (
actor text,
release_year int,
movie_id uuid,
genres set,
rating float,
title text,
PRIMARY KEY (actor, release_year, movie_id)
) WITH CLUSTERING ORDER BY (release_year DESC, movie_id ASC)

Continue reading

Posted in apache spark, big data, Cassandra, Scala, Spark | 2 Comments

JWT Authentication with Play Framework


In this blog, I will demonstrate how to implement JWT Authentication with Play Framework.

JSON Web Token (JWT) is a compact, self-contained which means securely transfer the information between two parties. It can be sent via Post request or inside the HTTP header. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret or a public/private key pair using RSA It consists three parts separated by the dot(.)  i.e Header, Payload and Signature. The header consists type of the token and hashing algorithm, the payload contains the claims and the claims in a JWT are encoded as a JSON object that is used as the payload or as the plaintext, the signature part is used to verify that the sender of the JWT.

Here, we are using JSON Web Token for authentication with Play Framework, This is a most common way of using JWT. Once the user is logged in, we need to include JWT with each request that allows the user to access the routes, service and resources which authenticate the token in order to permit the request.

Let’s start with the implementation of JWT Authentication using Play Framework:

1. First, we need to include JWT library in our project. There are several libraries for JWT, you can use any of them depending on your requirement, here I am using one of the library i.e.

"com.jason-goodwin" %% "authentikat-jwt" % "0.4.1"

2. Next, you need to create JWT utility class in which you need to add all these methods for creating, verifying and decode the JWT token and provide the secret key and algorithm such as HMAC, SHA256.

val JwtSecretKey = "secretKey"
val JwtSecretAlgo = "HS256"

def createToken(payload: String): String = {
  val header = JwtHeader(JwtSecretAlgo)
  val claimsSet = JwtClaimsSet(payload)

  JsonWebToken(header, claimsSet, JwtSecretKey)
}

def isValidToken(jwtToken: String): Boolean =
  JsonWebToken.validate(jwtToken, JwtSecretKey)

def decodePayload(jwtToken: String): Option[String] =
  jwtToken match {
    case JsonWebToken(header, claimsSet, signature) => Option(claimsSet.asJsonString)
    case _                                          => None
  }

3. To implement JWT authentication, we need to create reusable custom secured action by using ActionBulder that authenticates the each subsequent request and verifies the JWT in order to permit the request to access the corresponding service. ActionBulder is the special case of functions that take request as input and thus can build actions and provides several factory methods that help for creating action. To implement ActionBuilder, we need to implement invokeBlock method. So here I have created a custom JWTAuthentication by using ActionBuilder.

case class UserInfo(id: Int,
                    firstName: String,
                    lastName: String,
                    email: String)

case class User(email: String, userId: String)

case class UserRequest[A](userInfo: UserInfo, request: Request[A]) extends WrappedRequest(request)

class SecuredAuthenticator @Inject()(dataSource: DataSource) extends Controller {
  implicit val formatUserDetails = Json.format[User]

  object JWTAuthentication extends ActionBuilder[UserRequest] {
    def invokeBlock[A](request: Request[A], block: (UserRequest[A]) => Future[Result]): Future[Result] = {
      val jwtToken = request.headers.get("jw_token").getOrElse("")

      if (JwtUtility.isValidToken(jwtToken)) {
        JwtUtility.decodePayload(jwtToken).fold {
          Future.successful(Unauthorized("Invalid credential"))
        } { payload =>
          val userCredentials = Json.parse(payload).validate[User].get

          // Replace this block with data source
          val maybeUserInfo = dataSource.getUser(userCredentials.email, userCredentials.userId)

          maybeUserInfo.fold(Future.successful(Unauthorized("Invalid credential")))(userInfo => block(UserRequest(userInfo, request)))
        }
      } else {
        Future.successful(Unauthorized("Invalid credential"))
      }
    }
  }

}

4. Now we can use “JWTAuthentication” the same way we use Action.

  def index = auth.JWTAuthentication { implicit request =>
    Ok(views.html.index(s"Hello ${request.userInfo.firstName} ${request.userInfo.lastName}"))
  }

5.  You can test it through Postman(on which you can send the request and view response),  all we need to do is create a JWT and pass it to the Headers, corresponding to the field “jw_token”. You can create JSON web token by “createToken” method that I have shown you in step 2 by passing payload as a parameter which can be anything, here is the example: 

val payload = """{"email":"test@example.com","userId":"userId123"}"""

JWT looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20iLCJ1c2VySWQiOiJ1c2VySWQxMjMifQ.mjMQN8m_wH1NSE9GGexCW_GUh8uruNco18jgt7AWuO4

jwt.png

You can get the source code from here.

I hope this blog is helpful to you!

Thanks 

References:
 

KNOLDUS-advt-sticker

Posted in JWT, Play 2.4.X, Play Framework, Scala | Tagged , , , | 2 Comments

Building Microservices Based Enterprise Applications in Java Using Lagom – Part I


As we know, now days, most of the enterprise applications design as a “Microservices Architecture” because of scalability, sharding, loosely-coupling and many others reasons are there. On the other hand  JavaEE help us for building an Enterprise Applications. As we know, Java help us for building a good applications, but with JavaEE monolithic approach our applications are not scalable as compare to microservices.

That’s why, Lagom comes into picture. Lagom provides a way for building an Enterprise Application with design of Microservices based architecture and also give us Responsive, Resilient, Elastic and Message Driven features or in other words a Reactive Approach. Lagom design philosophy as :

  1. Asynchronous.
  2. Distributed Persistent.
  3. Developer Productivity.

In this blog, we are building a sample application, for managing user module and performing CRUD on user.

Note: Lagom gives us strict approach for designing applications with Domain Driven Design (DDD) manner and also follow CQRS for event sourcing.

Step I:

We are building a maven based project using Lagom and our project structure is as below:

 lagom-structure

Continue reading

Posted in Akka, Java, Microservices, Scala | Tagged , , , , , , , , , , | 2 Comments