Annotations have been a powerful part of Java, but most times we tend to use them rather than create them. In this journal entry, we will be having a look at the creation process of Annotations in Java.

How to Create Annotations in Java?

Annotations have been a powerful part of Java, but most times we tend to use them rather than create them. For example, it is not always difficult to find annotations in Java source code like @Override which is processed by the Java compiler, @Autowired used by the Spring framework. But how often do you see custom annotations? Yes, very rarely. Custom annotations at times can be very useful and become so handy in developing readable code. Creating custom annotations can also be useful in understanding how the common frameworks, such as Hibernate, Spring, etc they accomplish their goals. Let’s now dig into “How to Create Annotations in Java?”

Before creating the annotations lets first understand:

What annotations are?

Why were annotations introduced?

How are they Created?

How to process them?

What are Annotations?

One word to explain Annotation is Metadata. (Metadata is data about data). Basically, Annotations are decorators that when applied to Java code, such as classes, methods, or fields associate the metadata with the construct. The annotations defined are benign and do not execute any code of themselves, instead, they can be used by runtime frameworks or the compiler to perform certain actions.

An annotation is a marker which associates information with a program construct, but has no effect at run time.

Why were Annotations Introduced?

Prior to the introduction of annotations (and even after), XML was extensively used for metadata and separate the configurations from the code. With the growing up of enterprise applications, XML maintenance was getting troublesome. The Application developers and Architects started to look for solutions which could be coupled closely with the code instead of XML which is loosely couples (in some of the cases almost separate) from the code.

Suppose, you want to set some application-wide constants/parameters. In this scenario, XML would be a better choice because this is not related to any specific piece of code. If you want to expose some method as a service, annotation would be a better choice as it needs to be tightly coupled with that method and developer of the method must be aware of this.

Another important factor is that annotation defines a standard way of defining metadata in code. Prior to annotations people also used their own ways to define metadata. Some examples are – using marker interfaces, comments, transient keywords etc. Each developer decided his own way to decide metadata, but annotation standardized things.

These days most frameworks use the combination of both XML and Annotations to leverage positive aspects of both.

How are they Created?

In order to start creating an annotation, we first need to have two important pieces of information:

Retention Policy and Target

A retention policy specifies how long, in terms of the program lifecycle, the annotation should be retained for. For example, annotations may be retained during compile-time or runtime, depending on the retention policy associated with the annotation. As of Java 9, there are three standard retention policies, as summarized below:

Source Annotations are discarded by the compilerClassAnnotations are recorded in the class file generated by the compiler but are not required to be retained by the Java Virtual Machine (JVM) that processes the class file at runtimeRuntimeAnnotations are recorded in the class file by the compiler and retained at runtime by the JVM

Annotation has exactly one associated retention policy.

The runtime option for annotation retention is one of the most common, as it allows for Java programs to reflectively access the annotation and execute code based on the presence of an annotation, as well as access the data associated with an annotation.

The targetof an annotation specifies which Java constructs an annotation can be applied to. For example, some annotations may be valid for methods only, while others may be valid for both classes and fields. As of Java 9, there are eleven standard annotation targets, as summarized below:

Annotation Type Annotates another annotationConstructor Annotates a constructorField Annotates a field, such as an instance variable of a class or an enum constantLocal variable Annotates a local variableMethodAnnotates a method of a classModuleAnnotates a module (new in Java 9)Package Annotates a packageParameter Annotates a parameter to a method or constructorTypeAnnotates a type, such as a class, interfaces, annotation types, or enum declarationsType Parameter Annotates a type parameter, such as those used as formal generic parametersType Use Annotates the use of a type, such as when an object of a type is created using the new keyword, when an object is cast to a specified type, when a class implements an interface, or when the type of a throwable object is declared using the throws keyword.

Annotations may also have associated parameters. These parameters may be a primitive (such as int or double), String, class, enum, annotation, or an array of any of the five preceding types (see Section 9.6.1 of the JLS).

In order to demonstrate how annotations work in practice, we will be creating a sample Annotation name.

