Friday, May 18, 2018

Refreshing - Android fragments


Fragments are ways by which you can create multiple views in a single Activity, to avoiding to create multiple activities. You can add / remove fragments while the activity is running. 

You can create a fragment in 2 ways: - static using XML and dynamic using programmatically

XML: 

  • Create 2 fragment classes using the wizard. This will create a class that extends Fragment and create the layout xml accordingly. 
    • headerFragment
    • ArticleFragment. 
  • Now add the 2 fragments in the main activity XML file as below. 
<fragment
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:id="@+id/headline_fragment"
    android:layout_weight="1"
    android:name="io.ctrlspace.fragmentexample.HeadlineFragment"> </fragment>

 <fragment
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:id="@+id/article_fragment"
     android:layout_weight="1"
     android:name="io.ctrlspace.fragmentexample.ArticleFragment"> </fragment>


Now this is not of much use since we add these in static xml, often we may need to add dynamically fragments based on runtime logic. 


Programmatically: 

  • Create a simple Empty Activity - say MainActivity. 
  • In the main Activity layout file, add a layout to hold the fragments, say a frame layout 
  • Now create a Fragment using Android studio - call it as HomeFragment. This will create a Java class that extends Fragment and a fragment layout file. 
  • Add some content for the fragment in the layout design to identify that its a fragment content, say add a text box with a text inside first fragment. 
  • In the main Activity add the following code. 
    • Get the FragmentManager instance
    • Start the transaction of the fragment manager.
    • Add or replace the fragment using the add / replace method in the fragment transaction, pass the fragment container and the fragment to be added or replaced to this method. 
    • Commit the transaction. 

public static FragmentManager fragmentManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    fragmentManager = getSupportFragmentManager();
    if(findViewById(R.id.fragment_container) != null) {
        if (savedInstanceState != null) {
            return;
        }

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        HomeFragment homeFragment = new HomeFragment();
        fragmentTransaction.add(R.id.fragment_container, homeFragment, null);
        fragmentTransaction.commit();
    }
}

Fragment to Activity communication is handled in a different way - you can view the source code for this here. 


Thursday, May 10, 2018

Google IO 2018 highlights


Google IO 2018 Highlights:
  • Google assistant: 
    • AI: speech conversation from AI to actual person and taking decisions, Booking for a haircut, room, ordering item in Starbucks. 
  • Android P: 
    • Effective battery utilization based on usage pattern of the user by optimizing battery usage on apps that you might use, adaptive brightness. 
    • Understands more about you and what are u going to do next. 
    • Lets you decide how much time you can spend on your app (well there are apps already, now its part of Android P). 
    • Turn your phone down and it goes to vibration.
  • Maps: 
    • Walking navigation. 
    • Augmented reality in showing information on nearby places 
    • VPS: Visual positioning system. 
    • Better way to choose restaurants, maps can show customized preferred restaurant by showing your match score based on your interests. 
  • Speech conversion from morse code for challenged people. 
  • Lens
    • Smart text selection: tap the item in your food menu via the phone camera and see what dish it is. 
    • Style match: Find price and product details based on the picture which your phone camera is pointing to. 
    • Point and view product details demo. 
  • Gmail
    • Smart compose: provide intelligent suggestions while you type your email.
  • Photos:
    • Photos to PDF
    • Coloring old photos. 

Reference:

Wednesday, February 28, 2018

CUPS & services


What is a service? Can you name some examples? 
  • A service is a PCF component (a resource reserved) to access on demand components. 
  • Examples
    • Database on a shared server. 
    • Access to a SaaS app. 

What is the “marketplace”? Does it show all services? 
  • Is a list of all service brokers
  • Cf marketplace will show all services. And 
  • Cf services will show all the services available inside a particular space. 

What is the difference between a managed and user-provided service? 
  • Managed services are services available in the marketplace. 
  • User provided service enable developers to create and use custom services. 

How would you create a managed service? 
  cf create-service SERVICE PLAN SERVICE_INSTANCE -c '{"name":"value","name":"value"}'
  cf create-service db-service silver mydb -c '{"ram_gb":4}'

How would you use a managed service? 
   cf bind-service APP_NAME SERVICE_INSTANCE -c '{"name":"value","name":"value"}'
      cf bind-service myapp mydb -c '{"permissions":"read-only"}'


How would you create a user-provided service? 
   cf create-user-provided-service SERVICE_INSTANCE [-p CREDENTIALS] [-l SYSLOG_DRAIN_URL] [-r ROUTE_SERVICE_URL]
  cf create-user-provided-service my-db-mine -p "username, password"

How would you use a user-provided service? 
  cf bind-service APP_NAME SERVICE_INSTANCE -c '{"name":"value","name":"value"}'

What is VCAPS_SERVICES? 
VCAP_SERVICES are environment variables that contain the details of bindable services that CF adde

Buildpack basics


What is a buildpack? 
Any application deployment will require softwares to be downloaded, container to be initialized and app to be deployed. A build pack is noting but the runtime and libraries on which the apps will be deployed. It defines how to run application - provide runtime support and framework for apps. 

A Java build pack for example takes care of the JRE and memory management, Container which the app should run on (tomcat, spring boot etc) and makes it easy for the developer to configure with the service. 

Why are they important?
provides runtime support and framework for applications. 
- examine your app artifacts, decides which build pack to use. 
  • Determines which dependencies to download.

