Sunday, October 22, 2017

Java 9 Collection Changes Overview

Introduction
Java 9 finally brings the convenience of creating small unmodifiable Collection instances using just one line code. New APIs make it convenient to create instances of collections and maps with small number of elements.

Driving Factor
Too much code is required to be written to create a small, unmodifiable collection, which involves constructing it, then storing it in a local variable, and calling methods e.g.
Set<String> set = new HashSet<>();
set.add("first");
set.add("second");
set.add("third");
set = Collections.unmodifiableSet(set);

Alternatively one can create same using constructor method.
Set<String> set = Collections.unmodifiableSet
(new HashSet<>(Arrays.asList("first", "second", "third")));

Or using Double brace method
Set<String> set = Collections.unmodifiableSet
(new HashSet<String>() {{ 
             add("first"); 
             add("second"); 
             add("third");}});

or using Java 8 Streams
Stream.of("first", "second", "third")
.collect(collectingAndThen(toSet(),
Collections::unmodifiableSet));

New Methods 
Java 9 provides static methods for List, Set, and Map interfaces which take the elements as arguments
List<String> list = List.of("first", "second", "third");
Set<String> set = Set.of("first", "second", "third");
Map<Integer, String> map = Map.of(1, "first", 2, "second");

For maps this method is overloaded to have 0 to 10 key-value pairs, e.g.


Map<String, String> map = Map.of("1", "first");
Map<String, String> map = Map.of("1", "first", "2", "second");
Map<String, String> map = Map.of("1", "first", "2", "second", "3", "third");

Similarly you can have up to ten entries.

For a case where we have more than 10 key-value pairs, there is a different method:

static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)

Java 9 has definitely made creating collection so easy.


Wednesday, May 3, 2017

Java 8 streams performance on mathematical calculations

Java 8 Streams API supports many parallel operations to process the data, it abstracts low level multithreading logic. To test performance did following simple test to calculate factorial of first X number starting with N.

Following program calculates factorial of first 1000 numbers.

package com.java.examples;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
public class MathCalculation {
 public static void main(String[] args) {
  List < Runnable > runnables = generateRunnables(1, 1000);
  Instant start = Instant.now();
  // Comment one of the lines below to test parallel or sequential streams
  runnables.parallelStream().forEach(r -> r.run());
  // runnables.stream().forEach(r -> r.run());
  Instant end = Instant.now();
  System.out.println("Calculated in " + Duration.between(start, end));
 }

 private static void factorial(int number) {
  int i;
  BigInteger fact = BigInteger.valueOf(1);
  for (i = 1; i <= number; i++) {
   fact = fact.multiply(BigInteger.valueOf(i));
  }
  System.out.println("Factorial of " + number + " is: " + fact);
 }

 private static List < Runnable > generateRunnables(Integer num, int count) {
  List < Runnable > l = new ArrayList < Runnable > ();
  for (int i = 0; i < count; i++) {
   int n = num + i;
   Runnable r = () -> {
    factorial(n);
   };
   l.add(r);
  }
  return l;
 }
}


Results:

Parallel stream -> 0.765S 
Sequential stream -> 0.849S

This is just one example to demonstrate how Streams can improve performance, there are several use cases. Also notice how Java 8 changes the way we use to write programs before this version was released.




Thursday, April 27, 2017

Mobile Testing

Mobile application testing falls into broadly two types:

Hardware Testing
This includes testing internal hardware, screen size, resolution, space, camera, Bluetooth, WIFI etc.

Software or Application Testing
This includes testing the application that are running on device. Because of types of apps this can be divided into following categories:
  • Native apps
  • Mobile web apps
  • Hybrid apps
There are some key things to be considered when testing mobile apps:
  • Native apps have single platform
  • Native apps are written in platforms like SDKs while Mobile web are written in html, css
  • Native/Hybrid apps may or may not require internet connection
  • Mobile web apps require internet connection
  • Native/Hybrid apps are downloaded from playstore
  • Mobile web apps are accessible from internet
