Tag: java web development

HOW TO USE JENKINS WEB-BASED BUILD MANAGEMENT TOOL IN JAVA APPLICATIONS?

In this post, java application development experts will discuss Jenkins web-based build management tool and its requirement in developing projects. You can read this post and learn how to install Jenkins and make the best use of this management tool.

Introduction:

The necessity of building a tool is to integrate the source code properly which is developed by many people for a single project. Each developer works on different modules from the same code base, so frequently the code gets updated.

The build management tool’s responsibility is to take the latest version of code from the repository and produce the new version of Project.  The good feature of Jenkins is we can use any build tool and version control. For example, if you are using ANT based build tool, we can configure ANT in Jenkins for your project build process.

If your project is using a Maven-based build, you can configure Maven for your Project. Similarly, you can set up any version control which is available from Jenkins. You can use CVS, SVN, and GIT, etc.  So, The Jenkins is not live with one particular tool, based on the project requirement, we can customize the Jenkins.

I will be explaining the following things in this article.

  1. Jenkins installation steps.
  2. Creating Project in Jenkins
  3. Integrating the Maven build tool in Jenkins
  4. Building project using Jenkins.

Jenkins installation steps

Go to the following official website for Jenkins

https://jenkins.io/

Once you click the download button it will prompt the following window

Click LTS Release which is a stable one. You will be getting the installer file from the download. Double click on the installer and follow the steps to install. You will be seeing the following steps to install it successfully.

After successful installation following folder should create in your windows S.

<Your drive>:\Program Files (x86)\Jenkins

Following the path, you can see a Jenkins.war.

C:\Program Files (x86)\Jenkins

Copy Jenkins war file to your tomcat location of web app folder. Start the tomcat server by clicking the startup.bat file. After starting the server, you can see the Jenkins-related logs in the server console without error. It means Jenkins deployed in the server successfully.


In the web app folder, you can see the Jenkins folder which is extracted from Jenkins.war.

Use the following URL to get the Jenkins home page in your local.

http://localhost:8080/

This URL gives the home page of Jenkins as in the below screenshot.

Now, we have installed Jenkins in our system and it is running successfully.

Creating Project in Jenkins

Creating Project means you are creating a building management Project for your existing Java Project.

Click “create new jobs”. It will show the following screen.

Select maven project and enter the project name. Here I have entered it as “java-spring-maven” then click ok. Next it will ask you to enter project settings for “java-spring-maven” as in the screenshot.

Add some description about the project as in the screenshot.

Select source management as none because I have not used any source management.

Enter the pom.xml file path in the Root POM text field and enter the maven Goals as in the screenshot. The pom.xml file path should be from your java project folder. In this example, I am using the java-spring Project which is coming from “F:\Work\example-workspace\java-spring”. Create a simple maven-based project using eclipse and share that pom.xml file in the field as in the above screenshots.

If you want to get an email notification while building failure, select the “E-mail Notification” check box and enter a valid email as in the screenshot.

Once you enter all, click the Save button and the following screen will appear.

Till now we have integrated the maven build tool in Jenkins for a java based maven Project.

We have configured the maven build tool in our project and the next step is we need to add JDK and maven in Jenkins to run the build.

Click manage Jenkins, you will get the following screens.

Click Configuring system
Click Add JDK Button as in the screenshot

Once you click “Add JDK” the following section will appear.

Deselect install automatically checkbox. Once you have done that, the following section will appear.

Enter your Java version name in the JDK Name field and enter your java home in the JAVA_HOME field as in the screenshot.

Now we need to give maven information as follows. Click Add maven button as in the screenshot.

Once you click, the following section will appear.

Unselect the “install automatically” check box. You will get the following section.

In the Above section, you need to enter the maven name and maven home as in the screenshot below.

We have entered the JDK details and Maven details. Now click the save button. Once it is saved successfully following screen will appear.

The screen shows the Project details. Click on the project name. Once you click it, navigate to the following screen where it says about the Project information.

We have completed the build setup. Now, this is a time to build the application using Jenkins. Click the “Build Now” link in the side navigation bar as in the above screenshot. Once you click the “Build Now” link, your project build will start and shows a progress bar as in the below screenshot.

If the build is completed the progress bar will disappear. Now click the #1 link, it will show the build details as in the screenshot.

As per the above screenshot, we have completed one build successfully. If you want to see the build log click “Console Output” in the side navigation bar. It will show the build log as in the below two screenshots.

Click “Back to Project” from the side navigation bar.

Once you click, you will be navigated to the project home page as in the below screenshot

If you see highlighted red color box, it shows the build details such as build happened time and how the build went whether success or failure, etc. This is showing that our build is successful.

If you click “#1”, it will go to the following details page.

The ‘Module builds” showing as java-spring. It is our java project nameWhenI set the pom.xml path in the project settings, I have pointed out the pom.xml file which belongs to “java-spring” if don’t remember, go back and check the project settings in the document.

When clicking the “Java-spring” link, the following screen will appear. This shows generated war file for our deployment which is java-spring-0.0.1-SNAPSHOT.war

Hope this article will help you in making the best use of the Jenkins tool in java application development. If you did not understand anything, contact professionals and ask your doubts. You can leave your feedback for this post in your comments.

Related Article:

How To Protect Your Intellectual Property While Outsourcing Java Development Projects

Why Java Developers Need Java Messaging System?

Spring Data Rest – Repositories

Professionals of Java outsourcing company are sharing this post with an intention to make you learn about Spring Data Rest and repositories. You will also learn about the customization methods used for Spring Data Rest.

Technology: Spring Data Rest is the framework on top of Spring Data Framework for producing the Rest API. It uses Spring MVC and Spring Data frameworks to export all functionalities through Rest API and integrates the resources with hyper media-based functionality using Spring Hateos automatically.

Getting Started:

Spring Data Rest is implemented as a plugin for Spring-based applications, we can easily integrate this with spring.

Prerequisite:

Integrating with Spring Boot Applications:

  • Maven Dependency:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
  • Gradle Dependency:
compile("org.springframework.boot:spring-boot-starter-data-rest")

Integrating with Spring MVC applications:

  • Gradle Dependency:
Compile ("org.springframework.data:spring-data-rest-webmvc:2.5.2.RELEASE")
  • Maven Dependency:
<Dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-webmvc</artifactId>
            <version>2.5.2.RELEASE</version>
</dependency>

Configuring Spring Data Rest:

Spring Data Rest provides RepositoryRestMvcConfiguration configuration java file which will contain all beans required for Spring Data Rest.

We need to import RepositoryRestMvcConfiguration class to our application configuration so that Spring Data Rest will bootstrap.

This step is not needed if we are using Spring Boot’s auto-configuration.

Spring Boot will automatically enable Spring Data REST if we include spring-boot-starter-data-rest and either in the list of dependencies, and application is flagged with either @SpringBootApplication or @EnableAutoConfiguration.

We can also customize the Spring Data Rest default behavior in two ways:

  • We can implement RepositoryRestConfigurer
  • We can extend the RepositoryRestConfigurerAdapter It is one of the empty implementations of the RepositoryRestConfigurer interface. And we can override the methods for our customization.

The list of methods available in the RepositoryRestConfigurer interface:

public interface RepositoryRestConfigurer {
            void configureRepositoryRestConfiguration(RepositoryRestConfiguration config);
            void configureConversionService(ConfigurableConversionService conversionService);
            void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener);
            void configureExceptionHandlerExceptionResolver(ExceptionHandlerExceptionResolver exceptionResolver);
            void configureHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters);
            void configureJacksonObjectMapper(ObjectMapper objectMapper);
}