The core of the above declaration is the, public @interface MethodInfo which declares an annotation type with a public modifier, which allows our annotation to be used in any package. The body of the annotation declares a single String parameter, named author, that has a type of String and a default value of “DJ”.

Important point of notice in the above example is the variable named author. This variable has a special meaning as it defines a Single-Element Annotation (Section 9.7.3. of the JLS). This allows users using this annotation to supply a single parameter to the annotation without specifying the name of the parameter. Let’s understand this by taking an example, a user can annotate a field using @MethodInfo("developersjournal") and is not required to declare the annotation as @MethodInfo(author = "developersjournal"). Although, the latter can be used but it’s not required.

The inclusion of a default value of string allows for the value to be omitted, resulting in value holding the default string if no value is explicitly specified. For example, if a user declares the above annotation using the form @MethodInfo, then the author parameter is set to “DJ” string.

Notice the two annotations used in the above example @Retention and @Target, these are used to specify the Retention Policy and Target. The retention policy is specified using the java.lang.annotation.RetentionPolicy enum and includes constants for each of the three standard retention policies. The target is specified using the java.lang.annotation.ElementType enum and includes constants for each of the eleven standard target types.

In a short summary, we just created a public, single-element annotation named MethodInfo. This annotation is retained by the JVM during runtime and may only be applied to methods. This annotation created has a single parameter, author, of type String with a default value of “DJ” string. With our annotation created, we can now annotate fields.

Let’s take an example now to understand how to use this newly created annotation.

How are Annotations Processed?

Processing annotations are accomplished through the Java Reflection Application Programming Interface (API). We will use the Reflection API to parse java annotations from a class. Please make a point of the Annotation Retention policy, this should be set to RUNTIME otherwise the information will not be available at runtime and we won’t be able to fetch any data from it.

Annotation in Method: public java.lang.String com.eightbytestech.AnnotationExample.toString(): @com.eightbytestech.MethodInfo(author=&quot;DevelopersJournal&quot;)
Author of the Method is DevelopersJournal
Annotation in Method: public static void com.eightbytestech.AnnotationExample.oldMethod(): @com.eightbytestech.MethodInfo(author=&quot;DJ&quot;)
Author of the Method is DJ

What is a QR Code?

You may have already seen QR Code many times. The best example is Whatsapp Web and we are pretty sure that if not all then most of you know that Whatsapp Web also uses QR Code for login. Let’s understand first what QR Code is? – It stands for Quick Response Code and is a 2-Dimensional Bar Code. This Code stores some data and is represented by black squares over white background. The data stored can be read by the camera or other imaging devices. Below you will see a sample QR Code that we have generated to create a sample Android QR code scanner tutorial.

Sample QR Code

How to Generate QR Code?

The first thing needed to scan a QR Code is a QR Code itself. So for this tutorial, we have already generated a simple QR code consisting the Fruit Name, Size, and Color. Below is the QR Code that we have generated using the free service.

Sample QR Code

To generate your own QR Code you can go to this link. Below the sample JSON String which we have used to generate this QR Code.

We have three values (Fruit, Size, and Color) in the QR Code that we generated. So we have designed the following layout that will display Fruit Name, Size, and Color. We also have a button in the layout that will open up the camera for scanning the QR Code.

Android QR Code Scanner Layout

For your quick reference, we have provided below the XML layout file.

Let’s Code Android QR Code Scanner

Open up your MainActivity.java file and define the view objects.

Next step is to attach OnClickListener to the button.

Once you are done with the above-mentioned steps, its time to Scan the QR Code. But aren’t we missing the main part here? Where is the code for scanning the QR? Well for your reference we have provided below the complete code for MainActivity.java file with proper comments for your easy understanding.

Once you are done with your changes, now is the right time to run your app.

Bingo! Our Android QR Code Scanner is working absolutely fine. Feel free to leave out your comments if having any confusions or queries. Thank You