Mobile Testing complexity in comparison web applications
  • Different range of mobile devices, screen sizes etc.
  • Various manufactures customizations
  • OS types iOS, Android, Windows etc.
  • Different versions of OS e.g. Android 4.x, 5.x, 6.x, 7.x
  • Spectrum of mobile networks GSM, CDMA 3G/4G
  • Frequent updates (security patches)
Manual or Automation ?
Both have advantages and disadvantages similar to web application testing
Manual Testing : Usability, Ad-hoc test cases
Automation Testing : Regression testing, Repeated Execution of use cases

Top open source Mobile Testing Frameworks

Testing ToolAndroidIOSNative AppsHybrid AppsScripting LanguageTest same app
AppiumYYYYAlmost anyY
RobotiumYNYYJavaN
SelendroidYNYYSelenium 2 APIN
Keep it FunctionalNYYYObjection CY
Monkey TalkYYYYMonkey Talk Script/JSN

Recommended - Appium
  • Test the same app you submit to the marketplace. 
  • Write your tests in any framework, using any language. 
  • Standard automation specification and API. 
  • Large open-source community effort. 
Cloud based mobile testing solutions
  • Perfecto Mobile
  • DeviceAnywhere

Thursday, March 30, 2017

Java keytool to create keypair

Use following command to create a public/private keypair using java keytool command.

keytool -genkey -keyalg RSA -alias mykeystore -keystore keystore.jks -validity 30 -keysize 2048

Once you run the command follow the steps to complete generation of keypair, make sure you remember the password that you provide during generation.

Windows to Mac cheatsheet

For any user who moves from windows to Mac here are some frequently used shortcuts that we commonly use on windows

Task Manager
Command+Option+Esc

Screenshot
Shift+Command+4

Eclipse Preferences
Unlike Windows where they are under Window -> preferences, on mac they are under eclipse -> preferences

Monday, August 22, 2016

Gulp command not found on Mac OSX

Was getting following error after installing gulp on mac.

Sachins-MBP:MyApp sachin$ gulp

-bash: gulp: command not found

After fighting for hours and searching on internet, tuned out to be a very simple fix. While installing gulp missed the parameter to install globally.

Sachins-MBP:MyApp sachin$ npm install -g gulp

Yay !!!! Its working, thought to write to save time for somebody else.

Monday, August 15, 2016

MQTT : Android step by step guide using Eclipse Paho

For MQTT integration, recently explored Paho Android project, very simple to use, here are the steps:

Intialize a client, set required options and connect.

    MqttAndroidClient mqttClient = new MqttAndroidClient(BaseApplication.getAppContext(), broker, MQTT_CLIENT_ID);
    //Set call back class
    mqttClient.setCallback(new MqttCallbackHandler(BaseApplication.getAppContext()));
    MqttConnectOptions connOpts = new MqttConnectOptions();
    IMqttToken token = mqttClient.connect(connOpts);

Subscribe to a topic.

    token.setActionCallback(new IMqttActionListener() {
      @Override
      public void onSuccess(IMqttToken arg0) {
           mqttClient.subscribe("TOPIC_NAME" + userId, 2, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.d(LOG_TAG, "Successfully subscribed to topic.");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.d(LOG_TAG, "Failed to subscribed to topic.");
                }
            });
      }
 
      @Override
      public void onFailure(IMqttToken arg0, Throwable arg1) {
           Log.d(LOG_TAG, errorMsg);
      }
    });

Define your callback handler class.

    public class MqttCallbackHandler implements MqttCallbackExtended {
        @Override
            public void connectComplete(boolean b, String s) {
                Log.w("mqtt", s);
            }
 
            @Override
            public void connectionLost(Throwable throwable) {
 
            }
 
            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                Log.w("Anjing", mqttMessage.toString());
            }
 
            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
 
            }
      }
             
Also set following in manifest file.

    <service android:name="org.eclipse.paho.android.service.MqttService" >
    </service>

Would recommend visiting their project on GitHub and going through samples online.

https://github.com/eclipse/paho.mqtt.android

Hoping this helps.

Cheers !


Java 9 Collection Changes Overview

Introduction Java 9 finally brings the convenience of creating small unmodifiable Collection instances using just one line code. New APIs...