Using configureRepositoryRestConfiguration we can override the baseUri, pageSize, maxPagesize, and pageParamName,sortParamName,limitParamName,and defaultMediaType.

Using this also we can configure

1)returnBodyOnCreate: if the object is created do we need to send the created object in response body or not. If this property is true then it will send the created object in response body otherwise it will not.

2) returnBodyOnUpdate: If the object is updated do we need to send the updated object in response body or not. If this property is true then it will send the updated object in the response body otherwise it will not.

3)useHalAsDefaultJsonMediaType: we need HAL(Hypermedia Links) to response or not.

configureConversionService: It will override with this Spring Default conversion service factory, if we added any new conversion services, for matters we can add to ConfigurableConversionService class.

configureValidatingRepositoryEventListener: we can configure the validator manually, for each type of event we can add the validator.

While saving the entity Spring Data will raise beforeSave, after saving events, what are the different validators we need to invoke for each event?

configureExceptionHandlerExceptionResolver: The default exception resolver on which we can add custom argument resolvers.

configureHttpMessageConverters: we can configure all HTTP Message Converters.

configureJacksonObjectMapper: we can customize the object mapper. Object Mapper to be used by the system.

Spring Data REST uses a RepositoryDetectionStrategy to determine if a repository will be exported as a REST resource or not. The following strategies

(enumeration values of RepositoryDiscoveryStrategies) are available:

NameDescription
DEFAULTExposes all public repository interfaces but considers @(Repository)RestResource’s exported flag.
ALLExposes all repositories independently of type visibility and annotations.
ANNOTATIONOnly repositories annotated with @(Repository)RestResource are exposed, unless their exported flag is set to false.
VISIBILITYOnly public repositories annotated are exposed.

Customizing the base URI:

  • spring data rest provides RepositoryRestProperties class, using this we can customize the properties.

Eg: spring.data.rest.basePath=/api

  • We can create a configuration class extending RepositoryRestConfigurerAdapter
@Component
Public class RepositoryRestConfigurer extends RepositoryRestConfigurerAdapter {
      @Override
      Public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {  
            config.setBasePath("/api")
      }
}

Resource discoverability: The main advantage of HATEOAS is that resources should be discoverable through the publication of links that point to the available resources.

HATE OS has some standards to show how to represent links in JSON format; by default, Spring Data Rest uses HAL to render its responses. Resource Discovery will start from the root, we can extract the links the from root response and every child resource link can be found from their parent.

We can use the curl command to get the resource links:

After the server starts, we can hit the command curl -v http://localhost:8080 it will show all possible children to it.

Sample response will be:

* Rebuilt URL to: http://localhost:8080/
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET / HTTP/1.1
> Host: localhost: 8080
> User-Agent: curl/7.50.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Content-Type: application/hal+json; charset=UTF-8
< Transfer-Encoding: chunked
< Date: Fri, 22 Jul 2016 17:17:59 GMT
< 
{
  "_links”: {
    "people”: {
      "Href”: "http://localhost:8080/people{?page,size,sort}",
      "templated”: true
    },
    "profile”: {
      "Href" : "http://localhost:8080/profile"
    }
  }
}* Connection #0 to host localhost left intact

Creating Spring Data Rest applications:

We require to create a model class and mark it as an entity.

Import javax.persistence.Entity;
Import javax.persistence.GeneratedValue;
Import javax.persistence.GenerationType;
Import javax.persistence.Id; 
@Entit
public class Person 
      @Id
      @GeneratedValue (strategy = GenerationType.AUTO)
      privatelong id
      private String firstName;
      Private String lastName;
      public String getFirstName() 
            returnfirstName;
      }
      Public void setFirstName (String firstName) {
            this.firstName = firstName;
      }
      public String getLastName() {
            returnlastName;
      }
      public void setLastName(String lastName) {
            this.lastName = lastName;
      }
}

And we can use PagingAndSortingRepository which is provided by Spring Data, it will provide all the methods not only for CRUD operations and also for pagination support.

Spring Data rest provides @RepositoryRestResource annotation which will expose all public methods which are marked with exported=true are exported as Rest API endpoints.

Creating Spring Data Rest Repositories:

Import java.util.List;
Import org.springframework.data.repository.PagingAndSortingRepository;
Import org.springframework.data.repository.query.Param;
Import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "people", path = "people")
publicinterface PersonRepository extends PagingAndSortingRepository<Person, Long> {
      public List<Person> findByLastName(@Param("name") String name);
}

RepositoryRestResource annotation will create endpoints for all the CRUD and as well as paging and sorting endpoints.

Creating the Main class for Spring Boot:

@SpringBootApplication
public class Application {
      public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
      }
}

1) GET: to get the data for the entity.

2) POST: saving the entity.

3) PUT: updating the entity.

4) DELETE: deleting the entity.

If we run the application and when we run the curl command for people:

E:\curl>curl -v http://localhost:8080/people
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET /people HTTP/1.1
> Host: localhost: 8080
> User-Agent: curl/7.50.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Content-Type: application/hal+json;charset=UTF-8
<Transfer-Encoding: chunked
< Date: Fri, 22 Jul 2016 17:35:28 GMT
< 
{
  "_embedded" : {
    "people" : [ ]
  },
  "_links”: {
    "self”: {
      "href" : "http://localhost:8080/people"
    },
    "profile" : {
      "href”: "http://localhost:8080/profile/people"
    },
    "search" : {
      "href" : "http://localhost:8080/people/search"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 0,
    "totalPages" : 0,
    "number" : 0
  }
}* Connection #0 to host localhost left intact

Creating a Person record:

We can create a record either using the curl command or we can use postman to create a record using the POST method with http://localhost:8080/people.

curl -i -X POST -H “Content-Type: application/json” -d ‘{ “firstName” : “sravan”, “lastName” : “Kumar” }’ http://localhost:8080/people

Response from endpoint:
{
 
  “firstName”: “sravan”,
 
  “lastName”: “kumar”,
 
  “_links”: {
 
    “self”: {
 
      “href”: “http://localhost:8080/people/1&#8221;
 
    },
 
    “person”: {
 
      “href”: “http://localhost:8080/people/1&#8221;
 
    }
 
  }
 
}
Response headers:
 
Location →http://localhost:8080/people/1

The response will depend upon the returnBodyOnCreate property.

The location header will give the URL to generated record.

The query for all records:

We can use the same URL 
http://localhost:8080/people GET method to get the data.
 
The response will look like this:
 
{
 
  “_embedded”: {
 
    “people”: [
 
      {
 
        “firstName”: “sravan”,
 
        “lastName”: “kumar”,
 
        “_links”: {
 
          “self”: {
 
            “href”: “http://localhost:8080/people/1&#8221;
 
          },
 
          “person”: {
 
            “href”: “http://localhost:8080/people/1&#8221;
 
          }
 
        }
 
      }
 
    ]
 
  },
 
  “_links”: {
 
    “self”: {
 
      “href”: “http://localhost:8080/people&#8221;
 
    },
 
    “profile”: {
 
      “href”: “http://localhost:8080/profile/people&#8221;
 
    },
 
    “search”: {
 
      “href”: “http://localhost:8080/people/search&#8221;
 
    }
 
  },
 
  “page”: {
 
    “size”: 20,
 
    “totalElements”: 1,
 
    “totalPages”: 1,
 
    “number”: 0
 
  }
 
}
 