Are you a developer working on a Node.js application which requires you to provide the functionality of login and registering users. You also want to hash password before saving them to the database. Recently, while working on a similar kind of project we were in the same position and then we recognised the features of BCrypt module to hash passwords. Now taking not much of your precious time, lets quickly dive into understanding this journal entry “Nodejs Hash Password using BCrypt“.

Node.js Hash Password using BCrypt

In this journal entry we’ll not be comparing the different ways of storing passwords. Instead, we’ll be looking at the implementation of salt hashing mechanism for storing passwords in NodeJS. You can be rest assured that this is one of the better ways to store passwords if not the best way.

What is Salt Hashing?

Salt hashing is a technique where we combine the user entered password and a random string with a suitable hashing algorithm. Here the random string of characters are called as salt. Once we get the final result of the combined string and the hashing algorithm we got ahead and store the results in database.

Why Salt Hash?

MD5, SHA1, SHA256, SHA512, SHA-3 are all general purpose hash functions, designed to calculate a digest of huge amounts of data in as short a time as possible. Hashes generated of the same password text are same, they become much easier to crack using rainbow tables or lookup tables. So, if two or more users have the same password, it becomes very easy to predict the password for the attackers. As a rule of thumb, no two or more users should be having the same password hash. Adding salt to a password and then hashing the result reduces the possibility of having duplicate hashes and if your salt length is long enough, chances are minimal.

Understanding BCrypt

Let’s look at the implementation of one of the most popular salt hashing algorithm known as bcrypt.

bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher, and presented at USENIX in 1999.[1] Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power.

The bcrypt function is the default password hash algorithm for OpenBSD.

Bcrypt specification defined a prefix of $2a$. This follows the Modular Crypt Format used when storing passwords in the OpenBSD password file:

$1$: MD5

$2a$: Bcrypt

$sha1$: SHA-1

$5$: SHA-256

$6$: SHA-512

Now lets take a practical look at implementation of bcrypt using NodeJS.

Practical Implementation

Lets first make sure that the version of node we are using is the latest and stable version. If you are not on the latest version then go ahead and check out the following journal entry Upgrade Nodejs Version.

The above command will install the bcrypt module locally in your project under the “node_modules” folder. The --save option here basically makes the changes inside your package.json file. In case you miss the --save option then you have to modify the package.json file yourself and make an entry in the “dependencies” block.

Usage

Ok, now that you have your project ready with the bcrypt module added, let’s see how are we gonna use this module.

with promises

bcrypt uses whatever Promise implementation is available in global.Promise. NodeJS >= 0.12 has a native Promise implementation built in. However, this should work in any Promises/A+ compilant implementation.

Async methods that accept a callback, return a Promise when callback is not specified if Promise support is available.

Why is async mode recommended over sync mode?

If you are using bcrypt on a simple script, using the sync mode is perfectly fine. However, if you are using bcrypt on a server, the async mode is recommended. This is because the hashing done by bcrypt is CPU intensive, so the sync version will block the event loop and prevent your application from servicing any other inbound requests or events.

A Note on Rounds

When you are hashing your data the module will go through a series of rounds to give you a secure hash. The value you submit there is not just the number of rounds that the module will go through to hash your data. The module will use the value you enter and go through 2^rounds iterations of processing.

Conclusion

If you are working on any web application that stores users password, it is very easy to get things wrong, here we saw how we can store passwords using salt-hash technique which is highly recommended, however it is a request to the readers to look up at recent techniques of storing passwords from the time you are reading this article.

Your First Node Project

To start writing and creating your first Node project, pick up your favorite editor. We are using Brackets as one of our favorites editor.

Once you are all setup with your editor, lets create a new file and copy the following content.

console.log("Hello World!!!");

Save the file as firstnode.js. You can also choose the name as per your likings.

Go to the Command Prompt in windows or Terminal in Linux/Mac. Change the directory where you have saved the above file. Now run the following command and see the magic.

node firstnode.js

The output that you will see on the screen is Hello World!!!

Wooo hooo! You just ran your first Node project.

But wait didn’t you ganna ask the question What is this? Is creating a Node project just like that simple? Where is the npm used in this project?

