Dockerise Micronaut application.

Micronauts is a java framework to develop a cloud-native microservices application easily and seamlessly. If you don’t know about Micronaut Please go through below two articles. 

In this article, we are exploring a micronaut framework and How to dockerize it. 

Let us create a small micronaut REST service application and try to dockerize it.

Micronaut provides a CLI option to create an application easily.

$ mn create-app helloworld

This will scaffold a new Gradle project. If you prefer Maven, add a --build maven parameter. If you want to create a new Groovy or Kotlin project, add a --lang parameter.

$ mn create-app --lang groovy helloworld-groovy
$ mn create-app --lang kotlin helloworld-kotlin

These options depend on you, which language are you comfortable with.

These options depend on you, which language are you comfortable with. 

Once the project is ready we can import that in your favorite editor. I am using IntelliJ.

We are using already created Hello world app, source code is available at below location you can clone

https://github.com/maheshwarLigade/micronaut-examples/tree/master/helloworld

By default, micronaut app can create Docker file for you and docker file you can locate on current directory of your project <appname>/Docker 

e.g helloworld/Docker

The Default content of Docker file:

FROM adoptopenjdk/openjdk13-openj9:jdk-13.0.2_8_openj9-0.18.0-alpine-slim
COPY build/libs/helloworld-*-all.jar helloworld.jar
EXPOSE 8080
CMD ["java", "-Dcom.sun.management.jmxremote", "-Xmx128m", "-XX:+IdleTuningGcOnIdle", "-Xtune:virtualized", "-jar", "helloworld.jar"]

If you are familiar with docker then fine if not you can explore below article to understand docker.

https://www.techwasti.com/demystify-docker-container-technology-9a8e1ec3968b/

Micronaut create docker file with alpine-slim 

and JDK image which is used here is unofficial.

This repo provides Unofficial AdoptOpenJDK Docker Images,

Reference:- https://hub.docker.com/r/adoptopenjdk/openjdk13-openj9

Thrid line to copy the generated jar(helloworld.jar) file and the expose default port as 8080. Last line to launch the jar file.

For this example, I am using Gradle as a build tool

$ cd helloworld
$ ./gradlew run