To get the individual records: use the GET method of http://localhost:8080/people/1
The response will look like this:
 
{
 
  “firstName”: “sravan”,
 
  “lastName”: “kumar”,
 
  “_links”: {
 
    “self”: {
 
      “href”: “http://localhost:8080/people/1&#8221;
 
    },
 
    “person”: {
 
      “href”: “http://localhost:8080/people/1&#8221;
 
    }
 
  }
 
}
Searching for entity:

Listing all possible search endpoints:
 
GET method of http://localhost:8080/people/search
 
It will show the all possible methods that we specified in Repository Resource.

Sample response will look like this:
 
{
 
  “_links”: {
 
    “findByLastName”: {
 
      “href”: “http://localhost:8080/people/search/findByLastName{?name}”,
 
      “Templated”: true
 
    },
 
    “self”: {
 
      “href”: “http://localhost:8080/people/search&#8221;
 
    }
 
  }
 
}
 
In PersonRepository class we only specified one method to the records, so the response will contain only the search method.

Searching for entities using findByLastName endpoint:
Ex: http://localhost:8080/people/search/findByLastName?name=kumar

If we remembered the method argument for findByLastName we have a specified name argument that is annotated with @Param, which means for executing this method it needs a name parameter.

The Response will look like this:
 
{
 
  “_embedded”: {
 
    “People”: [
 
      {
 
        “firstName”: “sravan”,
 
        “lastName”: “kumar”,
 
        “_links”: {
 
          “self”: {
 
            “href”: “http://localhost:8080/people/1&#8221;
 
          },
 
          “person”: {
 
            “href”: “http://localhost:8080/people/1&#8221;
 
          }
 
        }
 
      }
 
    ]
 
},
 
  “_links”: {
 
    “self”: {
 
      “href”: “http://localhost:8080/people/search/findByLastName?name=kumar&#8221;
 
    }
 
  }
 
}
 
Updating an entity:
PUT method: http://localhost:8080/people/1
We can pass the JSON as a request body it will update the record.
Sample request body:
 
{  “firstName” : “sravan1”,  “lastName” : “kumar1” }
 
Sample response will look like this:
 
{
 
  “firstName”: “sravan1”,
 
  “lastName”: “kumar1”,
 
  “_links”: {
 
    “self”: {
 
      “href”: “http://localhost:8080/people/1&#8221;
 
    },
 
    “person”: {
 
      “href”: “http://localhost:8080/people/1&#8221;
 
    }
 
  }
 
}
 
Deleting the record:
DELETE method for http://localhost:8080/people/1
It will delete the record.

Conclusion:
Using Spring Data Rest, repositories can be exposed as rest services. By writing entity class and repository interface, all CRUD and search paging and sorted related endpoints will be generated by Spring Data Rest without writing any code.

Spring Data Rest uses HAL (hypermedia links) to render their response.

Hope the experts of the java outsourcing company have made you clear about the concept of Spring Data Rest. If you want to ask anything related to the subject, mention it in your comments and wait for their response.

Related Articles:

How to use AWS Cloud watch? Explain the concept to make a Java application development process simpler

Can Outsourcing Java Services Be An Answer To Technology Concerning Doubts Of People?

SPRING RETRY FRAMEWORK FOR BETTER JAVA DEVELOPMENT

In this article, you will get knowledge about the Spring Retry framework. Professionals of Java development company have introduced this technology and shared their top knowledge for the same. You can read this article and obtain how they use this technology.

Technology: Spring Retry is the framework to support retries support for spring-based applications in a declarative way. This framework immediately recreates the method for booming operation for specified attempts, this framework also supports after the many times attempts we can define the fallback method so that it will be executed.

Whenever software applications communicate with each other there is a chance of temporary self-correcting faults, like unavailability of services, temporary loss of network, or request timeouts because of server busy, in these cases, we can use another implement so that problems can be decreased.

Setup:

To use Spring Retry we need to add the below dependency.

<dependency>
<groupid>org.springframework.retry</groupid>
<artifactid>spring-retry</artifactid>
<version>1.1.2.RELEASE</version>
</dependency>

Spring Retry uses Spring AOP, we need to add Spring AOP dependency to the classpath.

<dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-aop</artifactid>
  <version>4.2.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.8</version>
</dependency>

If we are utilizing spring boot then we require to use then we can add the spring boot app as a dependency.

<dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-aop</artifactid>
</dependency>

Enable Spring retry in spring based applications:

Spring Retry provides @EnableRetry annotation to bootstrap the framework. We need to add this annotation on any one of the @Configuration annotated classes.

This framework was developed using spring AOP proxies. In spring AOP supports two types of proxies, JDK dynamic proxies, and CGLIB proxies.

@EnableRetry provides one attribute proxy target class to specify either to use CGLIB proxy or JDK dynamic proxy.

Adding spring retry annotation to spring classes:

We can add @Retry annotation to any method that we want to repeat the method if any exception occurs during the execution.

We can customize the re-try configuration using annotation attributes.

•    Include: accepts comma-separated exceptions, for which exceptions this method has to invoke.

•    Interceptor: Try again the interceptor bean name to be applied for the retryable method.

•    Value: Exception types that are retryable. Synonym for includes(). Defaults to empty (and if excludes is also empty all exceptions are retried).

•    Exclude: Exception types that are not again triable. Defaults to empty (and if includes is also empty all exceptions are retried).

    Stateful: Flag to represent the retry is stateful: i.e. exceptions are again thrown, but the retry policy is applied with the same policy to the next invitation with the same arguments. If false then retriable exceptions are not again thrown. The default is value.

•    Max attempts: the maximum number of attempts (including the first failure), the default value is 3

•    Backoff: define the backoff properties to try again this operation. The default is no backoff.

BackOff attribute is used to provide inputs to retry operations like specifying delay, max-delay, etc… using @backoff annotation.

Example:

@Retryable(value = {SampleException.class, SimpleException.class}, maxAttempts = 5)
publicvoidretryWithException() {
System.out.println("retryWithException");
thrownewSampleException("exception in retry annotate method");
    }

@Recover: we can annotate any method with this annotation to mark it as a recovery method for retry operations. Recovery handler methods need to have the first argument of type Throwable (or any subtype of Throwable) and the return type of this method must be the same as the return type of @Retryable to the method. The Throwable first argument is optional (but it will be called only if none of the recovery methods matches), and the subsequent arguments are populated from the @Retryable method.

Example:

@Recover
publicvoid recover(SampleExceptionexception) {
System.out.println("recovering from SampleException ->" + exception.getMessage());
    }

Some of the most useful Classes in the spring retry framework:

RetryTemplate: To make it robust and less error-prone to failure sometimes we need to retry failed operations on a subsequent attempt. For example, a remote call to web service that fails on network failures or deadlock situation which may be resolved after a short wait, to automate the retry of such operations springRetry has a strategy RetryOperations strategy.

The RetryOperation will look like this:

public interface RetryOperations {
    <T, E extends Throwable> T execute(RetryCallback<T, E>retryCallback) throws E;
    <T, E extends Throwable> T execute(RetryCallback<T, E>retryCallback, RecoveryCallback<T>recoveryCallback) throws E;
    <T, E extends Throwable> T execute(RetryCallback<T, E>retryCallback, RetryStateretryState) throws E, ExhaustedRetryException;
    <T, E extends Throwable> T execute(RetryCallback<T, E>retryCallback, RecoveryCallback<T>recoveryCallback, RetryStateretryState) throws E;
}