Let’s understand what exactly npm is?

The main purpose of npm is used to maintain the dependencies used in the Node projects and in the above example, we haven’t used any depedent module.

In the next example, we will try to use npm for creating a Node project.

Lets create a new folder and move to that folder on the terminal screen. Now lets use the following command to create a new Node project:

npm init

The above command will ask you few question, answer all those questions.

You must be wondering what all these questions are? So let’s understand these questions in slightly more details.

Name: This is the actual name of your application, you are writing. Point of note here is that the name should be in lowercase letters, with no spaces between words. You are allowed to use dashes/underscores in between.

Version: This will be version of your application. Its your responsibility to update the Major or Minor release version of your application. The updation of the version number should follow the Semantic Versioning.

Git Repository: If you are looking for source control, then you can specify your git repository url for this question.

Keywords: These will be main words related to your project which comes up during search for a Node module.

Author: You want the popularity, use this question to fill out your Name and Email address.

License: Licensing option for your project.

Once you are done with all the questionnaire you are ready with the your First Node project using npm to handle all your dependencies for your project. You might find a new file automatically created for you “package.json” in your project folder.

To modify the answer to any of the above questions, you can directly update the package.json file in your favorite editor.

The Java Platform, Standard Edition (Java SE) is used by wide variety of applications whether its a small applet on desktops or web services on large servers. In order to support this diverse range of deployments, the Java HotSpot VM provides multiple garbage collectors, each designed to satisfy different requirements. Java SE selects the most appropriate garbage collector based on the class of the computer on which the application is run. However, users, developers, and administrators with strict performance goals or other requirements may need to explicitly select the garbage collector and tune certain parameters to achieve the desired level of performance. This journal entry is the first part of the series Introduction to Java Garbage Collection Tuning.

Why Does the Choice of Garbage Collector Matter?

The purpose of a garbage collector is to free the application developer from manual dynamic memory management. The developer is freed of the requirement to match allocations with deallocations and closely take care of the lifetimes of allocated dynamic memory. This completely eliminates some classes of errors related to memory management at the cost of some additional runtime overhead. The Java HotSpot VM provides a selection of garbage collection algorithms to choose from.

When does the choice of a garbage collector matter? For some applications, the answer is never. That is, the application can perform well in the presence of garbage collection with pauses of modest frequency and duration. However, this isn’t the case for a large class of applications, particularly those with large amounts of data (multiple gigabytes), many threads, and high transaction rates.

Amdahl’s law (parallel speedup in a given problem is limited by the sequential portion of the problem) implies that most workloads can’t be perfectly parallelized; some portion is always sequential and doesn’t benefit from parallelism. In the Java platform, there are currently four supported garbage collection alternatives and all but one of them, the serial GC, parallelize the work to improve performance. It’s very important to keep the overhead of doing garbage collection as low as possible. This can be seen in the following example.

The graph in Figure 1-1 models an ideal system that’s perfectly scalable with the exception of garbage collection. The red line is an application spending only 1% of the time in garbage collection on a uniprocessor system. This translates to more than a 20% loss in throughput on systems with 32 processors. The magenta line shows that for an application at 10% of the time in garbage collection (not considered an outrageous amount of time in garbage collection in uniprocessor applications), more than 75% of throughput is lost when scaling up to 32 processors.

This figure shows that negligible throughput issues when developing on small systems may become principal bottlenecks when scaling up to large systems. However, small improvements in reducing such a bottleneck can produce large gains in performance. For a sufficiently large system, it becomes worthwhile to select the right garbage collector and to tune it if necessary.

The serial collector is usually adequate for most small applications, in particular those requiring heaps of up to approximately 100 megabytes on modern processors. The other collectors have additional overhead or complexity, which is the price for specialized behavior. If the application does not need the specialized behavior of an alternate collector, use the serial collector. One situation where the serial collector isn’t expected to be the best choice is a large, heavily threaded application that runs on a machine with a large amount of memory and two or more processors. When applications are run on such server-class machines, the Garbage-First (G1) collector is selected by default.

