How To Manipulate Source Code Using Java Annotation Processing API

word-image

Technology

The source level annotations are introducing in Java 5, it provides the features to create additional source files during the compilation stage.

The source code files are not limited to java files, files can be any kind like metadata, documentation or any type of resource.

Annotation Processing API is actively used in many open source frameworks like Spring Query DSL and JPA etc.

The limitation with this API is it only used to generate new files, it will not modify the existing files.

Execution

word-image

The annotation processing is done at multiple rounds. Each round starts with compiler searching for the annotations in java source, choosing the annotation processors suited for these annotations, each annotation processor is called in corresponding sources.

If any files are created during the process, another round start with generated source files as input, it will continue until no new files are generated during the processing stage.

The annotation processing API is located in the javax.annotation.processing package. The main interface that you’ll have to implement is the Processor interface, which has a partial implementation in the form of AbstractProcessor class. This class is the one we’re going to extend to create our own annotation processor.

Setting Up the Project

For demonstrations of annotation processing, we will spilt our project into 2 modules, one of them annotation-processing module which will contain annotation processor, another will be annotation-user module.

First, we will implement annotation-processing module, for annotation processing we are going to use Google`s auto-service library which used to create processor meta-data.

It is recommended to use Google auto-service and maven compiler plugin latest versions found in Maven Central Repository.

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<auto-service.version>1.0-rc4</auto-service.version>

</properties>

<dependencies>

<dependency>

<groupId>com.google.auto.service</groupId>

<artifactId>auto-service</artifactId>

<version>${auto-service.version}</version>

<scope>provided</scope>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.8.0</version>

<configuration>

<release>11</release>

</configuration>

</plugin>

</plugins>

</build>

And annotation-user simply use annotation-processor as its dependency.

<dependency>

<groupId>org.sravan</groupId>

<artifactId>Annotation-Processing</artifactId>

<version>${project.version}</version>

</dependency>

Let’s create a @BuilderProperty annotation in the annotation-processor module for the setter methods. It will allow us to generate the Builder class for each class that has its setter methods annotated:

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.SOURCE)

public@interfaceBuilderProperty {

}

The @Target annotation with the ElementType.METHOD parameter ensures that this annotation can be only put on a method.

The SOURCE retention policy means that this annotation is only available during source processing and is not available at runtime.

Implementing Processor

word-image

AbstractProcessor is the abstract implementation of Processor interface, now lets extends the this class and implement the abstract methods.

@SupportedSourceVersion(SourceVersion.RELEASE_8)

@SupportedAnnotationTypes(“org.sravan.annotation.processor.BuilderProperty”)

@AutoService(Processor.class)

publicclass BuilderProcessor extends AbstractProcessor {

@Override

publicboolean process(Set<? extends TypeElement>annotations, RoundEnvironment roundEnv) {

returnfalse;

}

We should specify the annotations that this processor is capable of processing and also source code version. This can be done either by implementing getSupportedAnnotationTypes and getSupportedSourceVersion of the Processor interface or by annotating your class with @SupportedAnnotationTypes and @SupportedSourceVersion annotations.

And the process method returns true if all supported annotations are processed, and don’t want to process by another annotation processor down the list.

@AutoService annotation is itself processed by the annotation processor from the auto-service library. This processor generates the META-INF/services/javax.annotation.processing.Processor file containing the BuilderProcessor class name.
annotations variable in process method will contain all the annotation types found in the class.

RoundEnvironment instance to receive all elements annotated with the @BuilderProperty annotation.

for(TypeElement annotation: annotations)

{

Set<? extends Element>annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);

}

@BuilderProperty annotation’s user could erroneously annotate methods that are not actually setters. The setter method name should start with set, and the method should receive a single argument. So lets separate the methods which are correctly annotated and other erroneously annotated methods using Collections.partitionBy() collector.

Map<Boolean, List<Element>>annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType)element.asType()).getParameterTypes().size()==1 &&

element.getSimpleName().toString().startsWith(“set”)));

List<Element>setters = annotatedMethods.get(true);

List<Element>otherMethods = annotatedMethods.get(false);

We should warn the user if the method is incorrectly annotated, for this we can use AbstractProcessor.processingEnv protected field.

otherMethods.forEach(element ->processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, “@BuilderProperty must be applied to a setXxx method with a single argument”, element));

and also if the correctly annotated methods are not present then we can skip the current iteration.

if(setters.isEmpty())

{

continue;

}

Then we need to get the fully qualified class name using setter methods using below code.

String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();

we will store setter methods name, and argument type in map and use it iterate to generate source file.

Map<String,String>setterMap = setters.stream().collect(Collectors.toMap(setter ->setter.getSimpleName().toString(), setter -> ((ExecutableType)setter.asType()).getParameterTypes().get(0).toString()));

Now lets create Person class in annotation-user module like below,

publicclass Person {

privateintage;

private String name;

publicint getAge() {

returnage;

}

@BuilderProperty

publicvoidsetAge(intage) {

this.age = age;

}

public String getName() {

returnname;

}

@BuilderProperty

publicvoid setName(String name) {

this.name = name;

}

}

Running the Example

Although the Java Annotation Processing API is easy but sometimes you would need a custom development to do the source level annotation.

If you don’t want to go through all that trouble I would suggest you should consider Java development outsourcing which is rather easy and hassle-free.

Anyways moving on, now if we compile annotation-user module below java file is generated under annotation-user/target/generated-Sources/annotations/com/baeldung/annotation/PersonBuilder.java and it will look like below:

package org.sravan.annotation;

public class PersonBuilder {

private Person object = new Person();

public Person build() {

return object;

}

public PersonBuilder setName(java.lang.String value) {

object.setName(value);

return this;

}

public PersonBuilder setAge(int value) {

object.setAge(value);

return this;

}

}

Conclusion

In this content, we learned how source-level annotations are processed to generate the source files using the Google Auto Service Library.

The Source code can be found in the attached zip file.

https://drive.google.com/file/d/1z0sszFN47JZAYimd1oexHF2v7bGZQ1Vb/view?usp=sharing

How to Keep Your Design Files Organized

design folders

A logo is only one of the many designs you will use as a business. The logo may have several versions stored in different files. You then have the designs for letterheads, identities, brochures, promotional materials, and many others to maintain. It doesn’t take long before you start dealing with hundreds of design files related to your business.

Keeping them organized is a necessity and not an option. When you have a good design file management system, you can always find the design files you need at any moment. The file management system also allows you to protect your design files better, all while maintaining consistency with your materials.

Even better, you don’t have to use a complex system to keep your design files organized. These tips and tricks will help you get started with managing your files. Continue reading

5 Warning Signs Of A Bad Web Design Company

web designIf you’re a business owner and you want to expand and strengthen your branding, you need to have a good representation of your products and services. An excellent way to do this is by using an online marketing strategy, typically in the form of a website.

You can either do a crash course on web design and create your own website or leave it to the experts by hiring web designers. To make sure that you’re looking at a web design company with a good reputation, you can look for some warning signs that will help you avoid choosing the bad ones. Continue reading

How your Business can Contain and Recover from a Cyber Attack

cyber attacker - hacker

There’s no doubt that cyber attacks and data breaches have become more common than ever before, with more than 66% of businesses falling victim in recent years. These attacks get larger and impact more people as the frequency increases as well, reportedly affecting 2.3 billion users in 2017 alone. This escalation of cybercrime puts businesses and individuals on high alert and increases the need to implement online security measures in order to protect sensitive information. Luckily, there are proven steps you can take preemptively and in reaction to a breach that will minimize the damage in the case that an attack does occur. A few of these preemptive measures include knowing what risks look like, installing firewall and antivirus technologies, creating a file backup and recovery plan, creating strong passwords, locking down mobile devices and utilizing administration access. Following suit with the preemptive precautions, there are many reactive measures you can take in response to an attack to minimize the negative impact on your business, employees and customers. Here are a few of those reactive tips that can help your business build its defenses against and respond to cyber attacks should one occur: Continue reading

Improving Your Legal Business in 2019

legal

Would you like to make 2019 the best year ever for your legal business? To make any kind of difference you’re going to need to make manageable changes. There are a variety of ways this can be done. This includes making use of the latest productivity tools, investing in your employees professional development, and making use of data. You’re also going to have to do everything you can to stand out from the competition, entice new clients and encourage loyalty in your current customer base. Continue reading

10 Extra Rich Mega Bundles For WordPress Users

image8

In 2019, bundles are extremely popular and there’s nothing unusual. These packages literally allow you to save money without trouble. In this post, we are about to showcase you 10 amazing WordPress bundles that are totally code-free.

Needless to say, building a website is an important and even must-have process for any company. And how can you do it without having any extra skills or web design experience? Well, actually, there is nothing complicated. Thanks to such graphics resources providers as  MasterBundles website creation became a fast and simple process.

To make a long story short, let name the main reasons why these WordPress bundles are worthy of your attention!

  1. To start with, all these bundles contain numerous website themes, fonts, assets, plugins, options, and other UI components. All of them are fully customizable, so you can quickly build the very website or websites.
  2. Secondly, there will be regular updates and free technical support which is a coll beginning for any project.
  3. Thirdly, you won’t need to touch a single line of code working with these items!
  4. On the other hand, you can save good money by buying a bundle. Just look at these discounts!

#1 Mega Web Design Bundle with Extended License – Only $19

image8

Let’s start with this rich product that was professionally designed for users of any skills levels. As the name of the product says, Mega Web Design Bundle contains a huge amount of colorful designs. There are so many styles to choose from! On average, the package consists of 17 themes, 4 scripts, and 9 plugins. Each of theme has a unique style, so everyone will find there something up to their personal taste.

What will you get choosing Mega Web Design Bundle? Here are the themes:

  • Artemis Responsive One Page Parallax WordPress Theme;
  • Sipress Community Responsive WordPress Theme;
  • Ferado – WooCommerce Fashion Theme;
  • Recipesbook (Gustos) – Recipe Social Network WordPress Theme;
  • Agenture Ultimate Premium Multipurpose WordPress Theme;
  • Gravity Responsive Coming Soon Theme;
  • Xenia Responsive One Page Parallax Theme;
  • Artemis Responsive One Page Parallax Theme;
  • RK Theme;
  • Confidence – OnePage HTML5 Template;
  • Baily – Responsive Resume Template;
  • Rangbazz – Responsive One Page Template;
  • Star Host – HTML5 Responsive Website Template;
  • Baktigoto – Responsive Resume & Portfolio HTML5 Template;
  • Fitness – One Page Responsive Template;
  • Building Structures PSD Template;
  • and Phyon – Multipurpose Responsive PSD Template.

And the price is only $19!

#2 Crocoblock Elementor Subscription

image1

in 2019, Crocoblock is already quite a popular thing. It allows users to get everything and anything for a web design without running out of the budget. To make a long story short, choosing Crocoblock, you will get:

  • an ace package of 11 premium Jet Plugins that were made for the most popular drag & drop page builder – Elementor;
  • 30+ demos;
  • more than +1000 ready-to-use sections;
  • 300+ unique pages;
  • 8 stunning gallery layouts’
  • header & footer builder;
  • friendly technical support;
  • regular updates, and much more!

Today, Crocoblock comes with a 40% discount. Thus, it will cost you $47!

#3 29 Premium Responsive WordPress Theme Mega Bundle

image5

Talking about this comfy WordPress Theme Mega Bundle, let’s start with its price. Why? Simply because right now the item has 97% off! It will cost you only $29. And what will you find inside the bundle? There are such things as:

Visual Composer for WP;

  • premium addons for Visual Composer;
  • visual elements Plugin;
  • fully customizable themes options,
  • shortcodes
  • frontend and backend editors
  • Advanced Grid Builder
  • many background options (like parallax and video backgrounds)
  • fully customizable headers, and much more!

#4 12 Modern and Responsive WordPress themes

image2

Here is another smart product which comes with this amazing 98% discount. Today’s price for the bundle is only $29 and here is what you will find inside its pack:

  • 12 fully responsive WP themes with unique design,
  • commercial license,
  • free24/7 tech support,
  • numerous Retina-ready icons,
  • Search Engines Optimization,
  • 600+ readable web fonts,
  • MegaMenu plugin, and much more!

On average, all of these would cost you almost $1.200 but bundles were invended to save your money. That’s why you can get all the named options just for $29.

#5 WordPress Themes Bundle: 19 Premium Themes for just $27

image6

Here is a handy WP themes bundle which contains 19 premium WordPress themes and not only! For these simple reasons, using the bundle you can easily build such projects as:

  • a designer portfolio,
  • a lifestyle blog,
  • a fashion website,
  • a full-fledged web store, etc.

And what is waiting for you inside the pack? You’ll get the next features:

  • choice of color schemes
  • Google Fonts integration
  • custom plugins & widgets
  • high-quality stock images
  • 100% responsive layouts, etc.

By tradition, after the discount, the price of the bundle is only $27.

#6 10 Restaurant WordPress Themes

image3

In case you are looking for a 100% customizable and easy-to-use set of templates, check out this amazing WP bundle! After the discount, the items price is $39, so don’t miss the boat. Among the main features you will get, there are:

  • Cherry Framework;
  • Back To Top Button;
  • calendar;
  • Crossbrowser Compatibility;
  • custom page templates;
  • Dropdown Menu;
  • Favicon;
  • Social Options;
  • and Tag Cloud.

#7 WordPress Bundle: 10 Premium Themes for $15 ONLY!

image7

First things first, this bundle contains 10 premium themes and you can get them for $15 only! Here are some of the main features you will get:

  • Improved navigation (MegaMenu)
  • Custom Page Templates
  • Google Fonts integration
  • Custom plugins & widgets
  • Social Options
  • Cherry Framework 4
  • WPML readiness

#8 19 Premium Templates & Plugins for $15 ONLY

And the next impressing bungle which will cost you only $15 is 19 Premium Templates & Plugins. Here is what you will get inside the package:

  • Claire Elegant Blog & Magazine WordPress Theme;
  • Photo Portfolio Professional Template;
  • 3D Photo Html5 Template;
  • Full Creative Portfolio Template;
  • Photo Video Htm5 Template;
  • Sevens Modern Template;
  • Freshener Modern Template;
  • Hero Business Template;
  • Creative Photo Album Template;
  • CSS Background Styles, and more!

#9 Mega WordPress Theme Bundle

image9

Mega WordPress Theme Bundle is a wonderful collection of 15 modern web designs. All of them are creator-friendly and come with many useful features. There are multiple trendy elements as well! Here is what you will get for $15 only:

  • 15 ready-made WP themes;
  • customizable colors, fonts & backgrounds;
  • built-in galleries;
  • high-quality plugins & widgets;
  • stock images;
  • 100% responsive layouts;
  • SEO-readiness, etc.

#10 Mega Developer Bundle – $49 ONLY

image4

Finally, it’s time to view out our last but not least bundle. It was designed for big web developers and web designers. In the pack of the item, you’ll find:

  • WordPress Themes,
  • HTML5 & Bootstrap Templates,
  • HTML5 Galleries,
  • Landing Pages,
  • Newsletter Templates,
  • HTML5 Apps,
  • CSS Menus & Utilities.

 

On average, there are over 80 premium products in the bundle!

Learning From Mistakes: 6 Things I wish I Did Earlier As A Blogger

For the past 3 years, I have been blogging and I am fortunate enough to make a living out of it.

You might think that 3 years is not that big of a deal but it is for me. At first, I was doing it for money then I got to know more about it and I got very passionate about it.

So over these years I have learned a lot and made many mistakes along the way. So today I am going to share with you what mistakes I made and what should you learn from them if you starting out as a blogger. Continue reading

8 Signs That Your Business Should Outsource Digital Marketing Services

Guy looking at digital marketing strategy and being overwhelmed

Your business or brand will significantly benefit from the right marketing strategies. Digital marketing has existed for quite a while, but it continues to change and evolve as technology advances and becomes more innovative. You need to be up-to-date with the trends and keep up so that you won’t be left behind by competition. Regardless of the industry that you’re in, the digital marketing techniques of your company need to work together to thrive in an Internet-based society.

If you’ve been making your own marketing efforts alone and didn’t see any significant results, it may be time to hire some outsourced help. Here are eight signs that your business should outsource digital marketing services: Continue reading

Top Amazon Small Business Ideas for Beginners to Make Passive Income

making money with amazon
Looking for Amazon business ideas where you can start with a small capital that will generate passive income? If you answered YES, then read on for some business ideas for beginners that will jumpstart your way to earn money. You can also check out academy journalreview.org for tips on how to run a successful business.

Amazon is arguably the largest e-commerce website that caters to customers worldwide. The giant marketplace has sold more than 362 million products and gained more than 6.1 million visits daily. It is indeed an e-commerce giant that can help you succeed, so why not take this opportunity?

Here are the ways beginners can make a passive income with Amazon. Continue reading

The Best VPNs to Access Social Media And Netflix

VPN

Geo-blocking is the mood killer for any Netflix fan and social media dweller. Your favorite movie or series could finally appear in Netflix’s library only for you to find out that it’s not available to stream from where you live. However, geo-blocking applies not only for streaming sites but for other websites like social media, as well.

If you’re on holiday abroad, nothing would be a bigger downer than discovering that you can’t share that Instagram story to your friends because the local networks are blocking access to your social media of choice. Thankfully, there are ways to enjoy geo-blocked content from anywhere in the world with an internet connection. Continue reading

6 Features That Every Business Website Need

Do something great sign for your business website

Every entrepreneur is aware of the importance of a website for their business as this is how you raise awareness about your brand in today’s digital marketplace. While it is true that every company needs a website no matter what industry they are in, there is much more to it than this as you will need to have a high-quality website which converts the visitor into a customer. This is an enormous challenge that business owners face, but once you know exactly what your website needs then it can make it much easier to convert visitors. Read on for aspects that all business websites need: Continue reading

5 Essential Steps To Become A WordPress Developer

wordpress developerWordPress is the most popular content management system (CMS) today, powering more than 30% of websites on the internet. Among the top CMS platforms, it holds around 60% market share, far ahead from second contender Joomla (6%).

Since the CMS has more than 76 million users, not all of them can do development work on their own. They look for WordPress developers to improve their site or add new functionalities. The work of a WP developer will include creating useful plugins, beautiful themes, improve core of the platform, and more.

The above stats show how much popular a platform WordPress is. Becoming a WordPress developer will prove to be a right choice for people who are interested in the platform.

I guess this is enough for encouragement. The next question that remains unanswered is how to become a WordPress developer. Well, this article is all about that. Below are the key steps that you should follow for a successful career as WordPress developer. Continue reading