And the retrycallback will look like this:

public interface RetryCallback<T, E extends Throwable> {
    T doWithRetry(RetryContext context) throws E;
}

This is a basic callback to insert some business logic to retry the operation.

The callback is performed and if it fails (by throwing an Exception), it will be tried again until either it is successful, or the execution decides to abort. There are a number of overloaded performance methods in the RetryOperations interface dealing with several use cases for recovery when all try again attempts are exhausted, and also with try again state, which permits customers and implementations to store information between calls.

For example, for timeout retry operations spring retry framework has a TimeoutRetryPolicy policy.

We can add this retry policy in the retry template so that it will be retried until timeout for a successful response.

RetryTemplateretryTemplate = new RetryTemplate();
TimeoutRetryPolicyretryPolicy = new TimeoutRetryPolicy();
retryPolicy.setTimeout(1000L);
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.execute(new RetryCallback<HelloWorld, Exception>() {
    @Override
    public HelloWorld doWithRetry(RetryContext context) throws Exception {
        return result;
    }
});

The above example executes a web service call and returns the result to the user, if that fails then it is retried until the timeout is reached.

RetryContext: The method argument for the RetryCallback is a RetryContext.It is used as an attribute bag to store data for the duration of the iteration.ARetryContext will have a parent context if there is a fixed retry in progress in the same thread. The parent context is sometimes useful for holding data that need to be shared between calls to execute.