It is critical to update WordPress plugins associated with your WordPress Site as often as possible. An updated WordPress site not only keeps you updated with the latest versions but can help you with an increase in the traffic and bring in more users.

To keep your website secure, you might set the security settings to be as read-only. By keeping these settings you also prevent your WordPress installation and the plugins from updating. Sometimes not updating your WordPress installation seems to be a bigger issue than those security settings.

However, in some of the cases, you are not able to update/upgrade your WordPress and plugins to the latest versions without providing a valid FTP connection information. This is one of the common issues whereby the WordPress system can’t access to write/update your /wp-content folder.

Update WordPress Plugins

To solve these types of issues there are two ways:

Define the FTP details in the /wp-config.php file. This will be picked up by WordPress while updating the system.

You may provide the Write access to the /wp-content folder. This can be done by changing the folder file permission (CHMOD) to 775. Normally the default file permissions are 755 or 644.

However, there is another easier way to deal with updating the WordPress installation and the associated plugins. It’s simple and straightforward, you have to define a constant, FS_METHOD in your wp-config.php file. This constant bypasses WordPress’s recurring prompts and allows auto-updates of your files. This process just needs only 1 line of code to be written.

For your ease of understanding here the steps taken to do this:

1. Open /wp-config.php

Now the first thing you need to do is to open the wp-config.php file from your WordPress root folder (you may access this file from your WordPress installer folder). From the installation folder, the file is located at WordPress/wp-config.php

2. Insert FS_METHOD

Paste the following code into your wp-config.php file, preferably just below every other line of code. define(‘FS_METHOD’, ‘direct’);

3. Save And Upload

When you have already pasted the one-line code, you can proceed to upload the file to your WordPress root folder on your server, and it should work right away. Uploading can be done directly from your host control panel.

Dependency Injection (DI) is a design pattern which has been around for while, but recently it has become more commonly used in the development of Android applications, due mainly to the implementation of some rather nifty DI frameworks. You must be aware of Marinator – Dependency Injection Framework for Android. However, in this journal entry we will be having a look at Koin Dependency Injection which uses Kotlin for Android.

DI allows developers to write code that has low coupling and which can therefore be easily tested. The more complex and longer lived your Android software the more important it becomes to be able to test it effectively.

Koin Dependency Injection

KOIN is a simple (but powerful) dependency injection framework for Android. It uses Kotlin and its functional power to get things done! No proxy/CGLib, no code generation, no introspection. Just functional Kotlin and DSL magic

KOIN is a very small library, that aims to be as simple as possible and let’s you write dependency injection in a breath.

Just describe your stuff and inject it!

Getting Started

To get started with using Koin on your Kotlin based Android application make sure that you have jcenter repository in your gradle.build file. Once confirmed, add the following gradle dependency to your Android app:

When using dependency injection, getting access to the classes which perform the injection is a common problem. On Android, the most common solution to this tends to be to store the components in the Application object. But this then requires the developer to reach into their Application object in multiple places throughout their code. This creates several challenges – in addition to just looking ugly, it can make it harder to write pure JUnit tests. In this journal entry, we will be having a look at Marinator Dependency Injection.

Marinator Dependency Injection made delicious

Marinator helps solve this problem by wrapping your components with a simple static class. Instead of calling code like MyApplication.get().getComponent().inject(this), you can simply call Marinator.inject(this). Marinator relies on an annotation processor to generate a helper that registers your injectors – as a developer, all you have to do is annotate your injector methods and provide the component to the MarinadeHelper.

Marinator was created with Dagger2 style dependency injection in mind. But there’s no requirement that you use Dagger2 or even any sort of framework for DI to use Marinator. As long as your injector class has a method annotated with @Injector, Marinator will recognize this and add it to the prepare method.

Setup

Marinator is distributed via Jitpack. To use Marinator in your project, add the following lines to your build.gradlefile:

When you define your components, declare the injector methods and annotate them with @Injector. So, as an example:

