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 - Eclipse Paho integration for Android

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 !


Monday, November 3, 2014

Parsing mailing address in Java

Recently came across a problem to parse postal address String using Java, did some research here are some findings.

Given
String s = "60 Strawberry Hill Ave Stamford CT 06901"
Required Result
Street = Strawberry Hill Ave
City = Stamford
Number = 60
zip = 06901
state = CT
You can use JGeocoder

public static void main(String[] args) {
Map<AddressComponent, String> parsedAddr  =     AddressParser.parseAddress("Google Inc, 1600 Amphitheatre Parkway, Mountain View, CA 94043");
System.out.println(parsedAddr);
     
Map<AddressComponent, String> normalizedAddr  = AddressStandardizer.normalizeParsedAddress(parsedAddr);
        System.out.println(normalizedAddr);
}
Output will be:

{street=Amphitheatre, city=Mountain View, number=1600, zip=94043, state=CA, name=Google Inc, type=Parkway}
{street=AMPHITHEATRE, city=MOUNTAIN VIEW, number=1600, zip=94043, state=CA, name=GOOGLE INC, type=PKWY}

There is another library International Address Parser , it provides a trial version. It supports country as well.


AddressParser addressParser = AddressParser.getInstance();
AddressStandardizer standardizer = AddressStandardizer.getInstance();  
AddressFormater formater = AddressFormater.getInstance();
String rawAddress = "101 Avenue des Champs-Elysées 75008 Paris";

//you can try to detect the country
CountryDetector detector = CountryDetector.getInstance();
String countryCode = detector.getCountryCode("7580 Commerce Center Dr ALABAMA");
System.out.println("detected country=" + countryCode);

Also, please check Implemented Countries

Hope you find this helpful

Cheers !!



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 d...