RecoveryCallback: It is the callback interface if all configured retry policies are executed but don`t receive a successful response.

Listeners: Spring retry provides a RetryListener interface for cross-cutting features in retry operations; RetryTemplate provides a way to attach a listener to it so that it will be called in respected operations.

The RetryListener interface will look like this:

public interface RetryListener {
    <T, E extends Throwable>booleanopen(RetryContext context, RetryCallback<T, E> callback);
    <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwablethrowable);
    <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwablethrowable);
}

Open and close methods will be performed before and after the whole retry operation, and the onError method is performed on all individual callback, the close method might also receive a Throwable, if there is an error it is the last one thrown by the RetryCallback.

If more than one listener is configured, there must be some order of execution of listener, open method is executed in the same order as configured, and onErrror and close method will be called in reverse order.

The sample RetryTemplate will be:

publicRetryTemplateretryTemplate() {
SimpleRetryPolicyretryPolicy = newSimpleRetryPolicy();
retryPolicy.setMaxAttempts(5);
 
FixedBackOffPolicybackOffPolicy = newFixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds
 
RetryTemplatetemplate = newRetryTemplate();
template.setRetryPolicy(retryPolicy);
template.setBackOffPolicy(backOffPolicy);
 
RetryListener[] listeners = newRetryListener[2];
listeners[0] = newSampleRetryListener();
listeners[1] = newSimpleRetryListener();
        template.setListeners(listeners);
        
returntemplate;
    }

Conclusion:

Spring Retry is the framework for declarative using @Retryable and @Recover, and programmatic way using RetryCallback and RecoveryCallBack to support retry operations in spring-based applications, this framework also supports cross-cutting using retry listeners.

Source code can be downloaded at: https://github.com/sravan4rmhyd/SpringRetryDemo.git

So, you now know the Spring Retry technology. If you have any questions, ask experts of Java development company straightforward in the comments. Do share your feedback for this post and tell other readers what your experience with this framework was.

Related Article:

Java Developers Sharing Node.Js Performance Tips For Adoption

Exploring The Java Platform Through Best Java Jobs

How to Wrap Text inside the Column in SWT Java-Based Framework?

In this article post, java development company experts will explain the SWT framework. They will guide you on how to wrap text inside the column in SWT. For in-depth information, please read the article.       

Introduction

SWT is for Software Widget Toolkit, its Java-based open-source framework at first developed by IBM now carry on by the Eclipse community.

The eclipse itself is developed on the SWT framework. This framework is used to develop desktop applications. It resembles Java Swings, SWT.

The key topics in this framework are Shell, Display, Perspective, Plug-in, Composite, Group, etc…

You may find many tutorials on the internet

@http://www.vogella.com/tutorials/SWT/article.html

@http://www.java2s.com/Tutorial/Java/0280__SWT/Catalog0280__SWT.htm

@https://www.eclipse.org/swt/examples.php

Problem:-Expressive SWT desktop application will be in the form of tree structure or table: There is the performance that the text inside the cell should be covered if you resize the cell: SWT framework does not provide this functionality directly so that we can implement it on the fly. So we have to make our own execution on top of the SWT framework.

In general, if the values inside the column are larger than the column sizes then SWT displays it as dots appending at the last positions of the column. If we need to look at the whole text then we have to drag the header and look at it.
  • If we want to see the whole text then without dragging the column header then we have to implement our tailored label supplier because SWT does not hold up this feature directly.

Solution: We have solved this matter by applying our own label supplier. We will convince in the sample code, that how we solved this problem. One should have good information about the SWT framework then only he may recognize this solution.  The below code sample will provide the solution for this problem. One requires having SWT, SWTX jar files to run this sample. 

First, make a table using SWT set the label supplier and an implement paint listener so that the column size will be bigger.

Code snippet to create table:

Paint Listener:

privatefinal Listener paintListener = new Listener() {

intheightValue = 69;

intimgX = 40;

privateintimgY = 5;;

privateinttxtX = 4;

privateinttxtY = 5;

@Override

publicvoidhandleEvent(Event event) {

finalTableItemitem = (TableItem) event.item;

switch (event.type) {

caseSWT.MeasureItem: {

String itemText = item.getText(event.index);

Point size = event.gc.textExtent(itemText);

event.width = size.x;

event.height = heightValue;

break;

}

caseSWT.PaintItem: {

final String itemText = item.getText(event.index);

final Image img = item.getImage(event.index);

finalintoffset2 = 0;

intoffsetx = 0;

if (img != null) {

event.gc.drawImage(img, event.x + imgX, event.y + imgY + offset2);

offsetx = 19;

}

if (itemText != null) {

event.gc.drawText(itemText, event.x + txtX + offsetx, event.y + txtY + offset2, true);

}

break;

}

caseSWT.EraseItem: {

event.detail&= ~SWT.FOREGROUND;

break;

}

default:

break;

}

}

<strong>Table Creation:</strong>

tableViewer = newTableViewer(container, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);

tableViewer.setContentProvider(newContentProvider());

ColumnViewerToolTipSupport.enableFor(tableViewer, ToolTip.RECREATE);

table = tableViewer.getTable();

finalFormDatafdFroTable = newFormData();

fdFroTable.top = newFormAttachment(0, 5);

fdFroTable.left = newFormAttachment(0, 4);

fdFroTable.right = newFormAttachment(100, -15);

fdFroTable.bottom = newFormAttachment(100, -35);

table.setLayoutData(fdFroTable);

table.setLinesVisible(true);

table.setHeaderVisible(true);

shell.setSize(400, 400);

shell.open();

finalTableViewerColumntableViewerColumn = newTableViewerColumn(tableViewer, SWT.NONE);

finalTableColumntableColumn = tableViewerColumn.getColumn();

tableColumn.setWidth(100);

ValueLabelProviderlabelProvider1 = newValueLabelProvider(0);

tableViewerColumn.setLabelProvider(labelProvider1);

tableColumn.setText(“Column1”);

tableViewerColumn.setLabelProvider(newTextWrapperLabelProvider(tableViewer, 0, labelProvider1));

tableViewerColumn.getColumn().addControlListener(newControlAdapter() {

@Override

publicvoidcontrolResized(ControlEvente) {

tableViewer.refresh(true);

}

});

addColResizeListener(tableColumn);

Collection<ValuObject>valuObjects = newArrayList<>();

for (inti = 0; i< 3; i++) {

ValuObjectvaluObject = newValuObject();

valuObject.setValue1(” Hi this is test program for text wrapper example” + i);

valuObjects.add(valuObject);

}

table.addListener(SWT.MeasureItem, paintListener);

table.addListener(SWT.PaintItem, paintListener);

table.addListener(SWT.EraseItem, paintListener);

tableViewer.setInput(valuObjects);

Set the label to supply for each column otherwise, it will throw an exception and use this label provider to get its corresponding values while wrapping

Set text wrapper label supplier, so that text will be wrapped for all changes in the header of the column. Don’t forget to add Resize listener, otherwise, the label supplier will not be called for each change.

finalstaticclassValueLabelProviderextendsColumnLabelProvider {

privatefinalintcolumnIndex;

protectedValueLabelProvider(intcolumn) {

super();

this.columnIndex = column;

}

/**

* {@inheritDoc}

*/

@Override

public String getText(Object element) {

String text = null;

finalValuObjectvaluObject = (ValuObject) element;

switch (columnIndex) {

case 0:

text = valuObject.getValue1();

break;

default:

text = null;

}

returntext;

}

}

<strong>Content Provider:</strong>

/**

* The Class ContentProvider.

*/

publicclassContentProviderimplementsIStructuredContentProvider {   

@Override

publicvoid dispose() {

}

@Override

@SuppressWarnings(“rawtypes”)

public Object[] getElements(Object inputElement) {

if (inputElementinstanceof Collection) {

return ((Collection) inputElement).toArray();

} else {

returnnull;

}

}  

@Override

publicvoidinputChanged(Viewer viewer, Object oldInput, Object newInput) {

}

}

publicclassTextWrapperLabelProviderextendsColumnLabelProvider {

privatefinalintcolumnIndex;

privatefinalColumnViewerviewer;

privateColumnLabelProviderlabelProvider;   

publicTextWrapperLabelProvider(ColumnViewerviewer, intindex, ColumnLabelProviderlp) {

this.labelProvider = lp;

this.viewer = viewer;

this.columnIndex = index;

}

/**

* {@inheritDoc}

*/

@Override

public String getText(Object element) {

GC gc = null;

try {

gc = new GC(viewer.getControl());

intcolumnWidth = getColumnWidth();

intcolumnHeight = findHeight();

String columnText = “”;

Font columnFont = null;

columnText = labelProvider.getText(element);

columnFont = labelProvider.getFont(element);

gc.setFont(columnFont);

final String text = TextWrapperExample.wrapColumnText(gc, columnText, columnWidth, columnHeight);

returntext;

} finally {

if (gc != null) {

gc.dispose();

}

}

}  

privateintfindHeight() {

intitemHeight;

if (viewerinstanceofTableViewer) {

TableViewertableViewer = (TableViewer) viewer;

final Table table = tableViewer.getTable();

itemHeight = table.getItemHeight();

} elseif (viewerinstanceofTreeViewer) {

TreeViewertreeViewer = (TreeViewer) viewer;

final Tree tree = treeViewer.getTree();

itemHeight = tree.getItemHeight();

} else {

itemHeight = 0;

}

returnitemHeight;

}  

privateintgetColumnWidth() {

intwidth;

if (viewerinstanceofTableViewer) {

TableViewertableViewer = (TableViewer) viewer;

final Table table = tableViewer.getTable();

TableColumncolumn = table.getColumn(columnIndex);

width = column.getWidth() – table.getBorderWidth() – table.getBorderWidth();

} elseif (viewerinstanceofTreeViewer) {

TreeViewertreeViewer = (TreeViewer) viewer;

final Tree tree = treeViewer.getTree();

TreeColumncolumn = tree.getColumn(columnIndex);

width = column.getWidth() – tree.getBorderWidth() – tree.getBorderWidth();

} else {

width = 0;

}

returnwidth;

}

}

VERY important

The table viewer should be regenerated for all header changes. So, that’s why control listener for table viewer column.

Build data for the table column, in this case, there is only one column, so I am setting only one column value. If you have various columns then want to set many values to a value object

After table design without wrapper if you start the program the output will be like the below:

If you notice in the above screenshot the text inside column1 is not wrapped in the text is superior to the length of the column.

If you put the text wrapper label supplier then the text in the table cell will be wrapped as per the column header exchange. The screenshot will see below.

  • First, look over the number of possible lines for the changed header size. If the number of possible lines is greater than 1 then only wrap the text.
  • To wrap text first the string inside the cell is spitted by delimiter either empty space or tab space, they will be stored inside a collection. So that they will be used at the time of wrapping based on header size.
  • Upon the new column, header size gets the text wrapper to be wrapped add that to the last of the string by adjoining \n that is a new line so that the wrapped text segment will be presented in a new.
  • It’s very essential to add a new line, then only it will present as a new line that is as a wrapped line. SWT can handle this case.

protectedstatic String wrapColumnText(GC gc, final String inputString, intlineWidth, intitemHeight) {

intfontHeight = gc.getFontMetrics().getHeight();

intleadingAreaLenght = gc.getFontMetrics().getLeading();

intlineHeight = fontHeight – leadingAreaLenght + 4;

intnoOfLinesPossible = itemHeight / lineHeight;

if (noOfLinesPossible == 1) {

returninputString;

}

Point resizePoint = getResizedPoint(gc, inputString);

if (resizePoint.x<= lineWidth&& (itemHeight == 0 || resizePoint.y<= itemHeight)) {

returninputString;

}

intlines = 1;

Pattern p = END_LINE;

String input = p.matcher(inputString).replaceAll(“\n”);

List<WrappedText>wrappedTextCol = getWrappedTextCol(input);

StringBufferbuffer = newStringBuffer();

intstart = 0;

intwrappedTextIndex = -1;

while (true) {

intwrappingIndex = findWrappingTextIndex(gc, lineWidth, lineHeight, input, wrappedTextCol,

start, wrappedTextIndex);

if (wrappingIndex<= wrappedTextIndex) {

wrappingIndex++;

}

booleanisLast = wrappingIndex>= wrappedTextCol.size();

intend;

intnextStart;

if (isLast) {

end = input.length();

nextStart = end + 1;

} else {

WrappedTextwrappedText = wrappedTextCol.get(wrappingIndex);

end = wrappedText.getStartPos();

nextStart = wrappedText.getEndPos();

}

addText(buffer, input, start, end);

lines++;

if (isLast) {

break;

} else {

start = nextStart;

wrappedTextIndex = wrappingIndex;

}

if (noOfLinesPossible> 0 &&lines>= noOfLinesPossible) {

end = input.length();

addText(buffer, input, start, end);

break;

}

}

String string = buffer.toString();

returnstring;

}

Change the input by empty space or minus delimiter and add to the wrapped text collection

privatestatic List<WrappedText>getWrappedTextCol(String input) {

List<WrappedText>wrappedTextCol = newArrayList<WrappedText>();

Pattern p = Pattern.compile(“[ \t]+|[^ \t\n]-|[\n]|[,]”);

Matcher matcher = p.matcher(input);

WrappedTextwrappedText;

while (matcher.find()) {

booleanminus = ‘-‘ == input.charAt(matcher.end() – 1);

if (minus) {

wrappedText = newWrappedText(matcher.end(), matcher.end());

} else {

wrappedText = newWrappedText(matcher.start(), matcher.end());

}

wrappedTextCol.add(wrappedText);

}

returnwrappedTextCol;

}

Then, getting the wrapping segments to check whether the changed header length is greater than the text inside the cell, then we want to wrap the text by calculating which wrapped text of the group should be wrapped.

To evaluate which wrap text logic is as below:

privatestaticintfindWrappingTextIndexRec(GC gc, intlineWidth, intlineHeight, String input,

List<WrappedText>wrappingCol, inttextStartPos, intstartIndex, intendIndex) {

inttestIndex = (startIndex + endIndex) / 2;

inttextEndPos = testIndex< 0 ? textStartPos

: testIndex>= wrappingCol.size() ? input.length()

: wrappingCol.get(testIndex).getStartPos();

String text = input.substring(textStartPos, textEndPos);

intnextStart = startIndex;

intnextEnd = endIndex;

booleantooBig = checkIfStringLongerThanResize(gc, lineWidth, lineHeight, text);

if (tooBig) {

nextEnd = testIndex;

} else {

nextStart = testIndex;

}

if (nextEnd – nextStart<= 1) {

returnnextStart;

} else {

intindex = findWrappingTextIndexRec(gc, lineWidth, lineHeight, input, wrappingCol, textStartPos,

nextStart, nextEnd);

returnindex;

}

}

Helper methods:

privatestaticbooleancheckIfStringLongerThanResize(GC gc, intlineWidth, intlineHeight, String text) {

Point textSize = getResizedPoint(gc, text);

booleanwidth = textSize.x>= lineWidth;

booleanheight = textSize.y>lineHeight;

returnwidth || height;

}

privatestatic Point getResizedPoint(GC gc, String string) {

Point extend = SWTX.getCachedStringExtent(gc, string);

returnextend;

}

After setting the text wrapping label supplier if you run the program output will be like this:

After wrapping the screenshot will see it like this. If you notice the text inside the cell is wrapped according to the column header size.

Java development company specialists just shared the guide to wrapping text into the column in the SWT java based framework. You can try and observe your own and share the results with our readers by commenting below.

Related Articles:

Social Networks And B2b: Do Not Miss The Boat Trends

ARM 64-bit quad-core 1.8 GHz for the new 96Board

How to use DynamoDB and cloud in Java web development

How to use DynamoDB and cloud in Java web development

Concept of NoSQL, AWS, and DynamoDB by Aegis Softtech

In this post, the Aegis java development team will discuss the concept of NoSQL, AWS, and DynamoDB and how to use them in java web development projects. The viewer will also want to know about Amazon DynamoDB architecture and its data model idea.

What is NoSQL?

NoSQL – often referred to as Not a SQL – is a database that offers storage and retrieval of data that is stored in a way other than the normal RDBMS. Relational databases were never meant to handle the scale and cleverness challenges that face current applications, nor were they designed to handle the huge amounts of data to bring out ‘information’ it. NoSQL comprised of a variety of database technologies was developed in response to a rise in the volume of data stored about users, their data patterns, the frequency and way in which this data is accessed, and performance and processing needs. Java has primarily been the language since the early days to connect and play with NoSQL databases. Being the strong part, we are going to delve in-depth into how Java development connects with NoSQL DB.

With the advent of the Internet age, the rise of social media, social applications, e-commerce, etc., there has been a burst of data production containing useful information. The current RDBMS techniques though can be handled somehow to store the large amounts of volume but then it becomes increasingly difficult to process those data in order to fetch ‘useful information. A NoSQL technique answers the questions by storing the data in key-value, graphs, documents, etc., which is different from relational databases, making some operations faster in NoSQL and others faster in relational databases. The choice of what technology to use depends on the problem at hand to be solved.

There are many different NoSQL databases in the market. Some of the examples include Cassandra, MongoDB, DynamoDB, Hbase, MemcacheDB, etc.

AWS(Amazon Web Services) and DynamoDB?

Amazon Web Services is a Cloud Service and it is one of the huge Cloud suppliers amongst all those who are supplied. AWS comes with a group of services, all of them serving the cloud model, that permits any application to use the powerful benefits that the Cloud model advises. Begining from sharing of the processing power to the database to the security system to the sharing of computer hardware, it is the one-stop store for any cloud necessity application. One of the most famous and widely used services is DynamoDB: A NoSQL approach to storing data. DynamoDBis a very flexible service that provides a seamless interface for creating, storing, and retrieval of data.

The operations on DynamoDB can either be performed using the AWS UI, AWS CLI (Command Line Interface), or the AWS SDK. The SDK comes in a variety of languages enabling a wide variety of developers to code the applications performing operations on the service. We shall be discussing the Java approach to the system because the Java team in the company has had a long experience developing the applications that have DynamoDB as the back-end database. The pre-requisites for operating in Java would be a JAVA SDK and Maven installed on the machine.

Some Of The Advantages Of Using Dynamodb Are As Follows:

  • Scalable – DynamoDB is created for perfect throughput and storage scaling.
  • It is fast and has a predictable performance
  • Easy Administration – The service is a fully managed one. One creates the DB and the service handles the rest without worrying about the hardware and software provisioning.
  • Built-in Fault Tolerance – The built-in fault tolerance feature of DynamoDB is a rather powerful one. It automatically and synchronously replicas your data across multiple Availability Zones
  • Secure – The service uses proven cryptographic methods to authenticate users and prevent unauthorized data access
  • Integrated Performance – DynamoDB displays a variety of operational metrics for each table in the console. It can also be integrated with another AWS Service called CloudWatch for enhancing metrics.

How to use Amazon DynamoDB?

To use AWS DynamoDB, or as a matter of fact, any of AWS Services, one must download the AWS SDK to use its features. In the case of expert utilization, the following extracts of code are used to download the SDK. If the expert is not present, one can manually download the AWS-java-SDK from the web.

The category can be changed to suit the necessity.

Amazon DynamoDB Architecture

Before proceeding further it would be nice to understand some technical jargon associated with DynamoDB. The DynamoDB data model idea includes tables, products, and attributes.

  1. Table – A database is a collection of tables. A table is an entity that stores the data. A table is a group of products and each product is a group of attributes. In difference to relational databases, DynamoDB needs that the table has the main key, and it does not necessary to mark all of the attribute names and data types further. All products can have any number of attributes.
  • Item – Each item in a DynamoDB table corresponds to a row in a relational database.
  • Attribute – Each attribute in an item is a name-value pair. An attribute could be a single or multi-valued set.

DynamoDB API:

Following are the most important DynamoDB API calls that are used very frequently and are the ones that we have been using in our projects.

  1. CreateTable: This is the API call that is used to create a table in an AWS account in a particular region.

When you create or update a table, you define how much equipped throughput volume you need to save for reads and writing. DynamoDB will save the required machine resources to meet your throughput needs while securing compatible low-latency execution.

Related Articles:

Java Development Company Taking You on Java SE 8 Latest Features Tour

Java Major Milestones And Disappointments – Get To Know Now!

Which Java version do you use? It could affect the main application

Which Java version do you use? It could affect the main application

Java has been significantly modernized with the new outline of the Java Platform Component Systems and with the help of these new modules to produce all of its platforms like the Java SE as well as JDK the existence concerns because of the variations are recognized in the possibilities and expectations. If you are a starter, it might take a little time to see and experience the differences that Java 9 and 10 had long back started. For learning there won’t be any difficulty if a person is making use of Java 8, nothing has been missed here or something out-of-date. As an alternative, the provision and apprises that have been said to be one of the parts of Java license would at present be obtainable only from a distinct payment provision service. Everything relies on the situation when it comes to using Java web development versions in any application. In space, the newest version is perfect. JDK 12, on the other hand, has continuously used the most modern and utmost and keeps informing the slight forms as they are unconfined.

 JDK 11 is called to be an Extended Term Provision” (LTS) release; on the other hand, JDK 12 is recognized as the Feature Release. The envisioned difference among LTS as well as the JDK Feature issues is is that in over-all, organized software must use an LTS release. The LTS releases would rationalize along with the security and bug repairs for numerous years when the LTS was released. It lets an individual endure going through your software in a place that supported for a lot of years.

JDK 12 continuously will give and use the modern and utmost bring up-to-date the lesser types when they are brought up. JDK 12 even has a few of the advantages like adjustment languages, fresh untried trash amasser along with continuous pause periods irrespective of load size. Java has numerous purposes or usages. A lot of its determinations are, for file distribution and extensive desktop usages like the Net Beans and Eclipse combined expansion surroundings. Not only this, but this processer application could also be cast-off for moveable devices anywhere that it offers as a challenger to NET Compressed Outline and Symbian.

The envisioned use of a Feature Release is to let designers to trial with different features and to begin getting prepared to organize software with the help of updated features only at the time the next LTS form gets released.

Perceptibly there would be nobody for you when you want to deploy an app with the help of Feature Release. Nevertheless, if bugs or security problems are exposed down and arise, there will be no informs to hit the concern. You could every time promote to another level of Feature Release. However a 100 percent assurance won’t be there for, backward compatibility, you might here take some risk.

In case if you are planning to build an app that you feel to organize, you must make use of JDK 11. However, if you want to experiment and use this version as a knowledge prospect, you could make use of JDK 12. In both cases you have to be assured of the new features of JDK 11 and JDK 12, thus to reverse the decision to create JDK 11 acquiescent application you would know what characteristics you can apply or not apply in the application. The JDK is mostly dogged by the tool that is used to connect Java. A lot of peoples are supporting the smallest version of Java 8 on a temporary basis.

A lot of confusion has been taken place from the past few years in regards to Java and its available SDKs known as Software Development Kits). You may have perceived the Java SDK known as JDK, both the things are the same. Java SE (Standard Edition) is a requirement that is ruled by the JCP (Java Public Procedure). This procedure chooses what will go in or what will take out of the JDK. Anybody could apply the Java requirement. They are known to be a feasible JDK.

Below is a summary of Oracle’s modifications:

  • Oracle at present allocates Oracle OpenJDK and Oracle JDK
  • For testing Oracle JDK is free. However, you should in case you use its production
  • It has a few new language features
  • OpenJDK is open for any environment

Promising future features:

  • Objects without identity
  • 64-bit relating collections to maintain massive information sets
  • Raw string after removed from JDK 12 will restore in JDK 13.

There are a lot of thoughts in regards to which java version should be used in growth and manufacture. In realism, you may have no choice of what circulation you use in the making. It is always advisable to use the latest and most excellent versions.

Parsing YAML files using SnakeYAML

Technology: YAML is one of the formats to provide configuration files for any type of language. Previously we used to write properties files for configuration, but if the text repeated and it is very tedious construct the hierarchy keys.

YAML is a Human-friendly data serialization standard for, all major programming languages, most languages now support YAML file formats.

YAML is a superset version of JSON file format, and it is a very convenient format for specifying the hierarchical configuration properties.

SnakeYAML is one of the libraries, most used in the Java-based App Development, spring boot also uses the same for processing YAML files internally.

YAML specifications:

  • YAML is easy to read by humans
  • YAML files will be portable across all programming languages.
  • YAML is easy to use and implement.
  • YAML is very extensible and expressive.
  • YAML has a specific format to support tools.

We will understand how to write yaml files and compare with a properties file format.

Suppose we have below configuration data if we are used properties file format it will like below:

spring.datasource.url =jdbc:mysql://localhost:3306/test
spring.datasource.username =sa
spring.datasource.username=password
spring.jpa.show-sql=true
server.port=8081

If we see spring and data source words are a repeat and it is hard to visualize the hierarchy structure also if we write the same in the yaml file, the structure will look like below:

spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: sa
password: password
jpa:
show-sql: true
server:
port: 8081

Here we can easily visualize the configuration data hierarchy and will be used as the delimiter for line and space data.

SnakeYAML dependency:

Let’s create sample maven project and add the below maven dependency for snakeYAML.

org.yaml
snakeyaml
1.23

Loading yaml file into library:

Library provides support for loading the content from the string, inputstream, and reader classes.

For now, we will use the inputstream to load the file to the library and parse it.

Yaml is the class for the entry point of the library since the yaml class is not a singleton, then different threads will contain their yaml class instance.

Suppose below is the YAML stored in an application.yml file.

firstName: sravan
lastName: kumar
age: 28
Now let’s create inputstream for application.yml file.
InputStream stream = YAMLExample.class.getClassLoader().getResourceAsStream("application.yml");

Where YAMLExample is our main class.

yaml.load(stream) method will load the inputstream and return the object type, we can cast to either Map, custom object.

Suppose if we are using Map as the return type, then

Map<String,Object> yamlData = yaml.load(stream);
System.out.println(yamlData.get("firstName"));

The output will be

sravan
now let`s create new custom object with firstName, lastName, and age fields.