To test whether code is working fine or not. (curl http://localhost:8080/hello)

Now build a Docker image from the docker file for that fire below command. 

To run the application with IntelliJ IDEA, you need to enable annotation processing:

  1. open Settings → Build → Execution → Deployment → Compiler →Annotation Processors
  2. Set the checkbox Enable annotation processing

As we know micronaut CLI generates a Dockerfile by default, making it easy to package your application for a container environment such as Kubernetes.

$ docker build . -t hello-world-ex

Fire above command to create a docker image. -t 1.0.0 indicates the tag for this image. Now our image is ready to make a container from its fire below command. 

$ docker run --rm -p 8080:8080 hello-world-ex

As we have exposed 8080 port in docker file. We are doing port mapping to an external system.

to verify the docker image fire below command.

$ curl http://localhost:8080/hello

In this article, we have seen dockerizing micronaut apps. We have created helloworld application and created a docker image using the existing Docker file. You can edit the docker file and optimize it as per your requirement. 

Compare Strings in kotlin

String comparison in kotlin. Equality of String in kotlin. In this tutorial, we will discuss how to compare strings in kotlin?

1. Using “==” Operator:-

As we are aware every programming language gas equal to an operator ( == ) to compare two things. Kotlin also allows equal to equal to as a comparator operator. Let’s start with the “==” operator. This operator can be used to check if the strings are structurally equal. It’s the equivalent of using the equals method in Java. According to the documentation of Equality in Kotlin,  ==  operator is used for Structural Equality.

str1==str2  is implicitly translated to str1?.equals(str2) ?: (str2 === null)  by Kotlin language.

# main method to compare two string using == operator.
fun main(args: Array<String>) {
    var a: String = "kotlin is very easy"
    var b: String = "kotlin is very" + " easy"
    if(a==b){
        println("Strings '$a' and '$b' are equal.")
    } else {
        println("Strings '$a' and '$b' are not equal.")
    }
    # change the content
    b = "Kotlin runs on JVM:)"
    if(a==b){
        println("Strings '$a' and '$b' are equal.")
    } else {
        println("Strings '$a' and '$b' are not equal.")
    }
}

In the above example if you see we have defined string using string literals ‘kotlin is very easy’ so, both the content of the variables is the same and they are pointing to the same object thats why both are equal.

It’s the equivalent of using == in Java

When we initialize string values using String literals, they point to the same object. However, if we build a string separately, the variable will point to a separate object. Let us take one more example.

fun main(args: Array<String>) {
    val a: String = "kotlin"
    val b: String = "kotlin"
    val c = buildString { "kotlin" }
    if(a==b){
        println("Strings '$a' and '$b' are equal.")
    } else {
        println("Strings '$a' and '$b' are not equal.")
    }
   
    if(a==c){
        println("Strings '$a' and '$c' are equal.")
    } else {
        println("Strings '$a' and '$c' are not equal.")
    }
}

2. Using equals():-

In this section, we will explore equals() method to compare two string in kotlin. This method will compare string with case-sensitive nature. “kotlin” and “KoTlin” both are different.

val a = "JVM"
val b = "jvm"

a.equals(b) # this will be return false.

The equals method returns the same result as the “ == ” operator.

If you want to have a case insensitive comparison. Then just pass true as the second argument.

Case-insensitive string comparison in kotlin, we can use the equals method and pass true as the second argument.

a.equals(b, true) # this will be return true.

3. Using compareTo:-

Kotlin provides compareTo() extension function to String, to compare strings equality. Like equals method, compareTo method which can be used to compare the order of the two strings.

Syntax:-

fun String.compareTo(     
 other: String,      
 ignoreCase: Boolean = false 
 ): Int

The compareTo method also comes with an optional ignoreCase argument, like a equal method. But compareTo return int value not a boolean.

Return ValueDescription
0The two strings are equal.
negative integerIf the string is less than the other string
positive integerIf the string is greater than the other string
a.compareTo(b, true) # case-insensitive
b.compareTo(b)  #case sensitive.

4. Conclusion:-

In this tutorial we have discussed comparing strings in kotlin using equal to operator “==”, equals() method and compareTo(). Comparing strings in kotlin is easy and straight forward.

Progurad for android kotlin

Progurad for android kotlin

For more stories.

Something interesting for #AndroidDev

If already new to Proguard read my this two article which will help you to enable proguard for any android project.

  1. Enabling Proguard for Android
  2. How to de-obfuscate stack Trace is here?
This is it.

Google has announced to official kotlin support for Android development. which is really a very cool language. If you haven’t try now.

This is the link sample Project AndroidWithKotlin.

Now in this post, we will look into How we can use progurad in kotlin android project.

Before deep dive here I will recommend you to read my first article Enabling Proguard for Android, then move on.

Enabling proguard is the same process for any kind of the android project.

If you enable proguard for the android project and if you are using some of the kotlin extension libraries then you will come across some issues.

jackson-kotlin-module that provides deserializing kotlin classes and data classes which is a really cool feature.

The fix is here:-

This rule will help you to keep your annotation classes and it won’t warn for reflection classes.

-dontwarn kotlin.**
-dontwarn kotlin.reflect.jvm.internal.**
-keep class kotlin.reflect.jvm.internal.** { *; }

If you have an issue with kotlin MetaData. Especially in case of Jackson kotlin module.

-keep class kotlin.Metadata { *; }
-keepclassmembers public class com.mypackage.** {
    public synthetic <methods>;
}
-keepclassmembers class kotlin.Metadata {
    public <methods>;
}

For enum

-keepclassmembers class **$WhenMappings {
    <fields>;
}

The consolidated rule for kotlin android project.

-keep class kotlin.** { *; }
-keep class kotlin.Metadata { *; }
-dontwarn kotlin.**
-keepclassmembers class **$WhenMappings {
    <fields>;
}
-keepclassmembers class kotlin.Metadata {
    public <methods>;
}
-assumenosideeffects class kotlin.jvm.internal.Intrinsics {
    static void checkParameterIsNotNull(java.lang.Object, java.lang.String);
}

Above rule will sufficient for kotlin android Project. But if you are using different libraries in your project then you have to add those specific configuration based on the error and warnings.

for Moshi

-keep class kotlin.reflect.jvm.internal.impl.builtins.BuiltInsLoaderImpl

which will keep only the no-arg constructor of the service defined in META-INF/services/kotlin.reflect.jvm.internal.impl.builtins.BuiltInsLoader

Thanks, Jake Wharton for this config.

To Learn more about kolin,

kotlin-bootcamp-for-programmers.

I have been following this path, love to hear more from you.

For more stories.

Lets connect on Stackoverflow , LinkedIn , Facebook& Twitter.

Android KTX :- Sweeter kotlin for android

Android KTX :- Sweeter kotlin for android

Google announced android-ktx, which is a set of Kotlin extensions for Android app development. The goal of this sweet killer is to make, kotlin code for Android more concise, idiomatic, and pleasant.

https://youtu.be/kmvS3sZF_y0

Android KTX provides a nice API layer on top of both Android framework and Support Library to make writing your Kotlin code more natural.

Now, the library is only in the preview so it is likely to change – try it out to give your feedback and contributions.

The documentation for KTX can be found here :

and the library is here :

Let’s take a look at some examples of how Android KTX can help you write more natural and concise Kotlin code.

Getting Started :-

To add android KTX to your project add dependencies in your build.gradle file

repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:0.1'
}

Then in your kotlin file import appropriate package and enjoy the coding.

This project will not add any new feature to existing android API. This are the wrapper APIs for android kotlin, this makes kotlin developer life more simple.

String to URI

Kotlin:

val uri = Uri.parse(myUriString)

Kotlin with Android KTX:

val uri = myUriString.toUri()

The simple shared Preference

Kotlin:

sharedPreferences.edit()
    .putBoolean("key", value)
    .apply()

Kotlin with Android KTX:

sharedPreferences.edit {
    putBoolean("key", value)
}

If you are canvas lover

Kotlin:

val pathDifference = Path(myPath1).apply {
    op(myPath2, Path.Op.DIFFERENCE)
}
canvas.apply {
  val checkpoint = save()
  translate(0F, 100F)
  drawPath(pathDifference, myPaint)
  restoreToCount(checkpoint)
}

Kotlin with Android KTX:

val pathDifference = myPath1 - myPath2
canvas.withTranslation(y = 100F) {
    drawPath(pathDifference, myPaint)
}

This is the AndroidX. Add this extension to your tool suite.

Let us apply thoughts and let me know your experience.

If you enjoyed this article, please don’t forget to Clap.

For more stories.

Lets connect on Stackoverflow , LinkedIn , Facebook& Twitter.