Can you name some buildpacks? 
  • Go, Java, .net, Node.js, PHP, Python, Ruby, Staticfile. 

How does Cloud Foundry know which buildpack to run? 
  • Each build pack has a position in the priority list. If it is in 1 position and is compatible then it takes the 1st build pack, if not it goes on to second build pack and so on till the correct build pack. If no build pack found it says staging failed - no app detected error. 


How does a buildpack work? Are you aware of the scripts that run and how they might be written or modified? 
A build pack is in the form of a script, bash script. 
  • Detect script
    • Identifies which language this code and decides if it need to apply the build pack to an app. 
  • Supply script: 
    • Provides the dependencies for the app. 
    • Installing the runtime libraries 
      • Java: (JAR files, tomcat, sprint boot etc., 
      • Python (Puython2x, package manager, flask etc., )
  • Finalize script
    • prepares the app for launch. 
      • Handle and config params, 

  • Release script
    • Tell the cloud foundry platform how to start the application
    • Spits out a YML file which explains how to start. 
      • Tomcat - catalina.sh file. 

Config server - Basics


Cloud Config server: 
Its a way by which we can externalize the property values by moving out of the project. Primarily kept for properties that you normally override or keep secret values out of the project src. 

Motivation:
  • Externalize config data from the applications across all environments. 
  • Store crucial information such as password for DB in a centralized place. 
  • Share data between different services. 
  • See who changed which property and when and why. 

What should you do to use Spring cloud config
  1. Application configuration: 
    • Manage app configuration in a git hub or a local file system. 
  2. Config server
    • Point the location of GIT or local file system where the app config is located (i.e., GIT URI)
    • @EnableConfigServer
  3. Config client
    • Use it normally as how you would read from the properties file 
      • @Value or 

Features
  • Many storage options including Git, Subversion. 
  • Pull model
  • Traceability
  • @RefreshScope for allowing properties to refresh. Calls the constructor of the beans and reinitializes it. 
  • @ConfigurationProperties alternate for @RefreshScope which does reinitialize the Bean that is annotated with @ConfigurationProperties. 
  • Encrypt and decrypt property values. 

Usecases for Cloud config: 
  • Change log level in the properties. 
  • Environment config - containing passwords. 
  • Toggle a feature on or off. 
  • Using @RefreshScope
  • @ConfigurationProperties. 

Order in which the Cloud config looks into the properties files. 
  • Config server. 
  • Command line parameters
  • System properties.
  • Classpath: application.yml file
  • Classpath: bootstrap.yml

Things that you can try: 
  • Simple example to demonstrate properties in Git and reading from config server and client 
  • Using maven profiles specific properties in Config server in Github. 
  • Managing log levels in the Config server
  • Using @RefreshScope and @CofigurationProperties. 

Best practices: 
  • Config server communication with the Git hub, pull every time when client requests for properties file. Use a Jenkins job which will push the properties to a Config server properties (clone). 
  • Single repository for all teams, subdirectories for different environments. 
  • Source code maintenance, having branch per release vs always using the master. 
  • Managing encrypted values for secure data, using JWT with Config server.
  • Use Spring cloud bus to refresh all the services which listens to the rabbitmq.

Note: 
  • Store only things that need to be externalized, I.e., Resource bundles for internationalization should be at the project level. 

PCF Dev - Get started


PCF dev: lightweight version of PCF for local app development, It contains basic services such as mysql, reds etc., 

Requirements: Good memory, 8 GB, 16 GB preferred. 

Getting started with PCF dev: 
  • Installing the PCF dev environment: 
  • Starting PCF dev environment: 
cf dev start
  • Logging into pcfdev: 
cf login -a api.local.pcfdev.io --skip-ssl-validation
user/pass

Have fun with pcf dev in local :-)

Reference:

PCF Manifest file - reference


Manifest file is a way by which you can configure a pcf application without having to use much CLI commands every time you deploy an application. 

A sample manifest file for reference. The application name is mandatory. 

--applications: 
  • Name: myappname <name of the application>
Memory: 512M <Mmemory to allocate for this app M, MB, G, GB (upper or lower case)
Instances: 2 <no. Of instances> 
Buildpack: https://github.com/cloudfoundry/java-buildpack.git <buildpack url or local build pack name>
path: /dist/myapp.jar <location of your application artifact>
host: my-application
(or)
hosts: 
- my-application-1
- my application-2
(or)
no-hostname: true

Command: bundle exec rake VERBOSE=true <command to be executed during startup>
disk_quota: 1024M <disk quota to allocate> 
docker: 
image: dockerimage-repo/imagename <docker image name>
username: docker-user-name <user-name for the docker>
domain: abc.com <domain name>
(or)
domains:

random-route: true <do you want to use a random route to be generated dynamically>
(or)
routes:
- route: test1.abc.com
- route: test2.abc.com
(or)
route-path: test.abc.com
(or)
no-route: true <do you want the app to not have any route> 
stack: cflinuxfs2 <stack to be used>
timeout: 60 <timeout in seconds for starting the application> 
services: 
- mysql-db <name of the service to be bound>
- dvn-new-relic <name of the service to be bound>
env: <environment variables to be used >
APP_HEADER_NAME=Deivee APP
LOCATION=TEXAS
health-check-type: http <http | port | process>
health-check-http-endpoint: /performHealthcheck <custom url for CF to check health of app>