public class Person {
private String firstName;
private String lastName;
private int age;

// setters and getters
@Override
public String toString() {
return "firstName "+firstName+" lastName "+lastName+" age "+age;
}
}
And update the application.yml with below content.
!!org.sample.Person
firstName: sravan
lastName: kumar
age: 28

Where first line is the class name to which we want to cast the load method output.

Person person = yaml.load(stream);

System.out.println(person);

Replace the above lines with previous load method, then output will be

firstName sravan lastName kumar age 28

The drawback of this approach is, to specify the return type in yml file, it should be exported as library/jar file wherever we used.

The snakeYAML library provides another type of the YAML constructor for creating the YAML object.

Yaml yaml = new Yaml(new Constructor(Person.class));

And remove first line of yml file where we specified the class name.

If we execute the same, then we will get the same output as in previous case.

Casting to Nested Objects and Collections:

Update yml with below content:

firstName: sravan
lastName: kumar
age: 28
contactDetails:
- type: mobile
number: 1234567890
- type: landline
number: 9876543210

“-” means collection of object.

contactDetails will contain the collection of type and number fields.

Let`s create the object which contain type and number fields and add a collection of this type with variable conatctDetails in Person class.

public class Contact {
private String type;
private String number;

// setters and getters
@Override
public String toString() {
return "type "+type+" number "+number;
}
}

And updated person class will be:

public class Person {
private String firstName;
private String lastName;
private int age;
private List contactDetails;

// getters and setters
@Override
public String toString() {
return "firstName "+firstName+" lastName "+lastName+" age "+age +" contacts "+contactDetails;
}
}

If we execute the same the output will look like below:

firstName sravan lastName kumar age 28 contacts [type mobile number 1234567890, type landline number 9876543210]

Conclusion: YAML is one of the file format used for providing the configuration data, SnakeYAML is one of the libraries to parse the YML files.

Download the sample code at https://github.com/sravan4rmhyd/snakeYAML.git

See more at –

Aegis SoftTech won Best IT & Software Services Company Award

power bi tableau dashboard software

The Java Web Development Trends to Pick Momentum in 2018

Java is a development and programming language that’s been around for decades now. As we have stepped into 2018, we are sure there will be numerous Java web development innovations and challenges that we will have to talk about in the future.

We will also have to wait and see how these development challenges affect the people working on the language. According to Markus Eisele, a regular speaker at Java conferences and one of the leading Java enthusiasts, a major change happening in the Java community is that the general notion of Java release cycles from one major release in two years has shifted to more regular updates every few months. In the Open JDK, organizations will have to battle with the short support cycles, and up their levels.

java development trends

Some Java development trends that will be the focal of programming this year are-

  • Artificial Intelligence and Machine Learning – Previously, most of the AI and ML applications were developed in C and Python, but these programming languages are not exclusive to the applications anymore. Some Java frameworks like Deep learning help Java developers get a hand at developing quick and robust Artificial Intelligence and Machine Learning applications. And, Java developers throughout the world want to do that because these technologies are growing the fastest.
  • Microservices – The evolutionary architecture concepts like microservices will be pushing harder on developers this year. Microservice architecture demands that an application be built as a collection of a few modular services that are loosely coupled with each other. Microservices are a variant of the popular Service-Oriented Architecture. Data Distribution happens to be a challenge around building working microservices. While most companies have figured the functional and technical aspects of microservices, still data distribution needs to be addressed.
  • Serverless apps – There is a rise in the demand and applications of Functions as a Service that allows developers to build applications and services from tiny components and provides the ability to scale cost and capacity of applications as and when the demand arrives. Developers’ interest in serverless applications is bound to increase as the demand for such applications ad the knowledge base around the subject increases.
  • Blockchain – Blockchain has become the official buzzword for 2018, too. After the ebb and flow in the cryptocurrency market, governments trying to make order out of the chaos, people investing in cryptocurrencies, and organizations hoping to exploit Blockchain technology, Java developers have not been far behind. The Java tech community is trying to find out many other uses of the technology and will be on the top of its toes developing some revolutionary applications based on Blockchain.
  • Java Development – The Java community is expected to be more vibrant this year than ever. With Java SE entering into a phase of six-month release cycles, Oracle’s JDK components migrating to the open-source OpenJDK, Java EE coming to Eclipse, the Java community will grow cohesive and will be buzzing all year round in 2018. Java had often faced the criticism of being a slowly updated language, and with the six-month release cycles, each year, the Java developers will see new features brought in, twice!
  • Java 10 – Java 9 arrived last year, but as the predictions were rife, the update did not have an impact that Java 8 did. Therefore, Java 9 has had a slow adoption as it forces developers to update their applications for using the modular system. Java 10 has been predicted to showcase some major performance features, and people are vouching for it.

With all these latest developments in the programming language, the Java Web Development is excited to be a part of it this time in their lives, and we can hope to see some major feature and performance upgrades from Java!

Read more – Can This Be a Possible End to the Functional Programming Debate?

How Java Programmers Make Conversion Between Collections Of Wrapper Objects And Wrapped Objects

Essential Frameworks For Trailblazing Java Web Development Solutions

Enterprises using java apps and java web development frameworks are increasing every day. But the problem is that few enterprises are still using conventional web frameworks and they are not pretty much sure about the best web development framework. Even experts are not sure about the best framework as there are plenty of choices available and all of them have some unique and interesting features.

In brief, we can say the web arena is facing a broad change due to technology advancements, market trends, and experts’ choices. It is the reason after deep research and expensive hands-on experience in Java; we have concluded 10 most popular web development frameworks that will help you in making the right decision.

Java Web Development framework

Let us discuss all of these frameworks for trailblazing web development solutions one by one:

  1. Struts 2

The robust Web Development Framework Association has been designed to deploy web applications from sourcing. The strut is a framework for joint efforts of Community and Webwork. The best part is that it can create dynamic responses.

“Struts 2” is an improved version of the previous one that assures clean code for web apps. It uses AJAX tags to create flexibility and making web apps more interactive. For the Java developers who want to play with open source code, Struts 2 is the recommended option.

  1. JSF

JSF is used to prepare server-side interfaces for web applications. JSF is based on component-oriented approach, not on object-oriented which makes java web development easy and more robust. It can integrate with other Java frameworks on request.

Advantages:

  • Enterprise app development is easy and robust
  • JSF is considered fast as compared to server-side interfaces
  • There is plenty of component libraries to help you
  1. Spring MVC

Spring MVC works on the presentation layer and applicable to the wide product range. When working with Spring MVC, you can use objects everywhere there is a need to implement any base class. It also allows for flexible data binding. It takes as a strategic and flexible web platform for Java web apps.

  1. Wicket

Wicket is a lightweight component for designing robust java apps. It is suitable for apps that a require high-end GUI interface. It temporarily separates the business and app-level to eat template editing. It is a component-based mode where the component has its state and model. If developers wanted to make, most of their resources then wicket can be considered the best web development framework available so far.

  1. Stripes

This framework allows the interaction between complex data objects. It supports data binding, data validation, and data conversion. It is used to handle a large volume of data, which are highly complex and difficult to manage by experts. Once you have registered, for this web framework then it does not need for any external configuration. We can say stripes offer an easy and efficient solution of complex problems in a web tier. It is a compact web framework with few dependencies.

  1. Tapestry

It is an open source and object-oriented framework for designing powerful Java apps. It is based on MVC i.e. Model – View – Controller method and allows quick implantation of apps. The framework is much focused on methods, queries, and functions instead of queries and URLs. It is based on a modular approach for web development where UI on web pages combined with their corresponding Java classes.

  1. RIFE

In this framework, each small focused and approached carefully. A single app is divide into different modules; each developer has it’s his task so that it can complete successfully. Whenever it is needed, one module can effortlessly integrate with another one that is called seamless integration of modules. In this way, it is easy for developers to manage code, code replication and redundancies can also reduce significantly.

  1. SEAM

It is an open-source web framework suitable for designing internet-rich applications. It integrates, different technologies together like AJAX, Business Process Management (BPM), JSF, Java beans, etc. it also deals with context basics. Web development is easy with JBoss tools and design issues also eliminate to a large extent. Some of the highlights of SEAM include – Emailing, PDF creation, graph designing, worksheet formation, etc.

  1. Google Web Toolkit

GWT is a web development framework that allows developers to maintain and build Java apps. It would be easy for you to implement Google maps and Gmail with Google web toolkit. There are plenty of tools that make web development easy for developers. There is also AJAX assistance that allows them to write applications quicker. You can also test, share or edit AJAZ apps whenever necessary.

  1. OpenXava

It is a web development framework for designing AJAX apps at the enterprise level. It helps the developer in designing full-fledged Java apps that ready to market. It allows for easy report generation and module generation. It is much faster as compared to MVC, Ruby, etc.

See more at –

  • Spring Retry framework for Better Java Development
  • Top 5 Java-Based Tools for Business Intelligence