@Singleton@Component(modules=ApplicationModule.class)
publicinterfaceApplicationComponent {
@Injectorvoidinject(Reciperecipe);
// Note that the injector method can be named// whatever you want - it doesn't have to be// called "inject".@Injectorvoidprovide(Winewine);
// Other Dagger component dependencies declared here.
}

The next time you compile after adding this annotation, the annotation processor will generate the MarinadeHelperclass for you. Wherever you create your components, you can use the MarinadeHelper to register them as injectors:

You can also register/unregister injectors dynamincally using Marinator. This helps if you need to register an injector for less than the entire lifecycle of the application.

Finally, in your classes, use Marinator to inject the necessary dependencies. The code doesn’t care whether the components were provided by the application, by a unit test, or by something else altogether:

Visual Studio Code is a lightweight but powerful source code editor which runs on your desktop and is available for Windows, macOS, and Linux. It comes with built-in support for JavaScript, TypeScript and Node.js and has a rich ecosystem of extensions for other languages (such as C++, C#, Python, PHP, Go) and runtimes (such as .NET and Unity). As VS Code is a cross-platform tool that runs on Windows, Linux and macOS — and JavaScript is becoming the programming language for all kinds of cross-platform projects, here are some of the most useful JavaScript snippet packagesavailable in the marketplace, based on the number of downloads, ratings, and plain old subjective assessment.

JavaScript (ES6) Code Snippets

As JavaScript evolves in a series of new versions, the Sixth Edition of the ECMA-262 standard, otherwise known as ECMAScript 2015 or ES6 is a hot topic, with many features being adopted by major browsers.

Charalampos Karypidis has published JavaScript (ES6) code snippets: “Code snippets for JavaScript in ES6 syntax.”, to help you quickly take advantage of new features such as classes, arrow functions, promises and much more.

The snippet package — which supports both JavaScript and TypeScript — has been installed more than 418,562 times and has a rating of 4.5 out of 5 at the time of writing this post.

Angular v4 TypeScript Snippets

The AngularJSand Angular(TypeScript-based) frameworks, originally developed by Google, are all over the VS Code extension marketplace.

We will be discussing Angular v4 TypeScript Snippets from John Papa, for Angular 4.0.0, just formally released in March. It’s said to be smaller and faster and includes new featureslike a revamped ahead-of-time view engine, TypeScript 2.1 and 2.2 compatibilities, experimental ES2015 builds and more.

This snippet package has been installed more than 526,076 times and had a rating of 5 out of 5.

In this journal entry, we will be having a look at AngularJS vs jQuery. We will also try to list down some of the best features available in both of these technologies. But before diving deep into this topic lets first understand these topics in slight more details.

AngularJS

AngularJS is a product by Google and it’s MVC-based framework. AngularJS is a great tool for creating dynamic and highly rich client side web applications. As being a framework, it dictates us to follow some rules and a structured approach. It’s not just a JavaScript library but a framework that is perfectly designed.

AngularJS utilizes HTML’s syntax as your template language and develop the components of your application compactly. Dependency Injection and data binding, few of the features of AngularJS helps to eliminate major chunk of the code which otherwise had to be written.

If the end-user disables JavaScript on their browsers then they only see the basic HTML page.

jQuery

jQuery is a lightweight, quick, small, and feature-rich Javascript Library. jQuery tries to make HTML tag traversal and control, animations, event handling, and Ajax calls more straightforward. All of these are done via a simple API calls that works over many programs.

Using jQuery, we can:

easily manipulate the contents of a webpage

apply styles to make UI more attractive

easy DOM traversal

effects and animation

simple to make AJAX calls and

utilities and much more… etc.

Now we have a slight understanding of what these two technologies exactly are and capable of, let’s look at some of the differences and features of AngularJS and jQuery.

AngularJS vs jQuery

AngularJS

jQuery

AngularJS is best suited for the web application development

jQuery is a fast and feature-rich language

Helps in developing interactive and robust web applications.

A commendable JavaScript library and a great tool for creating feature-rich websites